   ,¦ (¦ !¦ {"files":{"package.json":{"size":416,"integrity":{"algorithm":"SHA256","hash":"e055b7c58acc149ed814838cb6493a66d4a849177316f6a29166aaf4699fc705","blockSize":4194304,"blocks":["e055b7c58acc149ed814838cb6493a66d4a849177316f6a29166aaf4699fc705"]},"offset":"0"},"resources":{"files":{"icon.icns":{"size":181949,"integrity":{"algorithm":"SHA256","hash":"14177bf2399bfb85209018ba1b0627feabc1ee0aa3e954e636dc4decd58d1169","blockSize":4194304,"blocks":["14177bf2399bfb85209018ba1b0627feabc1ee0aa3e954e636dc4decd58d1169"]},"offset":"416"},"icon.ico":{"size":36119,"integrity":{"algorithm":"SHA256","hash":"887287f986f29fdffb940b98ca830ffefc7e126315514b8d700bbacdb64a9648","blockSize":4194304,"blocks":["887287f986f29fdffb940b98ca830ffefc7e126315514b8d700bbacdb64a9648"]},"offset":"182365"},"icon.svg":{"size":349,"integrity":{"algorithm":"SHA256","hash":"92d6be883d07b8f191451fd03d3a40151b6c896a36c7c9b04b851388b3bb921d","blockSize":4194304,"blocks":["92d6be883d07b8f191451fd03d3a40151b6c896a36c7c9b04b851388b3bb921d"]},"offset":"218484"},"icon_raw.png":{"size":17115,"integrity":{"algorithm":"SHA256","hash":"291b687ca3122061b702eedc71e835cf3c065097a9104b6eded587a0d6fbbca4","blockSize":4194304,"blocks":["291b687ca3122061b702eedc71e835cf3c065097a9104b6eded587a0d6fbbca4"]},"offset":"218833"}}},"extensions":{"files":{"translator":{"files":{"content.js":{"size":330,"integrity":{"algorithm":"SHA256","hash":"2b163e108ced6bf2dad8386a98fbea48a99b76084bb791f08c2cb30c00a8bdb6","blockSize":4194304,"blocks":["2b163e108ced6bf2dad8386a98fbea48a99b76084bb791f08c2cb30c00a8bdb6"]},"offset":"235948"},"icon.svg":{"size":484,"integrity":{"algorithm":"SHA256","hash":"33813eb068900f9b5b54bb86a68cc32afa1d598bef448e40f4bddf2b613d750b","blockSize":4194304,"blocks":["33813eb068900f9b5b54bb86a68cc32afa1d598bef448e40f4bddf2b613d750b"]},"offset":"236278"},"manifest.json":{"size":492,"integrity":{"algorithm":"SHA256","hash":"d5c2955e8221cedf21b865b0ab6d1a9ab26a638753f3d82c70ed9e1ef3503ca2","blockSize":4194304,"blocks":["d5c2955e8221cedf21b865b0ab6d1a9ab26a638753f3d82c70ed9e1ef3503ca2"]},"offset":"236762"}}},"screenshot":{"files":{"icon.svg":{"size":389,"integrity":{"algorithm":"SHA256","hash":"bb476ac11eafff89526a94c375088742c57cb45eee053ec8a891d9ed52f5025b","blockSize":4194304,"blocks":["bb476ac11eafff89526a94c375088742c57cb45eee053ec8a891d9ed52f5025b"]},"offset":"237254"},"manifest.json":{"size":503,"integrity":{"algorithm":"SHA256","hash":"27b2ec0aa50f2460ada7683c6dcef5865d120ee8c52b4ac35937a0be90e72398","blockSize":4194304,"blocks":["27b2ec0aa50f2460ada7683c6dcef5865d120ee8c52b4ac35937a0be90e72398"]},"offset":"237643"},"popup.html":{"size":430,"integrity":{"algorithm":"SHA256","hash":"6e1437645f045745bfdef15e7a6d9fe0c160c4521207e0a1a8352f2dcba1eb61","blockSize":4194304,"blocks":["6e1437645f045745bfdef15e7a6d9fe0c160c4521207e0a1a8352f2dcba1eb61"]},"offset":"238146"},"popup.js":{"size":223,"integrity":{"algorithm":"SHA256","hash":"a691734e8b5d75445805b9c291ee33dca709a19a0d7fcd0785f7de0babaedf4f","blockSize":4194304,"blocks":["a691734e8b5d75445805b9c291ee33dca709a19a0d7fcd0785f7de0babaedf4f"]},"offset":"238576"}}},"dark-mode":{"files":{"content.js":{"size":412,"integrity":{"algorithm":"SHA256","hash":"d038093a2b6e1062d9ec0aa698cb0c530dd620daec70068dcba771e9b0e4bc67","blockSize":4194304,"blocks":["d038093a2b6e1062d9ec0aa698cb0c530dd620daec70068dcba771e9b0e4bc67"]},"offset":"238799"},"icon.svg":{"size":303,"integrity":{"algorithm":"SHA256","hash":"21c8b3b54de02355a1e4dd19cc765b23179a21abf292928b4a1cec71b9b744bc","blockSize":4194304,"blocks":["21c8b3b54de02355a1e4dd19cc765b23179a21abf292928b4a1cec71b9b744bc"]},"offset":"239211"},"manifest.json":{"size":491,"integrity":{"algorithm":"SHA256","hash":"16e0f94a406e380c122eed3bb6c4fdb2adaac023c70edacbaa08ed487d6c618b","blockSize":4194304,"blocks":["16e0f94a406e380c122eed3bb6c4fdb2adaac023c70edacbaa08ed487d6c618b"]},"offset":"239514"}}},"ad-blocker":{"files":{"icon.svg":{"size":270,"integrity":{"algorithm":"SHA256","hash":"950d49f9cad77026114fc83cb9c0cab58c8ce5fb3349ed2ca970bbf8b66c4ffc","blockSize":4194304,"blocks":["950d49f9cad77026114fc83cb9c0cab58c8ce5fb3349ed2ca970bbf8b66c4ffc"]},"offset":"240005"},"manifest.json":{"size":495,"integrity":{"algorithm":"SHA256","hash":"f56a2a749c26447cfd249d56a11fd1d48bb6586d9a970c4a8def2bdcdad56f94","blockSize":4194304,"blocks":["f56a2a749c26447cfd249d56a11fd1d48bb6586d9a970c4a8def2bdcdad56f94"]},"offset":"240275"},"rules.json":{"size":424,"integrity":{"algorithm":"SHA256","hash":"fc7479e82ae23aa4b2985378ec568c116c522a8abf016ece2d98861cdfbf3248","blockSize":4194304,"blocks":["fc7479e82ae23aa4b2985378ec568c116c522a8abf016ece2d98861cdfbf3248"]},"offset":"240770"}}}}},"dist":{"files":{"renderer":{"files":{"index.html":{"size":576,"integrity":{"algorithm":"SHA256","hash":"68db6286fac4cf3444c1515fd12d022633239a28b023dbad84feba9a24bd1078","blockSize":4194304,"blocks":["68db6286fac4cf3444c1515fd12d022633239a28b023dbad84feba9a24bd1078"]},"offset":"241194"},"assets":{"files":{"main-BrdiVs7r.js":{"size":207652,"integrity":{"algorithm":"SHA256","hash":"bbc6e326c3502b754a195b13c399805e74a5d2a7e26a466e55c86410611dc0b4","blockSize":4194304,"blocks":["bbc6e326c3502b754a195b13c399805e74a5d2a7e26a466e55c86410611dc0b4"]},"offset":"241770"},"main-CPnYvJoG.css":{"size":19891,"integrity":{"algorithm":"SHA256","hash":"2ae824475a96d8a5f2134856235d6017aca8dedd45372d54f9dac4d059006d45","blockSize":4194304,"blocks":["2ae824475a96d8a5f2134856235d6017aca8dedd45372d54f9dac4d059006d45"]},"offset":"449422"}}}}},"main":{"files":{"shared":{"files":{"constants.js":{"size":3645,"integrity":{"algorithm":"SHA256","hash":"dfb25d1e52ed64c95de1b79a39e3186a8ebba87aab9ce9fc83fa5a21349f7895","blockSize":4194304,"blocks":["dfb25d1e52ed64c95de1b79a39e3186a8ebba87aab9ce9fc83fa5a21349f7895"]},"offset":"469313"},"constants.js.map":{"size":2416,"integrity":{"algorithm":"SHA256","hash":"5c8b7959060987cc60f9bf2e3a94700f27782fc9399d6405857bfa7760adbc0a","blockSize":4194304,"blocks":["5c8b7959060987cc60f9bf2e3a94700f27782fc9399d6405857bfa7760adbc0a"]},"offset":"472958"},"types.js":{"size":110,"integrity":{"algorithm":"SHA256","hash":"b0d2bc4142d0c62d43f996aaeb64f22c4889ac853f8a3765758b505d972d0149","blockSize":4194304,"blocks":["b0d2bc4142d0c62d43f996aaeb64f22c4889ac853f8a3765758b505d972d0149"]},"offset":"475374"},"types.js.map":{"size":115,"integrity":{"algorithm":"SHA256","hash":"9cfca4af5d3f3210cabd58ccbfafcbd895e94605e1b3362028371d900ac024a8","blockSize":4194304,"blocks":["9cfca4af5d3f3210cabd58ccbfafcbd895e94605e1b3362028371d900ac024a8"]},"offset":"475484"}}},"preload":{"files":{"index.js":{"size":10376,"integrity":{"algorithm":"SHA256","hash":"a44fb06373c6fb00085dc85030c4647304a9f4b262d0b8969ede486bc48e5ff2","blockSize":4194304,"blocks":["a44fb06373c6fb00085dc85030c4647304a9f4b262d0b8969ede486bc48e5ff2"]},"offset":"475599"},"index.js.map":{"size":6665,"integrity":{"algorithm":"SHA256","hash":"dc9c26f5e03ca040f6b82361d4108991ef50c3c4b07c3db53138b575f5dddd70","blockSize":4194304,"blocks":["dc9c26f5e03ca040f6b82361d4108991ef50c3c4b07c3db53138b575f5dddd70"]},"offset":"485975"}}},"main":{"files":{"auth-window.js":{"size":3013,"integrity":{"algorithm":"SHA256","hash":"7f30e9548c41c3d00acb56a505f403a4108146079829804629b52a0cf9364d33","blockSize":4194304,"blocks":["7f30e9548c41c3d00acb56a505f403a4108146079829804629b52a0cf9364d33"]},"offset":"492640"},"auth-window.js.map":{"size":2042,"integrity":{"algorithm":"SHA256","hash":"7daf40d11b667115bda6982553c966cc2387124e3e31568fedcc5b327538d6c1","blockSize":4194304,"blocks":["7daf40d11b667115bda6982553c966cc2387124e3e31568fedcc5b327538d6c1"]},"offset":"495653"},"database.js":{"size":5017,"integrity":{"algorithm":"SHA256","hash":"fe359da3e63a6a2204b32f2c0467f4f759f5036674121fa8c6aae786f7555598","blockSize":4194304,"blocks":["fe359da3e63a6a2204b32f2c0467f4f759f5036674121fa8c6aae786f7555598"]},"offset":"497695"},"database.js.map":{"size":5001,"integrity":{"algorithm":"SHA256","hash":"4abbb8c98e62fe30c4c2284f1d3e204b6b75edabe512efb15f880fed10d5e820","blockSize":4194304,"blocks":["4abbb8c98e62fe30c4c2284f1d3e204b6b75edabe512efb15f880fed10d5e820"]},"offset":"502712"},"download-manager.js":{"size":2452,"integrity":{"algorithm":"SHA256","hash":"60391279a9593f9541521fd6b69196abee14c53093f413f5ce09203dbd0c910c","blockSize":4194304,"blocks":["60391279a9593f9541521fd6b69196abee14c53093f413f5ce09203dbd0c910c"]},"offset":"507713"},"download-manager.js.map":{"size":2283,"integrity":{"algorithm":"SHA256","hash":"f5e8c9db3a17db000afe1d9e6f747de12c05c5e75be8e25eb27f5e2348ccfeb6","blockSize":4194304,"blocks":["f5e8c9db3a17db000afe1d9e6f747de12c05c5e75be8e25eb27f5e2348ccfeb6"]},"offset":"510165"},"extension-manager.js":{"size":3761,"integrity":{"algorithm":"SHA256","hash":"cfaf6e8209b29ed756cd28f7b026d7a80dc11b1ece979b4efbaa5a0f58436cea","blockSize":4194304,"blocks":["cfaf6e8209b29ed756cd28f7b026d7a80dc11b1ece979b4efbaa5a0f58436cea"]},"offset":"512448"},"extension-manager.js.map":{"size":3240,"integrity":{"algorithm":"SHA256","hash":"51d8df9122cdfd7b16a0d3fac25b2662bad1f482094edb0ff4e4a8bddca25d35","blockSize":4194304,"blocks":["51d8df9122cdfd7b16a0d3fac25b2662bad1f482094edb0ff4e4a8bddca25d35"]},"offset":"516209"},"index.js":{"size":2829,"integrity":{"algorithm":"SHA256","hash":"3414cab23899524a54de3ae657416399a3bf061aca8d5d78f5c137f3618e7d89","blockSize":4194304,"blocks":["3414cab23899524a54de3ae657416399a3bf061aca8d5d78f5c137f3618e7d89"]},"offset":"519449"},"index.js.map":{"size":2547,"integrity":{"algorithm":"SHA256","hash":"bbfd84649cfd758211674c735194c65f23ee995984f277c56091f569ed807a55","blockSize":4194304,"blocks":["bbfd84649cfd758211674c735194c65f23ee995984f277c56091f569ed807a55"]},"offset":"522278"},"ipc-handlers.js":{"size":12587,"integrity":{"algorithm":"SHA256","hash":"a1818283d963d4346dfa5e76fe6ebdec1cc5e7ea3b5e688b5d6d292acf8563b1","blockSize":4194304,"blocks":["a1818283d963d4346dfa5e76fe6ebdec1cc5e7ea3b5e688b5d6d292acf8563b1"]},"offset":"524825"},"ipc-handlers.js.map":{"size":12654,"integrity":{"algorithm":"SHA256","hash":"45913437a2d6ecbca9914a95987c7af276b6b9801b50bdb615472ee89e7075c7","blockSize":4194304,"blocks":["45913437a2d6ecbca9914a95987c7af276b6b9801b50bdb615472ee89e7075c7"]},"offset":"537412"},"menu.js":{"size":5257,"integrity":{"algorithm":"SHA256","hash":"1a6ce303ca9a6e050a18d7727f9d09558b6f0ded80b4e03aa1b4be9db1503672","blockSize":4194304,"blocks":["1a6ce303ca9a6e050a18d7727f9d09558b6f0ded80b4e03aa1b4be9db1503672"]},"offset":"550066"},"menu.js.map":{"size":3634,"integrity":{"algorithm":"SHA256","hash":"39eb080bea1c8abb618be1f9a6e91fb062bae49fd7255c07e178ecd9ddd4b055","blockSize":4194304,"blocks":["39eb080bea1c8abb618be1f9a6e91fb062bae49fd7255c07e178ecd9ddd4b055"]},"offset":"555323"},"session-manager.js":{"size":2238,"integrity":{"algorithm":"SHA256","hash":"934af9d5ded043b85f6294c6cf8a85a8fd52685076914abcb8e6f2a1d1930c81","blockSize":4194304,"blocks":["934af9d5ded043b85f6294c6cf8a85a8fd52685076914abcb8e6f2a1d1930c81"]},"offset":"558957"},"session-manager.js.map":{"size":1775,"integrity":{"algorithm":"SHA256","hash":"8b415a6696e3cfc627f31591d775c9a73b9df686428d663d9d4afe88091b6f3e","blockSize":4194304,"blocks":["8b415a6696e3cfc627f31591d775c9a73b9df686428d663d9d4afe88091b6f3e"]},"offset":"561195"},"tab-manager.js":{"size":13185,"integrity":{"algorithm":"SHA256","hash":"7ccb5fafdd12a3ac167a114303fe7632bc9ddec5bb3433d742d41e3d101c4e0d","blockSize":4194304,"blocks":["7ccb5fafdd12a3ac167a114303fe7632bc9ddec5bb3433d742d41e3d101c4e0d"]},"offset":"562970"},"tab-manager.js.map":{"size":13192,"integrity":{"algorithm":"SHA256","hash":"e8259b6b6b2cb2521372e54d012efc4e9fc6f43f964a8c80f961964d7231b2bf","blockSize":4194304,"blocks":["e8259b6b6b2cb2521372e54d012efc4e9fc6f43f964a8c80f961964d7231b2bf"]},"offset":"576155"},"window-manager.js":{"size":4463,"integrity":{"algorithm":"SHA256","hash":"e8fdcc53c6b3ffc3c557acf3dcde39772f3564a0eb32dde9bea56ff5f88c970c","blockSize":4194304,"blocks":["e8fdcc53c6b3ffc3c557acf3dcde39772f3564a0eb32dde9bea56ff5f88c970c"]},"offset":"589347"},"window-manager.js.map":{"size":3654,"integrity":{"algorithm":"SHA256","hash":"a04efd6e05bdf4b8ba302221cdf3643ad2aacef1a4be8759ce9b6d50d3e89824","blockSize":4194304,"blocks":["a04efd6e05bdf4b8ba302221cdf3643ad2aacef1a4be8759ce9b6d50d3e89824"]},"offset":"593810"}}}}}}},"node_modules":{"files":{"@remix-run":{"files":{"router":{"files":{"LICENSE.md":{"size":1161,"integrity":{"algorithm":"SHA256","hash":"77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49","blockSize":4194304,"blocks":["77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49"]},"offset":"597464"},"history.ts":{"size":21635,"integrity":{"algorithm":"SHA256","hash":"277b18702ca035ce47cb31a188baa86d22310d51e2bcd0ab5dc045e8d1b57bab","blockSize":4194304,"blocks":["277b18702ca035ce47cb31a188baa86d22310d51e2bcd0ab5dc045e8d1b57bab"]},"offset":"598625"},"index.ts":{"size":2454,"integrity":{"algorithm":"SHA256","hash":"5c1cecacc18ea052f2241e1a53bf898d9ef44c82faed4d80daee83d0119e91ab","blockSize":4194304,"blocks":["5c1cecacc18ea052f2241e1a53bf898d9ef44c82faed4d80daee83d0119e91ab"]},"offset":"620260"},"package.json":{"size":638,"integrity":{"algorithm":"SHA256","hash":"b4ed6b6c120781299c55adb1c4af4f388a0cc1f9b16ed4062eb0f03f8caee583","blockSize":4194304,"blocks":["b4ed6b6c120781299c55adb1c4af4f388a0cc1f9b16ed4062eb0f03f8caee583"]},"offset":"622714"},"router.ts":{"size":185290,"integrity":{"algorithm":"SHA256","hash":"35434892c773caacfe5a111c8903423618567ae71a8808a294f105a326b05f07","blockSize":4194304,"blocks":["35434892c773caacfe5a111c8903423618567ae71a8808a294f105a326b05f07"]},"offset":"623352"},"utils.ts":{"size":49305,"integrity":{"algorithm":"SHA256","hash":"b6288e98939232da43492540606450a80ca1bc773e3d6a04d807e3c9359661f8","blockSize":4194304,"blocks":["b6288e98939232da43492540606450a80ca1bc773e3d6a04d807e3c9359661f8"]},"offset":"808642"},"dist":{"files":{"router.cjs.js":{"size":208121,"integrity":{"algorithm":"SHA256","hash":"d005b6a787a24216fb84257d1dd91572a06e596680e370395775e9b94b7295bd","blockSize":4194304,"blocks":["d005b6a787a24216fb84257d1dd91572a06e596680e370395775e9b94b7295bd"]},"offset":"857947"},"router.cjs.js.map":{"size":452090,"integrity":{"algorithm":"SHA256","hash":"5a0318ee10578ff2a70e71f92d5594b2381f0ff46d0f040fb779c54a631cf464","blockSize":4194304,"blocks":["5a0318ee10578ff2a70e71f92d5594b2381f0ff46d0f040fb779c54a631cf464"]},"offset":"1066068"},"router.js":{"size":198208,"integrity":{"algorithm":"SHA256","hash":"b99ec1f525cbbdc424746b09746a1030e3810e00011d1997f8376fddf31ced14","blockSize":4194304,"blocks":["b99ec1f525cbbdc424746b09746a1030e3810e00011d1997f8376fddf31ced14"]},"offset":"1518158"},"router.js.map":{"size":449400,"integrity":{"algorithm":"SHA256","hash":"66bf9fc5fe0d212f375b0fb55718b2e85e26c9a7fa5db70047682c952f4532c1","blockSize":4194304,"blocks":["66bf9fc5fe0d212f375b0fb55718b2e85e26c9a7fa5db70047682c952f4532c1"]},"offset":"1716366"},"router.umd.js":{"size":219190,"integrity":{"algorithm":"SHA256","hash":"ac1e501f330c5629dc64e449dfeb56a6d215a948f1a365d33716463075e72c22","blockSize":4194304,"blocks":["ac1e501f330c5629dc64e449dfeb56a6d215a948f1a365d33716463075e72c22"]},"offset":"2165766"},"router.umd.js.map":{"size":452100,"integrity":{"algorithm":"SHA256","hash":"0c03b9c963fe69f49d66e6b5a1eecb782e758d4ee35ee55b12de6be9a6d4835c","blockSize":4194304,"blocks":["0c03b9c963fe69f49d66e6b5a1eecb782e758d4ee35ee55b12de6be9a6d4835c"]},"offset":"2384956"},"router.umd.min.js":{"size":59190,"integrity":{"algorithm":"SHA256","hash":"89e7bfb10f2a28422a47e3927adab76a95c27875fc99ced8c83e316e04127178","blockSize":4194304,"blocks":["89e7bfb10f2a28422a47e3927adab76a95c27875fc99ced8c83e316e04127178"]},"offset":"2837056"},"router.umd.min.js.map":{"size":354706,"integrity":{"algorithm":"SHA256","hash":"3cfee02fa6588cb99e1431604a8c3a8364014cbf3882078ae944c7a8066daf80","blockSize":4194304,"blocks":["3cfee02fa6588cb99e1431604a8c3a8364014cbf3882078ae944c7a8066daf80"]},"offset":"2896246"}}}}}}},"ajv-formats":{"files":{"LICENSE":{"size":1074,"integrity":{"algorithm":"SHA256","hash":"9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf","blockSize":4194304,"blocks":["9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf"]},"offset":"3250952"},"package.json":{"size":1307,"integrity":{"algorithm":"SHA256","hash":"ca76c549d158d201b424ecf63eb28474173da2d8cb8c8266ba06a2ee19f9d669","blockSize":4194304,"blocks":["ca76c549d158d201b424ecf63eb28474173da2d8cb8c8266ba06a2ee19f9d669"]},"offset":"3252026"},"src":{"files":{"formats.ts":{"size":11476,"integrity":{"algorithm":"SHA256","hash":"01c1c1aa3feec9f4555e46609aade1763bf1d95083ae752b7d0b3dfe7f19d8d7","blockSize":4194304,"blocks":["01c1c1aa3feec9f4555e46609aade1763bf1d95083ae752b7d0b3dfe7f19d8d7"]},"offset":"3253333"},"index.ts":{"size":1793,"integrity":{"algorithm":"SHA256","hash":"fb330a47ec7d2c8498d03078834603dab1a0689f40ca15875e6d57d740c5ff71","blockSize":4194304,"blocks":["fb330a47ec7d2c8498d03078834603dab1a0689f40ca15875e6d57d740c5ff71"]},"offset":"3264809"},"limit.ts":{"size":3074,"integrity":{"algorithm":"SHA256","hash":"62402e4fcb3bd9a0f4a22d2b228f1371897d47982e67ecd62950fdadb46261e6","blockSize":4194304,"blocks":["62402e4fcb3bd9a0f4a22d2b228f1371897d47982e67ecd62950fdadb46261e6"]},"offset":"3266602"}}},"dist":{"files":{"formats.js":{"size":10870,"integrity":{"algorithm":"SHA256","hash":"0970043fe6605b30a696562ff8f1ff621eff5f1250f961a92668db8ad9d0cf8c","blockSize":4194304,"blocks":["0970043fe6605b30a696562ff8f1ff621eff5f1250f961a92668db8ad9d0cf8c"]},"offset":"3269676"},"formats.js.map":{"size":5586,"integrity":{"algorithm":"SHA256","hash":"166778cb8feec069034babf6e20700d9c92220d04d70b9d2f90cce95de7fae24","blockSize":4194304,"blocks":["166778cb8feec069034babf6e20700d9c92220d04d70b9d2f90cce95de7fae24"]},"offset":"3280546"},"index.js":{"size":1498,"integrity":{"algorithm":"SHA256","hash":"25ae29038da0fd1021a623de0db504f2eff2d2e1fed832f3a41b795833182dde","blockSize":4194304,"blocks":["25ae29038da0fd1021a623de0db504f2eff2d2e1fed832f3a41b795833182dde"]},"offset":"3286132"},"index.js.map":{"size":1524,"integrity":{"algorithm":"SHA256","hash":"aaec578d5a2af589e3d726a6383198fa7b116b4e6c41900f4e5fb285bc9f6a67","blockSize":4194304,"blocks":["aaec578d5a2af589e3d726a6383198fa7b116b4e6c41900f4e5fb285bc9f6a67"]},"offset":"3287630"},"limit.js":{"size":2850,"integrity":{"algorithm":"SHA256","hash":"8ed43a480952d8aa1afa2da3c41450cadf9a39995be7c4e0e54cd75a9c373944","blockSize":4194304,"blocks":["8ed43a480952d8aa1afa2da3c41450cadf9a39995be7c4e0e54cd75a9c373944"]},"offset":"3289154"},"limit.js.map":{"size":2818,"integrity":{"algorithm":"SHA256","hash":"80835360b0867a81d4761783a4aec70825d658474e57dbd2a740c05d7b607bba","blockSize":4194304,"blocks":["80835360b0867a81d4761783a4aec70825d658474e57dbd2a740c05d7b607bba"]},"offset":"3292004"}}},"node_modules":{"files":{"ajv":{"files":{".runkit_example.js":{"size":496,"integrity":{"algorithm":"SHA256","hash":"e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf","blockSize":4194304,"blocks":["e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf"]},"offset":"10385765"},"LICENSE":{"size":1090,"integrity":{"algorithm":"SHA256","hash":"a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3","blockSize":4194304,"blocks":["a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]},"offset":"10386261"},"package.json":{"size":2245,"integrity":{"algorithm":"SHA256","hash":"c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84","blockSize":4194304,"blocks":["c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84"]},"offset":"10387351"},"lib":{"files":{"2019.ts":{"size":2502,"integrity":{"algorithm":"SHA256","hash":"d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc","blockSize":4194304,"blocks":["d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc"]},"offset":"10389596"},"2020.ts":{"size":2217,"integrity":{"algorithm":"SHA256","hash":"0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603","blockSize":4194304,"blocks":["0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603"]},"offset":"10392098"},"ajv.ts":{"size":2229,"integrity":{"algorithm":"SHA256","hash":"db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85","blockSize":4194304,"blocks":["db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85"]},"offset":"10394315"},"core.ts":{"size":30790,"integrity":{"algorithm":"SHA256","hash":"c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d","blockSize":4194304,"blocks":["c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d"]},"offset":"10396544"},"jtd.ts":{"size":4172,"integrity":{"algorithm":"SHA256","hash":"e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262","blockSize":4194304,"blocks":["e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262"]},"offset":"10427334"},"vocabularies":{"files":{"code.ts":{"size":5247,"integrity":{"algorithm":"SHA256","hash":"f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7","blockSize":4194304,"blocks":["f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7"]},"offset":"10431506"},"draft2020.ts":{"size":698,"integrity":{"algorithm":"SHA256","hash":"840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea","blockSize":4194304,"blocks":["840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea"]},"offset":"10436753"},"draft7.ts":{"size":496,"integrity":{"algorithm":"SHA256","hash":"9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4","blockSize":4194304,"blocks":["9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4"]},"offset":"10437451"},"errors.ts":{"size":731,"integrity":{"algorithm":"SHA256","hash":"ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b","blockSize":4194304,"blocks":["ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b"]},"offset":"10437947"},"metadata.ts":{"size":304,"integrity":{"algorithm":"SHA256","hash":"a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1","blockSize":4194304,"blocks":["a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1"]},"offset":"10438678"},"next.ts":{"size":320,"integrity":{"algorithm":"SHA256","hash":"b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443","blockSize":4194304,"blocks":["b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443"]},"offset":"10438982"},"validation":{"files":{"const.ts":{"size":863,"integrity":{"algorithm":"SHA256","hash":"9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5","blockSize":4194304,"blocks":["9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5"]},"offset":"10439302"},"dependentRequired.ts":{"size":510,"integrity":{"algorithm":"SHA256","hash":"082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b","blockSize":4194304,"blocks":["082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b"]},"offset":"10440165"},"enum.ts":{"size":1837,"integrity":{"algorithm":"SHA256","hash":"f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911","blockSize":4194304,"blocks":["f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911"]},"offset":"10440675"},"index.ts":{"size":1271,"integrity":{"algorithm":"SHA256","hash":"72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c","blockSize":4194304,"blocks":["72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c"]},"offset":"10442512"},"limitContains.ts":{"size":485,"integrity":{"algorithm":"SHA256","hash":"3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5","blockSize":4194304,"blocks":["3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5"]},"offset":"10443783"},"limitItems.ts":{"size":812,"integrity":{"algorithm":"SHA256","hash":"32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176","blockSize":4194304,"blocks":["32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176"]},"offset":"10444268"},"limitLength.ts":{"size":1025,"integrity":{"algorithm":"SHA256","hash":"72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de","blockSize":4194304,"blocks":["72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de"]},"offset":"10445080"},"limitNumber.ts":{"size":1350,"integrity":{"algorithm":"SHA256","hash":"61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298","blockSize":4194304,"blocks":["61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298"]},"offset":"10446105"},"limitProperties.ts":{"size":851,"integrity":{"algorithm":"SHA256","hash":"d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048","blockSize":4194304,"blocks":["d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048"]},"offset":"10447455"},"multipleOf.ts":{"size":1072,"integrity":{"algorithm":"SHA256","hash":"5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c","blockSize":4194304,"blocks":["5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c"]},"offset":"10448306"},"pattern.ts":{"size":1299,"integrity":{"algorithm":"SHA256","hash":"7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829","blockSize":4194304,"blocks":["7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829"]},"offset":"10449378"},"required.ts":{"size":2961,"integrity":{"algorithm":"SHA256","hash":"73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa","blockSize":4194304,"blocks":["73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa"]},"offset":"10450677"},"uniqueItems.ts":{"size":2690,"integrity":{"algorithm":"SHA256","hash":"9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0","blockSize":4194304,"blocks":["9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0"]},"offset":"10453638"}}},"unevaluated":{"files":{"index.ts":{"size":257,"integrity":{"algorithm":"SHA256","hash":"0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40","blockSize":4194304,"blocks":["0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40"]},"offset":"10456328"},"unevaluatedItems.ts":{"size":1524,"integrity":{"algorithm":"SHA256","hash":"c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2","blockSize":4194304,"blocks":["c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2"]},"offset":"10456585"},"unevaluatedProperties.ts":{"size":2440,"integrity":{"algorithm":"SHA256","hash":"7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de","blockSize":4194304,"blocks":["7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de"]},"offset":"10458109"}}},"jtd":{"files":{"discriminator.ts":{"size":2656,"integrity":{"algorithm":"SHA256","hash":"9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d","blockSize":4194304,"blocks":["9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d"]},"offset":"10460549"},"elements.ts":{"size":976,"integrity":{"algorithm":"SHA256","hash":"54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33","blockSize":4194304,"blocks":["54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33"]},"offset":"10463205"},"enum.ts":{"size":1627,"integrity":{"algorithm":"SHA256","hash":"a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd","blockSize":4194304,"blocks":["a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd"]},"offset":"10464181"},"error.ts":{"size":746,"integrity":{"algorithm":"SHA256","hash":"e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5","blockSize":4194304,"blocks":["e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5"]},"offset":"10465808"},"index.ts":{"size":1007,"integrity":{"algorithm":"SHA256","hash":"4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a","blockSize":4194304,"blocks":["4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a"]},"offset":"10466554"},"metadata.ts":{"size":716,"integrity":{"algorithm":"SHA256","hash":"558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01","blockSize":4194304,"blocks":["558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01"]},"offset":"10467561"},"nullable.ts":{"size":649,"integrity":{"algorithm":"SHA256","hash":"75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8","blockSize":4194304,"blocks":["75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8"]},"offset":"10468277"},"optionalProperties.ts":{"size":394,"integrity":{"algorithm":"SHA256","hash":"03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77","blockSize":4194304,"blocks":["03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77"]},"offset":"10468926"},"properties.ts":{"size":6244,"integrity":{"algorithm":"SHA256","hash":"930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5","blockSize":4194304,"blocks":["930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5"]},"offset":"10469320"},"ref.ts":{"size":2346,"integrity":{"algorithm":"SHA256","hash":"f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d","blockSize":4194304,"blocks":["f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d"]},"offset":"10475564"},"type.ts":{"size":2547,"integrity":{"algorithm":"SHA256","hash":"0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45","blockSize":4194304,"blocks":["0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45"]},"offset":"10477910"},"union.ts":{"size":292,"integrity":{"algorithm":"SHA256","hash":"1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536","blockSize":4194304,"blocks":["1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536"]},"offset":"10480457"},"values.ts":{"size":1681,"integrity":{"algorithm":"SHA256","hash":"86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd","blockSize":4194304,"blocks":["86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd"]},"offset":"10480749"}}},"format":{"files":{"format.ts":{"size":3987,"integrity":{"algorithm":"SHA256","hash":"5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148","blockSize":4194304,"blocks":["5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148"]},"offset":"10482430"},"index.ts":{"size":148,"integrity":{"algorithm":"SHA256","hash":"804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a","blockSize":4194304,"blocks":["804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a"]},"offset":"10486417"}}},"dynamic":{"files":{"dynamicAnchor.ts":{"size":1122,"integrity":{"algorithm":"SHA256","hash":"bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f","blockSize":4194304,"blocks":["bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f"]},"offset":"10486565"},"dynamicRef.ts":{"size":1797,"integrity":{"algorithm":"SHA256","hash":"92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d","blockSize":4194304,"blocks":["92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d"]},"offset":"10487687"},"index.ts":{"size":328,"integrity":{"algorithm":"SHA256","hash":"c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b","blockSize":4194304,"blocks":["c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b"]},"offset":"10489484"},"recursiveAnchor.ts":{"size":401,"integrity":{"algorithm":"SHA256","hash":"7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a","blockSize":4194304,"blocks":["7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a"]},"offset":"10489812"},"recursiveRef.ts":{"size":253,"integrity":{"algorithm":"SHA256","hash":"6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3","blockSize":4194304,"blocks":["6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3"]},"offset":"10490213"}}},"discriminator":{"files":{"index.ts":{"size":4304,"integrity":{"algorithm":"SHA256","hash":"9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3","blockSize":4194304,"blocks":["9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3"]},"offset":"10490466"},"types.ts":{"size":251,"integrity":{"algorithm":"SHA256","hash":"537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da","blockSize":4194304,"blocks":["537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da"]},"offset":"10494770"}}},"core":{"files":{"id.ts":{"size":224,"integrity":{"algorithm":"SHA256","hash":"241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1","blockSize":4194304,"blocks":["241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1"]},"offset":"10495021"},"index.ts":{"size":274,"integrity":{"algorithm":"SHA256","hash":"43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62","blockSize":4194304,"blocks":["43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62"]},"offset":"10495245"},"ref.ts":{"size":4384,"integrity":{"algorithm":"SHA256","hash":"0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8","blockSize":4194304,"blocks":["0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8"]},"offset":"10495519"}}},"applicator":{"files":{"additionalItems.ts":{"size":1824,"integrity":{"algorithm":"SHA256","hash":"0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a","blockSize":4194304,"blocks":["0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a"]},"offset":"10499903"},"additionalProperties.ts":{"size":3782,"integrity":{"algorithm":"SHA256","hash":"1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55","blockSize":4194304,"blocks":["1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55"]},"offset":"10501727"},"allOf.ts":{"size":717,"integrity":{"algorithm":"SHA256","hash":"cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa","blockSize":4194304,"blocks":["cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa"]},"offset":"10505509"},"anyOf.ts":{"size":380,"integrity":{"algorithm":"SHA256","hash":"2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594","blockSize":4194304,"blocks":["2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594"]},"offset":"10506226"},"contains.ts":{"size":3278,"integrity":{"algorithm":"SHA256","hash":"731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05","blockSize":4194304,"blocks":["731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05"]},"offset":"10506606"},"dependencies.ts":{"size":3391,"integrity":{"algorithm":"SHA256","hash":"d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65","blockSize":4194304,"blocks":["d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65"]},"offset":"10509884"},"dependentSchemas.ts":{"size":280,"integrity":{"algorithm":"SHA256","hash":"ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc","blockSize":4194304,"blocks":["ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc"]},"offset":"10513275"},"if.ts":{"size":2395,"integrity":{"algorithm":"SHA256","hash":"676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f","blockSize":4194304,"blocks":["676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f"]},"offset":"10513555"},"index.ts":{"size":1592,"integrity":{"algorithm":"SHA256","hash":"85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6","blockSize":4194304,"blocks":["85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6"]},"offset":"10515950"},"items.ts":{"size":1892,"integrity":{"algorithm":"SHA256","hash":"9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3","blockSize":4194304,"blocks":["9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3"]},"offset":"10517542"},"items2020.ts":{"size":1053,"integrity":{"algorithm":"SHA256","hash":"939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668","blockSize":4194304,"blocks":["939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668"]},"offset":"10519434"},"not.ts":{"size":859,"integrity":{"algorithm":"SHA256","hash":"a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971","blockSize":4194304,"blocks":["a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971"]},"offset":"10520487"},"oneOf.ts":{"size":2197,"integrity":{"algorithm":"SHA256","hash":"ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0","blockSize":4194304,"blocks":["ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0"]},"offset":"10521346"},"patternProperties.ts":{"size":2870,"integrity":{"algorithm":"SHA256","hash":"80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75","blockSize":4194304,"blocks":["80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75"]},"offset":"10523543"},"prefixItems.ts":{"size":292,"integrity":{"algorithm":"SHA256","hash":"ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b","blockSize":4194304,"blocks":["ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b"]},"offset":"10526413"},"properties.ts":{"size":1845,"integrity":{"algorithm":"SHA256","hash":"76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1","blockSize":4194304,"blocks":["76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1"]},"offset":"10526705"},"propertyNames.ts":{"size":1247,"integrity":{"algorithm":"SHA256","hash":"ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f","blockSize":4194304,"blocks":["ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f"]},"offset":"10528550"},"thenElse.ts":{"size":441,"integrity":{"algorithm":"SHA256","hash":"29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4","blockSize":4194304,"blocks":["29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4"]},"offset":"10529797"}}}}},"types":{"files":{"index.ts":{"size":7289,"integrity":{"algorithm":"SHA256","hash":"3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8","blockSize":4194304,"blocks":["3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8"]},"offset":"10530238"},"json-schema.ts":{"size":6380,"integrity":{"algorithm":"SHA256","hash":"4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8","blockSize":4194304,"blocks":["4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8"]},"offset":"10537527"},"jtd-schema.ts":{"size":9321,"integrity":{"algorithm":"SHA256","hash":"1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42","blockSize":4194304,"blocks":["1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42"]},"offset":"10543907"}}},"standalone":{"files":{"index.ts":{"size":4151,"integrity":{"algorithm":"SHA256","hash":"3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed","blockSize":4194304,"blocks":["3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed"]},"offset":"10553228"},"instance.ts":{"size":1272,"integrity":{"algorithm":"SHA256","hash":"9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82","blockSize":4194304,"blocks":["9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82"]},"offset":"10557379"}}},"runtime":{"files":{"equal.ts":{"size":236,"integrity":{"algorithm":"SHA256","hash":"013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10","blockSize":4194304,"blocks":["013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10"]},"offset":"10558651"},"parseJson.ts":{"size":4553,"integrity":{"algorithm":"SHA256","hash":"79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5","blockSize":4194304,"blocks":["79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5"]},"offset":"10558887"},"quote.ts":{"size":802,"integrity":{"algorithm":"SHA256","hash":"b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3","blockSize":4194304,"blocks":["b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3"]},"offset":"10563440"},"re2.ts":{"size":157,"integrity":{"algorithm":"SHA256","hash":"10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7","blockSize":4194304,"blocks":["10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7"]},"offset":"10564242"},"timestamp.ts":{"size":1492,"integrity":{"algorithm":"SHA256","hash":"08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4","blockSize":4194304,"blocks":["08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4"]},"offset":"10564399"},"ucs2length.ts":{"size":629,"integrity":{"algorithm":"SHA256","hash":"a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6","blockSize":4194304,"blocks":["a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6"]},"offset":"10565891"},"uri.ts":{"size":162,"integrity":{"algorithm":"SHA256","hash":"4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb","blockSize":4194304,"blocks":["4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb"]},"offset":"10566520"},"validation_error.ts":{"size":336,"integrity":{"algorithm":"SHA256","hash":"abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64","blockSize":4194304,"blocks":["abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64"]},"offset":"10566682"}}},"refs":{"files":{"data.json":{"size":409,"integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]},"offset":"10567018"},"json-schema-draft-06.json":{"size":3449,"integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]},"offset":"10567427"},"json-schema-draft-07.json":{"size":3811,"integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]},"offset":"10570876"},"json-schema-secure.json":{"size":2521,"integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]},"offset":"10574687"},"jtd-schema.ts":{"size":2586,"integrity":{"algorithm":"SHA256","hash":"76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003","blockSize":4194304,"blocks":["76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003"]},"offset":"10577208"},"json-schema-2020-12":{"files":{"index.ts":{"size":982,"integrity":{"algorithm":"SHA256","hash":"9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000","blockSize":4194304,"blocks":["9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000"]},"offset":"10579794"},"schema.json":{"size":2166,"integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]},"offset":"10580776"},"meta":{"files":{"applicator.json":{"size":1441,"integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]},"offset":"10582942"},"content.json":{"size":479,"integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]},"offset":"10584383"},"core.json":{"size":1344,"integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]},"offset":"10584862"},"format-annotation.json":{"size":420,"integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]},"offset":"10586206"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]},"offset":"10586626"},"unevaluated.json":{"size":472,"integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]},"offset":"10587384"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]},"offset":"10587856"}}}}},"json-schema-2019-09":{"files":{"index.ts":{"size":899,"integrity":{"algorithm":"SHA256","hash":"b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d","blockSize":4194304,"blocks":["b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d"]},"offset":"10590120"},"schema.json":{"size":1579,"integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]},"offset":"10591019"},"meta":{"files":{"applicator.json":{"size":1566,"integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]},"offset":"10592598"},"content.json":{"size":477,"integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]},"offset":"10594164"},"core.json":{"size":1273,"integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]},"offset":"10594641"},"format.json":{"size":375,"integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]},"offset":"10595914"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]},"offset":"10596289"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]},"offset":"10597047"}}}}}}},"compile":{"files":{"errors.ts":{"size":5269,"integrity":{"algorithm":"SHA256","hash":"088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480","blockSize":4194304,"blocks":["088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480"]},"offset":"10599311"},"index.ts":{"size":12299,"integrity":{"algorithm":"SHA256","hash":"fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869","blockSize":4194304,"blocks":["fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869"]},"offset":"10604580"},"names.ts":{"size":1116,"integrity":{"algorithm":"SHA256","hash":"7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64","blockSize":4194304,"blocks":["7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64"]},"offset":"10616879"},"ref_error.ts":{"size":513,"integrity":{"algorithm":"SHA256","hash":"1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac","blockSize":4194304,"blocks":["1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac"]},"offset":"10617995"},"resolve.ts":{"size":4674,"integrity":{"algorithm":"SHA256","hash":"83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5","blockSize":4194304,"blocks":["83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5"]},"offset":"10618508"},"rules.ts":{"size":1456,"integrity":{"algorithm":"SHA256","hash":"d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85","blockSize":4194304,"blocks":["d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85"]},"offset":"10623182"},"util.ts":{"size":6639,"integrity":{"algorithm":"SHA256","hash":"2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad","blockSize":4194304,"blocks":["2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad"]},"offset":"10624638"},"validate":{"files":{"applicability.ts":{"size":739,"integrity":{"algorithm":"SHA256","hash":"22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497","blockSize":4194304,"blocks":["22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497"]},"offset":"10631277"},"boolSchema.ts":{"size":1298,"integrity":{"algorithm":"SHA256","hash":"e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf","blockSize":4194304,"blocks":["e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf"]},"offset":"10632016"},"dataType.ts":{"size":7094,"integrity":{"algorithm":"SHA256","hash":"37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3","blockSize":4194304,"blocks":["37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3"]},"offset":"10633314"},"defaults.ts":{"size":1215,"integrity":{"algorithm":"SHA256","hash":"8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27","blockSize":4194304,"blocks":["8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27"]},"offset":"10640408"},"index.ts":{"size":19445,"integrity":{"algorithm":"SHA256","hash":"841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48","blockSize":4194304,"blocks":["841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48"]},"offset":"10641623"},"keyword.ts":{"size":5337,"integrity":{"algorithm":"SHA256","hash":"83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f","blockSize":4194304,"blocks":["83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f"]},"offset":"10661068"},"subschema.ts":{"size":4366,"integrity":{"algorithm":"SHA256","hash":"79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e","blockSize":4194304,"blocks":["79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e"]},"offset":"10666405"}}},"jtd":{"files":{"parse.ts":{"size":12345,"integrity":{"algorithm":"SHA256","hash":"3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6","blockSize":4194304,"blocks":["3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6"]},"offset":"10670771"},"serialize.ts":{"size":8573,"integrity":{"algorithm":"SHA256","hash":"f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7","blockSize":4194304,"blocks":["f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7"]},"offset":"10683116"},"types.ts":{"size":311,"integrity":{"algorithm":"SHA256","hash":"4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822","blockSize":4194304,"blocks":["4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822"]},"offset":"10691689"}}},"codegen":{"files":{"code.ts":{"size":4474,"integrity":{"algorithm":"SHA256","hash":"3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85","blockSize":4194304,"blocks":["3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85"]},"offset":"10692000"},"index.ts":{"size":23051,"integrity":{"algorithm":"SHA256","hash":"5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6","blockSize":4194304,"blocks":["5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6"]},"offset":"10696474"},"scope.ts":{"size":5981,"integrity":{"algorithm":"SHA256","hash":"a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16","blockSize":4194304,"blocks":["a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16"]},"offset":"10719525"}}}}}}},"dist":{"files":{"2019.js":{"size":3188,"integrity":{"algorithm":"SHA256","hash":"4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4","blockSize":4194304,"blocks":["4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4"]},"offset":"10725506"},"2019.js.map":{"size":1639,"integrity":{"algorithm":"SHA256","hash":"a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f","blockSize":4194304,"blocks":["a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f"]},"offset":"10728694"},"2020.js":{"size":2894,"integrity":{"algorithm":"SHA256","hash":"908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a","blockSize":4194304,"blocks":["908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a"]},"offset":"10730333"},"2020.js.map":{"size":1473,"integrity":{"algorithm":"SHA256","hash":"845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5","blockSize":4194304,"blocks":["845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5"]},"offset":"10733227"},"ajv.js":{"size":2841,"integrity":{"algorithm":"SHA256","hash":"edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297","blockSize":4194304,"blocks":["edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297"]},"offset":"10734700"},"ajv.js.map":{"size":1476,"integrity":{"algorithm":"SHA256","hash":"f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44","blockSize":4194304,"blocks":["f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44"]},"offset":"10737541"},"core.js":{"size":25202,"integrity":{"algorithm":"SHA256","hash":"51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603","blockSize":4194304,"blocks":["51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603"]},"offset":"10739017"},"core.js.map":{"size":21608,"integrity":{"algorithm":"SHA256","hash":"0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472","blockSize":4194304,"blocks":["0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472"]},"offset":"10764219"},"jtd.js":{"size":3360,"integrity":{"algorithm":"SHA256","hash":"9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44","blockSize":4194304,"blocks":["9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44"]},"offset":"10785827"},"jtd.js.map":{"size":2036,"integrity":{"algorithm":"SHA256","hash":"b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51","blockSize":4194304,"blocks":["b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51"]},"offset":"10789187"},"vocabularies":{"files":{"code.js":{"size":6216,"integrity":{"algorithm":"SHA256","hash":"9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63","blockSize":4194304,"blocks":["9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63"]},"offset":"10791223"},"code.js.map":{"size":6030,"integrity":{"algorithm":"SHA256","hash":"1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534","blockSize":4194304,"blocks":["1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534"]},"offset":"10797439"},"draft2020.js":{"size":762,"integrity":{"algorithm":"SHA256","hash":"2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445","blockSize":4194304,"blocks":["2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445"]},"offset":"10803469"},"draft2020.js.map":{"size":419,"integrity":{"algorithm":"SHA256","hash":"a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891","blockSize":4194304,"blocks":["a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891"]},"offset":"10804231"},"draft7.js":{"size":557,"integrity":{"algorithm":"SHA256","hash":"8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170","blockSize":4194304,"blocks":["8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170"]},"offset":"10804650"},"draft7.js.map":{"size":328,"integrity":{"algorithm":"SHA256","hash":"e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62","blockSize":4194304,"blocks":["e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62"]},"offset":"10805207"},"errors.js":{"size":111,"integrity":{"algorithm":"SHA256","hash":"7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc","blockSize":4194304,"blocks":["7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc"]},"offset":"10805535"},"errors.js.map":{"size":120,"integrity":{"algorithm":"SHA256","hash":"d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675","blockSize":4194304,"blocks":["d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675"]},"offset":"10805646"},"metadata.js":{"size":427,"integrity":{"algorithm":"SHA256","hash":"45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609","blockSize":4194304,"blocks":["45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609"]},"offset":"10805766"},"metadata.js.map":{"size":299,"integrity":{"algorithm":"SHA256","hash":"7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd","blockSize":4194304,"blocks":["7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd"]},"offset":"10806193"},"next.js":{"size":433,"integrity":{"algorithm":"SHA256","hash":"491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7","blockSize":4194304,"blocks":["491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7"]},"offset":"10806492"},"next.js.map":{"size":243,"integrity":{"algorithm":"SHA256","hash":"79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918","blockSize":4194304,"blocks":["79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918"]},"offset":"10806925"},"validation":{"files":{"const.js":{"size":852,"integrity":{"algorithm":"SHA256","hash":"ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a","blockSize":4194304,"blocks":["ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a"]},"offset":"10807168"},"const.js.map":{"size":819,"integrity":{"algorithm":"SHA256","hash":"5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea","blockSize":4194304,"blocks":["5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea"]},"offset":"10808020"},"dependentRequired.js":{"size":403,"integrity":{"algorithm":"SHA256","hash":"cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa","blockSize":4194304,"blocks":["cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa"]},"offset":"10808839"},"dependentRequired.js.map":{"size":376,"integrity":{"algorithm":"SHA256","hash":"62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4","blockSize":4194304,"blocks":["62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4"]},"offset":"10809242"},"enum.js":{"size":1901,"integrity":{"algorithm":"SHA256","hash":"61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22","blockSize":4194304,"blocks":["61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22"]},"offset":"10809618"},"enum.js.map":{"size":1999,"integrity":{"algorithm":"SHA256","hash":"3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b","blockSize":4194304,"blocks":["3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b"]},"offset":"10811519"},"index.js":{"size":1036,"integrity":{"algorithm":"SHA256","hash":"4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4","blockSize":4194304,"blocks":["4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4"]},"offset":"10813518"},"index.js.map":{"size":595,"integrity":{"algorithm":"SHA256","hash":"42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4","blockSize":4194304,"blocks":["42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4"]},"offset":"10814554"},"limitContains.js":{"size":495,"integrity":{"algorithm":"SHA256","hash":"0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d","blockSize":4194304,"blocks":["0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d"]},"offset":"10815149"},"limitContains.js.map":{"size":473,"integrity":{"algorithm":"SHA256","hash":"56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445","blockSize":4194304,"blocks":["56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445"]},"offset":"10815644"},"limitItems.js":{"size":852,"integrity":{"algorithm":"SHA256","hash":"49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec","blockSize":4194304,"blocks":["49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec"]},"offset":"10816117"},"limitItems.js.map":{"size":905,"integrity":{"algorithm":"SHA256","hash":"4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459","blockSize":4194304,"blocks":["4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459"]},"offset":"10816969"},"limitLength.js":{"size":1130,"integrity":{"algorithm":"SHA256","hash":"379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2","blockSize":4194304,"blocks":["379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2"]},"offset":"10817874"},"limitLength.js.map":{"size":1145,"integrity":{"algorithm":"SHA256","hash":"bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5","blockSize":4194304,"blocks":["bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5"]},"offset":"10819004"},"limitNumber.js":{"size":1036,"integrity":{"algorithm":"SHA256","hash":"3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65","blockSize":4194304,"blocks":["3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65"]},"offset":"10820149"},"limitNumber.js.map":{"size":1300,"integrity":{"algorithm":"SHA256","hash":"8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f","blockSize":4194304,"blocks":["8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f"]},"offset":"10821185"},"limitProperties.js":{"size":896,"integrity":{"algorithm":"SHA256","hash":"8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac","blockSize":4194304,"blocks":["8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac"]},"offset":"10822485"},"limitProperties.js.map":{"size":915,"integrity":{"algorithm":"SHA256","hash":"0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa","blockSize":4194304,"blocks":["0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa"]},"offset":"10823381"},"multipleOf.js":{"size":1023,"integrity":{"algorithm":"SHA256","hash":"df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd","blockSize":4194304,"blocks":["df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd"]},"offset":"10824296"},"multipleOf.js.map":{"size":986,"integrity":{"algorithm":"SHA256","hash":"ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69","blockSize":4194304,"blocks":["ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69"]},"offset":"10825319"},"pattern.js":{"size":1323,"integrity":{"algorithm":"SHA256","hash":"86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195","blockSize":4194304,"blocks":["86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195"]},"offset":"10826305"},"pattern.js.map":{"size":1449,"integrity":{"algorithm":"SHA256","hash":"87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77","blockSize":4194304,"blocks":["87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77"]},"offset":"10827628"},"required.js":{"size":3188,"integrity":{"algorithm":"SHA256","hash":"b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054","blockSize":4194304,"blocks":["b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054"]},"offset":"10829077"},"required.js.map":{"size":2994,"integrity":{"algorithm":"SHA256","hash":"93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd","blockSize":4194304,"blocks":["93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd"]},"offset":"10832265"},"uniqueItems.js":{"size":3037,"integrity":{"algorithm":"SHA256","hash":"666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52","blockSize":4194304,"blocks":["666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52"]},"offset":"10835259"},"uniqueItems.js.map":{"size":3354,"integrity":{"algorithm":"SHA256","hash":"ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5","blockSize":4194304,"blocks":["ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5"]},"offset":"10838296"}}},"unevaluated":{"files":{"index.js":{"size":350,"integrity":{"algorithm":"SHA256","hash":"4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4","blockSize":4194304,"blocks":["4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4"]},"offset":"10841650"},"index.js.map":{"size":236,"integrity":{"algorithm":"SHA256","hash":"8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be","blockSize":4194304,"blocks":["8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be"]},"offset":"10842000"},"unevaluatedItems.js":{"size":1588,"integrity":{"algorithm":"SHA256","hash":"4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda","blockSize":4194304,"blocks":["4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda"]},"offset":"10842236"},"unevaluatedItems.js.map":{"size":1813,"integrity":{"algorithm":"SHA256","hash":"03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8","blockSize":4194304,"blocks":["03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8"]},"offset":"10843824"},"unevaluatedProperties.js":{"size":2608,"integrity":{"algorithm":"SHA256","hash":"665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe","blockSize":4194304,"blocks":["665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe"]},"offset":"10845637"},"unevaluatedProperties.js.map":{"size":2518,"integrity":{"algorithm":"SHA256","hash":"7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0","blockSize":4194304,"blocks":["7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0"]},"offset":"10848245"}}},"jtd":{"files":{"discriminator.js":{"size":2785,"integrity":{"algorithm":"SHA256","hash":"14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2","blockSize":4194304,"blocks":["14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2"]},"offset":"10850763"},"discriminator.js.map":{"size":2701,"integrity":{"algorithm":"SHA256","hash":"c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848","blockSize":4194304,"blocks":["c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848"]},"offset":"10853548"},"elements.js":{"size":949,"integrity":{"algorithm":"SHA256","hash":"b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b","blockSize":4194304,"blocks":["b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b"]},"offset":"10856249"},"elements.js.map":{"size":908,"integrity":{"algorithm":"SHA256","hash":"2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05","blockSize":4194304,"blocks":["2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05"]},"offset":"10857198"},"enum.js":{"size":1745,"integrity":{"algorithm":"SHA256","hash":"4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154","blockSize":4194304,"blocks":["4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154"]},"offset":"10858106"},"enum.js.map":{"size":1708,"integrity":{"algorithm":"SHA256","hash":"87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff","blockSize":4194304,"blocks":["87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff"]},"offset":"10859851"},"error.js":{"size":893,"integrity":{"algorithm":"SHA256","hash":"d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9","blockSize":4194304,"blocks":["d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9"]},"offset":"10861559"},"error.js.map":{"size":716,"integrity":{"algorithm":"SHA256","hash":"4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f","blockSize":4194304,"blocks":["4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f"]},"offset":"10862452"},"index.js":{"size":962,"integrity":{"algorithm":"SHA256","hash":"c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d","blockSize":4194304,"blocks":["c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d"]},"offset":"10863168"},"index.js.map":{"size":530,"integrity":{"algorithm":"SHA256","hash":"31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028","blockSize":4194304,"blocks":["31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028"]},"offset":"10864130"},"metadata.js":{"size":810,"integrity":{"algorithm":"SHA256","hash":"237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68","blockSize":4194304,"blocks":["237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68"]},"offset":"10864660"},"metadata.js.map":{"size":797,"integrity":{"algorithm":"SHA256","hash":"b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538","blockSize":4194304,"blocks":["b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538"]},"offset":"10865470"},"nullable.js":{"size":859,"integrity":{"algorithm":"SHA256","hash":"ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a","blockSize":4194304,"blocks":["ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a"]},"offset":"10866267"},"nullable.js.map":{"size":821,"integrity":{"algorithm":"SHA256","hash":"4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08","blockSize":4194304,"blocks":["4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08"]},"offset":"10867126"},"optionalProperties.js":{"size":436,"integrity":{"algorithm":"SHA256","hash":"82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62","blockSize":4194304,"blocks":["82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62"]},"offset":"10867947"},"optionalProperties.js.map":{"size":398,"integrity":{"algorithm":"SHA256","hash":"58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898","blockSize":4194304,"blocks":["58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898"]},"offset":"10868383"},"properties.js":{"size":6320,"integrity":{"algorithm":"SHA256","hash":"4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35","blockSize":4194304,"blocks":["4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35"]},"offset":"10868781"},"properties.js.map":{"size":5884,"integrity":{"algorithm":"SHA256","hash":"7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380","blockSize":4194304,"blocks":["7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380"]},"offset":"10875101"},"ref.js":{"size":2648,"integrity":{"algorithm":"SHA256","hash":"4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460","blockSize":4194304,"blocks":["4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460"]},"offset":"10880985"},"ref.js.map":{"size":2476,"integrity":{"algorithm":"SHA256","hash":"1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001","blockSize":4194304,"blocks":["1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001"]},"offset":"10883633"},"type.js":{"size":2706,"integrity":{"algorithm":"SHA256","hash":"f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c","blockSize":4194304,"blocks":["f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c"]},"offset":"10886109"},"type.js.map":{"size":2614,"integrity":{"algorithm":"SHA256","hash":"8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2","blockSize":4194304,"blocks":["8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2"]},"offset":"10888815"},"union.js":{"size":343,"integrity":{"algorithm":"SHA256","hash":"f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280","blockSize":4194304,"blocks":["f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280"]},"offset":"10891429"},"union.js.map":{"size":320,"integrity":{"algorithm":"SHA256","hash":"53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519","blockSize":4194304,"blocks":["53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519"]},"offset":"10891772"},"values.js":{"size":1838,"integrity":{"algorithm":"SHA256","hash":"6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2","blockSize":4194304,"blocks":["6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2"]},"offset":"10892092"},"values.js.map":{"size":1783,"integrity":{"algorithm":"SHA256","hash":"0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a","blockSize":4194304,"blocks":["0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a"]},"offset":"10893930"}}},"format":{"files":{"format.js":{"size":4317,"integrity":{"algorithm":"SHA256","hash":"6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f","blockSize":4194304,"blocks":["6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f"]},"offset":"10895713"},"format.js.map":{"size":3832,"integrity":{"algorithm":"SHA256","hash":"35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5","blockSize":4194304,"blocks":["35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5"]},"offset":"10900030"},"index.js":{"size":209,"integrity":{"algorithm":"SHA256","hash":"d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67","blockSize":4194304,"blocks":["d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67"]},"offset":"10903862"},"index.js.map":{"size":205,"integrity":{"algorithm":"SHA256","hash":"ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d","blockSize":4194304,"blocks":["ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d"]},"offset":"10904071"}}},"dynamic":{"files":{"dynamicAnchor.js":{"size":1261,"integrity":{"algorithm":"SHA256","hash":"78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7","blockSize":4194304,"blocks":["78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7"]},"offset":"10904276"},"dynamicAnchor.js.map":{"size":1351,"integrity":{"algorithm":"SHA256","hash":"a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7","blockSize":4194304,"blocks":["a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7"]},"offset":"10905537"},"dynamicRef.js":{"size":1985,"integrity":{"algorithm":"SHA256","hash":"acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917","blockSize":4194304,"blocks":["acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917"]},"offset":"10906888"},"dynamicRef.js.map":{"size":1679,"integrity":{"algorithm":"SHA256","hash":"4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f","blockSize":4194304,"blocks":["4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f"]},"offset":"10908873"},"index.js":{"size":457,"integrity":{"algorithm":"SHA256","hash":"8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b","blockSize":4194304,"blocks":["8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b"]},"offset":"10910552"},"index.js.map":{"size":278,"integrity":{"algorithm":"SHA256","hash":"cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14","blockSize":4194304,"blocks":["cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14"]},"offset":"10911009"},"recursiveAnchor.js":{"size":522,"integrity":{"algorithm":"SHA256","hash":"9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76","blockSize":4194304,"blocks":["9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76"]},"offset":"10911287"},"recursiveAnchor.js.map":{"size":435,"integrity":{"algorithm":"SHA256","hash":"14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f","blockSize":4194304,"blocks":["14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f"]},"offset":"10911809"},"recursiveRef.js":{"size":325,"integrity":{"algorithm":"SHA256","hash":"7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d","blockSize":4194304,"blocks":["7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d"]},"offset":"10912244"},"recursiveRef.js.map":{"size":339,"integrity":{"algorithm":"SHA256","hash":"aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6","blockSize":4194304,"blocks":["aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6"]},"offset":"10912569"}}},"discriminator":{"files":{"index.js":{"size":4845,"integrity":{"algorithm":"SHA256","hash":"b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e","blockSize":4194304,"blocks":["b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e"]},"offset":"10912908"},"index.js.map":{"size":4243,"integrity":{"algorithm":"SHA256","hash":"5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2","blockSize":4194304,"blocks":["5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2"]},"offset":"10917753"},"types.js":{"size":308,"integrity":{"algorithm":"SHA256","hash":"2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa","blockSize":4194304,"blocks":["2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa"]},"offset":"10921996"},"types.js.map":{"size":239,"integrity":{"algorithm":"SHA256","hash":"4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa","blockSize":4194304,"blocks":["4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa"]},"offset":"10922304"}}},"core":{"files":{"id.js":{"size":267,"integrity":{"algorithm":"SHA256","hash":"49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11","blockSize":4194304,"blocks":["49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11"]},"offset":"10922543"},"id.js.map":{"size":257,"integrity":{"algorithm":"SHA256","hash":"fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897","blockSize":4194304,"blocks":["fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897"]},"offset":"10922810"},"index.js":{"size":357,"integrity":{"algorithm":"SHA256","hash":"f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e","blockSize":4194304,"blocks":["f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e"]},"offset":"10923067"},"index.js.map":{"size":306,"integrity":{"algorithm":"SHA256","hash":"47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d","blockSize":4194304,"blocks":["47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d"]},"offset":"10923424"},"ref.js":{"size":5234,"integrity":{"algorithm":"SHA256","hash":"1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1","blockSize":4194304,"blocks":["1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1"]},"offset":"10923730"},"ref.js.map":{"size":5094,"integrity":{"algorithm":"SHA256","hash":"102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745","blockSize":4194304,"blocks":["102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745"]},"offset":"10928964"}}},"applicator":{"files":{"additionalItems.js":{"size":1931,"integrity":{"algorithm":"SHA256","hash":"7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099","blockSize":4194304,"blocks":["7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099"]},"offset":"10934058"},"additionalItems.js.map":{"size":2093,"integrity":{"algorithm":"SHA256","hash":"f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571","blockSize":4194304,"blocks":["f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571"]},"offset":"10935989"},"additionalProperties.js":{"size":4309,"integrity":{"algorithm":"SHA256","hash":"e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a","blockSize":4194304,"blocks":["e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a"]},"offset":"10938082"},"additionalProperties.js.map":{"size":3762,"integrity":{"algorithm":"SHA256","hash":"90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a","blockSize":4194304,"blocks":["90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a"]},"offset":"10942391"},"allOf.js":{"size":756,"integrity":{"algorithm":"SHA256","hash":"98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7","blockSize":4194304,"blocks":["98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7"]},"offset":"10946153"},"allOf.js.map":{"size":812,"integrity":{"algorithm":"SHA256","hash":"bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b","blockSize":4194304,"blocks":["bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b"]},"offset":"10946909"},"anyOf.js":{"size":343,"integrity":{"algorithm":"SHA256","hash":"8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5","blockSize":4194304,"blocks":["8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5"]},"offset":"10947721"},"anyOf.js.map":{"size":327,"integrity":{"algorithm":"SHA256","hash":"c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3","blockSize":4194304,"blocks":["c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3"]},"offset":"10948064"},"contains.js":{"size":3680,"integrity":{"algorithm":"SHA256","hash":"56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c","blockSize":4194304,"blocks":["56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c"]},"offset":"10948391"},"contains.js.map":{"size":3843,"integrity":{"algorithm":"SHA256","hash":"b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069","blockSize":4194304,"blocks":["b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069"]},"offset":"10952071"},"dependencies.js":{"size":3198,"integrity":{"algorithm":"SHA256","hash":"c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b","blockSize":4194304,"blocks":["c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b"]},"offset":"10955914"},"dependencies.js.map":{"size":3172,"integrity":{"algorithm":"SHA256","hash":"58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af","blockSize":4194304,"blocks":["58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af"]},"offset":"10959112"},"dependentSchemas.js":{"size":354,"integrity":{"algorithm":"SHA256","hash":"d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e","blockSize":4194304,"blocks":["d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e"]},"offset":"10962284"},"dependentSchemas.js.map":{"size":353,"integrity":{"algorithm":"SHA256","hash":"acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69","blockSize":4194304,"blocks":["acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69"]},"offset":"10962638"},"if.js":{"size":2438,"integrity":{"algorithm":"SHA256","hash":"42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4","blockSize":4194304,"blocks":["42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4"]},"offset":"10962991"},"if.js.map":{"size":2455,"integrity":{"algorithm":"SHA256","hash":"ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939","blockSize":4194304,"blocks":["ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939"]},"offset":"10965429"},"index.js":{"size":1529,"integrity":{"algorithm":"SHA256","hash":"5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3","blockSize":4194304,"blocks":["5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3"]},"offset":"10967884"},"index.js.map":{"size":766,"integrity":{"algorithm":"SHA256","hash":"0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50","blockSize":4194304,"blocks":["0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50"]},"offset":"10969413"},"items.js":{"size":1993,"integrity":{"algorithm":"SHA256","hash":"fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e","blockSize":4194304,"blocks":["fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e"]},"offset":"10970179"},"items.js.map":{"size":2052,"integrity":{"algorithm":"SHA256","hash":"a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f","blockSize":4194304,"blocks":["a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f"]},"offset":"10972172"},"items2020.js":{"size":1037,"integrity":{"algorithm":"SHA256","hash":"c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f","blockSize":4194304,"blocks":["c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f"]},"offset":"10974224"},"items2020.js.map":{"size":947,"integrity":{"algorithm":"SHA256","hash":"8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc","blockSize":4194304,"blocks":["8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc"]},"offset":"10975261"},"not.js":{"size":773,"integrity":{"algorithm":"SHA256","hash":"ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718","blockSize":4194304,"blocks":["ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718"]},"offset":"10976208"},"not.js.map":{"size":831,"integrity":{"algorithm":"SHA256","hash":"c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db","blockSize":4194304,"blocks":["c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db"]},"offset":"10976981"},"oneOf.js":{"size":2257,"integrity":{"algorithm":"SHA256","hash":"e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2","blockSize":4194304,"blocks":["e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2"]},"offset":"10977812"},"oneOf.js.map":{"size":2046,"integrity":{"algorithm":"SHA256","hash":"ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526","blockSize":4194304,"blocks":["ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526"]},"offset":"10980069"},"patternProperties.js":{"size":3236,"integrity":{"algorithm":"SHA256","hash":"0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655","blockSize":4194304,"blocks":["0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655"]},"offset":"10982115"},"patternProperties.js.map":{"size":2734,"integrity":{"algorithm":"SHA256","hash":"a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1","blockSize":4194304,"blocks":["a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1"]},"offset":"10985351"},"prefixItems.js":{"size":354,"integrity":{"algorithm":"SHA256","hash":"16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23","blockSize":4194304,"blocks":["16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23"]},"offset":"10988085"},"prefixItems.js.map":{"size":381,"integrity":{"algorithm":"SHA256","hash":"1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c","blockSize":4194304,"blocks":["1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c"]},"offset":"10988439"},"properties.js":{"size":2153,"integrity":{"algorithm":"SHA256","hash":"c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f","blockSize":4194304,"blocks":["c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f"]},"offset":"10988820"},"properties.js.map":{"size":2054,"integrity":{"algorithm":"SHA256","hash":"33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3","blockSize":4194304,"blocks":["33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3"]},"offset":"10990973"},"propertyNames.js":{"size":1221,"integrity":{"algorithm":"SHA256","hash":"b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7","blockSize":4194304,"blocks":["b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7"]},"offset":"10993027"},"propertyNames.js.map":{"size":1230,"integrity":{"algorithm":"SHA256","hash":"a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64","blockSize":4194304,"blocks":["a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64"]},"offset":"10994248"},"thenElse.js":{"size":446,"integrity":{"algorithm":"SHA256","hash":"9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d","blockSize":4194304,"blocks":["9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d"]},"offset":"10995478"},"thenElse.js.map":{"size":442,"integrity":{"algorithm":"SHA256","hash":"474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e","blockSize":4194304,"blocks":["474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e"]},"offset":"10995924"}}}}},"types":{"files":{"index.js":{"size":110,"integrity":{"algorithm":"SHA256","hash":"fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71","blockSize":4194304,"blocks":["fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71"]},"offset":"10996366"},"index.js.map":{"size":111,"integrity":{"algorithm":"SHA256","hash":"dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6","blockSize":4194304,"blocks":["dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6"]},"offset":"10996476"},"json-schema.js":{"size":116,"integrity":{"algorithm":"SHA256","hash":"2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28","blockSize":4194304,"blocks":["2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28"]},"offset":"10996587"},"json-schema.js.map":{"size":123,"integrity":{"algorithm":"SHA256","hash":"c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221","blockSize":4194304,"blocks":["c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221"]},"offset":"10996703"},"jtd-schema.js":{"size":115,"integrity":{"algorithm":"SHA256","hash":"6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d","blockSize":4194304,"blocks":["6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d"]},"offset":"10996826"},"jtd-schema.js.map":{"size":121,"integrity":{"algorithm":"SHA256","hash":"c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9","blockSize":4194304,"blocks":["c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9"]},"offset":"10996941"}}},"standalone":{"files":{"index.js":{"size":4480,"integrity":{"algorithm":"SHA256","hash":"361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f","blockSize":4194304,"blocks":["361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f"]},"offset":"10997062"},"index.js.map":{"size":4078,"integrity":{"algorithm":"SHA256","hash":"a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860","blockSize":4194304,"blocks":["a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860"]},"offset":"11001542"},"instance.js":{"size":1015,"integrity":{"algorithm":"SHA256","hash":"4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3","blockSize":4194304,"blocks":["4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3"]},"offset":"11005620"},"instance.js.map":{"size":1091,"integrity":{"algorithm":"SHA256","hash":"7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7","blockSize":4194304,"blocks":["7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7"]},"offset":"11006635"}}},"runtime":{"files":{"equal.js":{"size":286,"integrity":{"algorithm":"SHA256","hash":"c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274","blockSize":4194304,"blocks":["c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274"]},"offset":"11007726"},"equal.js.map":{"size":199,"integrity":{"algorithm":"SHA256","hash":"addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae","blockSize":4194304,"blocks":["addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae"]},"offset":"11008012"},"parseJson.js":{"size":5401,"integrity":{"algorithm":"SHA256","hash":"1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e","blockSize":4194304,"blocks":["1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e"]},"offset":"11008211"},"parseJson.js.map":{"size":5339,"integrity":{"algorithm":"SHA256","hash":"cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7","blockSize":4194304,"blocks":["cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7"]},"offset":"11013612"},"quote.js":{"size":943,"integrity":{"algorithm":"SHA256","hash":"1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2","blockSize":4194304,"blocks":["1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2"]},"offset":"11018951"},"quote.js.map":{"size":877,"integrity":{"algorithm":"SHA256","hash":"299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9","blockSize":4194304,"blocks":["299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9"]},"offset":"11019894"},"re2.js":{"size":213,"integrity":{"algorithm":"SHA256","hash":"e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361","blockSize":4194304,"blocks":["e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361"]},"offset":"11020771"},"re2.js.map":{"size":182,"integrity":{"algorithm":"SHA256","hash":"891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc","blockSize":4194304,"blocks":["891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc"]},"offset":"11020984"},"timestamp.js":{"size":1536,"integrity":{"algorithm":"SHA256","hash":"05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef","blockSize":4194304,"blocks":["05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef"]},"offset":"11021166"},"timestamp.js.map":{"size":1994,"integrity":{"algorithm":"SHA256","hash":"4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe","blockSize":4194304,"blocks":["4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe"]},"offset":"11022702"},"ucs2length.js":{"size":808,"integrity":{"algorithm":"SHA256","hash":"1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890","blockSize":4194304,"blocks":["1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890"]},"offset":"11024696"},"ucs2length.js.map":{"size":728,"integrity":{"algorithm":"SHA256","hash":"5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d","blockSize":4194304,"blocks":["5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d"]},"offset":"11025504"},"uri.js":{"size":218,"integrity":{"algorithm":"SHA256","hash":"d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578","blockSize":4194304,"blocks":["d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578"]},"offset":"11026232"},"uri.js.map":{"size":182,"integrity":{"algorithm":"SHA256","hash":"7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955","blockSize":4194304,"blocks":["7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955"]},"offset":"11026450"},"validation_error.js":{"size":337,"integrity":{"algorithm":"SHA256","hash":"11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815","blockSize":4194304,"blocks":["11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815"]},"offset":"11026632"},"validation_error.js.map":{"size":332,"integrity":{"algorithm":"SHA256","hash":"833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2","blockSize":4194304,"blocks":["833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2"]},"offset":"11026969"}}},"refs":{"files":{"data.json":{"size":409,"integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]},"offset":"11027301"},"json-schema-draft-06.json":{"size":3449,"integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]},"offset":"11027710"},"json-schema-draft-07.json":{"size":3811,"integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]},"offset":"11031159"},"json-schema-secure.json":{"size":2521,"integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]},"offset":"11034970"},"jtd-schema.js":{"size":2882,"integrity":{"algorithm":"SHA256","hash":"ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92","blockSize":4194304,"blocks":["ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92"]},"offset":"11037491"},"jtd-schema.js.map":{"size":2824,"integrity":{"algorithm":"SHA256","hash":"732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b","blockSize":4194304,"blocks":["732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b"]},"offset":"11040373"},"json-schema-2020-12":{"files":{"index.js":{"size":1026,"integrity":{"algorithm":"SHA256","hash":"2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1","blockSize":4194304,"blocks":["2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1"]},"offset":"11043197"},"index.js.map":{"size":751,"integrity":{"algorithm":"SHA256","hash":"79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877","blockSize":4194304,"blocks":["79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877"]},"offset":"11044223"},"schema.json":{"size":2166,"integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]},"offset":"11044974"},"meta":{"files":{"applicator.json":{"size":1441,"integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]},"offset":"11047140"},"content.json":{"size":479,"integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]},"offset":"11048581"},"core.json":{"size":1344,"integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]},"offset":"11049060"},"format-annotation.json":{"size":420,"integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]},"offset":"11050404"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]},"offset":"11050824"},"unevaluated.json":{"size":472,"integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]},"offset":"11051582"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]},"offset":"11052054"}}}}},"json-schema-2019-09":{"files":{"index.js":{"size":938,"integrity":{"algorithm":"SHA256","hash":"ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d","blockSize":4194304,"blocks":["ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d"]},"offset":"11054318"},"index.js.map":{"size":726,"integrity":{"algorithm":"SHA256","hash":"3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01","blockSize":4194304,"blocks":["3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01"]},"offset":"11055256"},"schema.json":{"size":1579,"integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]},"offset":"11055982"},"meta":{"files":{"applicator.json":{"size":1566,"integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]},"offset":"11057561"},"content.json":{"size":477,"integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]},"offset":"11059127"},"core.json":{"size":1273,"integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]},"offset":"11059604"},"format.json":{"size":375,"integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]},"offset":"11060877"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]},"offset":"11061252"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]},"offset":"11062010"}}}}}}},"compile":{"files":{"errors.js":{"size":5771,"integrity":{"algorithm":"SHA256","hash":"53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2","blockSize":4194304,"blocks":["53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2"]},"offset":"11064274"},"errors.js.map":{"size":6085,"integrity":{"algorithm":"SHA256","hash":"5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294","blockSize":4194304,"blocks":["5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294"]},"offset":"11070045"},"index.js":{"size":10046,"integrity":{"algorithm":"SHA256","hash":"05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac","blockSize":4194304,"blocks":["05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac"]},"offset":"11076130"},"index.js.map":{"size":9269,"integrity":{"algorithm":"SHA256","hash":"ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a","blockSize":4194304,"blocks":["ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a"]},"offset":"11086176"},"names.js":{"size":1440,"integrity":{"algorithm":"SHA256","hash":"3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493","blockSize":4194304,"blocks":["3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493"]},"offset":"11095445"},"names.js.map":{"size":974,"integrity":{"algorithm":"SHA256","hash":"2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7","blockSize":4194304,"blocks":["2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7"]},"offset":"11096885"},"ref_error.js":{"size":543,"integrity":{"algorithm":"SHA256","hash":"81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7","blockSize":4194304,"blocks":["81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7"]},"offset":"11097859"},"ref_error.js.map":{"size":474,"integrity":{"algorithm":"SHA256","hash":"3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b","blockSize":4194304,"blocks":["3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b"]},"offset":"11098402"},"resolve.js":{"size":5006,"integrity":{"algorithm":"SHA256","hash":"df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9","blockSize":4194304,"blocks":["df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9"]},"offset":"11098876"},"resolve.js.map":{"size":4850,"integrity":{"algorithm":"SHA256","hash":"837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce","blockSize":4194304,"blocks":["837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce"]},"offset":"11103882"},"rules.js":{"size":918,"integrity":{"algorithm":"SHA256","hash":"ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9","blockSize":4194304,"blocks":["ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9"]},"offset":"11108732"},"rules.js.map":{"size":1030,"integrity":{"algorithm":"SHA256","hash":"d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6","blockSize":4194304,"blocks":["d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6"]},"offset":"11109650"},"util.js":{"size":7103,"integrity":{"algorithm":"SHA256","hash":"fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5","blockSize":4194304,"blocks":["fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5"]},"offset":"11110680"},"util.js.map":{"size":7083,"integrity":{"algorithm":"SHA256","hash":"9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442","blockSize":4194304,"blocks":["9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442"]},"offset":"11117783"},"validate":{"files":{"applicability.js":{"size":853,"integrity":{"algorithm":"SHA256","hash":"50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0","blockSize":4194304,"blocks":["50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0"]},"offset":"11124866"},"applicability.js.map":{"size":775,"integrity":{"algorithm":"SHA256","hash":"399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad","blockSize":4194304,"blocks":["399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad"]},"offset":"11125719"},"boolSchema.js":{"size":1531,"integrity":{"algorithm":"SHA256","hash":"c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f","blockSize":4194304,"blocks":["c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f"]},"offset":"11126494"},"boolSchema.js.map":{"size":1380,"integrity":{"algorithm":"SHA256","hash":"d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9","blockSize":4194304,"blocks":["d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9"]},"offset":"11128025"},"dataType.js":{"size":8409,"integrity":{"algorithm":"SHA256","hash":"697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52","blockSize":4194304,"blocks":["697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52"]},"offset":"11129405"},"dataType.js.map":{"size":7776,"integrity":{"algorithm":"SHA256","hash":"5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08","blockSize":4194304,"blocks":["5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08"]},"offset":"11137814"},"defaults.js":{"size":1448,"integrity":{"algorithm":"SHA256","hash":"05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428","blockSize":4194304,"blocks":["05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428"]},"offset":"11145590"},"defaults.js.map":{"size":1342,"integrity":{"algorithm":"SHA256","hash":"dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5","blockSize":4194304,"blocks":["dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5"]},"offset":"11147038"},"index.js":{"size":20552,"integrity":{"algorithm":"SHA256","hash":"cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd","blockSize":4194304,"blocks":["cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd"]},"offset":"11148380"},"index.js.map":{"size":21391,"integrity":{"algorithm":"SHA256","hash":"fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c","blockSize":4194304,"blocks":["fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c"]},"offset":"11168932"},"keyword.js":{"size":5695,"integrity":{"algorithm":"SHA256","hash":"ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76","blockSize":4194304,"blocks":["ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76"]},"offset":"11190323"},"keyword.js.map":{"size":6011,"integrity":{"algorithm":"SHA256","hash":"3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e","blockSize":4194304,"blocks":["3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e"]},"offset":"11196018"},"subschema.js":{"size":3858,"integrity":{"algorithm":"SHA256","hash":"ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc","blockSize":4194304,"blocks":["ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc"]},"offset":"11202029"},"subschema.js.map":{"size":3148,"integrity":{"algorithm":"SHA256","hash":"9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a","blockSize":4194304,"blocks":["9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a"]},"offset":"11205887"}}},"jtd":{"files":{"parse.js":{"size":13727,"integrity":{"algorithm":"SHA256","hash":"548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f","blockSize":4194304,"blocks":["548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f"]},"offset":"11209035"},"parse.js.map":{"size":15725,"integrity":{"algorithm":"SHA256","hash":"90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0","blockSize":4194304,"blocks":["90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0"]},"offset":"11222762"},"serialize.js":{"size":9391,"integrity":{"algorithm":"SHA256","hash":"1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0","blockSize":4194304,"blocks":["1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0"]},"offset":"11238487"},"serialize.js.map":{"size":10737,"integrity":{"algorithm":"SHA256","hash":"faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd","blockSize":4194304,"blocks":["faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd"]},"offset":"11247878"},"types.js":{"size":291,"integrity":{"algorithm":"SHA256","hash":"e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78","blockSize":4194304,"blocks":["e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78"]},"offset":"11258615"},"types.js.map":{"size":236,"integrity":{"algorithm":"SHA256","hash":"b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5","blockSize":4194304,"blocks":["b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5"]},"offset":"11258906"}}},"codegen":{"files":{"code.js":{"size":4676,"integrity":{"algorithm":"SHA256","hash":"1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d","blockSize":4194304,"blocks":["1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d"]},"offset":"11259142"},"code.js.map":{"size":5309,"integrity":{"algorithm":"SHA256","hash":"6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60","blockSize":4194304,"blocks":["6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60"]},"offset":"11263818"},"index.js":{"size":23127,"integrity":{"algorithm":"SHA256","hash":"f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c","blockSize":4194304,"blocks":["f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c"]},"offset":"11269127"},"index.js.map":{"size":23829,"integrity":{"algorithm":"SHA256","hash":"081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc","blockSize":4194304,"blocks":["081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc"]},"offset":"11292254"},"scope.js":{"size":5198,"integrity":{"algorithm":"SHA256","hash":"d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286","blockSize":4194304,"blocks":["d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286"]},"offset":"11316083"},"scope.js.map":{"size":5174,"integrity":{"algorithm":"SHA256","hash":"a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec","blockSize":4194304,"blocks":["a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec"]},"offset":"11321281"}}}}}}}}},"json-schema-traverse":{"files":{".eslintrc.yml":{"size":630,"integrity":{"algorithm":"SHA256","hash":"b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc","blockSize":4194304,"blocks":["b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc"]},"offset":"11326455"},"LICENSE":{"size":1074,"integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]},"offset":"11327085"},"index.js":{"size":2428,"integrity":{"algorithm":"SHA256","hash":"024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350","blockSize":4194304,"blocks":["024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350"]},"offset":"11328159"},"package.json":{"size":553,"integrity":{"algorithm":"SHA256","hash":"c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262","blockSize":4194304,"blocks":["c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262"]},"offset":"11330587"},"spec":{"files":{".eslintrc.yml":{"size":91,"integrity":{"algorithm":"SHA256","hash":"8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c","blockSize":4194304,"blocks":["8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c"]},"offset":"11331140"},"index.spec.js":{"size":6042,"integrity":{"algorithm":"SHA256","hash":"40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69","blockSize":4194304,"blocks":["40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69"]},"offset":"11331231"},"fixtures":{"files":{"schema.js":{"size":5544,"integrity":{"algorithm":"SHA256","hash":"0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27","blockSize":4194304,"blocks":["0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27"]},"offset":"11337273"}}}}}}}}}}},"atomically":{"files":{".editorconfig":{"size":189,"integrity":{"algorithm":"SHA256","hash":"42a82ef9e641f12b19ae3919e6fe8ef14f9c4c3b4185df730a82d04300b4620e","blockSize":4194304,"blocks":["42a82ef9e641f12b19ae3919e6fe8ef14f9c4c3b4185df730a82d04300b4620e"]},"offset":"3294822"},".nvmrc":{"size":9,"integrity":{"algorithm":"SHA256","hash":"890a9ba685b9cb0ecf37267be4c5b5f76a404598d26897d9b0ab9b95c3fc308b","blockSize":4194304,"blocks":["890a9ba685b9cb0ecf37267be4c5b5f76a404598d26897d9b0ab9b95c3fc308b"]},"offset":"3295011"},"LICENSE":{"size":1091,"integrity":{"algorithm":"SHA256","hash":"716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500","blockSize":4194304,"blocks":["716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500"]},"offset":"3295020"},"package.json":{"size":793,"integrity":{"algorithm":"SHA256","hash":"119eab3c437e45dd45e6c67a2ecf8009511675c7803bc1baca07b1f52a7809f8","blockSize":4194304,"blocks":["119eab3c437e45dd45e6c67a2ecf8009511675c7803bc1baca07b1f52a7809f8"]},"offset":"3296111","executable":true},"tsconfig.json":{"size":687,"integrity":{"algorithm":"SHA256","hash":"be665bb12b0c8433412ccc07afdcffbb5cd4b5770a028ff39067cb177c4f85d0","blockSize":4194304,"blocks":["be665bb12b0c8433412ccc07afdcffbb5cd4b5770a028ff39067cb177c4f85d0"]},"offset":"3296904","executable":true},"tasks":{"files":{"benchmark.js":{"size":2747,"integrity":{"algorithm":"SHA256","hash":"988ecbd8462edfc5867759fc55613c0d90462d43b54078b13124b0301be040ce","blockSize":4194304,"blocks":["988ecbd8462edfc5867759fc55613c0d90462d43b54078b13124b0301be040ce"]},"offset":"3297591"}}},"src":{"files":{"consts.ts":{"size":856,"integrity":{"algorithm":"SHA256","hash":"f498bdb1bc9c896023263b55f186acb6cc6126aa4e5f0607cf5b6333425297e8","blockSize":4194304,"blocks":["f498bdb1bc9c896023263b55f186acb6cc6126aa4e5f0607cf5b6333425297e8"]},"offset":"3300338"},"index.ts":{"size":7267,"integrity":{"algorithm":"SHA256","hash":"36c448bdc9880cf8c0ee392d40f8115aa96e1503fb18aba6c2d3b48f7f3386fa","blockSize":4194304,"blocks":["36c448bdc9880cf8c0ee392d40f8115aa96e1503fb18aba6c2d3b48f7f3386fa"]},"offset":"3301194","executable":true},"types.ts":{"size":860,"integrity":{"algorithm":"SHA256","hash":"bfc9769ba84d2652939c183db17be1161e0b529773c1191c64b935d73e6fce83","blockSize":4194304,"blocks":["bfc9769ba84d2652939c183db17be1161e0b529773c1191c64b935d73e6fce83"]},"offset":"3308461"},"utils":{"files":{"attemptify.ts":{"size":718,"integrity":{"algorithm":"SHA256","hash":"12c5cf67f4b8b370d186692ba1a8db7bf3bbceafd4701f3dc6bf3bc6d21765b2","blockSize":4194304,"blocks":["12c5cf67f4b8b370d186692ba1a8db7bf3bbceafd4701f3dc6bf3bc6d21765b2"]},"offset":"3309321"},"fs.ts":{"size":2374,"integrity":{"algorithm":"SHA256","hash":"1b8572451d5aa1dd0edb3b2053893097f4013c7a849366c47b52d6a9fe174b19","blockSize":4194304,"blocks":["1b8572451d5aa1dd0edb3b2053893097f4013c7a849366c47b52d6a9fe174b19"]},"offset":"3310039"},"fs_handlers.ts":{"size":896,"integrity":{"algorithm":"SHA256","hash":"c21cfc9b2f8399f1b907cb616e96d9ab67945976a53c143240ba083b4a6afab4","blockSize":4194304,"blocks":["c21cfc9b2f8399f1b907cb616e96d9ab67945976a53c143240ba083b4a6afab4"]},"offset":"3312413"},"lang.ts":{"size":331,"integrity":{"algorithm":"SHA256","hash":"2e48eb2ab29cc4322a9705bd044cd95cdea462b162a010001a299bf793b799d9","blockSize":4194304,"blocks":["2e48eb2ab29cc4322a9705bd044cd95cdea462b162a010001a299bf793b799d9"]},"offset":"3313309"},"retryify.ts":{"size":1515,"integrity":{"algorithm":"SHA256","hash":"5752dea4d9e9fd1d55bcc5197997dbda25e46bff94a67da1e3cf2d5a7d32f00e","blockSize":4194304,"blocks":["5752dea4d9e9fd1d55bcc5197997dbda25e46bff94a67da1e3cf2d5a7d32f00e"]},"offset":"3313640"},"retryify_queue.ts":{"size":1752,"integrity":{"algorithm":"SHA256","hash":"08a6494e551620918c9025946503ad62aed236065d3489cc1cccfcfb11907681","blockSize":4194304,"blocks":["08a6494e551620918c9025946503ad62aed236065d3489cc1cccfcfb11907681"]},"offset":"3315155"},"scheduler.ts":{"size":818,"integrity":{"algorithm":"SHA256","hash":"09ba274d361ae2924a87f38c0fe8879b1a3fe310e036118b4975520d28588606","blockSize":4194304,"blocks":["09ba274d361ae2924a87f38c0fe8879b1a3fe310e036118b4975520d28588606"]},"offset":"3316907"},"temp.ts":{"size":2711,"integrity":{"algorithm":"SHA256","hash":"cc5627b41c491382129794303a218536417f3bbb7e9f143778e55e2f6d84cd0d","blockSize":4194304,"blocks":["cc5627b41c491382129794303a218536417f3bbb7e9f143778e55e2f6d84cd0d"]},"offset":"3317725"}}}}},"dist":{"files":{"consts.js":{"size":1572,"integrity":{"algorithm":"SHA256","hash":"feb31cc92d3c258df9008e9584d74362e661cac42ad6abb4cc305ff2d7432337","blockSize":4194304,"blocks":["feb31cc92d3c258df9008e9584d74362e661cac42ad6abb4cc305ff2d7432337"]},"offset":"3320436"},"index.js":{"size":7780,"integrity":{"algorithm":"SHA256","hash":"95c30ea2977ce45e25f8b42ae64b58f8c90543cbd9763c828f6170e554ff680a","blockSize":4194304,"blocks":["95c30ea2977ce45e25f8b42ae64b58f8c90543cbd9763c828f6170e554ff680a"]},"offset":"3322008"},"types.js":{"size":89,"integrity":{"algorithm":"SHA256","hash":"b4435decae0d0ea87851e7cdd3139043de0246a78302b6f355e5b059b50e6553","blockSize":4194304,"blocks":["b4435decae0d0ea87851e7cdd3139043de0246a78302b6f355e5b059b50e6553"]},"offset":"3329788"},"utils":{"files":{"attemptify.js":{"size":788,"integrity":{"algorithm":"SHA256","hash":"f570e6c261b2c413992073e48023163b21afb5f4cf1ad7ee2d230566595ddf82","blockSize":4194304,"blocks":["f570e6c261b2c413992073e48023163b21afb5f4cf1ad7ee2d230566595ddf82"]},"offset":"3329877"},"fs.js":{"size":3037,"integrity":{"algorithm":"SHA256","hash":"b15a3ea242de95a06402dd37172412553e481c67f7cd9bbaf4f8a3edeaca52e6","blockSize":4194304,"blocks":["b15a3ea242de95a06402dd37172412553e481c67f7cd9bbaf4f8a3edeaca52e6"]},"offset":"3330665"},"fs_handlers.js":{"size":865,"integrity":{"algorithm":"SHA256","hash":"b7cb366f755bb3297cf90797a6b0db7a1c7c0e23f2350eb09cffb16eecab16d9","blockSize":4194304,"blocks":["b7cb366f755bb3297cf90797a6b0db7a1c7c0e23f2350eb09cffb16eecab16d9"]},"offset":"3333702"},"lang.js":{"size":356,"integrity":{"algorithm":"SHA256","hash":"e84c44f703058eca395c41920501b3c450de15d687e1b509716fcda3e029d822","blockSize":4194304,"blocks":["e84c44f703058eca395c41920501b3c450de15d687e1b509716fcda3e029d822"]},"offset":"3334567"},"retryify.js":{"size":1653,"integrity":{"algorithm":"SHA256","hash":"2bd96d6f5af98a990f6774f28a943a2126d98df3bd66e25eb5bc546ac12b7338","blockSize":4194304,"blocks":["2bd96d6f5af98a990f6774f28a943a2126d98df3bd66e25eb5bc546ac12b7338"]},"offset":"3334923"},"retryify_queue.js":{"size":1836,"integrity":{"algorithm":"SHA256","hash":"9b6e5ad524ac9f29d9fab8fe740b660caebf54f0da7554541c8edb4c74710951","blockSize":4194304,"blocks":["9b6e5ad524ac9f29d9fab8fe740b660caebf54f0da7554541c8edb4c74710951"]},"offset":"3336576"},"scheduler.js":{"size":860,"integrity":{"algorithm":"SHA256","hash":"f32626546190ecb8dd54cdf66ccf6a82f17b23efb8d287ed656e189086b34de6","blockSize":4194304,"blocks":["f32626546190ecb8dd54cdf66ccf6a82f17b23efb8d287ed656e189086b34de6"]},"offset":"3338412"},"temp.js":{"size":2458,"integrity":{"algorithm":"SHA256","hash":"f4dad31de0b8d678dacbf7b6ee0f182575dc6555871a42a3a73506f9c37090b5","blockSize":4194304,"blocks":["f4dad31de0b8d678dacbf7b6ee0f182575dc6555871a42a3a73506f9c37090b5"]},"offset":"3339272"}}}}}}},"conf":{"files":{"license":{"size":1117,"integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]},"offset":"3341730"},"package.json":{"size":1233,"integrity":{"algorithm":"SHA256","hash":"c4bc0707fe539ef6b2f4dd240329bc6cddcf0051209a79eb79a41bf4d331bd12","blockSize":4194304,"blocks":["c4bc0707fe539ef6b2f4dd240329bc6cddcf0051209a79eb79a41bf4d331bd12"]},"offset":"3342847"},"dist":{"files":{"source":{"files":{"index.js":{"size":20779,"integrity":{"algorithm":"SHA256","hash":"bb9f43d6800ae8a54239dffdb4d8bf9532a3620454d2195762e91daf4303e586","blockSize":4194304,"blocks":["bb9f43d6800ae8a54239dffdb4d8bf9532a3620454d2195762e91daf4303e586"]},"offset":"3344080"},"types.js":{"size":77,"integrity":{"algorithm":"SHA256","hash":"d43aa81f5bc89faa359e0f97c814ba25155591ff078fbb9bfd40f8c7c9683230","blockSize":4194304,"blocks":["d43aa81f5bc89faa359e0f97c814ba25155591ff078fbb9bfd40f8c7c9683230"]},"offset":"3364859"}}}}},"node_modules":{"files":{"ajv":{"files":{".runkit_example.js":{"size":496,"integrity":{"algorithm":"SHA256","hash":"e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf","blockSize":4194304,"blocks":["e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf"]},"offset":"11342817"},"LICENSE":{"size":1090,"integrity":{"algorithm":"SHA256","hash":"a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3","blockSize":4194304,"blocks":["a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]},"offset":"11343313"},"package.json":{"size":2245,"integrity":{"algorithm":"SHA256","hash":"c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84","blockSize":4194304,"blocks":["c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84"]},"offset":"11344403"},"lib":{"files":{"2019.ts":{"size":2502,"integrity":{"algorithm":"SHA256","hash":"d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc","blockSize":4194304,"blocks":["d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc"]},"offset":"11346648"},"2020.ts":{"size":2217,"integrity":{"algorithm":"SHA256","hash":"0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603","blockSize":4194304,"blocks":["0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603"]},"offset":"11349150"},"ajv.ts":{"size":2229,"integrity":{"algorithm":"SHA256","hash":"db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85","blockSize":4194304,"blocks":["db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85"]},"offset":"11351367"},"core.ts":{"size":30790,"integrity":{"algorithm":"SHA256","hash":"c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d","blockSize":4194304,"blocks":["c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d"]},"offset":"11353596"},"jtd.ts":{"size":4172,"integrity":{"algorithm":"SHA256","hash":"e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262","blockSize":4194304,"blocks":["e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262"]},"offset":"11384386"},"vocabularies":{"files":{"code.ts":{"size":5247,"integrity":{"algorithm":"SHA256","hash":"f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7","blockSize":4194304,"blocks":["f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7"]},"offset":"11388558"},"draft2020.ts":{"size":698,"integrity":{"algorithm":"SHA256","hash":"840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea","blockSize":4194304,"blocks":["840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea"]},"offset":"11393805"},"draft7.ts":{"size":496,"integrity":{"algorithm":"SHA256","hash":"9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4","blockSize":4194304,"blocks":["9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4"]},"offset":"11394503"},"errors.ts":{"size":731,"integrity":{"algorithm":"SHA256","hash":"ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b","blockSize":4194304,"blocks":["ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b"]},"offset":"11394999"},"metadata.ts":{"size":304,"integrity":{"algorithm":"SHA256","hash":"a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1","blockSize":4194304,"blocks":["a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1"]},"offset":"11395730"},"next.ts":{"size":320,"integrity":{"algorithm":"SHA256","hash":"b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443","blockSize":4194304,"blocks":["b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443"]},"offset":"11396034"},"validation":{"files":{"const.ts":{"size":863,"integrity":{"algorithm":"SHA256","hash":"9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5","blockSize":4194304,"blocks":["9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5"]},"offset":"11396354"},"dependentRequired.ts":{"size":510,"integrity":{"algorithm":"SHA256","hash":"082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b","blockSize":4194304,"blocks":["082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b"]},"offset":"11397217"},"enum.ts":{"size":1837,"integrity":{"algorithm":"SHA256","hash":"f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911","blockSize":4194304,"blocks":["f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911"]},"offset":"11397727"},"index.ts":{"size":1271,"integrity":{"algorithm":"SHA256","hash":"72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c","blockSize":4194304,"blocks":["72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c"]},"offset":"11399564"},"limitContains.ts":{"size":485,"integrity":{"algorithm":"SHA256","hash":"3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5","blockSize":4194304,"blocks":["3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5"]},"offset":"11400835"},"limitItems.ts":{"size":812,"integrity":{"algorithm":"SHA256","hash":"32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176","blockSize":4194304,"blocks":["32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176"]},"offset":"11401320"},"limitLength.ts":{"size":1025,"integrity":{"algorithm":"SHA256","hash":"72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de","blockSize":4194304,"blocks":["72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de"]},"offset":"11402132"},"limitNumber.ts":{"size":1350,"integrity":{"algorithm":"SHA256","hash":"61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298","blockSize":4194304,"blocks":["61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298"]},"offset":"11403157"},"limitProperties.ts":{"size":851,"integrity":{"algorithm":"SHA256","hash":"d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048","blockSize":4194304,"blocks":["d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048"]},"offset":"11404507"},"multipleOf.ts":{"size":1072,"integrity":{"algorithm":"SHA256","hash":"5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c","blockSize":4194304,"blocks":["5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c"]},"offset":"11405358"},"pattern.ts":{"size":1299,"integrity":{"algorithm":"SHA256","hash":"7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829","blockSize":4194304,"blocks":["7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829"]},"offset":"11406430"},"required.ts":{"size":2961,"integrity":{"algorithm":"SHA256","hash":"73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa","blockSize":4194304,"blocks":["73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa"]},"offset":"11407729"},"uniqueItems.ts":{"size":2690,"integrity":{"algorithm":"SHA256","hash":"9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0","blockSize":4194304,"blocks":["9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0"]},"offset":"11410690"}}},"unevaluated":{"files":{"index.ts":{"size":257,"integrity":{"algorithm":"SHA256","hash":"0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40","blockSize":4194304,"blocks":["0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40"]},"offset":"11413380"},"unevaluatedItems.ts":{"size":1524,"integrity":{"algorithm":"SHA256","hash":"c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2","blockSize":4194304,"blocks":["c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2"]},"offset":"11413637"},"unevaluatedProperties.ts":{"size":2440,"integrity":{"algorithm":"SHA256","hash":"7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de","blockSize":4194304,"blocks":["7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de"]},"offset":"11415161"}}},"jtd":{"files":{"discriminator.ts":{"size":2656,"integrity":{"algorithm":"SHA256","hash":"9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d","blockSize":4194304,"blocks":["9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d"]},"offset":"11417601"},"elements.ts":{"size":976,"integrity":{"algorithm":"SHA256","hash":"54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33","blockSize":4194304,"blocks":["54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33"]},"offset":"11420257"},"enum.ts":{"size":1627,"integrity":{"algorithm":"SHA256","hash":"a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd","blockSize":4194304,"blocks":["a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd"]},"offset":"11421233"},"error.ts":{"size":746,"integrity":{"algorithm":"SHA256","hash":"e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5","blockSize":4194304,"blocks":["e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5"]},"offset":"11422860"},"index.ts":{"size":1007,"integrity":{"algorithm":"SHA256","hash":"4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a","blockSize":4194304,"blocks":["4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a"]},"offset":"11423606"},"metadata.ts":{"size":716,"integrity":{"algorithm":"SHA256","hash":"558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01","blockSize":4194304,"blocks":["558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01"]},"offset":"11424613"},"nullable.ts":{"size":649,"integrity":{"algorithm":"SHA256","hash":"75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8","blockSize":4194304,"blocks":["75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8"]},"offset":"11425329"},"optionalProperties.ts":{"size":394,"integrity":{"algorithm":"SHA256","hash":"03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77","blockSize":4194304,"blocks":["03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77"]},"offset":"11425978"},"properties.ts":{"size":6244,"integrity":{"algorithm":"SHA256","hash":"930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5","blockSize":4194304,"blocks":["930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5"]},"offset":"11426372"},"ref.ts":{"size":2346,"integrity":{"algorithm":"SHA256","hash":"f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d","blockSize":4194304,"blocks":["f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d"]},"offset":"11432616"},"type.ts":{"size":2547,"integrity":{"algorithm":"SHA256","hash":"0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45","blockSize":4194304,"blocks":["0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45"]},"offset":"11434962"},"union.ts":{"size":292,"integrity":{"algorithm":"SHA256","hash":"1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536","blockSize":4194304,"blocks":["1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536"]},"offset":"11437509"},"values.ts":{"size":1681,"integrity":{"algorithm":"SHA256","hash":"86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd","blockSize":4194304,"blocks":["86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd"]},"offset":"11437801"}}},"format":{"files":{"format.ts":{"size":3987,"integrity":{"algorithm":"SHA256","hash":"5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148","blockSize":4194304,"blocks":["5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148"]},"offset":"11439482"},"index.ts":{"size":148,"integrity":{"algorithm":"SHA256","hash":"804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a","blockSize":4194304,"blocks":["804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a"]},"offset":"11443469"}}},"dynamic":{"files":{"dynamicAnchor.ts":{"size":1122,"integrity":{"algorithm":"SHA256","hash":"bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f","blockSize":4194304,"blocks":["bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f"]},"offset":"11443617"},"dynamicRef.ts":{"size":1797,"integrity":{"algorithm":"SHA256","hash":"92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d","blockSize":4194304,"blocks":["92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d"]},"offset":"11444739"},"index.ts":{"size":328,"integrity":{"algorithm":"SHA256","hash":"c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b","blockSize":4194304,"blocks":["c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b"]},"offset":"11446536"},"recursiveAnchor.ts":{"size":401,"integrity":{"algorithm":"SHA256","hash":"7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a","blockSize":4194304,"blocks":["7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a"]},"offset":"11446864"},"recursiveRef.ts":{"size":253,"integrity":{"algorithm":"SHA256","hash":"6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3","blockSize":4194304,"blocks":["6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3"]},"offset":"11447265"}}},"discriminator":{"files":{"index.ts":{"size":4304,"integrity":{"algorithm":"SHA256","hash":"9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3","blockSize":4194304,"blocks":["9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3"]},"offset":"11447518"},"types.ts":{"size":251,"integrity":{"algorithm":"SHA256","hash":"537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da","blockSize":4194304,"blocks":["537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da"]},"offset":"11451822"}}},"core":{"files":{"id.ts":{"size":224,"integrity":{"algorithm":"SHA256","hash":"241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1","blockSize":4194304,"blocks":["241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1"]},"offset":"11452073"},"index.ts":{"size":274,"integrity":{"algorithm":"SHA256","hash":"43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62","blockSize":4194304,"blocks":["43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62"]},"offset":"11452297"},"ref.ts":{"size":4384,"integrity":{"algorithm":"SHA256","hash":"0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8","blockSize":4194304,"blocks":["0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8"]},"offset":"11452571"}}},"applicator":{"files":{"additionalItems.ts":{"size":1824,"integrity":{"algorithm":"SHA256","hash":"0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a","blockSize":4194304,"blocks":["0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a"]},"offset":"11456955"},"additionalProperties.ts":{"size":3782,"integrity":{"algorithm":"SHA256","hash":"1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55","blockSize":4194304,"blocks":["1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55"]},"offset":"11458779"},"allOf.ts":{"size":717,"integrity":{"algorithm":"SHA256","hash":"cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa","blockSize":4194304,"blocks":["cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa"]},"offset":"11462561"},"anyOf.ts":{"size":380,"integrity":{"algorithm":"SHA256","hash":"2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594","blockSize":4194304,"blocks":["2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594"]},"offset":"11463278"},"contains.ts":{"size":3278,"integrity":{"algorithm":"SHA256","hash":"731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05","blockSize":4194304,"blocks":["731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05"]},"offset":"11463658"},"dependencies.ts":{"size":3391,"integrity":{"algorithm":"SHA256","hash":"d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65","blockSize":4194304,"blocks":["d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65"]},"offset":"11466936"},"dependentSchemas.ts":{"size":280,"integrity":{"algorithm":"SHA256","hash":"ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc","blockSize":4194304,"blocks":["ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc"]},"offset":"11470327"},"if.ts":{"size":2395,"integrity":{"algorithm":"SHA256","hash":"676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f","blockSize":4194304,"blocks":["676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f"]},"offset":"11470607"},"index.ts":{"size":1592,"integrity":{"algorithm":"SHA256","hash":"85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6","blockSize":4194304,"blocks":["85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6"]},"offset":"11473002"},"items.ts":{"size":1892,"integrity":{"algorithm":"SHA256","hash":"9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3","blockSize":4194304,"blocks":["9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3"]},"offset":"11474594"},"items2020.ts":{"size":1053,"integrity":{"algorithm":"SHA256","hash":"939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668","blockSize":4194304,"blocks":["939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668"]},"offset":"11476486"},"not.ts":{"size":859,"integrity":{"algorithm":"SHA256","hash":"a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971","blockSize":4194304,"blocks":["a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971"]},"offset":"11477539"},"oneOf.ts":{"size":2197,"integrity":{"algorithm":"SHA256","hash":"ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0","blockSize":4194304,"blocks":["ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0"]},"offset":"11478398"},"patternProperties.ts":{"size":2870,"integrity":{"algorithm":"SHA256","hash":"80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75","blockSize":4194304,"blocks":["80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75"]},"offset":"11480595"},"prefixItems.ts":{"size":292,"integrity":{"algorithm":"SHA256","hash":"ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b","blockSize":4194304,"blocks":["ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b"]},"offset":"11483465"},"properties.ts":{"size":1845,"integrity":{"algorithm":"SHA256","hash":"76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1","blockSize":4194304,"blocks":["76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1"]},"offset":"11483757"},"propertyNames.ts":{"size":1247,"integrity":{"algorithm":"SHA256","hash":"ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f","blockSize":4194304,"blocks":["ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f"]},"offset":"11485602"},"thenElse.ts":{"size":441,"integrity":{"algorithm":"SHA256","hash":"29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4","blockSize":4194304,"blocks":["29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4"]},"offset":"11486849"}}}}},"types":{"files":{"index.ts":{"size":7289,"integrity":{"algorithm":"SHA256","hash":"3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8","blockSize":4194304,"blocks":["3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8"]},"offset":"11487290"},"json-schema.ts":{"size":6380,"integrity":{"algorithm":"SHA256","hash":"4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8","blockSize":4194304,"blocks":["4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8"]},"offset":"11494579"},"jtd-schema.ts":{"size":9321,"integrity":{"algorithm":"SHA256","hash":"1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42","blockSize":4194304,"blocks":["1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42"]},"offset":"11500959"}}},"standalone":{"files":{"index.ts":{"size":4151,"integrity":{"algorithm":"SHA256","hash":"3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed","blockSize":4194304,"blocks":["3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed"]},"offset":"11510280"},"instance.ts":{"size":1272,"integrity":{"algorithm":"SHA256","hash":"9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82","blockSize":4194304,"blocks":["9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82"]},"offset":"11514431"}}},"runtime":{"files":{"equal.ts":{"size":236,"integrity":{"algorithm":"SHA256","hash":"013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10","blockSize":4194304,"blocks":["013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10"]},"offset":"11515703"},"parseJson.ts":{"size":4553,"integrity":{"algorithm":"SHA256","hash":"79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5","blockSize":4194304,"blocks":["79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5"]},"offset":"11515939"},"quote.ts":{"size":802,"integrity":{"algorithm":"SHA256","hash":"b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3","blockSize":4194304,"blocks":["b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3"]},"offset":"11520492"},"re2.ts":{"size":157,"integrity":{"algorithm":"SHA256","hash":"10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7","blockSize":4194304,"blocks":["10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7"]},"offset":"11521294"},"timestamp.ts":{"size":1492,"integrity":{"algorithm":"SHA256","hash":"08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4","blockSize":4194304,"blocks":["08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4"]},"offset":"11521451"},"ucs2length.ts":{"size":629,"integrity":{"algorithm":"SHA256","hash":"a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6","blockSize":4194304,"blocks":["a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6"]},"offset":"11522943"},"uri.ts":{"size":162,"integrity":{"algorithm":"SHA256","hash":"4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb","blockSize":4194304,"blocks":["4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb"]},"offset":"11523572"},"validation_error.ts":{"size":336,"integrity":{"algorithm":"SHA256","hash":"abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64","blockSize":4194304,"blocks":["abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64"]},"offset":"11523734"}}},"refs":{"files":{"data.json":{"size":409,"integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]},"offset":"11524070"},"json-schema-draft-06.json":{"size":3449,"integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]},"offset":"11524479"},"json-schema-draft-07.json":{"size":3811,"integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]},"offset":"11527928"},"json-schema-secure.json":{"size":2521,"integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]},"offset":"11531739"},"jtd-schema.ts":{"size":2586,"integrity":{"algorithm":"SHA256","hash":"76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003","blockSize":4194304,"blocks":["76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003"]},"offset":"11534260"},"json-schema-2020-12":{"files":{"index.ts":{"size":982,"integrity":{"algorithm":"SHA256","hash":"9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000","blockSize":4194304,"blocks":["9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000"]},"offset":"11536846"},"schema.json":{"size":2166,"integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]},"offset":"11537828"},"meta":{"files":{"applicator.json":{"size":1441,"integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]},"offset":"11539994"},"content.json":{"size":479,"integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]},"offset":"11541435"},"core.json":{"size":1344,"integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]},"offset":"11541914"},"format-annotation.json":{"size":420,"integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]},"offset":"11543258"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]},"offset":"11543678"},"unevaluated.json":{"size":472,"integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]},"offset":"11544436"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]},"offset":"11544908"}}}}},"json-schema-2019-09":{"files":{"index.ts":{"size":899,"integrity":{"algorithm":"SHA256","hash":"b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d","blockSize":4194304,"blocks":["b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d"]},"offset":"11547172"},"schema.json":{"size":1579,"integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]},"offset":"11548071"},"meta":{"files":{"applicator.json":{"size":1566,"integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]},"offset":"11549650"},"content.json":{"size":477,"integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]},"offset":"11551216"},"core.json":{"size":1273,"integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]},"offset":"11551693"},"format.json":{"size":375,"integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]},"offset":"11552966"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]},"offset":"11553341"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]},"offset":"11554099"}}}}}}},"compile":{"files":{"errors.ts":{"size":5269,"integrity":{"algorithm":"SHA256","hash":"088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480","blockSize":4194304,"blocks":["088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480"]},"offset":"11556363"},"index.ts":{"size":12299,"integrity":{"algorithm":"SHA256","hash":"fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869","blockSize":4194304,"blocks":["fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869"]},"offset":"11561632"},"names.ts":{"size":1116,"integrity":{"algorithm":"SHA256","hash":"7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64","blockSize":4194304,"blocks":["7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64"]},"offset":"11573931"},"ref_error.ts":{"size":513,"integrity":{"algorithm":"SHA256","hash":"1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac","blockSize":4194304,"blocks":["1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac"]},"offset":"11575047"},"resolve.ts":{"size":4674,"integrity":{"algorithm":"SHA256","hash":"83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5","blockSize":4194304,"blocks":["83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5"]},"offset":"11575560"},"rules.ts":{"size":1456,"integrity":{"algorithm":"SHA256","hash":"d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85","blockSize":4194304,"blocks":["d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85"]},"offset":"11580234"},"util.ts":{"size":6639,"integrity":{"algorithm":"SHA256","hash":"2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad","blockSize":4194304,"blocks":["2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad"]},"offset":"11581690"},"validate":{"files":{"applicability.ts":{"size":739,"integrity":{"algorithm":"SHA256","hash":"22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497","blockSize":4194304,"blocks":["22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497"]},"offset":"11588329"},"boolSchema.ts":{"size":1298,"integrity":{"algorithm":"SHA256","hash":"e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf","blockSize":4194304,"blocks":["e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf"]},"offset":"11589068"},"dataType.ts":{"size":7094,"integrity":{"algorithm":"SHA256","hash":"37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3","blockSize":4194304,"blocks":["37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3"]},"offset":"11590366"},"defaults.ts":{"size":1215,"integrity":{"algorithm":"SHA256","hash":"8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27","blockSize":4194304,"blocks":["8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27"]},"offset":"11597460"},"index.ts":{"size":19445,"integrity":{"algorithm":"SHA256","hash":"841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48","blockSize":4194304,"blocks":["841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48"]},"offset":"11598675"},"keyword.ts":{"size":5337,"integrity":{"algorithm":"SHA256","hash":"83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f","blockSize":4194304,"blocks":["83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f"]},"offset":"11618120"},"subschema.ts":{"size":4366,"integrity":{"algorithm":"SHA256","hash":"79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e","blockSize":4194304,"blocks":["79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e"]},"offset":"11623457"}}},"jtd":{"files":{"parse.ts":{"size":12345,"integrity":{"algorithm":"SHA256","hash":"3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6","blockSize":4194304,"blocks":["3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6"]},"offset":"11627823"},"serialize.ts":{"size":8573,"integrity":{"algorithm":"SHA256","hash":"f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7","blockSize":4194304,"blocks":["f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7"]},"offset":"11640168"},"types.ts":{"size":311,"integrity":{"algorithm":"SHA256","hash":"4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822","blockSize":4194304,"blocks":["4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822"]},"offset":"11648741"}}},"codegen":{"files":{"code.ts":{"size":4474,"integrity":{"algorithm":"SHA256","hash":"3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85","blockSize":4194304,"blocks":["3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85"]},"offset":"11649052"},"index.ts":{"size":23051,"integrity":{"algorithm":"SHA256","hash":"5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6","blockSize":4194304,"blocks":["5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6"]},"offset":"11653526"},"scope.ts":{"size":5981,"integrity":{"algorithm":"SHA256","hash":"a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16","blockSize":4194304,"blocks":["a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16"]},"offset":"11676577"}}}}}}},"dist":{"files":{"2019.js":{"size":3188,"integrity":{"algorithm":"SHA256","hash":"4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4","blockSize":4194304,"blocks":["4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4"]},"offset":"11682558"},"2019.js.map":{"size":1639,"integrity":{"algorithm":"SHA256","hash":"a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f","blockSize":4194304,"blocks":["a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f"]},"offset":"11685746"},"2020.js":{"size":2894,"integrity":{"algorithm":"SHA256","hash":"908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a","blockSize":4194304,"blocks":["908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a"]},"offset":"11687385"},"2020.js.map":{"size":1473,"integrity":{"algorithm":"SHA256","hash":"845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5","blockSize":4194304,"blocks":["845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5"]},"offset":"11690279"},"ajv.js":{"size":2841,"integrity":{"algorithm":"SHA256","hash":"edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297","blockSize":4194304,"blocks":["edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297"]},"offset":"11691752"},"ajv.js.map":{"size":1476,"integrity":{"algorithm":"SHA256","hash":"f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44","blockSize":4194304,"blocks":["f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44"]},"offset":"11694593"},"core.js":{"size":25202,"integrity":{"algorithm":"SHA256","hash":"51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603","blockSize":4194304,"blocks":["51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603"]},"offset":"11696069"},"core.js.map":{"size":21608,"integrity":{"algorithm":"SHA256","hash":"0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472","blockSize":4194304,"blocks":["0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472"]},"offset":"11721271"},"jtd.js":{"size":3360,"integrity":{"algorithm":"SHA256","hash":"9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44","blockSize":4194304,"blocks":["9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44"]},"offset":"11742879"},"jtd.js.map":{"size":2036,"integrity":{"algorithm":"SHA256","hash":"b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51","blockSize":4194304,"blocks":["b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51"]},"offset":"11746239"},"vocabularies":{"files":{"code.js":{"size":6216,"integrity":{"algorithm":"SHA256","hash":"9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63","blockSize":4194304,"blocks":["9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63"]},"offset":"11748275"},"code.js.map":{"size":6030,"integrity":{"algorithm":"SHA256","hash":"1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534","blockSize":4194304,"blocks":["1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534"]},"offset":"11754491"},"draft2020.js":{"size":762,"integrity":{"algorithm":"SHA256","hash":"2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445","blockSize":4194304,"blocks":["2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445"]},"offset":"11760521"},"draft2020.js.map":{"size":419,"integrity":{"algorithm":"SHA256","hash":"a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891","blockSize":4194304,"blocks":["a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891"]},"offset":"11761283"},"draft7.js":{"size":557,"integrity":{"algorithm":"SHA256","hash":"8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170","blockSize":4194304,"blocks":["8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170"]},"offset":"11761702"},"draft7.js.map":{"size":328,"integrity":{"algorithm":"SHA256","hash":"e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62","blockSize":4194304,"blocks":["e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62"]},"offset":"11762259"},"errors.js":{"size":111,"integrity":{"algorithm":"SHA256","hash":"7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc","blockSize":4194304,"blocks":["7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc"]},"offset":"11762587"},"errors.js.map":{"size":120,"integrity":{"algorithm":"SHA256","hash":"d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675","blockSize":4194304,"blocks":["d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675"]},"offset":"11762698"},"metadata.js":{"size":427,"integrity":{"algorithm":"SHA256","hash":"45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609","blockSize":4194304,"blocks":["45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609"]},"offset":"11762818"},"metadata.js.map":{"size":299,"integrity":{"algorithm":"SHA256","hash":"7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd","blockSize":4194304,"blocks":["7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd"]},"offset":"11763245"},"next.js":{"size":433,"integrity":{"algorithm":"SHA256","hash":"491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7","blockSize":4194304,"blocks":["491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7"]},"offset":"11763544"},"next.js.map":{"size":243,"integrity":{"algorithm":"SHA256","hash":"79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918","blockSize":4194304,"blocks":["79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918"]},"offset":"11763977"},"validation":{"files":{"const.js":{"size":852,"integrity":{"algorithm":"SHA256","hash":"ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a","blockSize":4194304,"blocks":["ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a"]},"offset":"11764220"},"const.js.map":{"size":819,"integrity":{"algorithm":"SHA256","hash":"5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea","blockSize":4194304,"blocks":["5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea"]},"offset":"11765072"},"dependentRequired.js":{"size":403,"integrity":{"algorithm":"SHA256","hash":"cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa","blockSize":4194304,"blocks":["cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa"]},"offset":"11765891"},"dependentRequired.js.map":{"size":376,"integrity":{"algorithm":"SHA256","hash":"62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4","blockSize":4194304,"blocks":["62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4"]},"offset":"11766294"},"enum.js":{"size":1901,"integrity":{"algorithm":"SHA256","hash":"61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22","blockSize":4194304,"blocks":["61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22"]},"offset":"11766670"},"enum.js.map":{"size":1999,"integrity":{"algorithm":"SHA256","hash":"3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b","blockSize":4194304,"blocks":["3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b"]},"offset":"11768571"},"index.js":{"size":1036,"integrity":{"algorithm":"SHA256","hash":"4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4","blockSize":4194304,"blocks":["4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4"]},"offset":"11770570"},"index.js.map":{"size":595,"integrity":{"algorithm":"SHA256","hash":"42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4","blockSize":4194304,"blocks":["42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4"]},"offset":"11771606"},"limitContains.js":{"size":495,"integrity":{"algorithm":"SHA256","hash":"0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d","blockSize":4194304,"blocks":["0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d"]},"offset":"11772201"},"limitContains.js.map":{"size":473,"integrity":{"algorithm":"SHA256","hash":"56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445","blockSize":4194304,"blocks":["56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445"]},"offset":"11772696"},"limitItems.js":{"size":852,"integrity":{"algorithm":"SHA256","hash":"49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec","blockSize":4194304,"blocks":["49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec"]},"offset":"11773169"},"limitItems.js.map":{"size":905,"integrity":{"algorithm":"SHA256","hash":"4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459","blockSize":4194304,"blocks":["4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459"]},"offset":"11774021"},"limitLength.js":{"size":1130,"integrity":{"algorithm":"SHA256","hash":"379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2","blockSize":4194304,"blocks":["379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2"]},"offset":"11774926"},"limitLength.js.map":{"size":1145,"integrity":{"algorithm":"SHA256","hash":"bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5","blockSize":4194304,"blocks":["bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5"]},"offset":"11776056"},"limitNumber.js":{"size":1036,"integrity":{"algorithm":"SHA256","hash":"3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65","blockSize":4194304,"blocks":["3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65"]},"offset":"11777201"},"limitNumber.js.map":{"size":1300,"integrity":{"algorithm":"SHA256","hash":"8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f","blockSize":4194304,"blocks":["8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f"]},"offset":"11778237"},"limitProperties.js":{"size":896,"integrity":{"algorithm":"SHA256","hash":"8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac","blockSize":4194304,"blocks":["8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac"]},"offset":"11779537"},"limitProperties.js.map":{"size":915,"integrity":{"algorithm":"SHA256","hash":"0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa","blockSize":4194304,"blocks":["0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa"]},"offset":"11780433"},"multipleOf.js":{"size":1023,"integrity":{"algorithm":"SHA256","hash":"df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd","blockSize":4194304,"blocks":["df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd"]},"offset":"11781348"},"multipleOf.js.map":{"size":986,"integrity":{"algorithm":"SHA256","hash":"ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69","blockSize":4194304,"blocks":["ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69"]},"offset":"11782371"},"pattern.js":{"size":1323,"integrity":{"algorithm":"SHA256","hash":"86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195","blockSize":4194304,"blocks":["86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195"]},"offset":"11783357"},"pattern.js.map":{"size":1449,"integrity":{"algorithm":"SHA256","hash":"87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77","blockSize":4194304,"blocks":["87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77"]},"offset":"11784680"},"required.js":{"size":3188,"integrity":{"algorithm":"SHA256","hash":"b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054","blockSize":4194304,"blocks":["b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054"]},"offset":"11786129"},"required.js.map":{"size":2994,"integrity":{"algorithm":"SHA256","hash":"93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd","blockSize":4194304,"blocks":["93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd"]},"offset":"11789317"},"uniqueItems.js":{"size":3037,"integrity":{"algorithm":"SHA256","hash":"666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52","blockSize":4194304,"blocks":["666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52"]},"offset":"11792311"},"uniqueItems.js.map":{"size":3354,"integrity":{"algorithm":"SHA256","hash":"ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5","blockSize":4194304,"blocks":["ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5"]},"offset":"11795348"}}},"unevaluated":{"files":{"index.js":{"size":350,"integrity":{"algorithm":"SHA256","hash":"4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4","blockSize":4194304,"blocks":["4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4"]},"offset":"11798702"},"index.js.map":{"size":236,"integrity":{"algorithm":"SHA256","hash":"8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be","blockSize":4194304,"blocks":["8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be"]},"offset":"11799052"},"unevaluatedItems.js":{"size":1588,"integrity":{"algorithm":"SHA256","hash":"4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda","blockSize":4194304,"blocks":["4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda"]},"offset":"11799288"},"unevaluatedItems.js.map":{"size":1813,"integrity":{"algorithm":"SHA256","hash":"03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8","blockSize":4194304,"blocks":["03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8"]},"offset":"11800876"},"unevaluatedProperties.js":{"size":2608,"integrity":{"algorithm":"SHA256","hash":"665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe","blockSize":4194304,"blocks":["665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe"]},"offset":"11802689"},"unevaluatedProperties.js.map":{"size":2518,"integrity":{"algorithm":"SHA256","hash":"7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0","blockSize":4194304,"blocks":["7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0"]},"offset":"11805297"}}},"jtd":{"files":{"discriminator.js":{"size":2785,"integrity":{"algorithm":"SHA256","hash":"14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2","blockSize":4194304,"blocks":["14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2"]},"offset":"11807815"},"discriminator.js.map":{"size":2701,"integrity":{"algorithm":"SHA256","hash":"c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848","blockSize":4194304,"blocks":["c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848"]},"offset":"11810600"},"elements.js":{"size":949,"integrity":{"algorithm":"SHA256","hash":"b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b","blockSize":4194304,"blocks":["b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b"]},"offset":"11813301"},"elements.js.map":{"size":908,"integrity":{"algorithm":"SHA256","hash":"2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05","blockSize":4194304,"blocks":["2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05"]},"offset":"11814250"},"enum.js":{"size":1745,"integrity":{"algorithm":"SHA256","hash":"4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154","blockSize":4194304,"blocks":["4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154"]},"offset":"11815158"},"enum.js.map":{"size":1708,"integrity":{"algorithm":"SHA256","hash":"87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff","blockSize":4194304,"blocks":["87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff"]},"offset":"11816903"},"error.js":{"size":893,"integrity":{"algorithm":"SHA256","hash":"d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9","blockSize":4194304,"blocks":["d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9"]},"offset":"11818611"},"error.js.map":{"size":716,"integrity":{"algorithm":"SHA256","hash":"4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f","blockSize":4194304,"blocks":["4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f"]},"offset":"11819504"},"index.js":{"size":962,"integrity":{"algorithm":"SHA256","hash":"c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d","blockSize":4194304,"blocks":["c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d"]},"offset":"11820220"},"index.js.map":{"size":530,"integrity":{"algorithm":"SHA256","hash":"31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028","blockSize":4194304,"blocks":["31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028"]},"offset":"11821182"},"metadata.js":{"size":810,"integrity":{"algorithm":"SHA256","hash":"237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68","blockSize":4194304,"blocks":["237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68"]},"offset":"11821712"},"metadata.js.map":{"size":797,"integrity":{"algorithm":"SHA256","hash":"b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538","blockSize":4194304,"blocks":["b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538"]},"offset":"11822522"},"nullable.js":{"size":859,"integrity":{"algorithm":"SHA256","hash":"ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a","blockSize":4194304,"blocks":["ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a"]},"offset":"11823319"},"nullable.js.map":{"size":821,"integrity":{"algorithm":"SHA256","hash":"4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08","blockSize":4194304,"blocks":["4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08"]},"offset":"11824178"},"optionalProperties.js":{"size":436,"integrity":{"algorithm":"SHA256","hash":"82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62","blockSize":4194304,"blocks":["82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62"]},"offset":"11824999"},"optionalProperties.js.map":{"size":398,"integrity":{"algorithm":"SHA256","hash":"58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898","blockSize":4194304,"blocks":["58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898"]},"offset":"11825435"},"properties.js":{"size":6320,"integrity":{"algorithm":"SHA256","hash":"4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35","blockSize":4194304,"blocks":["4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35"]},"offset":"11825833"},"properties.js.map":{"size":5884,"integrity":{"algorithm":"SHA256","hash":"7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380","blockSize":4194304,"blocks":["7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380"]},"offset":"11832153"},"ref.js":{"size":2648,"integrity":{"algorithm":"SHA256","hash":"4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460","blockSize":4194304,"blocks":["4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460"]},"offset":"11838037"},"ref.js.map":{"size":2476,"integrity":{"algorithm":"SHA256","hash":"1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001","blockSize":4194304,"blocks":["1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001"]},"offset":"11840685"},"type.js":{"size":2706,"integrity":{"algorithm":"SHA256","hash":"f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c","blockSize":4194304,"blocks":["f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c"]},"offset":"11843161"},"type.js.map":{"size":2614,"integrity":{"algorithm":"SHA256","hash":"8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2","blockSize":4194304,"blocks":["8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2"]},"offset":"11845867"},"union.js":{"size":343,"integrity":{"algorithm":"SHA256","hash":"f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280","blockSize":4194304,"blocks":["f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280"]},"offset":"11848481"},"union.js.map":{"size":320,"integrity":{"algorithm":"SHA256","hash":"53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519","blockSize":4194304,"blocks":["53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519"]},"offset":"11848824"},"values.js":{"size":1838,"integrity":{"algorithm":"SHA256","hash":"6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2","blockSize":4194304,"blocks":["6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2"]},"offset":"11849144"},"values.js.map":{"size":1783,"integrity":{"algorithm":"SHA256","hash":"0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a","blockSize":4194304,"blocks":["0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a"]},"offset":"11850982"}}},"format":{"files":{"format.js":{"size":4317,"integrity":{"algorithm":"SHA256","hash":"6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f","blockSize":4194304,"blocks":["6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f"]},"offset":"11852765"},"format.js.map":{"size":3832,"integrity":{"algorithm":"SHA256","hash":"35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5","blockSize":4194304,"blocks":["35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5"]},"offset":"11857082"},"index.js":{"size":209,"integrity":{"algorithm":"SHA256","hash":"d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67","blockSize":4194304,"blocks":["d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67"]},"offset":"11860914"},"index.js.map":{"size":205,"integrity":{"algorithm":"SHA256","hash":"ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d","blockSize":4194304,"blocks":["ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d"]},"offset":"11861123"}}},"dynamic":{"files":{"dynamicAnchor.js":{"size":1261,"integrity":{"algorithm":"SHA256","hash":"78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7","blockSize":4194304,"blocks":["78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7"]},"offset":"11861328"},"dynamicAnchor.js.map":{"size":1351,"integrity":{"algorithm":"SHA256","hash":"a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7","blockSize":4194304,"blocks":["a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7"]},"offset":"11862589"},"dynamicRef.js":{"size":1985,"integrity":{"algorithm":"SHA256","hash":"acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917","blockSize":4194304,"blocks":["acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917"]},"offset":"11863940"},"dynamicRef.js.map":{"size":1679,"integrity":{"algorithm":"SHA256","hash":"4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f","blockSize":4194304,"blocks":["4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f"]},"offset":"11865925"},"index.js":{"size":457,"integrity":{"algorithm":"SHA256","hash":"8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b","blockSize":4194304,"blocks":["8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b"]},"offset":"11867604"},"index.js.map":{"size":278,"integrity":{"algorithm":"SHA256","hash":"cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14","blockSize":4194304,"blocks":["cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14"]},"offset":"11868061"},"recursiveAnchor.js":{"size":522,"integrity":{"algorithm":"SHA256","hash":"9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76","blockSize":4194304,"blocks":["9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76"]},"offset":"11868339"},"recursiveAnchor.js.map":{"size":435,"integrity":{"algorithm":"SHA256","hash":"14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f","blockSize":4194304,"blocks":["14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f"]},"offset":"11868861"},"recursiveRef.js":{"size":325,"integrity":{"algorithm":"SHA256","hash":"7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d","blockSize":4194304,"blocks":["7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d"]},"offset":"11869296"},"recursiveRef.js.map":{"size":339,"integrity":{"algorithm":"SHA256","hash":"aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6","blockSize":4194304,"blocks":["aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6"]},"offset":"11869621"}}},"discriminator":{"files":{"index.js":{"size":4845,"integrity":{"algorithm":"SHA256","hash":"b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e","blockSize":4194304,"blocks":["b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e"]},"offset":"11869960"},"index.js.map":{"size":4243,"integrity":{"algorithm":"SHA256","hash":"5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2","blockSize":4194304,"blocks":["5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2"]},"offset":"11874805"},"types.js":{"size":308,"integrity":{"algorithm":"SHA256","hash":"2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa","blockSize":4194304,"blocks":["2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa"]},"offset":"11879048"},"types.js.map":{"size":239,"integrity":{"algorithm":"SHA256","hash":"4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa","blockSize":4194304,"blocks":["4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa"]},"offset":"11879356"}}},"core":{"files":{"id.js":{"size":267,"integrity":{"algorithm":"SHA256","hash":"49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11","blockSize":4194304,"blocks":["49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11"]},"offset":"11879595"},"id.js.map":{"size":257,"integrity":{"algorithm":"SHA256","hash":"fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897","blockSize":4194304,"blocks":["fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897"]},"offset":"11879862"},"index.js":{"size":357,"integrity":{"algorithm":"SHA256","hash":"f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e","blockSize":4194304,"blocks":["f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e"]},"offset":"11880119"},"index.js.map":{"size":306,"integrity":{"algorithm":"SHA256","hash":"47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d","blockSize":4194304,"blocks":["47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d"]},"offset":"11880476"},"ref.js":{"size":5234,"integrity":{"algorithm":"SHA256","hash":"1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1","blockSize":4194304,"blocks":["1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1"]},"offset":"11880782"},"ref.js.map":{"size":5094,"integrity":{"algorithm":"SHA256","hash":"102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745","blockSize":4194304,"blocks":["102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745"]},"offset":"11886016"}}},"applicator":{"files":{"additionalItems.js":{"size":1931,"integrity":{"algorithm":"SHA256","hash":"7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099","blockSize":4194304,"blocks":["7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099"]},"offset":"11891110"},"additionalItems.js.map":{"size":2093,"integrity":{"algorithm":"SHA256","hash":"f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571","blockSize":4194304,"blocks":["f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571"]},"offset":"11893041"},"additionalProperties.js":{"size":4309,"integrity":{"algorithm":"SHA256","hash":"e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a","blockSize":4194304,"blocks":["e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a"]},"offset":"11895134"},"additionalProperties.js.map":{"size":3762,"integrity":{"algorithm":"SHA256","hash":"90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a","blockSize":4194304,"blocks":["90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a"]},"offset":"11899443"},"allOf.js":{"size":756,"integrity":{"algorithm":"SHA256","hash":"98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7","blockSize":4194304,"blocks":["98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7"]},"offset":"11903205"},"allOf.js.map":{"size":812,"integrity":{"algorithm":"SHA256","hash":"bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b","blockSize":4194304,"blocks":["bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b"]},"offset":"11903961"},"anyOf.js":{"size":343,"integrity":{"algorithm":"SHA256","hash":"8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5","blockSize":4194304,"blocks":["8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5"]},"offset":"11904773"},"anyOf.js.map":{"size":327,"integrity":{"algorithm":"SHA256","hash":"c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3","blockSize":4194304,"blocks":["c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3"]},"offset":"11905116"},"contains.js":{"size":3680,"integrity":{"algorithm":"SHA256","hash":"56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c","blockSize":4194304,"blocks":["56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c"]},"offset":"11905443"},"contains.js.map":{"size":3843,"integrity":{"algorithm":"SHA256","hash":"b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069","blockSize":4194304,"blocks":["b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069"]},"offset":"11909123"},"dependencies.js":{"size":3198,"integrity":{"algorithm":"SHA256","hash":"c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b","blockSize":4194304,"blocks":["c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b"]},"offset":"11912966"},"dependencies.js.map":{"size":3172,"integrity":{"algorithm":"SHA256","hash":"58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af","blockSize":4194304,"blocks":["58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af"]},"offset":"11916164"},"dependentSchemas.js":{"size":354,"integrity":{"algorithm":"SHA256","hash":"d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e","blockSize":4194304,"blocks":["d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e"]},"offset":"11919336"},"dependentSchemas.js.map":{"size":353,"integrity":{"algorithm":"SHA256","hash":"acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69","blockSize":4194304,"blocks":["acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69"]},"offset":"11919690"},"if.js":{"size":2438,"integrity":{"algorithm":"SHA256","hash":"42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4","blockSize":4194304,"blocks":["42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4"]},"offset":"11920043"},"if.js.map":{"size":2455,"integrity":{"algorithm":"SHA256","hash":"ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939","blockSize":4194304,"blocks":["ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939"]},"offset":"11922481"},"index.js":{"size":1529,"integrity":{"algorithm":"SHA256","hash":"5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3","blockSize":4194304,"blocks":["5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3"]},"offset":"11924936"},"index.js.map":{"size":766,"integrity":{"algorithm":"SHA256","hash":"0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50","blockSize":4194304,"blocks":["0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50"]},"offset":"11926465"},"items.js":{"size":1993,"integrity":{"algorithm":"SHA256","hash":"fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e","blockSize":4194304,"blocks":["fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e"]},"offset":"11927231"},"items.js.map":{"size":2052,"integrity":{"algorithm":"SHA256","hash":"a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f","blockSize":4194304,"blocks":["a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f"]},"offset":"11929224"},"items2020.js":{"size":1037,"integrity":{"algorithm":"SHA256","hash":"c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f","blockSize":4194304,"blocks":["c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f"]},"offset":"11931276"},"items2020.js.map":{"size":947,"integrity":{"algorithm":"SHA256","hash":"8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc","blockSize":4194304,"blocks":["8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc"]},"offset":"11932313"},"not.js":{"size":773,"integrity":{"algorithm":"SHA256","hash":"ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718","blockSize":4194304,"blocks":["ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718"]},"offset":"11933260"},"not.js.map":{"size":831,"integrity":{"algorithm":"SHA256","hash":"c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db","blockSize":4194304,"blocks":["c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db"]},"offset":"11934033"},"oneOf.js":{"size":2257,"integrity":{"algorithm":"SHA256","hash":"e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2","blockSize":4194304,"blocks":["e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2"]},"offset":"11934864"},"oneOf.js.map":{"size":2046,"integrity":{"algorithm":"SHA256","hash":"ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526","blockSize":4194304,"blocks":["ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526"]},"offset":"11937121"},"patternProperties.js":{"size":3236,"integrity":{"algorithm":"SHA256","hash":"0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655","blockSize":4194304,"blocks":["0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655"]},"offset":"11939167"},"patternProperties.js.map":{"size":2734,"integrity":{"algorithm":"SHA256","hash":"a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1","blockSize":4194304,"blocks":["a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1"]},"offset":"11942403"},"prefixItems.js":{"size":354,"integrity":{"algorithm":"SHA256","hash":"16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23","blockSize":4194304,"blocks":["16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23"]},"offset":"11945137"},"prefixItems.js.map":{"size":381,"integrity":{"algorithm":"SHA256","hash":"1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c","blockSize":4194304,"blocks":["1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c"]},"offset":"11945491"},"properties.js":{"size":2153,"integrity":{"algorithm":"SHA256","hash":"c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f","blockSize":4194304,"blocks":["c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f"]},"offset":"11945872"},"properties.js.map":{"size":2054,"integrity":{"algorithm":"SHA256","hash":"33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3","blockSize":4194304,"blocks":["33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3"]},"offset":"11948025"},"propertyNames.js":{"size":1221,"integrity":{"algorithm":"SHA256","hash":"b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7","blockSize":4194304,"blocks":["b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7"]},"offset":"11950079"},"propertyNames.js.map":{"size":1230,"integrity":{"algorithm":"SHA256","hash":"a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64","blockSize":4194304,"blocks":["a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64"]},"offset":"11951300"},"thenElse.js":{"size":446,"integrity":{"algorithm":"SHA256","hash":"9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d","blockSize":4194304,"blocks":["9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d"]},"offset":"11952530"},"thenElse.js.map":{"size":442,"integrity":{"algorithm":"SHA256","hash":"474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e","blockSize":4194304,"blocks":["474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e"]},"offset":"11952976"}}}}},"types":{"files":{"index.js":{"size":110,"integrity":{"algorithm":"SHA256","hash":"fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71","blockSize":4194304,"blocks":["fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71"]},"offset":"11953418"},"index.js.map":{"size":111,"integrity":{"algorithm":"SHA256","hash":"dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6","blockSize":4194304,"blocks":["dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6"]},"offset":"11953528"},"json-schema.js":{"size":116,"integrity":{"algorithm":"SHA256","hash":"2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28","blockSize":4194304,"blocks":["2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28"]},"offset":"11953639"},"json-schema.js.map":{"size":123,"integrity":{"algorithm":"SHA256","hash":"c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221","blockSize":4194304,"blocks":["c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221"]},"offset":"11953755"},"jtd-schema.js":{"size":115,"integrity":{"algorithm":"SHA256","hash":"6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d","blockSize":4194304,"blocks":["6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d"]},"offset":"11953878"},"jtd-schema.js.map":{"size":121,"integrity":{"algorithm":"SHA256","hash":"c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9","blockSize":4194304,"blocks":["c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9"]},"offset":"11953993"}}},"standalone":{"files":{"index.js":{"size":4480,"integrity":{"algorithm":"SHA256","hash":"361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f","blockSize":4194304,"blocks":["361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f"]},"offset":"11954114"},"index.js.map":{"size":4078,"integrity":{"algorithm":"SHA256","hash":"a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860","blockSize":4194304,"blocks":["a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860"]},"offset":"11958594"},"instance.js":{"size":1015,"integrity":{"algorithm":"SHA256","hash":"4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3","blockSize":4194304,"blocks":["4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3"]},"offset":"11962672"},"instance.js.map":{"size":1091,"integrity":{"algorithm":"SHA256","hash":"7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7","blockSize":4194304,"blocks":["7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7"]},"offset":"11963687"}}},"runtime":{"files":{"equal.js":{"size":286,"integrity":{"algorithm":"SHA256","hash":"c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274","blockSize":4194304,"blocks":["c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274"]},"offset":"11964778"},"equal.js.map":{"size":199,"integrity":{"algorithm":"SHA256","hash":"addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae","blockSize":4194304,"blocks":["addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae"]},"offset":"11965064"},"parseJson.js":{"size":5401,"integrity":{"algorithm":"SHA256","hash":"1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e","blockSize":4194304,"blocks":["1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e"]},"offset":"11965263"},"parseJson.js.map":{"size":5339,"integrity":{"algorithm":"SHA256","hash":"cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7","blockSize":4194304,"blocks":["cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7"]},"offset":"11970664"},"quote.js":{"size":943,"integrity":{"algorithm":"SHA256","hash":"1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2","blockSize":4194304,"blocks":["1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2"]},"offset":"11976003"},"quote.js.map":{"size":877,"integrity":{"algorithm":"SHA256","hash":"299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9","blockSize":4194304,"blocks":["299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9"]},"offset":"11976946"},"re2.js":{"size":213,"integrity":{"algorithm":"SHA256","hash":"e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361","blockSize":4194304,"blocks":["e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361"]},"offset":"11977823"},"re2.js.map":{"size":182,"integrity":{"algorithm":"SHA256","hash":"891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc","blockSize":4194304,"blocks":["891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc"]},"offset":"11978036"},"timestamp.js":{"size":1536,"integrity":{"algorithm":"SHA256","hash":"05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef","blockSize":4194304,"blocks":["05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef"]},"offset":"11978218"},"timestamp.js.map":{"size":1994,"integrity":{"algorithm":"SHA256","hash":"4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe","blockSize":4194304,"blocks":["4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe"]},"offset":"11979754"},"ucs2length.js":{"size":808,"integrity":{"algorithm":"SHA256","hash":"1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890","blockSize":4194304,"blocks":["1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890"]},"offset":"11981748"},"ucs2length.js.map":{"size":728,"integrity":{"algorithm":"SHA256","hash":"5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d","blockSize":4194304,"blocks":["5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d"]},"offset":"11982556"},"uri.js":{"size":218,"integrity":{"algorithm":"SHA256","hash":"d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578","blockSize":4194304,"blocks":["d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578"]},"offset":"11983284"},"uri.js.map":{"size":182,"integrity":{"algorithm":"SHA256","hash":"7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955","blockSize":4194304,"blocks":["7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955"]},"offset":"11983502"},"validation_error.js":{"size":337,"integrity":{"algorithm":"SHA256","hash":"11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815","blockSize":4194304,"blocks":["11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815"]},"offset":"11983684"},"validation_error.js.map":{"size":332,"integrity":{"algorithm":"SHA256","hash":"833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2","blockSize":4194304,"blocks":["833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2"]},"offset":"11984021"}}},"refs":{"files":{"data.json":{"size":409,"integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]},"offset":"11984353"},"json-schema-draft-06.json":{"size":3449,"integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]},"offset":"11984762"},"json-schema-draft-07.json":{"size":3811,"integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]},"offset":"11988211"},"json-schema-secure.json":{"size":2521,"integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]},"offset":"11992022"},"jtd-schema.js":{"size":2882,"integrity":{"algorithm":"SHA256","hash":"ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92","blockSize":4194304,"blocks":["ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92"]},"offset":"11994543"},"jtd-schema.js.map":{"size":2824,"integrity":{"algorithm":"SHA256","hash":"732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b","blockSize":4194304,"blocks":["732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b"]},"offset":"11997425"},"json-schema-2020-12":{"files":{"index.js":{"size":1026,"integrity":{"algorithm":"SHA256","hash":"2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1","blockSize":4194304,"blocks":["2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1"]},"offset":"12000249"},"index.js.map":{"size":751,"integrity":{"algorithm":"SHA256","hash":"79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877","blockSize":4194304,"blocks":["79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877"]},"offset":"12001275"},"schema.json":{"size":2166,"integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]},"offset":"12002026"},"meta":{"files":{"applicator.json":{"size":1441,"integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]},"offset":"12004192"},"content.json":{"size":479,"integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]},"offset":"12005633"},"core.json":{"size":1344,"integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]},"offset":"12006112"},"format-annotation.json":{"size":420,"integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]},"offset":"12007456"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]},"offset":"12007876"},"unevaluated.json":{"size":472,"integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]},"offset":"12008634"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]},"offset":"12009106"}}}}},"json-schema-2019-09":{"files":{"index.js":{"size":938,"integrity":{"algorithm":"SHA256","hash":"ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d","blockSize":4194304,"blocks":["ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d"]},"offset":"12011370"},"index.js.map":{"size":726,"integrity":{"algorithm":"SHA256","hash":"3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01","blockSize":4194304,"blocks":["3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01"]},"offset":"12012308"},"schema.json":{"size":1579,"integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]},"offset":"12013034"},"meta":{"files":{"applicator.json":{"size":1566,"integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]},"offset":"12014613"},"content.json":{"size":477,"integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]},"offset":"12016179"},"core.json":{"size":1273,"integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]},"offset":"12016656"},"format.json":{"size":375,"integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]},"offset":"12017929"},"meta-data.json":{"size":758,"integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]},"offset":"12018304"},"validation.json":{"size":2264,"integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]},"offset":"12019062"}}}}}}},"compile":{"files":{"errors.js":{"size":5771,"integrity":{"algorithm":"SHA256","hash":"53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2","blockSize":4194304,"blocks":["53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2"]},"offset":"12021326"},"errors.js.map":{"size":6085,"integrity":{"algorithm":"SHA256","hash":"5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294","blockSize":4194304,"blocks":["5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294"]},"offset":"12027097"},"index.js":{"size":10046,"integrity":{"algorithm":"SHA256","hash":"05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac","blockSize":4194304,"blocks":["05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac"]},"offset":"12033182"},"index.js.map":{"size":9269,"integrity":{"algorithm":"SHA256","hash":"ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a","blockSize":4194304,"blocks":["ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a"]},"offset":"12043228"},"names.js":{"size":1440,"integrity":{"algorithm":"SHA256","hash":"3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493","blockSize":4194304,"blocks":["3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493"]},"offset":"12052497"},"names.js.map":{"size":974,"integrity":{"algorithm":"SHA256","hash":"2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7","blockSize":4194304,"blocks":["2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7"]},"offset":"12053937"},"ref_error.js":{"size":543,"integrity":{"algorithm":"SHA256","hash":"81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7","blockSize":4194304,"blocks":["81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7"]},"offset":"12054911"},"ref_error.js.map":{"size":474,"integrity":{"algorithm":"SHA256","hash":"3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b","blockSize":4194304,"blocks":["3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b"]},"offset":"12055454"},"resolve.js":{"size":5006,"integrity":{"algorithm":"SHA256","hash":"df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9","blockSize":4194304,"blocks":["df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9"]},"offset":"12055928"},"resolve.js.map":{"size":4850,"integrity":{"algorithm":"SHA256","hash":"837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce","blockSize":4194304,"blocks":["837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce"]},"offset":"12060934"},"rules.js":{"size":918,"integrity":{"algorithm":"SHA256","hash":"ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9","blockSize":4194304,"blocks":["ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9"]},"offset":"12065784"},"rules.js.map":{"size":1030,"integrity":{"algorithm":"SHA256","hash":"d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6","blockSize":4194304,"blocks":["d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6"]},"offset":"12066702"},"util.js":{"size":7103,"integrity":{"algorithm":"SHA256","hash":"fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5","blockSize":4194304,"blocks":["fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5"]},"offset":"12067732"},"util.js.map":{"size":7083,"integrity":{"algorithm":"SHA256","hash":"9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442","blockSize":4194304,"blocks":["9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442"]},"offset":"12074835"},"validate":{"files":{"applicability.js":{"size":853,"integrity":{"algorithm":"SHA256","hash":"50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0","blockSize":4194304,"blocks":["50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0"]},"offset":"12081918"},"applicability.js.map":{"size":775,"integrity":{"algorithm":"SHA256","hash":"399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad","blockSize":4194304,"blocks":["399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad"]},"offset":"12082771"},"boolSchema.js":{"size":1531,"integrity":{"algorithm":"SHA256","hash":"c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f","blockSize":4194304,"blocks":["c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f"]},"offset":"12083546"},"boolSchema.js.map":{"size":1380,"integrity":{"algorithm":"SHA256","hash":"d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9","blockSize":4194304,"blocks":["d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9"]},"offset":"12085077"},"dataType.js":{"size":8409,"integrity":{"algorithm":"SHA256","hash":"697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52","blockSize":4194304,"blocks":["697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52"]},"offset":"12086457"},"dataType.js.map":{"size":7776,"integrity":{"algorithm":"SHA256","hash":"5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08","blockSize":4194304,"blocks":["5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08"]},"offset":"12094866"},"defaults.js":{"size":1448,"integrity":{"algorithm":"SHA256","hash":"05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428","blockSize":4194304,"blocks":["05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428"]},"offset":"12102642"},"defaults.js.map":{"size":1342,"integrity":{"algorithm":"SHA256","hash":"dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5","blockSize":4194304,"blocks":["dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5"]},"offset":"12104090"},"index.js":{"size":20552,"integrity":{"algorithm":"SHA256","hash":"cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd","blockSize":4194304,"blocks":["cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd"]},"offset":"12105432"},"index.js.map":{"size":21391,"integrity":{"algorithm":"SHA256","hash":"fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c","blockSize":4194304,"blocks":["fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c"]},"offset":"12125984"},"keyword.js":{"size":5695,"integrity":{"algorithm":"SHA256","hash":"ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76","blockSize":4194304,"blocks":["ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76"]},"offset":"12147375"},"keyword.js.map":{"size":6011,"integrity":{"algorithm":"SHA256","hash":"3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e","blockSize":4194304,"blocks":["3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e"]},"offset":"12153070"},"subschema.js":{"size":3858,"integrity":{"algorithm":"SHA256","hash":"ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc","blockSize":4194304,"blocks":["ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc"]},"offset":"12159081"},"subschema.js.map":{"size":3148,"integrity":{"algorithm":"SHA256","hash":"9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a","blockSize":4194304,"blocks":["9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a"]},"offset":"12162939"}}},"jtd":{"files":{"parse.js":{"size":13727,"integrity":{"algorithm":"SHA256","hash":"548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f","blockSize":4194304,"blocks":["548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f"]},"offset":"12166087"},"parse.js.map":{"size":15725,"integrity":{"algorithm":"SHA256","hash":"90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0","blockSize":4194304,"blocks":["90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0"]},"offset":"12179814"},"serialize.js":{"size":9391,"integrity":{"algorithm":"SHA256","hash":"1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0","blockSize":4194304,"blocks":["1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0"]},"offset":"12195539"},"serialize.js.map":{"size":10737,"integrity":{"algorithm":"SHA256","hash":"faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd","blockSize":4194304,"blocks":["faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd"]},"offset":"12204930"},"types.js":{"size":291,"integrity":{"algorithm":"SHA256","hash":"e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78","blockSize":4194304,"blocks":["e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78"]},"offset":"12215667"},"types.js.map":{"size":236,"integrity":{"algorithm":"SHA256","hash":"b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5","blockSize":4194304,"blocks":["b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5"]},"offset":"12215958"}}},"codegen":{"files":{"code.js":{"size":4676,"integrity":{"algorithm":"SHA256","hash":"1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d","blockSize":4194304,"blocks":["1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d"]},"offset":"12216194"},"code.js.map":{"size":5309,"integrity":{"algorithm":"SHA256","hash":"6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60","blockSize":4194304,"blocks":["6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60"]},"offset":"12220870"},"index.js":{"size":23127,"integrity":{"algorithm":"SHA256","hash":"f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c","blockSize":4194304,"blocks":["f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c"]},"offset":"12226179"},"index.js.map":{"size":23829,"integrity":{"algorithm":"SHA256","hash":"081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc","blockSize":4194304,"blocks":["081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc"]},"offset":"12249306"},"scope.js":{"size":5198,"integrity":{"algorithm":"SHA256","hash":"d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286","blockSize":4194304,"blocks":["d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286"]},"offset":"12273135"},"scope.js.map":{"size":5174,"integrity":{"algorithm":"SHA256","hash":"a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec","blockSize":4194304,"blocks":["a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec"]},"offset":"12278333"}}}}}}}}},"json-schema-traverse":{"files":{".eslintrc.yml":{"size":630,"integrity":{"algorithm":"SHA256","hash":"b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc","blockSize":4194304,"blocks":["b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc"]},"offset":"12283507"},"LICENSE":{"size":1074,"integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]},"offset":"12284137"},"index.js":{"size":2428,"integrity":{"algorithm":"SHA256","hash":"024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350","blockSize":4194304,"blocks":["024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350"]},"offset":"12285211"},"package.json":{"size":553,"integrity":{"algorithm":"SHA256","hash":"c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262","blockSize":4194304,"blocks":["c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262"]},"offset":"12287639"},"spec":{"files":{".eslintrc.yml":{"size":91,"integrity":{"algorithm":"SHA256","hash":"8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c","blockSize":4194304,"blocks":["8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c"]},"offset":"12288192"},"index.spec.js":{"size":6042,"integrity":{"algorithm":"SHA256","hash":"40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69","blockSize":4194304,"blocks":["40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69"]},"offset":"12288283"},"fixtures":{"files":{"schema.js":{"size":5544,"integrity":{"algorithm":"SHA256","hash":"0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27","blockSize":4194304,"blocks":["0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27"]},"offset":"12294325"}}}}}}}}}}},"debounce-fn":{"files":{"index.js":{"size":1080,"integrity":{"algorithm":"SHA256","hash":"c9b8c0476e48445718d35a34c18dae9eb7b07f63e84cb827f4eeb26c13508ea6","blockSize":4194304,"blocks":["c9b8c0476e48445718d35a34c18dae9eb7b07f63e84cb827f4eeb26c13508ea6"]},"offset":"3364936"},"license":{"size":1117,"integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]},"offset":"3366016"},"package.json":{"size":589,"integrity":{"algorithm":"SHA256","hash":"659179dad80757bfed72bb36a4684c777960279aae9f8b53e245bd71e67ce661","blockSize":4194304,"blocks":["659179dad80757bfed72bb36a4684c777960279aae9f8b53e245bd71e67ce661"]},"offset":"3367133"}}},"dot-prop":{"files":{"index.js":{"size":2705,"integrity":{"algorithm":"SHA256","hash":"9f475c2dcec98af9a2b7fa5017f09e734808aa0c1c8c61ac38ad161764b47c65","blockSize":4194304,"blocks":["9f475c2dcec98af9a2b7fa5017f09e734808aa0c1c8c61ac38ad161764b47c65"]},"offset":"3367722"},"license":{"size":1117,"integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]},"offset":"3370427"},"package.json":{"size":634,"integrity":{"algorithm":"SHA256","hash":"db15174cbb71d9836de1ace1c959bd2a83e54fee14cf34446ddfd469e74fad78","blockSize":4194304,"blocks":["db15174cbb71d9836de1ace1c959bd2a83e54fee14cf34446ddfd469e74fad78"]},"offset":"3371544"}}},"electron-store":{"files":{"index.js":{"size":1869,"integrity":{"algorithm":"SHA256","hash":"addc2492877598e1f510627408578aef5087b63897c15d79d928f0cc7c762f22","blockSize":4194304,"blocks":["addc2492877598e1f510627408578aef5087b63897c15d79d928f0cc7c762f22"]},"offset":"3372178"},"license":{"size":1117,"integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]},"offset":"3374047"},"package.json":{"size":721,"integrity":{"algorithm":"SHA256","hash":"1d31c5380e311f73e43b32648aedcf5e96c13d148df4dd0ce426e2543ffc7f98","blockSize":4194304,"blocks":["1d31c5380e311f73e43b32648aedcf5e96c13d148df4dd0ce426e2543ffc7f98"]},"offset":"3375164"}}},"env-paths":{"files":{"index.js":{"size":2155,"integrity":{"algorithm":"SHA256","hash":"84351667051b005f9856319267407b06affad12888355462c7c8740f22ca3999","blockSize":4194304,"blocks":["84351667051b005f9856319267407b06affad12888355462c7c8740f22ca3999"]},"offset":"3375885"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"3378040"},"package.json":{"size":484,"integrity":{"algorithm":"SHA256","hash":"de9602e1b482b8748b5550711f10f24fcc73d916806e1db497876fb2842ae6ba","blockSize":4194304,"blocks":["de9602e1b482b8748b5550711f10f24fcc73d916806e1db497876fb2842ae6ba"]},"offset":"3379149"}}},"fast-deep-equal":{"files":{"LICENSE":{"size":1074,"integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]},"offset":"3379633"},"index.js":{"size":1177,"integrity":{"algorithm":"SHA256","hash":"eb469e206280321a3878f2335ec98aa2104a155079d8ed83a23029098dccd215","blockSize":4194304,"blocks":["eb469e206280321a3878f2335ec98aa2104a155079d8ed83a23029098dccd215"]},"offset":"3380707"},"package.json":{"size":754,"integrity":{"algorithm":"SHA256","hash":"8364d2abc7912ad54eba3447f9da67767652c15bd65c0f7b7f35646bb4556758","blockSize":4194304,"blocks":["8364d2abc7912ad54eba3447f9da67767652c15bd65c0f7b7f35646bb4556758"]},"offset":"3381884"},"react.js":{"size":1451,"integrity":{"algorithm":"SHA256","hash":"37cbd168dbd42c73119ce7326556bddef40b3a5fbd2e215cf81a7c78fb73ff9a","blockSize":4194304,"blocks":["37cbd168dbd42c73119ce7326556bddef40b3a5fbd2e215cf81a7c78fb73ff9a"]},"offset":"3382638"},"es6":{"files":{"index.js":{"size":1935,"integrity":{"algorithm":"SHA256","hash":"d7f027497048c75e17268dbc66b670579d4f70f2dc0e019cdc9edf5078c247d6","blockSize":4194304,"blocks":["d7f027497048c75e17268dbc66b670579d4f70f2dc0e019cdc9edf5078c247d6"]},"offset":"3384089"},"react.js":{"size":2209,"integrity":{"algorithm":"SHA256","hash":"366779cbb7821d26d18b9eaa12b6788cbb101cdbbabcae36f2919a5f48534ef0","blockSize":4194304,"blocks":["366779cbb7821d26d18b9eaa12b6788cbb101cdbbabcae36f2919a5f48534ef0"]},"offset":"3386024"}}}}},"fast-uri":{"files":{"LICENSE":{"size":1813,"integrity":{"algorithm":"SHA256","hash":"b010b0dfdfdb23d7396e03b82cd4621fc9bb8f95d6b0aea70b9c24e12074c786","blockSize":4194304,"blocks":["b010b0dfdfdb23d7396e03b82cd4621fc9bb8f95d6b0aea70b9c24e12074c786"]},"offset":"3388233"},"eslint.config.js":{"size":135,"integrity":{"algorithm":"SHA256","hash":"52e3a2601a98f23c954d664ab8de95fddb390789f8b067815e484b010d3da2d0","blockSize":4194304,"blocks":["52e3a2601a98f23c954d664ab8de95fddb390789f8b067815e484b010d3da2d0"]},"offset":"3390046"},"index.js":{"size":22061,"integrity":{"algorithm":"SHA256","hash":"e82d3e55d954483e4927f9740bc3113a24d19ef5a73c7962d8a93c499fc982ff","blockSize":4194304,"blocks":["e82d3e55d954483e4927f9740bc3113a24d19ef5a73c7962d8a93c499fc982ff"]},"offset":"3390181"},"package.json":{"size":827,"integrity":{"algorithm":"SHA256","hash":"3f634af8714c2ff477cf8e7b1338273ab069b9c8f306a895003f8a494bbbcc67","blockSize":4194304,"blocks":["3f634af8714c2ff477cf8e7b1338273ab069b9c8f306a895003f8a494bbbcc67"]},"offset":"3412242"},"tsconfig.json":{"size":166,"integrity":{"algorithm":"SHA256","hash":"6bbba68684f6d6f1613d9ae79de617c25d8d749f30942307faee46a6d2fd721f","blockSize":4194304,"blocks":["6bbba68684f6d6f1613d9ae79de617c25d8d749f30942307faee46a6d2fd721f"]},"offset":"3413069"},"types":{"files":{"index.test-d.ts":{"size":479,"integrity":{"algorithm":"SHA256","hash":"ad36147194c3ecfaecf55d75dd22f0b2c6b4ca476d6450cd307dceaf39012b46","blockSize":4194304,"blocks":["ad36147194c3ecfaecf55d75dd22f0b2c6b4ca476d6450cd307dceaf39012b46"]},"offset":"3413235"}}},"lib":{"files":{"schemes.js":{"size":7367,"integrity":{"algorithm":"SHA256","hash":"c2c61d3fd0bc63a587100928a399e75be8c420d210c439d75f7346da4aa4f3c3","blockSize":4194304,"blocks":["c2c61d3fd0bc63a587100928a399e75be8c420d210c439d75f7346da4aa4f3c3"]},"offset":"3413714"},"utils.js":{"size":20835,"integrity":{"algorithm":"SHA256","hash":"610a6cfa7b1c9d5689443b3a3d14af4c24afed51ef5852495ae1489ae455a9f4","blockSize":4194304,"blocks":["610a6cfa7b1c9d5689443b3a3d14af4c24afed51ef5852495ae1489ae455a9f4"]},"offset":"3421081"}}},"benchmark":{"files":{"benchmark.mjs":{"size":4421,"integrity":{"algorithm":"SHA256","hash":"45ba9783c3258e448b05bd371161ef9fcbeed332ba1e9455ca9c98edb24e1f33","blockSize":4194304,"blocks":["45ba9783c3258e448b05bd371161ef9fcbeed332ba1e9455ca9c98edb24e1f33"]},"offset":"3441916"},"equal.mjs":{"size":1305,"integrity":{"algorithm":"SHA256","hash":"36eb5b2acea9c4e969ab8fe028e88b781aa948e597368655a13528c3a93f1d39","blockSize":4194304,"blocks":["36eb5b2acea9c4e969ab8fe028e88b781aa948e597368655a13528c3a93f1d39"]},"offset":"3446337"},"non-simple-domain.mjs":{"size":838,"integrity":{"algorithm":"SHA256","hash":"303eb41faa6c2489b5086f3d2764bf6ecaf3b937b385647c6e8b14aaf2582524","blockSize":4194304,"blocks":["303eb41faa6c2489b5086f3d2764bf6ecaf3b937b385647c6e8b14aaf2582524"]},"offset":"3447642"},"package.json":{"size":220,"integrity":{"algorithm":"SHA256","hash":"7e88fa1a8044e61f8784ba64266d4d097b878867cf3b9d82fa13ea6f2022e310","blockSize":4194304,"blocks":["7e88fa1a8044e61f8784ba64266d4d097b878867cf3b9d82fa13ea6f2022e310"]},"offset":"3448480"},"string-array-to-hex-stripped.mjs":{"size":819,"integrity":{"algorithm":"SHA256","hash":"693d4a312b0e275e02ef5531d707ff7df6cddf14cd83bc09a79909ea2008bfd4","blockSize":4194304,"blocks":["693d4a312b0e275e02ef5531d707ff7df6cddf14cd83bc09a79909ea2008bfd4"]},"offset":"3448700"},"ws-is-secure.mjs":{"size":1891,"integrity":{"algorithm":"SHA256","hash":"6f105dc633aadd4bd4b8362765f4a1d44fb31fe0c8754cb11d73f27ff7d6527b","blockSize":4194304,"blocks":["6f105dc633aadd4bd4b8362765f4a1d44fb31fe0c8754cb11d73f27ff7d6527b"]},"offset":"3449519"}}}}},"is-obj":{"files":{"index.js":{"size":144,"integrity":{"algorithm":"SHA256","hash":"0833a3eed3b0075f23e58f0107bebdedec6db53b4e7b1034d7ea7c9cfb932b0b","blockSize":4194304,"blocks":["0833a3eed3b0075f23e58f0107bebdedec6db53b4e7b1034d7ea7c9cfb932b0b"]},"offset":"3451410"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"3451554"},"package.json":{"size":449,"integrity":{"algorithm":"SHA256","hash":"d86f9e3ed1d4a30339fe5cf042cab7a2415369922aee3a6b13bc7df40814c8c9","blockSize":4194304,"blocks":["d86f9e3ed1d4a30339fe5cf042cab7a2415369922aee3a6b13bc7df40814c8c9"]},"offset":"3452663"}}},"js-tokens":{"files":{"LICENSE":{"size":1103,"integrity":{"algorithm":"SHA256","hash":"2213d91c606205c71eb051a199478cdc2adde945893404d7f1421436dd6d5cc1","blockSize":4194304,"blocks":["2213d91c606205c71eb051a199478cdc2adde945893404d7f1421436dd6d5cc1"]},"offset":"3453112"},"index.js":{"size":1448,"integrity":{"algorithm":"SHA256","hash":"b6f81c0531fc09be2f8a26059a5cb9f47150e550471da0ace5705a26d3c6268e","blockSize":4194304,"blocks":["b6f81c0531fc09be2f8a26059a5cb9f47150e550471da0ace5705a26d3c6268e"]},"offset":"3454215"},"package.json":{"size":351,"integrity":{"algorithm":"SHA256","hash":"32e60270091a039120ffd0d41bee1f47c7ab58d7104a67a0eb0794c10cae1f38","blockSize":4194304,"blocks":["32e60270091a039120ffd0d41bee1f47c7ab58d7104a67a0eb0794c10cae1f38"]},"offset":"3455663"}}},"json-schema-typed":{"files":{"LICENSE":{"size":1386,"integrity":{"algorithm":"SHA256","hash":"59992f12a42bfad11b6586e1bffda51749bb468847ca27c7070647462a66ed7b","blockSize":4194304,"blocks":["59992f12a42bfad11b6586e1bffda51749bb468847ca27c7070647462a66ed7b"]},"offset":"3456014"},"package.json":{"size":1548,"integrity":{"algorithm":"SHA256","hash":"7e19955319863014a6161f4ad8655d7ed60ff94523e65a619c0eb498d96bd7ed","blockSize":4194304,"blocks":["7e19955319863014a6161f4ad8655d7ed60ff94523e65a619c0eb498d96bd7ed"]},"offset":"3457400"},"dist-web":{"files":{"index.js":{"size":2592,"integrity":{"algorithm":"SHA256","hash":"2720267bff58c5728dd9ea8cfb1de124ce525003ea58a692c0bdb473f2a8d7e0","blockSize":4194304,"blocks":["2720267bff58c5728dd9ea8cfb1de124ce525003ea58a692c0bdb473f2a8d7e0"]},"offset":"3458948"},"index.js.map":{"size":5058,"integrity":{"algorithm":"SHA256","hash":"8a7fdb4ab2111b6add021fa38aaf10ccc1cad3a5d5034e3e1150a2720105e7c3","blockSize":4194304,"blocks":["8a7fdb4ab2111b6add021fa38aaf10ccc1cad3a5d5034e3e1150a2720105e7c3"]},"offset":"3461540"}}},"dist-src":{"files":{"index.js":{"size":2511,"integrity":{"algorithm":"SHA256","hash":"d7019674db69d5a5b7443d643a5c909b7b0a320183cb9a149603fb35fa16bf06","blockSize":4194304,"blocks":["d7019674db69d5a5b7443d643a5c909b7b0a320183cb9a149603fb35fa16bf06"]},"offset":"3466598"}}},"dist-node":{"files":{"index.js":{"size":2596,"integrity":{"algorithm":"SHA256","hash":"9fbf92ce11a8e03f63fca828fb7aa814b8f35f0e9d78ed95242988c71a82a3e2","blockSize":4194304,"blocks":["9fbf92ce11a8e03f63fca828fb7aa814b8f35f0e9d78ed95242988c71a82a3e2"]},"offset":"3469109"},"index.js.map":{"size":5062,"integrity":{"algorithm":"SHA256","hash":"f79d09e7609ed719a725eadbb67efac05f551a6c3cc4af8279d9bcae3bbb6e82","blockSize":4194304,"blocks":["f79d09e7609ed719a725eadbb67efac05f551a6c3cc4af8279d9bcae3bbb6e82"]},"offset":"3471705"}}}}},"loose-envify":{"files":{"LICENSE":{"size":1100,"integrity":{"algorithm":"SHA256","hash":"4eb7543b08d955a6d23fcc224601d43ff566e775be918805e26210d7f6eb4893","blockSize":4194304,"blocks":["4eb7543b08d955a6d23fcc224601d43ff566e775be918805e26210d7f6eb4893"]},"offset":"3476767"},"cli.js":{"size":356,"integrity":{"algorithm":"SHA256","hash":"6c656109d637b5b3488d6c7ec911fb773b6f97e3ad44355aa0e143f56a596e89","blockSize":4194304,"blocks":["6c656109d637b5b3488d6c7ec911fb773b6f97e3ad44355aa0e143f56a596e89"]},"offset":"3477867","executable":true},"custom.js":{"size":83,"integrity":{"algorithm":"SHA256","hash":"d5ff96773c0361dfa19b6abfc151a0b6933e4b3e22be4f6123853019b51f9ec8","blockSize":4194304,"blocks":["d5ff96773c0361dfa19b6abfc151a0b6933e4b3e22be4f6123853019b51f9ec8"]},"offset":"3478223"},"index.js":{"size":72,"integrity":{"algorithm":"SHA256","hash":"4f69358a355fe134166716d787d47e6f6ceb7edd6a4ed271e8cca6533d822441","blockSize":4194304,"blocks":["4f69358a355fe134166716d787d47e6f6ceb7edd6a4ed271e8cca6533d822441"]},"offset":"3478306"},"loose-envify.js":{"size":791,"integrity":{"algorithm":"SHA256","hash":"6bb457be810953557b1e2dc697efb5a72ea8091fb49da840c18f4af84e27903c","blockSize":4194304,"blocks":["6bb457be810953557b1e2dc697efb5a72ea8091fb49da840c18f4af84e27903c"]},"offset":"3478378"},"package.json":{"size":606,"integrity":{"algorithm":"SHA256","hash":"1f0843ec8b9eacb9ec54ed601d0354a854dc587fa3c07509a8418ffd7b11a821","blockSize":4194304,"blocks":["1f0843ec8b9eacb9ec54ed601d0354a854dc587fa3c07509a8418ffd7b11a821"]},"offset":"3479169"},"replace.js":{"size":1532,"integrity":{"algorithm":"SHA256","hash":"9a6e83da6f2ca08a5f88064181e8cdbff71086767dcd440e423e6e14b7a571ba","blockSize":4194304,"blocks":["9a6e83da6f2ca08a5f88064181e8cdbff71086767dcd440e423e6e14b7a571ba"]},"offset":"3479775"}}},"mimic-fn":{"files":{"index.js":{"size":2930,"integrity":{"algorithm":"SHA256","hash":"d4a832347a07a4df9b32a010fc5ffb1c4447c51769423cd5a3a47da0213fe5c0","blockSize":4194304,"blocks":["d4a832347a07a4df9b32a010fc5ffb1c4447c51769423cd5a3a47da0213fe5c0"]},"offset":"3481307"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"3484237"},"package.json":{"size":457,"integrity":{"algorithm":"SHA256","hash":"08497273cf6cf95285aa094c0be5aedd1b1101f5d1e8858f0c09510ce350cdbe","blockSize":4194304,"blocks":["08497273cf6cf95285aa094c0be5aedd1b1101f5d1e8858f0c09510ce350cdbe"]},"offset":"3485346"}}},"onetime":{"files":{"index.js":{"size":1120,"integrity":{"algorithm":"SHA256","hash":"59a0b25379fff19195343d47759339397c689e8ab93270adcab2d106a80e1625","blockSize":4194304,"blocks":["59a0b25379fff19195343d47759339397c689e8ab93270adcab2d106a80e1625"]},"offset":"3485803"},"license":{"size":1117,"integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]},"offset":"3486923"},"package.json":{"size":574,"integrity":{"algorithm":"SHA256","hash":"b155b599abc77980f0bb4835f6326d419de175e9c085198ed292199844dc1917","blockSize":4194304,"blocks":["b155b599abc77980f0bb4835f6326d419de175e9c085198ed292199844dc1917"]},"offset":"3488040"},"node_modules":{"files":{"mimic-fn":{"files":{"index.js":{"size":300,"integrity":{"algorithm":"SHA256","hash":"9ca2b409cdf1718ce957292dc479c83516e4ea369f4b2cb3510066d4e50074e2","blockSize":4194304,"blocks":["9ca2b409cdf1718ce957292dc479c83516e4ea369f4b2cb3510066d4e50074e2"]},"offset":"12299869"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"12300169"},"package.json":{"size":457,"integrity":{"algorithm":"SHA256","hash":"98daad7a76353462b42f4d89a340f54caae220bd83d6b46aaf181f77e28cd13f","blockSize":4194304,"blocks":["98daad7a76353462b42f4d89a340f54caae220bd83d6b46aaf181f77e28cd13f"]},"offset":"12301278"}}}}}}},"p-try":{"files":{"index.js":{"size":211,"integrity":{"algorithm":"SHA256","hash":"98b069ba5ff64b0f988162a310c47110d5c121d42c33aa7314817393f453c9e3","blockSize":4194304,"blocks":["98b069ba5ff64b0f988162a310c47110d5c121d42c33aa7314817393f453c9e3"]},"offset":"3488614"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"3488825"},"package.json":{"size":440,"integrity":{"algorithm":"SHA256","hash":"af5c7cbf707e18ced31d8a8732df1224b2af6bdc72c5de070fc1b2dea20706e8","blockSize":4194304,"blocks":["af5c7cbf707e18ced31d8a8732df1224b2af6bdc72c5de070fc1b2dea20706e8"]},"offset":"3489934"}}},"pkg-up":{"files":{"index.js":{"size":194,"integrity":{"algorithm":"SHA256","hash":"424a480322b22b7315bddab07ef565f450f6f63b5ab920d853237b986d419df2","blockSize":4194304,"blocks":["424a480322b22b7315bddab07ef565f450f6f63b5ab920d853237b986d419df2"]},"offset":"3490374"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"3490568"},"package.json":{"size":503,"integrity":{"algorithm":"SHA256","hash":"7b5ee94b454a2af0d92ee42654e876cb497d810c31a598aecb2212147980e694","blockSize":4194304,"blocks":["7b5ee94b454a2af0d92ee42654e876cb497d810c31a598aecb2212147980e694"]},"offset":"3491677"},"node_modules":{"files":{"find-up":{"files":{"index.js":{"size":968,"integrity":{"algorithm":"SHA256","hash":"b2b7a4a3a202785dfc044bc9d3798df684c9983008254e44e23258f80c7aba54","blockSize":4194304,"blocks":["b2b7a4a3a202785dfc044bc9d3798df684c9983008254e44e23258f80c7aba54"]},"offset":"12301735"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"12302703"},"package.json":{"size":505,"integrity":{"algorithm":"SHA256","hash":"47ba84a162be94305384419b4ea862550509f0bcaf675e548c5d147303c8ed1e","blockSize":4194304,"blocks":["47ba84a162be94305384419b4ea862550509f0bcaf675e548c5d147303c8ed1e"]},"offset":"12303812"}}},"locate-path":{"files":{"index.js":{"size":539,"integrity":{"algorithm":"SHA256","hash":"0d01be23e2a31212f61ae8856bd916709156f2c56c7434dbe97ea29624b77fd7","blockSize":4194304,"blocks":["0d01be23e2a31212f61ae8856bd916709156f2c56c7434dbe97ea29624b77fd7"]},"offset":"12304317"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"12304856"},"package.json":{"size":515,"integrity":{"algorithm":"SHA256","hash":"ce0e3f841bdf450a3c54421abf5b930daabe079e60c8f6ce2ba9252a017801f2","blockSize":4194304,"blocks":["ce0e3f841bdf450a3c54421abf5b930daabe079e60c8f6ce2ba9252a017801f2"]},"offset":"12305965"}}},"p-limit":{"files":{"index.js":{"size":1114,"integrity":{"algorithm":"SHA256","hash":"b005ce7e192e136df67e3b724bfc156c396ac46928c79508d6fd532bef98cbec","blockSize":4194304,"blocks":["b005ce7e192e136df67e3b724bfc156c396ac46928c79508d6fd532bef98cbec"]},"offset":"12306480"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"12307594"},"package.json":{"size":709,"integrity":{"algorithm":"SHA256","hash":"d4c39a75c26a413b0a7b28873811e5cfad2b1d134db1d9c19c7f566f3d25c212","blockSize":4194304,"blocks":["d4c39a75c26a413b0a7b28873811e5cfad2b1d134db1d9c19c7f566f3d25c212"]},"offset":"12308703"}}},"p-locate":{"files":{"index.js":{"size":1042,"integrity":{"algorithm":"SHA256","hash":"8e5e49ae61d019cf6f74e59e114190fc06bafa85c2084d1731b3ccbeb445e572","blockSize":4194304,"blocks":["8e5e49ae61d019cf6f74e59e114190fc06bafa85c2084d1731b3ccbeb445e572"]},"offset":"12309412"},"license":{"size":1109,"integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]},"offset":"12310454"},"package.json":{"size":575,"integrity":{"algorithm":"SHA256","hash":"8c699ec0acfdc16eab80011a4aa974195fb461aeb4d7b577f0af19c8636d32f8","blockSize":4194304,"blocks":["8c699ec0acfdc16eab80011a4aa974195fb461aeb4d7b577f0af19c8636d32f8"]},"offset":"12311563"}}},"path-exists":{"files":{"index.js":{"size":252,"integrity":{"algorithm":"SHA256","hash":"2557a5378ea2cab729e51b6fce5da24c782940d219a6bd6ade069190e919894f","blockSize":4194304,"blocks":["2557a5378ea2cab729e51b6fce5da24c782940d219a6bd6ade069190e919894f"]},"offset":"12312138"},"license":{"size":1119,"integrity":{"algorithm":"SHA256","hash":"6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c","blockSize":4194304,"blocks":["6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c"]},"offset":"12312390"},"package.json":{"size":402,"integrity":{"algorithm":"SHA256","hash":"30b5457bd77ccd35aa32ba51fa8296b0a3b682f6444f8dba1500559a645f6e95","blockSize":4194304,"blocks":["30b5457bd77ccd35aa32ba51fa8296b0a3b682f6444f8dba1500559a645f6e95"]},"offset":"12313509"}}}}}}},"react":{"files":{"LICENSE":{"size":1086,"integrity":{"algorithm":"SHA256","hash":"52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85","blockSize":4194304,"blocks":["52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85"]},"offset":"3492180"},"index.js":{"size":190,"integrity":{"algorithm":"SHA256","hash":"a216c390bf956cbb906c66d29fdb2e2ad6999464a5ca83e476533a6f25ad0ef3","blockSize":4194304,"blocks":["a216c390bf956cbb906c66d29fdb2e2ad6999464a5ca83e476533a6f25ad0ef3"]},"offset":"3493266"},"jsx-dev-runtime.js":{"size":222,"integrity":{"algorithm":"SHA256","hash":"25a7dbfdb2ae574b67fcdd2aab811080b415edd1c8043ead46866a533e99320e","blockSize":4194304,"blocks":["25a7dbfdb2ae574b67fcdd2aab811080b415edd1c8043ead46866a533e99320e"]},"offset":"3493456"},"jsx-runtime.js":{"size":214,"integrity":{"algorithm":"SHA256","hash":"28170e60f2ff0bc045bc7d175f5849e86f68dd02d76d7255369420718b30295a","blockSize":4194304,"blocks":["28170e60f2ff0bc045bc7d175f5849e86f68dd02d76d7255369420718b30295a"]},"offset":"3493678"},"package.json":{"size":912,"integrity":{"algorithm":"SHA256","hash":"9a394ce4f81b3df64aedfc9ee91eb7f3fc02063c5a52ad4161170d3b55b76ac1","blockSize":4194304,"blocks":["9a394ce4f81b3df64aedfc9ee91eb7f3fc02063c5a52ad4161170d3b55b76ac1"]},"offset":"3493892"},"react.shared-subset.js":{"size":218,"integrity":{"algorithm":"SHA256","hash":"6e0253e5955264bf6d1014066f3921ab0715f432f27c5983bc487ced2a64f95b","blockSize":4194304,"blocks":["6e0253e5955264bf6d1014066f3921ab0715f432f27c5983bc487ced2a64f95b"]},"offset":"3494804"},"umd":{"files":{"react.development.js":{"size":109931,"integrity":{"algorithm":"SHA256","hash":"28348fef6cb0ed8b2ceeb22deaf824428fd13875d84c73d38f77dd216fc24e7f","blockSize":4194304,"blocks":["28348fef6cb0ed8b2ceeb22deaf824428fd13875d84c73d38f77dd216fc24e7f"]},"offset":"3495022"},"react.production.min.js":{"size":10751,"integrity":{"algorithm":"SHA256","hash":"d949f1c3687aedadcedac85261865f29b17cd273997e7f6b2bfc53b2f9d4c4dd","blockSize":4194304,"blocks":["d949f1c3687aedadcedac85261865f29b17cd273997e7f6b2bfc53b2f9d4c4dd"]},"offset":"3604953"},"react.profiling.min.js":{"size":10750,"integrity":{"algorithm":"SHA256","hash":"68f54d810fd6c1acebfa38f7bed791bf1834f0fed4b2a5afe1cba5755dacd81a","blockSize":4194304,"blocks":["68f54d810fd6c1acebfa38f7bed791bf1834f0fed4b2a5afe1cba5755dacd81a"]},"offset":"3615704"}}},"cjs":{"files":{"react-jsx-dev-runtime.development.js":{"size":42101,"integrity":{"algorithm":"SHA256","hash":"cd9394f47e01e9f1d87f7a8adcfc0ad8f8813d5c124ee74627791921f3277ac5","blockSize":4194304,"blocks":["cd9394f47e01e9f1d87f7a8adcfc0ad8f8813d5c124ee74627791921f3277ac5"]},"offset":"3626454"},"react-jsx-dev-runtime.production.min.js":{"size":343,"integrity":{"algorithm":"SHA256","hash":"c46386ede6d3618f7fe15be9312f9660916828ec4e07bec6b76cc6636db34b0d","blockSize":4194304,"blocks":["c46386ede6d3618f7fe15be9312f9660916828ec4e07bec6b76cc6636db34b0d"]},"offset":"3668555"},"react-jsx-dev-runtime.profiling.min.js":{"size":342,"integrity":{"algorithm":"SHA256","hash":"1d59a4f1f92dd843203c5f55fe31a2b13a0d28cdeaebc89d3abf80a0c2547743","blockSize":4194304,"blocks":["1d59a4f1f92dd843203c5f55fe31a2b13a0d28cdeaebc89d3abf80a0c2547743"]},"offset":"3668898"},"react-jsx-runtime.development.js":{"size":42700,"integrity":{"algorithm":"SHA256","hash":"581f93fa33c32b3aa7ea35b85b80258922517de046f5447236047dcc2845d9ff","blockSize":4194304,"blocks":["581f93fa33c32b3aa7ea35b85b80258922517de046f5447236047dcc2845d9ff"]},"offset":"3669240"},"react-jsx-runtime.production.min.js":{"size":859,"integrity":{"algorithm":"SHA256","hash":"76e3364c46895ed2c4a8d5cc332e5e4ef31d6f732d35b1e56826dc5895245452","blockSize":4194304,"blocks":["76e3364c46895ed2c4a8d5cc332e5e4ef31d6f732d35b1e56826dc5895245452"]},"offset":"3711940"},"react-jsx-runtime.profiling.min.js":{"size":858,"integrity":{"algorithm":"SHA256","hash":"2178bc5a268f9dead7e6ac608fc4e1bf016ea04c64776ce19b11d1e99b103cd5","blockSize":4194304,"blocks":["2178bc5a268f9dead7e6ac608fc4e1bf016ea04c64776ce19b11d1e99b103cd5"]},"offset":"3712799"},"react.development.js":{"size":87593,"integrity":{"algorithm":"SHA256","hash":"1ff3a1d9861a87984329584fa1172aea920855d79eb57dae0d1cebe54093d7e3","blockSize":4194304,"blocks":["1ff3a1d9861a87984329584fa1172aea920855d79eb57dae0d1cebe54093d7e3"]},"offset":"3713657"},"react.production.min.js":{"size":6930,"integrity":{"algorithm":"SHA256","hash":"4b35e378f469c4f492c7514bb106b5833746dbbae80496bd4aa9acc6e9ac4b42","blockSize":4194304,"blocks":["4b35e378f469c4f492c7514bb106b5833746dbbae80496bd4aa9acc6e9ac4b42"]},"offset":"3801250"},"react.shared-subset.development.js":{"size":501,"integrity":{"algorithm":"SHA256","hash":"25226697f4b27212725d6095644af634094f13cd7d7f4020903c0708acf49747","blockSize":4194304,"blocks":["25226697f4b27212725d6095644af634094f13cd7d7f4020903c0708acf49747"]},"offset":"3808180"},"react.shared-subset.production.min.js":{"size":351,"integrity":{"algorithm":"SHA256","hash":"81dc1fd56b616aab4967a0505053942a460c22e51f0bbcfd05031d9908a3bc6e","blockSize":4194304,"blocks":["81dc1fd56b616aab4967a0505053942a460c22e51f0bbcfd05031d9908a3bc6e"]},"offset":"3808681"}}}}},"react-dom":{"files":{"LICENSE":{"size":1086,"integrity":{"algorithm":"SHA256","hash":"52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85","blockSize":4194304,"blocks":["52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85"]},"offset":"3809032"},"client.js":{"size":619,"integrity":{"algorithm":"SHA256","hash":"a510041dfc40d69b3aa574e5e111864186c711fbeb3db41aa2f27196b27c429f","blockSize":4194304,"blocks":["a510041dfc40d69b3aa574e5e111864186c711fbeb3db41aa2f27196b27c429f"]},"offset":"3810118"},"index.js":{"size":1363,"integrity":{"algorithm":"SHA256","hash":"f26fcb81b5d1dc32c6edea34645c75b60d259916293d3208c8be48ac33e882e4","blockSize":4194304,"blocks":["f26fcb81b5d1dc32c6edea34645c75b60d259916293d3208c8be48ac33e882e4"]},"offset":"3810737"},"package.json":{"size":1249,"integrity":{"algorithm":"SHA256","hash":"19827c73631833e751b3720ff1ae07b3c6c9eb7df6573015a026ce865b27d9ce","blockSize":4194304,"blocks":["19827c73631833e751b3720ff1ae07b3c6c9eb7df6573015a026ce865b27d9ce"]},"offset":"3812100"},"profiling.js":{"size":1362,"integrity":{"algorithm":"SHA256","hash":"4d7fc987f48ce3afc8ff9e19d6e1d0d643c14d9dd255ce0c4c177cc6e4af3e3e","blockSize":4194304,"blocks":["4d7fc987f48ce3afc8ff9e19d6e1d0d643c14d9dd255ce0c4c177cc6e4af3e3e"]},"offset":"3813349"},"server.browser.js":{"size":658,"integrity":{"algorithm":"SHA256","hash":"25b2a8fbe5dbf5e38f32fb11db0af0c67f6c61abb3ef22a7c71473202cabf653","blockSize":4194304,"blocks":["25b2a8fbe5dbf5e38f32fb11db0af0c67f6c61abb3ef22a7c71473202cabf653"]},"offset":"3814711"},"server.js":{"size":58,"integrity":{"algorithm":"SHA256","hash":"8a05db291adfdedb4e9509e524e4f499adec95f6ffb6b8d2e04ea73aa2950684","blockSize":4194304,"blocks":["8a05db291adfdedb4e9509e524e4f499adec95f6ffb6b8d2e04ea73aa2950684"]},"offset":"3815369"},"server.node.js":{"size":646,"integrity":{"algorithm":"SHA256","hash":"a0f7a56527b73f95ac283578815fad4a4e5e849f451267fb7a0d7b347453727c","blockSize":4194304,"blocks":["a0f7a56527b73f95ac283578815fad4a4e5e849f451267fb7a0d7b347453727c"]},"offset":"3815427"},"test-utils.js":{"size":220,"integrity":{"algorithm":"SHA256","hash":"96b11c202300fc90ed6766e170ae6c075f3950636c839371b90e1bbf1c074bc8","blockSize":4194304,"blocks":["96b11c202300fc90ed6766e170ae6c075f3950636c839371b90e1bbf1c074bc8"]},"offset":"3816073"},"umd":{"files":{"react-dom-server-legacy.browser.development.js":{"size":256331,"integrity":{"algorithm":"SHA256","hash":"0cc9b0e7062d1a319fed59a94b2020e27a82ff0c3f12ea955c7ad937a8e0603b","blockSize":4194304,"blocks":["0cc9b0e7062d1a319fed59a94b2020e27a82ff0c3f12ea955c7ad937a8e0603b"]},"offset":"3816293"},"react-dom-server-legacy.browser.production.min.js":{"size":35128,"integrity":{"algorithm":"SHA256","hash":"829b2f17da148d9bc5b635c329b67068e67e4bf7d6a5bb64e49e9e92483deee5","blockSize":4194304,"blocks":["829b2f17da148d9bc5b635c329b67068e67e4bf7d6a5bb64e49e9e92483deee5"]},"offset":"4072624"},"react-dom-server.browser.development.js":{"size":255190,"integrity":{"algorithm":"SHA256","hash":"bbd5a9cfa14dd6cb699fb2b8d5a1e0fa0f0778f8241c708e571304f9a29e0490","blockSize":4194304,"blocks":["bbd5a9cfa14dd6cb699fb2b8d5a1e0fa0f0778f8241c708e571304f9a29e0490"]},"offset":"4107752"},"react-dom-server.browser.production.min.js":{"size":35699,"integrity":{"algorithm":"SHA256","hash":"a9c88f10162c0d0100c91faa8f76b79729b8bd41800ac0fd82a04eb1d8c5ac3b","blockSize":4194304,"blocks":["a9c88f10162c0d0100c91faa8f76b79729b8bd41800ac0fd82a04eb1d8c5ac3b"]},"offset":"4362942"},"react-dom-test-utils.development.js":{"size":59128,"integrity":{"algorithm":"SHA256","hash":"66c94d915e0391534f3b188b18d496a351f5f400fac247be7328ba5df9676435","blockSize":4194304,"blocks":["66c94d915e0391534f3b188b18d496a351f5f400fac247be7328ba5df9676435"]},"offset":"4398641"},"react-dom-test-utils.production.min.js":{"size":12689,"integrity":{"algorithm":"SHA256","hash":"875a0d012022690560c81fa370847840c9306a8adfa27417122a93e9533920aa","blockSize":4194304,"blocks":["875a0d012022690560c81fa370847840c9306a8adfa27417122a93e9533920aa"]},"offset":"4457769"},"react-dom.development.js":{"size":1080227,"integrity":{"algorithm":"SHA256","hash":"f9044a5e9c39db8bb1a204dff924e526ec0a621e695bb69de1035811be8709e4","blockSize":4194304,"blocks":["f9044a5e9c39db8bb1a204dff924e526ec0a621e695bb69de1035811be8709e4"]},"offset":"4470458"},"react-dom.production.min.js":{"size":131835,"integrity":{"algorithm":"SHA256","hash":"35f4f974f4b2bcd44da73963347f8952e341f83909e4498227d4e26b98f66f0d","blockSize":4194304,"blocks":["35f4f974f4b2bcd44da73963347f8952e341f83909e4498227d4e26b98f66f0d"]},"offset":"5550685"},"react-dom.profiling.min.js":{"size":140569,"integrity":{"algorithm":"SHA256","hash":"2daedab06b577dc0674514e9fa738b9cce256741735451cadff6ee26aee0ff41","blockSize":4194304,"blocks":["2daedab06b577dc0674514e9fa738b9cce256741735451cadff6ee26aee0ff41"]},"offset":"5682520"}}},"cjs":{"files":{"react-dom-server-legacy.browser.development.js":{"size":244422,"integrity":{"algorithm":"SHA256","hash":"5acee43203eac80a9e45284d3e98ffeeac57de2a925299b0c70af639d14fc28e","blockSize":4194304,"blocks":["5acee43203eac80a9e45284d3e98ffeeac57de2a925299b0c70af639d14fc28e"]},"offset":"5823089"},"react-dom-server-legacy.browser.production.min.js":{"size":35019,"integrity":{"algorithm":"SHA256","hash":"55f08e1c365fa1525359467e68f72bf50f901a7c0b59685df168fdceb01593cb","blockSize":4194304,"blocks":["55f08e1c365fa1525359467e68f72bf50f901a7c0b59685df168fdceb01593cb"]},"offset":"6067511"},"react-dom-server-legacy.node.development.js":{"size":246340,"integrity":{"algorithm":"SHA256","hash":"a1ece181be0c98e5449cfd6c89f27f4d0b8ace7745566fb09ece37d79f1084d4","blockSize":4194304,"blocks":["a1ece181be0c98e5449cfd6c89f27f4d0b8ace7745566fb09ece37d79f1084d4"]},"offset":"6102530"},"react-dom-server-legacy.node.production.min.js":{"size":38796,"integrity":{"algorithm":"SHA256","hash":"570b36574af19640e243c8296257f3bad0fb41d84cc7f273bf752ccdf86b5b60","blockSize":4194304,"blocks":["570b36574af19640e243c8296257f3bad0fb41d84cc7f273bf752ccdf86b5b60"]},"offset":"6348870"},"react-dom-server.browser.development.js":{"size":243311,"integrity":{"algorithm":"SHA256","hash":"3515afa33dc9a1420d013be553c4e8a86cf128d83a47e70173d23c8163aa86bb","blockSize":4194304,"blocks":["3515afa33dc9a1420d013be553c4e8a86cf128d83a47e70173d23c8163aa86bb"]},"offset":"6387666"},"react-dom-server.browser.production.min.js":{"size":35597,"integrity":{"algorithm":"SHA256","hash":"89bde1aa0fb045330419c7d8900e33d43e693ae33a5baae5fdb6b126160fe292","blockSize":4194304,"blocks":["89bde1aa0fb045330419c7d8900e33d43e693ae33a5baae5fdb6b126160fe292"]},"offset":"6630977"},"react-dom-server.node.development.js":{"size":244692,"integrity":{"algorithm":"SHA256","hash":"6979be97ff88b4959a02c7af65a83f37084e1dd91cb59f95d9a6e8c3e039fbb6","blockSize":4194304,"blocks":["6979be97ff88b4959a02c7af65a83f37084e1dd91cb59f95d9a6e8c3e039fbb6"]},"offset":"6666574"},"react-dom-server.node.production.min.js":{"size":39058,"integrity":{"algorithm":"SHA256","hash":"967e9ceae29baf904e504b102061ca072015678e4e07121f212d5da23a1400af","blockSize":4194304,"blocks":["967e9ceae29baf904e504b102061ca072015678e4e07121f212d5da23a1400af"]},"offset":"6911266"},"react-dom-test-utils.development.js":{"size":56016,"integrity":{"algorithm":"SHA256","hash":"646e4ad0cda0a5479683dc329d5b158f206f0f709e813019272eff3b639b4eff","blockSize":4194304,"blocks":["646e4ad0cda0a5479683dc329d5b158f206f0f709e813019272eff3b639b4eff"]},"offset":"6950324"},"react-dom-test-utils.production.min.js":{"size":12616,"integrity":{"algorithm":"SHA256","hash":"4c207efafcf4ec20d48d4e735e4b16406ba4ce6cc3cc8a303c0fe5e656df0d33","blockSize":4194304,"blocks":["4c207efafcf4ec20d48d4e735e4b16406ba4ce6cc3cc8a303c0fe5e656df0d33"]},"offset":"7006340"},"react-dom.development.js":{"size":1029622,"integrity":{"algorithm":"SHA256","hash":"1459b808bc6991de5a1ec3a86d8beee32dbb6c14282cf13f84e00dfebfbdc025","blockSize":4194304,"blocks":["1459b808bc6991de5a1ec3a86d8beee32dbb6c14282cf13f84e00dfebfbdc025"]},"offset":"7018956"},"react-dom.production.min.js":{"size":131685,"integrity":{"algorithm":"SHA256","hash":"cbf7fe6b9726ee65f8bcd5715289cc5161c8dacf74d0b8aaa0d29412516f5f47","blockSize":4194304,"blocks":["cbf7fe6b9726ee65f8bcd5715289cc5161c8dacf74d0b8aaa0d29412516f5f47"]},"offset":"8048578"},"react-dom.profiling.min.js":{"size":141112,"integrity":{"algorithm":"SHA256","hash":"962c027be962261c45af4751cf219743e0537344db987d9aa89cbe3c8be3d36d","blockSize":4194304,"blocks":["962c027be962261c45af4751cf219743e0537344db987d9aa89cbe3c8be3d36d"]},"offset":"8180263"}}}}},"react-router":{"files":{"LICENSE.md":{"size":1161,"integrity":{"algorithm":"SHA256","hash":"77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49","blockSize":4194304,"blocks":["77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49"]},"offset":"8321375"},"package.json":{"size":802,"integrity":{"algorithm":"SHA256","hash":"eaa9ecd1bf0709f698f7eeec247392c45fca5e8f2a4ef51d7780d4f735ab86e2","blockSize":4194304,"blocks":["eaa9ecd1bf0709f698f7eeec247392c45fca5e8f2a4ef51d7780d4f735ab86e2"]},"offset":"8322536"},"dist":{"files":{"index.js":{"size":60628,"integrity":{"algorithm":"SHA256","hash":"34dc7626fd930453ee4a253e4ae67cdcbd1462a3d372d5a78beab3861b343371","blockSize":4194304,"blocks":["34dc7626fd930453ee4a253e4ae67cdcbd1462a3d372d5a78beab3861b343371"]},"offset":"8323338"},"index.js.map":{"size":129421,"integrity":{"algorithm":"SHA256","hash":"08e7c434214e53187f81d7e2b4bc0ee542935868600b1f7457f7472b22717175","blockSize":4194304,"blocks":["08e7c434214e53187f81d7e2b4bc0ee542935868600b1f7457f7472b22717175"]},"offset":"8383966"},"main.js":{"size":450,"integrity":{"algorithm":"SHA256","hash":"d33ceb86015c8ca06d46bec9e30f4ee4319ee55239a8350a130d13ac002eb8c3","blockSize":4194304,"blocks":["d33ceb86015c8ca06d46bec9e30f4ee4319ee55239a8350a130d13ac002eb8c3"]},"offset":"8513387"},"react-router.development.js":{"size":55984,"integrity":{"algorithm":"SHA256","hash":"3c34b972f94d986b4d8bb72793c19451d51e11f2280d4d5fec00dbfe2c8444b8","blockSize":4194304,"blocks":["3c34b972f94d986b4d8bb72793c19451d51e11f2280d4d5fec00dbfe2c8444b8"]},"offset":"8513837"},"react-router.development.js.map":{"size":124696,"integrity":{"algorithm":"SHA256","hash":"8b9eb8c707d3d3676f9d5115144a8d6a7c6221c5a1ae10add8c6a632fb5e53b2","blockSize":4194304,"blocks":["8b9eb8c707d3d3676f9d5115144a8d6a7c6221c5a1ae10add8c6a632fb5e53b2"]},"offset":"8569821"},"react-router.production.min.js":{"size":15543,"integrity":{"algorithm":"SHA256","hash":"8631280f3bc5d2489b619f6c05660e1414a6b5aeeec217ce9e99f77721211c49","blockSize":4194304,"blocks":["8631280f3bc5d2489b619f6c05660e1414a6b5aeeec217ce9e99f77721211c49"]},"offset":"8694517"},"react-router.production.min.js.map":{"size":98238,"integrity":{"algorithm":"SHA256","hash":"307e4ba06426a23b3f3b7d5156d81c712a6fcbb831088e7e55243cd841539e5c","blockSize":4194304,"blocks":["307e4ba06426a23b3f3b7d5156d81c712a6fcbb831088e7e55243cd841539e5c"]},"offset":"8710060"},"umd":{"files":{"react-router.development.js":{"size":66121,"integrity":{"algorithm":"SHA256","hash":"91c604844deb7c56d49a5d0a0bb7b0c79bb562615df0dc791e35fd33dd9ab1d5","blockSize":4194304,"blocks":["91c604844deb7c56d49a5d0a0bb7b0c79bb562615df0dc791e35fd33dd9ab1d5"]},"offset":"8808298"},"react-router.development.js.map":{"size":127357,"integrity":{"algorithm":"SHA256","hash":"06ba6c4cc713c5c7fe918166578d70d1f4de41ddcc298a16b5545aaad462caa2","blockSize":4194304,"blocks":["06ba6c4cc713c5c7fe918166578d70d1f4de41ddcc298a16b5545aaad462caa2"]},"offset":"8874419"},"react-router.production.min.js":{"size":18122,"integrity":{"algorithm":"SHA256","hash":"9bd95ffed036c27654da62baa601316bcea3bcc4e414b55fc027da0b93f77eeb","blockSize":4194304,"blocks":["9bd95ffed036c27654da62baa601316bcea3bcc4e414b55fc027da0b93f77eeb"]},"offset":"9001776"},"react-router.production.min.js.map":{"size":99138,"integrity":{"algorithm":"SHA256","hash":"720e7716c27eac6867bbb41844ec038165fa33db59fb51945dd0ed137a64a90a","blockSize":4194304,"blocks":["720e7716c27eac6867bbb41844ec038165fa33db59fb51945dd0ed137a64a90a"]},"offset":"9019898"}}}}}}},"react-router-dom":{"files":{"LICENSE.md":{"size":1161,"integrity":{"algorithm":"SHA256","hash":"77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49","blockSize":4194304,"blocks":["77c9ee6a9c5d5782fb0c50b50d101189116314c14f7df0a1b0d385fc96a7ba49"]},"offset":"9119036"},"package.json":{"size":936,"integrity":{"algorithm":"SHA256","hash":"a761f4896319dc47e82d06ff50a927d00ca763954be772572b717cb6374337aa","blockSize":4194304,"blocks":["a761f4896319dc47e82d06ff50a927d00ca763954be772572b717cb6374337aa"]},"offset":"9120197"},"server.js":{"size":10635,"integrity":{"algorithm":"SHA256","hash":"ceb85c499f69a52582828afa5b7a4cbe7659addbfbf827b620dae419165f995a","blockSize":4194304,"blocks":["ceb85c499f69a52582828afa5b7a4cbe7659addbfbf827b620dae419165f995a"]},"offset":"9121133"},"server.mjs":{"size":9831,"integrity":{"algorithm":"SHA256","hash":"0ff86121f86a721432f42b63d9b88dfd8e61f67aa79bf975415e7ee23116a59a","blockSize":4194304,"blocks":["0ff86121f86a721432f42b63d9b88dfd8e61f67aa79bf975415e7ee23116a59a"]},"offset":"9131768"},"dist":{"files":{"index.js":{"size":56504,"integrity":{"algorithm":"SHA256","hash":"4a4a81271d6ace4b1717635602f59150b1905fe1152b05c01b4bf62f501ae48e","blockSize":4194304,"blocks":["4a4a81271d6ace4b1717635602f59150b1905fe1152b05c01b4bf62f501ae48e"]},"offset":"9141599"},"index.js.map":{"size":125718,"integrity":{"algorithm":"SHA256","hash":"104e061e28278d2c776b5f0b2dc409d82c5a801ee359cb65599c5f15513aa0de","blockSize":4194304,"blocks":["104e061e28278d2c776b5f0b2dc409d82c5a801ee359cb65599c5f15513aa0de"]},"offset":"9198103"},"main.js":{"size":462,"integrity":{"algorithm":"SHA256","hash":"5cf8f3e7992052a9371a2e1d62f0d87c73ff35c4f67789adf4ca2a7e5a6f4daa","blockSize":4194304,"blocks":["5cf8f3e7992052a9371a2e1d62f0d87c73ff35c4f67789adf4ca2a7e5a6f4daa"]},"offset":"9323821"},"react-router-dom.development.js":{"size":54275,"integrity":{"algorithm":"SHA256","hash":"132c2cb1301cdcd73cbe6bf68a9be05cf7fac090c9664515520410fa47eb7be9","blockSize":4194304,"blocks":["132c2cb1301cdcd73cbe6bf68a9be05cf7fac090c9664515520410fa47eb7be9"]},"offset":"9324283"},"react-router-dom.development.js.map":{"size":123307,"integrity":{"algorithm":"SHA256","hash":"d1996fbc85af12a5c69939f9a1b00c7c25267809d162c568c81331d0f15e4371","blockSize":4194304,"blocks":["d1996fbc85af12a5c69939f9a1b00c7c25267809d162c568c81331d0f15e4371"]},"offset":"9378558"},"react-router-dom.production.min.js":{"size":17544,"integrity":{"algorithm":"SHA256","hash":"5d8cf64c6a1919882a72c5673f37a4d41b23b89ce9c06d0d6cd21ce3a5722bde","blockSize":4194304,"blocks":["5d8cf64c6a1919882a72c5673f37a4d41b23b89ce9c06d0d6cd21ce3a5722bde"]},"offset":"9501865"},"react-router-dom.production.min.js.map":{"size":97292,"integrity":{"algorithm":"SHA256","hash":"1e1f446d259997e6ec940cf4cf0a678540fa517339b069971fa2cfde0a2681e3","blockSize":4194304,"blocks":["1e1f446d259997e6ec940cf4cf0a678540fa517339b069971fa2cfde0a2681e3"]},"offset":"9519409"},"server.js":{"size":10635,"integrity":{"algorithm":"SHA256","hash":"ceb85c499f69a52582828afa5b7a4cbe7659addbfbf827b620dae419165f995a","blockSize":4194304,"blocks":["ceb85c499f69a52582828afa5b7a4cbe7659addbfbf827b620dae419165f995a"]},"offset":"9616701"},"server.mjs":{"size":9831,"integrity":{"algorithm":"SHA256","hash":"0ff86121f86a721432f42b63d9b88dfd8e61f67aa79bf975415e7ee23116a59a","blockSize":4194304,"blocks":["0ff86121f86a721432f42b63d9b88dfd8e61f67aa79bf975415e7ee23116a59a"]},"offset":"9627336"},"umd":{"files":{"react-router-dom.development.js":{"size":69034,"integrity":{"algorithm":"SHA256","hash":"2bbe76a6aa6a1a755d142e16ae580970c359b565910a04826f37f7cb9da49bff","blockSize":4194304,"blocks":["2bbe76a6aa6a1a755d142e16ae580970c359b565910a04826f37f7cb9da49bff"]},"offset":"9637167"},"react-router-dom.development.js.map":{"size":125746,"integrity":{"algorithm":"SHA256","hash":"0adbb9f970c040deeb7adcfdb0c4efae79baa030f22368e11e80cb6d413652e3","blockSize":4194304,"blocks":["0adbb9f970c040deeb7adcfdb0c4efae79baa030f22368e11e80cb6d413652e3"]},"offset":"9706201"},"react-router-dom.production.min.js":{"size":24177,"integrity":{"algorithm":"SHA256","hash":"4ede375f044b2fded3a4890973ab965404ce8a48e8c7870f0c832db09ca30507","blockSize":4194304,"blocks":["4ede375f044b2fded3a4890973ab965404ce8a48e8c7870f0c832db09ca30507"]},"offset":"9831947"},"react-router-dom.production.min.js.map":{"size":98812,"integrity":{"algorithm":"SHA256","hash":"2a8798dafa7661a2c3b4e6828b0d9ceb9c2357138a09df2cc44160442b160c99","blockSize":4194304,"blocks":["2a8798dafa7661a2c3b4e6828b0d9ceb9c2357138a09df2cc44160442b160c99"]},"offset":"9856124"}}}}}}},"require-from-string":{"files":{"index.js":{"size":866,"integrity":{"algorithm":"SHA256","hash":"cb059342a762b955997bf780f3693add176922727f2fa9f11fcaf1b3fc323239","blockSize":4194304,"blocks":["cb059342a762b955997bf780f3693add176922727f2fa9f11fcaf1b3fc323239"]},"offset":"9954936"},"license":{"size":1128,"integrity":{"algorithm":"SHA256","hash":"6ee0feb1f6ef996ff5a68600f8cf98909cf412d39ef3cdceaefd87d636fa1b7f","blockSize":4194304,"blocks":["6ee0feb1f6ef996ff5a68600f8cf98909cf412d39ef3cdceaefd87d636fa1b7f"]},"offset":"9955802"},"package.json":{"size":442,"integrity":{"algorithm":"SHA256","hash":"bbd907e5490c34cc6b814f56cd2180edb03bc594b88cdf1e112ed94d0d6218a3","blockSize":4194304,"blocks":["bbd907e5490c34cc6b814f56cd2180edb03bc594b88cdf1e112ed94d0d6218a3"]},"offset":"9956930"}}},"scheduler":{"files":{"LICENSE":{"size":1086,"integrity":{"algorithm":"SHA256","hash":"52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85","blockSize":4194304,"blocks":["52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85"]},"offset":"9957372"},"index.js":{"size":198,"integrity":{"algorithm":"SHA256","hash":"b413b3aac7bd209fd82cbe2241fda1467558daaef830744f45ed8396fac9185e","blockSize":4194304,"blocks":["b413b3aac7bd209fd82cbe2241fda1467558daaef830744f45ed8396fac9185e"]},"offset":"9958458"},"package.json":{"size":596,"integrity":{"algorithm":"SHA256","hash":"8ebd09b39742c90531b9210846c4207b962f7bedfb2b60d93c906e4019fb3bc0","blockSize":4194304,"blocks":["8ebd09b39742c90531b9210846c4207b962f7bedfb2b60d93c906e4019fb3bc0"]},"offset":"9958656"},"unstable_mock.js":{"size":226,"integrity":{"algorithm":"SHA256","hash":"4a49b7ebe0cd8195ece30c0eac5d3de2ecfb029dd8d86e8a2553c454cb3e93ec","blockSize":4194304,"blocks":["4a49b7ebe0cd8195ece30c0eac5d3de2ecfb029dd8d86e8a2553c454cb3e93ec"]},"offset":"9959252"},"unstable_post_task.js":{"size":236,"integrity":{"algorithm":"SHA256","hash":"01e9c25936b4a4f6c67ce37b1b23779d6e77c479c9cc61e23bc39d0a5139d1f9","blockSize":4194304,"blocks":["01e9c25936b4a4f6c67ce37b1b23779d6e77c479c9cc61e23bc39d0a5139d1f9"]},"offset":"9959478"},"umd":{"files":{"scheduler-unstable_mock.development.js":{"size":18776,"integrity":{"algorithm":"SHA256","hash":"8a2847daab23e5572bcf80053a30dff2e0b4c140c41b2e565dec4f33397797b5","blockSize":4194304,"blocks":["8a2847daab23e5572bcf80053a30dff2e0b4c140c41b2e565dec4f33397797b5"]},"offset":"9959714"},"scheduler-unstable_mock.production.min.js":{"size":4825,"integrity":{"algorithm":"SHA256","hash":"3a8bb5ae1b9d9657635def28f6664821ccee36594e4acfd99669edf22dc4caef","blockSize":4194304,"blocks":["3a8bb5ae1b9d9657635def28f6664821ccee36594e4acfd99669edf22dc4caef"]},"offset":"9978490"},"scheduler.development.js":{"size":4895,"integrity":{"algorithm":"SHA256","hash":"62c6b86d3ad00310d0f07c6ede5dad89a37a54f4f5fabc48f7032ac7febec76d","blockSize":4194304,"blocks":["62c6b86d3ad00310d0f07c6ede5dad89a37a54f4f5fabc48f7032ac7febec76d"]},"offset":"9983315"},"scheduler.production.min.js":{"size":4634,"integrity":{"algorithm":"SHA256","hash":"ee7000b09e9c669909d964d226ccb327c563764245f5e5afbdcd5a3971d9ac71","blockSize":4194304,"blocks":["ee7000b09e9c669909d964d226ccb327c563764245f5e5afbdcd5a3971d9ac71"]},"offset":"9988210"},"scheduler.profiling.min.js":{"size":4634,"integrity":{"algorithm":"SHA256","hash":"ee7000b09e9c669909d964d226ccb327c563764245f5e5afbdcd5a3971d9ac71","blockSize":4194304,"blocks":["ee7000b09e9c669909d964d226ccb327c563764245f5e5afbdcd5a3971d9ac71"]},"offset":"9992844"}}},"cjs":{"files":{"scheduler-unstable_mock.development.js":{"size":17457,"integrity":{"algorithm":"SHA256","hash":"ebf836ab57804b4e633b1a9d0eeb415ce9d3057ef54f794e89e5c29d8508e428","blockSize":4194304,"blocks":["ebf836ab57804b4e633b1a9d0eeb415ce9d3057ef54f794e89e5c29d8508e428"]},"offset":"9997478"},"scheduler-unstable_mock.production.min.js":{"size":4786,"integrity":{"algorithm":"SHA256","hash":"7f6f194583dd0c4527c05cbfea1692bdc8da9665bff3fd492ff2e9779f2e7f10","blockSize":4194304,"blocks":["7f6f194583dd0c4527c05cbfea1692bdc8da9665bff3fd492ff2e9779f2e7f10"]},"offset":"10014935"},"scheduler-unstable_post_task.development.js":{"size":6883,"integrity":{"algorithm":"SHA256","hash":"11bfb2ceafe56bc1bcf27267202b927859eff0e856d30836e5cced6a2b54e210","blockSize":4194304,"blocks":["11bfb2ceafe56bc1bcf27267202b927859eff0e856d30836e5cced6a2b54e210"]},"offset":"10019721"},"scheduler-unstable_post_task.production.min.js":{"size":1969,"integrity":{"algorithm":"SHA256","hash":"627a52293d236f8e621f2f1c5e5fa95d29c9d4562baf780f83d88dc217e5c045","blockSize":4194304,"blocks":["627a52293d236f8e621f2f1c5e5fa95d29c9d4562baf780f83d88dc217e5c045"]},"offset":"10026604"},"scheduler.development.js":{"size":17497,"integrity":{"algorithm":"SHA256","hash":"22e3d959dc9f9cd59fca4e1fc95fecb9fde4d2cb8ecadbd279137ada995983ac","blockSize":4194304,"blocks":["22e3d959dc9f9cd59fca4e1fc95fecb9fde4d2cb8ecadbd279137ada995983ac"]},"offset":"10028573"},"scheduler.production.min.js":{"size":4235,"integrity":{"algorithm":"SHA256","hash":"f6cb8cf42696980c702f6b879417ab8bd489660485eb012b46f67e92e18a78ee","blockSize":4194304,"blocks":["f6cb8cf42696980c702f6b879417ab8bd489660485eb012b46f67e92e18a78ee"]},"offset":"10046070"}}}}},"semver":{"files":{"LICENSE":{"size":765,"integrity":{"algorithm":"SHA256","hash":"4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b","blockSize":4194304,"blocks":["4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b"]},"offset":"10050305"},"index.js":{"size":2691,"integrity":{"algorithm":"SHA256","hash":"4b3e57d3d40e29e0706002eba113d09f35aea593578376bbeec83b777b9912ab","blockSize":4194304,"blocks":["4b3e57d3d40e29e0706002eba113d09f35aea593578376bbeec83b777b9912ab"]},"offset":"10051070"},"package.json":{"size":1348,"integrity":{"algorithm":"SHA256","hash":"58ad67ac517e1610524a9327efa766de640856fb2ea62244f9fb45aa7f9f3694","blockSize":4194304,"blocks":["58ad67ac517e1610524a9327efa766de640856fb2ea62244f9fb45aa7f9f3694"]},"offset":"10053761"},"preload.js":{"size":83,"integrity":{"algorithm":"SHA256","hash":"edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba","blockSize":4194304,"blocks":["edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba"]},"offset":"10055109"},"range.bnf":{"size":702,"integrity":{"algorithm":"SHA256","hash":"15d0baf9b7b98e6d862c0cb9e822d2533d2bc23e136bb75314d802ca1fcb0392","blockSize":4194304,"blocks":["15d0baf9b7b98e6d862c0cb9e822d2533d2bc23e136bb75314d802ca1fcb0392"]},"offset":"10055192"},"ranges":{"files":{"gtr.js":{"size":231,"integrity":{"algorithm":"SHA256","hash":"8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19","blockSize":4194304,"blocks":["8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19"]},"offset":"10055894"},"intersects.js":{"size":224,"integrity":{"algorithm":"SHA256","hash":"fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f","blockSize":4194304,"blocks":["fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f"]},"offset":"10056125"},"ltr.js":{"size":227,"integrity":{"algorithm":"SHA256","hash":"e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038","blockSize":4194304,"blocks":["e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038"]},"offset":"10056349"},"max-satisfying.js":{"size":593,"integrity":{"algorithm":"SHA256","hash":"e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416","blockSize":4194304,"blocks":["e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416"]},"offset":"10056576"},"min-satisfying.js":{"size":591,"integrity":{"algorithm":"SHA256","hash":"2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca","blockSize":4194304,"blocks":["2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca"]},"offset":"10057169"},"min-version.js":{"size":1514,"integrity":{"algorithm":"SHA256","hash":"fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b","blockSize":4194304,"blocks":["fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b"]},"offset":"10057760"},"outside.js":{"size":2204,"integrity":{"algorithm":"SHA256","hash":"3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca","blockSize":4194304,"blocks":["3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca"]},"offset":"10059274"},"simplify.js":{"size":1355,"integrity":{"algorithm":"SHA256","hash":"7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934","blockSize":4194304,"blocks":["7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934"]},"offset":"10061478"},"subset.js":{"size":7478,"integrity":{"algorithm":"SHA256","hash":"ceb9eb6ed5bfc6c7ac7af7f47e5c3535444a4e66a0e2b58cdad4bd02a35d454d","blockSize":4194304,"blocks":["ceb9eb6ed5bfc6c7ac7af7f47e5c3535444a4e66a0e2b58cdad4bd02a35d454d"]},"offset":"10062833"},"to-comparators.js":{"size":282,"integrity":{"algorithm":"SHA256","hash":"6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9","blockSize":4194304,"blocks":["6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9"]},"offset":"10070311"},"valid.js":{"size":326,"integrity":{"algorithm":"SHA256","hash":"5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac","blockSize":4194304,"blocks":["5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac"]},"offset":"10070593"}}},"internal":{"files":{"constants.js":{"size":873,"integrity":{"algorithm":"SHA256","hash":"38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9","blockSize":4194304,"blocks":["38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9"]},"offset":"10070919"},"debug.js":{"size":240,"integrity":{"algorithm":"SHA256","hash":"8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3","blockSize":4194304,"blocks":["8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3"]},"offset":"10071792"},"identifiers.js":{"size":525,"integrity":{"algorithm":"SHA256","hash":"b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7","blockSize":4194304,"blocks":["b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7"]},"offset":"10072032"},"lrucache.js":{"size":802,"integrity":{"algorithm":"SHA256","hash":"14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f","blockSize":4194304,"blocks":["14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f"]},"offset":"10072557"},"parse-options.js":{"size":338,"integrity":{"algorithm":"SHA256","hash":"fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01","blockSize":4194304,"blocks":["fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01"]},"offset":"10073359"},"re.js":{"size":8139,"integrity":{"algorithm":"SHA256","hash":"5833262888e2b5d843a69193f83c05e374818dbe55379b497819b5bf58e48cd8","blockSize":4194304,"blocks":["5833262888e2b5d843a69193f83c05e374818dbe55379b497819b5bf58e48cd8"]},"offset":"10073697"}}},"functions":{"files":{"clean.js":{"size":205,"integrity":{"algorithm":"SHA256","hash":"4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f","blockSize":4194304,"blocks":["4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f"]},"offset":"10081836"},"cmp.js":{"size":961,"integrity":{"algorithm":"SHA256","hash":"a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3","blockSize":4194304,"blocks":["a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3"]},"offset":"10082041"},"coerce.js":{"size":2004,"integrity":{"algorithm":"SHA256","hash":"28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a","blockSize":4194304,"blocks":["28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a"]},"offset":"10083002"},"compare-build.js":{"size":281,"integrity":{"algorithm":"SHA256","hash":"5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c","blockSize":4194304,"blocks":["5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c"]},"offset":"10085006"},"compare-loose.js":{"size":132,"integrity":{"algorithm":"SHA256","hash":"07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78","blockSize":4194304,"blocks":["07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78"]},"offset":"10085287"},"compare.js":{"size":170,"integrity":{"algorithm":"SHA256","hash":"d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c","blockSize":4194304,"blocks":["d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c"]},"offset":"10085419"},"diff.js":{"size":1423,"integrity":{"algorithm":"SHA256","hash":"7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31","blockSize":4194304,"blocks":["7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31"]},"offset":"10085589"},"eq.js":{"size":126,"integrity":{"algorithm":"SHA256","hash":"b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936","blockSize":4194304,"blocks":["b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936"]},"offset":"10087012"},"gt.js":{"size":124,"integrity":{"algorithm":"SHA256","hash":"135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93","blockSize":4194304,"blocks":["135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93"]},"offset":"10087138"},"gte.js":{"size":127,"integrity":{"algorithm":"SHA256","hash":"991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d","blockSize":4194304,"blocks":["991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d"]},"offset":"10087262"},"inc.js":{"size":478,"integrity":{"algorithm":"SHA256","hash":"952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493","blockSize":4194304,"blocks":["952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493"]},"offset":"10087389"},"lt.js":{"size":124,"integrity":{"algorithm":"SHA256","hash":"1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25","blockSize":4194304,"blocks":["1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25"]},"offset":"10087867"},"lte.js":{"size":127,"integrity":{"algorithm":"SHA256","hash":"3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800","blockSize":4194304,"blocks":["3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800"]},"offset":"10087991"},"major.js":{"size":136,"integrity":{"algorithm":"SHA256","hash":"5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276","blockSize":4194304,"blocks":["5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276"]},"offset":"10088118"},"minor.js":{"size":136,"integrity":{"algorithm":"SHA256","hash":"1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6","blockSize":4194304,"blocks":["1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6"]},"offset":"10088254"},"neq.js":{"size":128,"integrity":{"algorithm":"SHA256","hash":"a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127","blockSize":4194304,"blocks":["a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127"]},"offset":"10088390"},"parse.js":{"size":331,"integrity":{"algorithm":"SHA256","hash":"29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad","blockSize":4194304,"blocks":["29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad"]},"offset":"10088518"},"patch.js":{"size":136,"integrity":{"algorithm":"SHA256","hash":"f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd","blockSize":4194304,"blocks":["f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd"]},"offset":"10088849"},"prerelease.js":{"size":234,"integrity":{"algorithm":"SHA256","hash":"baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593","blockSize":4194304,"blocks":["baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593"]},"offset":"10088985"},"rcompare.js":{"size":132,"integrity":{"algorithm":"SHA256","hash":"84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0","blockSize":4194304,"blocks":["84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0"]},"offset":"10089219"},"rsort.js":{"size":163,"integrity":{"algorithm":"SHA256","hash":"6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3","blockSize":4194304,"blocks":["6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3"]},"offset":"10089351"},"satisfies.js":{"size":247,"integrity":{"algorithm":"SHA256","hash":"8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946","blockSize":4194304,"blocks":["8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946"]},"offset":"10089514"},"sort.js":{"size":161,"integrity":{"algorithm":"SHA256","hash":"c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8","blockSize":4194304,"blocks":["c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8"]},"offset":"10089761"},"truncate.js":{"size":1021,"integrity":{"algorithm":"SHA256","hash":"e145833a250311927c92f424f56498c52f1b7bb1271ce6afbf006db87773ff43","blockSize":4194304,"blocks":["e145833a250311927c92f424f56498c52f1b7bb1271ce6afbf006db87773ff43"]},"offset":"10089922"},"valid.js":{"size":176,"integrity":{"algorithm":"SHA256","hash":"0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025","blockSize":4194304,"blocks":["0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025"]},"offset":"10090943"}}},"classes":{"files":{"comparator.js":{"size":3631,"integrity":{"algorithm":"SHA256","hash":"054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac","blockSize":4194304,"blocks":["054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac"]},"offset":"10091119"},"index.js":{"size":143,"integrity":{"algorithm":"SHA256","hash":"3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17","blockSize":4194304,"blocks":["3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17"]},"offset":"10094750"},"range.js":{"size":15647,"integrity":{"algorithm":"SHA256","hash":"a6544485aa8575aa9854c67e2caa67726815de18a482d0ceb8a1003244de3bc1","blockSize":4194304,"blocks":["a6544485aa8575aa9854c67e2caa67726815de18a482d0ceb8a1003244de3bc1"]},"offset":"10094893"},"semver.js":{"size":9891,"integrity":{"algorithm":"SHA256","hash":"813b2c185512d30c9b931c2fed8140889d9d7490ceeeedc370da30337dc8ca57","blockSize":4194304,"blocks":["813b2c185512d30c9b931c2fed8140889d9d7490ceeeedc370da30337dc8ca57"]},"offset":"10110540"}}},"bin":{"files":{"semver.js":{"size":4957,"integrity":{"algorithm":"SHA256","hash":"bd6c871026985937dc945011fc54b74b47f5998154216d7b8d40d5ed782e4402","blockSize":4194304,"blocks":["bd6c871026985937dc945011fc54b74b47f5998154216d7b8d40d5ed782e4402"]},"offset":"10120431","executable":true}}}}},"type-fest":{"files":{"package.json":{"size":654,"integrity":{"algorithm":"SHA256","hash":"60eea41c2a8b76dd846b458bd18a4ea0b09b138a3bc244c079fc48dec3f746ad","blockSize":4194304,"blocks":["60eea41c2a8b76dd846b458bd18a4ea0b09b138a3bc244c079fc48dec3f746ad"]},"offset":"10125388"}}},"use-sync-external-store":{"files":{"LICENSE":{"size":1088,"integrity":{"algorithm":"SHA256","hash":"da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93","blockSize":4194304,"blocks":["da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93"]},"offset":"10126042"},"index.js":{"size":222,"integrity":{"algorithm":"SHA256","hash":"d21888099b46792f16d5a540623cda49d270a7346ffe3878435cc312abb17682","blockSize":4194304,"blocks":["d21888099b46792f16d5a540623cda49d270a7346ffe3878435cc312abb17682"]},"offset":"10127130"},"package.json":{"size":1248,"integrity":{"algorithm":"SHA256","hash":"dfdead719ce161e1c5edbf0fca0ce0e7d70ba87c8a8f249856c0afde81595f24","blockSize":4194304,"blocks":["dfdead719ce161e1c5edbf0fca0ce0e7d70ba87c8a8f249856c0afde81595f24"]},"offset":"10127352"},"with-selector.js":{"size":250,"integrity":{"algorithm":"SHA256","hash":"2e90f9e6323b863b6d6132e1f45fc262ceceb8c861f686a9593a2369cf5c609e","blockSize":4194304,"blocks":["2e90f9e6323b863b6d6132e1f45fc262ceceb8c861f686a9593a2369cf5c609e"]},"offset":"10128600"},"shim":{"files":{"index.js":{"size":234,"integrity":{"algorithm":"SHA256","hash":"de571b60495a636e12a24000b78531994a819aba03917e679803c2b482c66a89","blockSize":4194304,"blocks":["de571b60495a636e12a24000b78531994a819aba03917e679803c2b482c66a89"]},"offset":"10128850"},"index.native.js":{"size":248,"integrity":{"algorithm":"SHA256","hash":"d1211307208ab6270b30894af7c61d16c5f6588cb382ca6107d11f84ef8b11f6","blockSize":4194304,"blocks":["d1211307208ab6270b30894af7c61d16c5f6588cb382ca6107d11f84ef8b11f6"]},"offset":"10129084"},"with-selector.js":{"size":262,"integrity":{"algorithm":"SHA256","hash":"08f4e878658941dd77b3d9032d2f0818649dd0a093288e768526090e9f00556f","blockSize":4194304,"blocks":["08f4e878658941dd77b3d9032d2f0818649dd0a093288e768526090e9f00556f"]},"offset":"10129332"}}},"cjs":{"files":{"use-sync-external-store-shim.development.js":{"size":3457,"integrity":{"algorithm":"SHA256","hash":"6dfd5d60543b0a24a524d1366758ff6303fc67604a69eb1536d0b70c47af0e8d","blockSize":4194304,"blocks":["6dfd5d60543b0a24a524d1366758ff6303fc67604a69eb1536d0b70c47af0e8d"]},"offset":"10129594"},"use-sync-external-store-shim.native.development.js":{"size":3166,"integrity":{"algorithm":"SHA256","hash":"77fdf6e7158ca42db77846603e5404d6c1eae8e39c027ae6688ec31960130d10","blockSize":4194304,"blocks":["77fdf6e7158ca42db77846603e5404d6c1eae8e39c027ae6688ec31960130d10"]},"offset":"10133051"},"use-sync-external-store-shim.native.production.js":{"size":1712,"integrity":{"algorithm":"SHA256","hash":"854acd16966761052074efc076dda867c4fd2c3db41cb3b85ee8d15aaf072a21","blockSize":4194304,"blocks":["854acd16966761052074efc076dda867c4fd2c3db41cb3b85ee8d15aaf072a21"]},"offset":"10136217"},"use-sync-external-store-shim.production.js":{"size":1967,"integrity":{"algorithm":"SHA256","hash":"e8c2f1808804d75c9e0ffab8c37329b34f356140275dea0efe1e75684ded14fa","blockSize":4194304,"blocks":["e8c2f1808804d75c9e0ffab8c37329b34f356140275dea0efe1e75684ded14fa"]},"offset":"10137929"},"use-sync-external-store-with-selector.development.js":{"size":3468,"integrity":{"algorithm":"SHA256","hash":"48111cde39f0b32a3dbb4cdedecf31939450b233e7deedb0da9b74d58e4f97ac","blockSize":4194304,"blocks":["48111cde39f0b32a3dbb4cdedecf31939450b233e7deedb0da9b74d58e4f97ac"]},"offset":"10139896"},"use-sync-external-store-with-selector.production.js":{"size":2631,"integrity":{"algorithm":"SHA256","hash":"d634a0554277dcca162f5c1ae28978c5bf0f3c0f56f16e35e8926bd31021781e","blockSize":4194304,"blocks":["d634a0554277dcca162f5c1ae28978c5bf0f3c0f56f16e35e8926bd31021781e"]},"offset":"10143364"},"use-sync-external-store.development.js":{"size":1374,"integrity":{"algorithm":"SHA256","hash":"bd999528bc05772118316ace694df775169d2b6dece86a486d7a8a8567a50e39","blockSize":4194304,"blocks":["bd999528bc05772118316ace694df775169d2b6dece86a486d7a8a8567a50e39"]},"offset":"10145995"},"use-sync-external-store.production.js":{"size":387,"integrity":{"algorithm":"SHA256","hash":"4ed641853adbce751186824e8e661b7218a559cf7c148b810bd8d9bf29dc3a31","blockSize":4194304,"blocks":["4ed641853adbce751186824e8e661b7218a559cf7c148b810bd8d9bf29dc3a31"]},"offset":"10147369"},"use-sync-external-store-shim":{"files":{"with-selector.development.js":{"size":3526,"integrity":{"algorithm":"SHA256","hash":"47600087cfa6f998386b2d2b46072b28564d2992099676b0d3eed8c0031f78b9","blockSize":4194304,"blocks":["47600087cfa6f998386b2d2b46072b28564d2992099676b0d3eed8c0031f78b9"]},"offset":"10147756"},"with-selector.production.js":{"size":2685,"integrity":{"algorithm":"SHA256","hash":"fc76f309604db72c728d7c46cc593c6bba65e3f3d00dd38a1c32032927bb94d8","blockSize":4194304,"blocks":["fc76f309604db72c728d7c46cc593c6bba65e3f3d00dd38a1c32032927bb94d8"]},"offset":"10151282"}}}}}}},"zustand":{"files":{"LICENSE":{"size":1070,"integrity":{"algorithm":"SHA256","hash":"c1e6e266563517467b1bf874817d23e426f3149252bd7d42758cd697514b8417","blockSize":4194304,"blocks":["c1e6e266563517467b1bf874817d23e426f3149252bd7d42758cd697514b8417"]},"offset":"10153967"},"context.js":{"size":2006,"integrity":{"algorithm":"SHA256","hash":"73a2113c3e2dafdc36eedc541657ff2bec6a6196961bd300e5627210d1d31d74","blockSize":4194304,"blocks":["73a2113c3e2dafdc36eedc541657ff2bec6a6196961bd300e5627210d1d31d74"]},"offset":"10155037"},"index.js":{"size":2481,"integrity":{"algorithm":"SHA256","hash":"d4e46b7dfac60ee8ecda1eb1619020b4052d1a1f5366505d867eba1ee2ef4875","blockSize":4194304,"blocks":["d4e46b7dfac60ee8ecda1eb1619020b4052d1a1f5366505d867eba1ee2ef4875"]},"offset":"10157043"},"middleware.js":{"size":22167,"integrity":{"algorithm":"SHA256","hash":"de1f0a52459c3e8bf54bd1cafb01a57d6a83374e116b0bc293bb4e320975e347","blockSize":4194304,"blocks":["de1f0a52459c3e8bf54bd1cafb01a57d6a83374e116b0bc293bb4e320975e347"]},"offset":"10159524"},"package.json":{"size":5198,"integrity":{"algorithm":"SHA256","hash":"f39e0b89fdd06bf92da60d4ce987f423f80cecdc73fc6c9ab615fd878161cb34","blockSize":4194304,"blocks":["f39e0b89fdd06bf92da60d4ce987f423f80cecdc73fc6c9ab615fd878161cb34"]},"offset":"10181691"},"shallow.js":{"size":2831,"integrity":{"algorithm":"SHA256","hash":"e7b3a002b3c105d425a93665f74584dc3195112cf5b2ba19e07d236d53886a41","blockSize":4194304,"blocks":["e7b3a002b3c105d425a93665f74584dc3195112cf5b2ba19e07d236d53886a41"]},"offset":"10186889"},"traditional.js":{"size":1484,"integrity":{"algorithm":"SHA256","hash":"f2b0de3fefaba7bff5c78a51ed336f804d97a4cf2d3ee83684fa7f415c46983e","blockSize":4194304,"blocks":["f2b0de3fefaba7bff5c78a51ed336f804d97a4cf2d3ee83684fa7f415c46983e"]},"offset":"10189720"},"vanilla.js":{"size":2014,"integrity":{"algorithm":"SHA256","hash":"11b4ba22fadad3a5fe89438615c2099d4a839f64691c9435e46e0b2e793b9b08","blockSize":4194304,"blocks":["11b4ba22fadad3a5fe89438615c2099d4a839f64691c9435e46e0b2e793b9b08"]},"offset":"10191204"},"vanilla":{"files":{"shallow.js":{"size":2455,"integrity":{"algorithm":"SHA256","hash":"4c9420dfaf2578de400157beb6a1aa8a92fb8b7e10c9bcb6e0131b6496cefe1e","blockSize":4194304,"blocks":["4c9420dfaf2578de400157beb6a1aa8a92fb8b7e10c9bcb6e0131b6496cefe1e"]},"offset":"10193218"}}},"umd":{"files":{"context.development.js":{"size":2442,"integrity":{"algorithm":"SHA256","hash":"68e90d04fa79c7a90340f09d997ccbea5ebd8ac7eefa1fd098696d28e1b5b7eb","blockSize":4194304,"blocks":["68e90d04fa79c7a90340f09d997ccbea5ebd8ac7eefa1fd098696d28e1b5b7eb"]},"offset":"10195673"},"context.production.js":{"size":1138,"integrity":{"algorithm":"SHA256","hash":"e59fd0981e057de80f91a0e0887d609c70f414273b08f849c6e0890e7151f230","blockSize":4194304,"blocks":["e59fd0981e057de80f91a0e0887d609c70f414273b08f849c6e0890e7151f230"]},"offset":"10198115"},"index.development.js":{"size":2816,"integrity":{"algorithm":"SHA256","hash":"41911826807a263762687e96aa090f1b3d896cd1e8c9abe695f0705248d3bc41","blockSize":4194304,"blocks":["41911826807a263762687e96aa090f1b3d896cd1e8c9abe695f0705248d3bc41"]},"offset":"10199253"},"index.production.js":{"size":1120,"integrity":{"algorithm":"SHA256","hash":"decf2516ac2e4d7466d5f452cc9cbaf128c541cd345c72d5806b286762b93246","blockSize":4194304,"blocks":["decf2516ac2e4d7466d5f452cc9cbaf128c541cd345c72d5806b286762b93246"]},"offset":"10202069"},"middleware.development.js":{"size":23584,"integrity":{"algorithm":"SHA256","hash":"b4c95898b0eeffaad94bd553aa51a942c2a719f6200d235165ac5f420b912274","blockSize":4194304,"blocks":["b4c95898b0eeffaad94bd553aa51a942c2a719f6200d235165ac5f420b912274"]},"offset":"10203189"},"middleware.production.js":{"size":8854,"integrity":{"algorithm":"SHA256","hash":"2506378fa8dfd5682e4dda55721f766690e2a82808400aea9bfcf5c89964bf4f","blockSize":4194304,"blocks":["2506378fa8dfd5682e4dda55721f766690e2a82808400aea9bfcf5c89964bf4f"]},"offset":"10226773"},"shallow.development.js":{"size":3257,"integrity":{"algorithm":"SHA256","hash":"c21b791f8070937d835d7ed07e8bbad952f4aead8a97461b72f740f8a4adcdc7","blockSize":4194304,"blocks":["c21b791f8070937d835d7ed07e8bbad952f4aead8a97461b72f740f8a4adcdc7"]},"offset":"10235627"},"shallow.production.js":{"size":1751,"integrity":{"algorithm":"SHA256","hash":"405aa1d96f9a3279eaa2f76bda41d5512369164e059ad4a2e57fa5519561e19b","blockSize":4194304,"blocks":["405aa1d96f9a3279eaa2f76bda41d5512369164e059ad4a2e57fa5519561e19b"]},"offset":"10238884"},"traditional.development.js":{"size":2030,"integrity":{"algorithm":"SHA256","hash":"db8177da65f0322d113062b4fb8083d3af076d7675343a736ac31c31b5bcd0d9","blockSize":4194304,"blocks":["db8177da65f0322d113062b4fb8083d3af076d7675343a736ac31c31b5bcd0d9"]},"offset":"10240635"},"traditional.production.js":{"size":904,"integrity":{"algorithm":"SHA256","hash":"1e441ae28da79ea28eae313d1ad1962bd137ab37cf117092c19c66ed040eab56","blockSize":4194304,"blocks":["1e441ae28da79ea28eae313d1ad1962bd137ab37cf117092c19c66ed040eab56"]},"offset":"10242665"},"vanilla.development.js":{"size":2339,"integrity":{"algorithm":"SHA256","hash":"50e6e5f99c1964cb9b0b3505603ef9b27849dc6cae6b03082b5cda5d0f3b8b91","blockSize":4194304,"blocks":["50e6e5f99c1964cb9b0b3505603ef9b27849dc6cae6b03082b5cda5d0f3b8b91"]},"offset":"10243569"},"vanilla.production.js":{"size":811,"integrity":{"algorithm":"SHA256","hash":"8ae7edf7828217ed68f3907144e68d09b54ad73e567cef7878bd6d8e9c07b7b6","blockSize":4194304,"blocks":["8ae7edf7828217ed68f3907144e68d09b54ad73e567cef7878bd6d8e9c07b7b6"]},"offset":"10245908"},"vanilla":{"files":{"shallow.development.js":{"size":2948,"integrity":{"algorithm":"SHA256","hash":"e243a3b3f8fe109a48292e574c1d80e2339b266eb767e2046322af237af0ec1f","blockSize":4194304,"blocks":["e243a3b3f8fe109a48292e574c1d80e2339b266eb767e2046322af237af0ec1f"]},"offset":"10246719"},"shallow.production.js":{"size":1667,"integrity":{"algorithm":"SHA256","hash":"3dabbafdf883f16b216c86583e8dee8db02eea13d61c3967576b229e76e430ea","blockSize":4194304,"blocks":["3dabbafdf883f16b216c86583e8dee8db02eea13d61c3967576b229e76e430ea"]},"offset":"10249667"}}},"react":{"files":{"shallow.development.js":{"size":3257,"integrity":{"algorithm":"SHA256","hash":"aa3f99cde3d1b6e681c5f41f2a8f0eb65ae44a42e13571a4b253f7c536c9d019","blockSize":4194304,"blocks":["aa3f99cde3d1b6e681c5f41f2a8f0eb65ae44a42e13571a4b253f7c536c9d019"]},"offset":"10251334"},"shallow.production.js":{"size":1814,"integrity":{"algorithm":"SHA256","hash":"04b55bdf410f48c77ec44978882fceaeec2fac5183bc5ae4d71d58e9c6c0aa2c","blockSize":4194304,"blocks":["04b55bdf410f48c77ec44978882fceaeec2fac5183bc5ae4d71d58e9c6c0aa2c"]},"offset":"10254591"}}},"middleware":{"files":{"immer.development.js":{"size":1012,"integrity":{"algorithm":"SHA256","hash":"7dccf3f3b7480b36fc7c8e3a7248fefcb60ffd0b65219a40dd002549ffee6a9a","blockSize":4194304,"blocks":["7dccf3f3b7480b36fc7c8e3a7248fefcb60ffd0b65219a40dd002549ffee6a9a"]},"offset":"10256405"},"immer.production.js":{"size":556,"integrity":{"algorithm":"SHA256","hash":"dc8f02ef3133d9d12a6692613ccc9f71ee0903d11caa0d28b8d2637eea0e3b98","blockSize":4194304,"blocks":["dc8f02ef3133d9d12a6692613ccc9f71ee0903d11caa0d28b8d2637eea0e3b98"]},"offset":"10257417"}}}}},"system":{"files":{"context.development.js":{"size":2098,"integrity":{"algorithm":"SHA256","hash":"a1e2904f7a51eae28a37711809dc656342375a5627c70f89b2a45dfad6a1ea97","blockSize":4194304,"blocks":["a1e2904f7a51eae28a37711809dc656342375a5627c70f89b2a45dfad6a1ea97"]},"offset":"10257973"},"context.production.js":{"size":715,"integrity":{"algorithm":"SHA256","hash":"fa984b021f3dc0752d79409d94fcbb7e553488754916e00f1045dd939fb0f54c","blockSize":4194304,"blocks":["fa984b021f3dc0752d79409d94fcbb7e553488754916e00f1045dd939fb0f54c"]},"offset":"10260071"},"index.development.js":{"size":2612,"integrity":{"algorithm":"SHA256","hash":"54d8c7b7ab9982f86faad4a02702821714214db22d1d8d9f094f8cf3adc42461","blockSize":4194304,"blocks":["54d8c7b7ab9982f86faad4a02702821714214db22d1d8d9f094f8cf3adc42461"]},"offset":"10260786"},"index.production.js":{"size":697,"integrity":{"algorithm":"SHA256","hash":"f0063e476043dd24024c15433af266388848ff798d7bc6b84ec030adc2b270c9","blockSize":4194304,"blocks":["f0063e476043dd24024c15433af266388848ff798d7bc6b84ec030adc2b270c9"]},"offset":"10263398"},"middleware.development.js":{"size":22257,"integrity":{"algorithm":"SHA256","hash":"df6a2f584c0c9cad7a050d51cfad27c7716d5ab3653ef9fd7443bedb9da2028d","blockSize":4194304,"blocks":["df6a2f584c0c9cad7a050d51cfad27c7716d5ab3653ef9fd7443bedb9da2028d"]},"offset":"10264095"},"middleware.production.js":{"size":7159,"integrity":{"algorithm":"SHA256","hash":"353f3d7f161fcd9637d3cc250b738eab017049bd69c4db00d8f9f9432f2ad0e7","blockSize":4194304,"blocks":["353f3d7f161fcd9637d3cc250b738eab017049bd69c4db00d8f9f9432f2ad0e7"]},"offset":"10286352"},"shallow.development.js":{"size":1593,"integrity":{"algorithm":"SHA256","hash":"726ae573663a68055706ae552f23d839dca8b43bc7b22da78bdf64f309911b62","blockSize":4194304,"blocks":["726ae573663a68055706ae552f23d839dca8b43bc7b22da78bdf64f309911b62"]},"offset":"10293511"},"shallow.production.js":{"size":654,"integrity":{"algorithm":"SHA256","hash":"d868e5c08c361a4d7b66b1b0bd97bbfc3213e71e9db0a2a6be7be8e5d6d51016","blockSize":4194304,"blocks":["d868e5c08c361a4d7b66b1b0bd97bbfc3213e71e9db0a2a6be7be8e5d6d51016"]},"offset":"10295104"},"traditional.development.js":{"size":1629,"integrity":{"algorithm":"SHA256","hash":"a5ea25b4c75dd639b5601f1382e24fb8b2f8a5a6380d7465d12bd127edbd9576","blockSize":4194304,"blocks":["a5ea25b4c75dd639b5601f1382e24fb8b2f8a5a6380d7465d12bd127edbd9576"]},"offset":"10295758"},"traditional.production.js":{"size":577,"integrity":{"algorithm":"SHA256","hash":"96ff39cc65b0619cf9182b1d89ca92c77bc51e61dc4b07e41db2ee112d4aa2ac","blockSize":4194304,"blocks":["96ff39cc65b0619cf9182b1d89ca92c77bc51e61dc4b07e41db2ee112d4aa2ac"]},"offset":"10297387"},"vanilla.development.js":{"size":1889,"integrity":{"algorithm":"SHA256","hash":"44954d14819dc4ef65d92ac1bad573131fbec3f82ea28f91b74f78c2f28677de","blockSize":4194304,"blocks":["44954d14819dc4ef65d92ac1bad573131fbec3f82ea28f91b74f78c2f28677de"]},"offset":"10297964"},"vanilla.production.js":{"size":476,"integrity":{"algorithm":"SHA256","hash":"5da07bcf0f03bf3f429b3d9fca06f6c5bd2579820a36e97d8bbc42e7abc3bb69","blockSize":4194304,"blocks":["5da07bcf0f03bf3f429b3d9fca06f6c5bd2579820a36e97d8bbc42e7abc3bb69"]},"offset":"10299853"},"vanilla":{"files":{"shallow.development.js":{"size":1312,"integrity":{"algorithm":"SHA256","hash":"afa96285dde5004c3899bc9f2039a49dc245f66481c39fffc4d2f5c3d6f93632","blockSize":4194304,"blocks":["afa96285dde5004c3899bc9f2039a49dc245f66481c39fffc4d2f5c3d6f93632"]},"offset":"10300329"},"shallow.production.js":{"size":622,"integrity":{"algorithm":"SHA256","hash":"b19b2a0111bd6c8f341c17f67ef7543ecbc12e2f7eaa46490873283a3ae73241","blockSize":4194304,"blocks":["b19b2a0111bd6c8f341c17f67ef7543ecbc12e2f7eaa46490873283a3ae73241"]},"offset":"10301641"}}},"react":{"files":{"shallow.development.js":{"size":1703,"integrity":{"algorithm":"SHA256","hash":"43991159d9b2931c734151ce67495a2fd1f84ba0af7d25b54dc14220162b2469","blockSize":4194304,"blocks":["43991159d9b2931c734151ce67495a2fd1f84ba0af7d25b54dc14220162b2469"]},"offset":"10302263"},"shallow.production.js":{"size":786,"integrity":{"algorithm":"SHA256","hash":"43ee5f6a3010c82c12383cf67f0bd1fbbd01e729d7b2b080fe1db49e74a9de69","blockSize":4194304,"blocks":["43ee5f6a3010c82c12383cf67f0bd1fbbd01e729d7b2b080fe1db49e74a9de69"]},"offset":"10303966"}}},"middleware":{"files":{"immer.development.js":{"size":592,"integrity":{"algorithm":"SHA256","hash":"e8be94cda2c0732343ab82655616bd8052dde0d23d62a0c3d393f0b6c18c45f0","blockSize":4194304,"blocks":["e8be94cda2c0732343ab82655616bd8052dde0d23d62a0c3d393f0b6c18c45f0"]},"offset":"10304752"},"immer.production.js":{"size":254,"integrity":{"algorithm":"SHA256","hash":"46f84f7697054138d747fc1ed509b7727b0f16a29785408a772e5dfc6db7e146","blockSize":4194304,"blocks":["46f84f7697054138d747fc1ed509b7727b0f16a29785408a772e5dfc6db7e146"]},"offset":"10305344"}}}}},"react":{"files":{"shallow.js":{"size":2733,"integrity":{"algorithm":"SHA256","hash":"d3672223eb7727967661df44f13cf6a4ffed70215a010b289141a8491b43a7ea","blockSize":4194304,"blocks":["d3672223eb7727967661df44f13cf6a4ffed70215a010b289141a8491b43a7ea"]},"offset":"10305598"}}},"middleware":{"files":{"immer.js":{"size":615,"integrity":{"algorithm":"SHA256","hash":"459734c25a4b51b1b0463da697190f203fb72b5bd53b42f4a8a8b3bd86154d3c","blockSize":4194304,"blocks":["459734c25a4b51b1b0463da697190f203fb72b5bd53b42f4a8a8b3bd86154d3c"]},"offset":"10308331"}}},"esm":{"files":{"context.d.mts":{"size":879,"integrity":{"algorithm":"SHA256","hash":"2dc743f66b8c9fd3e7b94ddbb62a2840016045433b74b43b06939dd9aef0e328","blockSize":4194304,"blocks":["2dc743f66b8c9fd3e7b94ddbb62a2840016045433b74b43b06939dd9aef0e328"]},"offset":"10308946"},"context.js":{"size":1540,"integrity":{"algorithm":"SHA256","hash":"76b7eb61e7cf95eb274dc57807d8e9af6d3193017bb9b89c6c2fee0c806362b8","blockSize":4194304,"blocks":["76b7eb61e7cf95eb274dc57807d8e9af6d3193017bb9b89c6c2fee0c806362b8"]},"offset":"10309825"},"context.mjs":{"size":1569,"integrity":{"algorithm":"SHA256","hash":"504d48e839786bc8e88933585e1ba77810f92c7112a95e95e1ac071dfeeff8e0","blockSize":4194304,"blocks":["504d48e839786bc8e88933585e1ba77810f92c7112a95e95e1ac071dfeeff8e0"]},"offset":"10311365"},"index.d.mts":{"size":99,"integrity":{"algorithm":"SHA256","hash":"8258b4ec62cf9f136f1613e1602156fdd0852bb8715dde963d217ad4d61d8d09","blockSize":4194304,"blocks":["8258b4ec62cf9f136f1613e1602156fdd0852bb8715dde963d217ad4d61d8d09"]},"offset":"10312934"},"index.js":{"size":1927,"integrity":{"algorithm":"SHA256","hash":"3d861863e101a96fcaf8dadc878161ed235af8ba62f4e2651cd467d9fbbdbdf7","blockSize":4194304,"blocks":["3d861863e101a96fcaf8dadc878161ed235af8ba62f4e2651cd467d9fbbdbdf7"]},"offset":"10313033"},"index.mjs":{"size":2014,"integrity":{"algorithm":"SHA256","hash":"eaeb7f0cc57d925e6cc04636ee56cae378c1de249e2cd30dc892883e04ec4cda","blockSize":4194304,"blocks":["eaeb7f0cc57d925e6cc04636ee56cae378c1de249e2cd30dc892883e04ec4cda"]},"offset":"10314960"},"middleware.d.mts":{"size":223,"integrity":{"algorithm":"SHA256","hash":"3672426a97d387a710aa2d0c3804024769c310ce9953771d471062cc71f47d51","blockSize":4194304,"blocks":["3672426a97d387a710aa2d0c3804024769c310ce9953771d471062cc71f47d51"]},"offset":"10316974"},"middleware.js":{"size":18781,"integrity":{"algorithm":"SHA256","hash":"1f69053c68ce0f39286caf1b96cbcf53715352d8555e4af512b606e44a7d225b","blockSize":4194304,"blocks":["1f69053c68ce0f39286caf1b96cbcf53715352d8555e4af512b606e44a7d225b"]},"offset":"10317197"},"middleware.mjs":{"size":18897,"integrity":{"algorithm":"SHA256","hash":"4180bb568d264705d321b9868fb6a445b6d8df7a8e2bb686774b8e22eb775ee1","blockSize":4194304,"blocks":["4180bb568d264705d321b9868fb6a445b6d8df7a8e2bb686774b8e22eb775ee1"]},"offset":"10335978"},"react.d.mts":{"size":2035,"integrity":{"algorithm":"SHA256","hash":"98bb67aa18a720c471e2739441d8bdecdae17c40361914c1ccffab0573356a85","blockSize":4194304,"blocks":["98bb67aa18a720c471e2739441d8bdecdae17c40361914c1ccffab0573356a85"]},"offset":"10354875"},"shallow.d.mts":{"size":205,"integrity":{"algorithm":"SHA256","hash":"1e9d965049982390ed88f5b2572d6a695d58707218110d81ac13148198d6626e","blockSize":4194304,"blocks":["1e9d965049982390ed88f5b2572d6a695d58707218110d81ac13148198d6626e"]},"offset":"10356910"},"shallow.js":{"size":1252,"integrity":{"algorithm":"SHA256","hash":"f83b53aa4eaf44eba6d1af36b8838b1cb3315dfb73d8ded6a4e8edaf5594be5b","blockSize":4194304,"blocks":["f83b53aa4eaf44eba6d1af36b8838b1cb3315dfb73d8ded6a4e8edaf5594be5b"]},"offset":"10357115"},"shallow.mjs":{"size":1281,"integrity":{"algorithm":"SHA256","hash":"cdd99918df745a2a6fc202ba69d99211593982eb7f8c834a30f6c105fe88f7de","blockSize":4194304,"blocks":["cdd99918df745a2a6fc202ba69d99211593982eb7f8c834a30f6c105fe88f7de"]},"offset":"10358367"},"traditional.d.mts":{"size":1477,"integrity":{"algorithm":"SHA256","hash":"070429820a0c6e101b7a9d1836905c022469a341eddd4fcc1ce223980e08aa5c","blockSize":4194304,"blocks":["070429820a0c6e101b7a9d1836905c022469a341eddd4fcc1ce223980e08aa5c"]},"offset":"10359648"},"traditional.js":{"size":1158,"integrity":{"algorithm":"SHA256","hash":"4b0b75514cf5b7e4ca9363a18af33be7f4f0e75413cc74d1421607b755f7fc69","blockSize":4194304,"blocks":["4b0b75514cf5b7e4ca9363a18af33be7f4f0e75413cc74d1421607b755f7fc69"]},"offset":"10361125"},"traditional.mjs":{"size":1158,"integrity":{"algorithm":"SHA256","hash":"4b0b75514cf5b7e4ca9363a18af33be7f4f0e75413cc74d1421607b755f7fc69","blockSize":4194304,"blocks":["4b0b75514cf5b7e4ca9363a18af33be7f4f0e75413cc74d1421607b755f7fc69"]},"offset":"10362283"},"vanilla.d.mts":{"size":3351,"integrity":{"algorithm":"SHA256","hash":"41f45ed6b4cd7b8aec2e4888a47d5061ee1020f89375b57d388cfe1f05313991","blockSize":4194304,"blocks":["41f45ed6b4cd7b8aec2e4888a47d5061ee1020f89375b57d388cfe1f05313991"]},"offset":"10363441"},"vanilla.js":{"size":1632,"integrity":{"algorithm":"SHA256","hash":"53f33d090e9567f3726708546ec1d8ff5bd6595906f66977dfcaa44420dd4851","blockSize":4194304,"blocks":["53f33d090e9567f3726708546ec1d8ff5bd6595906f66977dfcaa44420dd4851"]},"offset":"10366792"},"vanilla.mjs":{"size":1690,"integrity":{"algorithm":"SHA256","hash":"6eea342dd71d7f242f499c34e2e5224a352f9f2d6142805d959deb9082feb074","blockSize":4194304,"blocks":["6eea342dd71d7f242f499c34e2e5224a352f9f2d6142805d959deb9082feb074"]},"offset":"10368424"},"vanilla":{"files":{"shallow.d.mts":{"size":63,"integrity":{"algorithm":"SHA256","hash":"79fd86f612b3a83813de1aa6b6218658fe67b53b99e51369a140966a8aabf439","blockSize":4194304,"blocks":["79fd86f612b3a83813de1aa6b6218658fe67b53b99e51369a140966a8aabf439"]},"offset":"10370114"},"shallow.js":{"size":965,"integrity":{"algorithm":"SHA256","hash":"f24dc618f248b5f66f60945e518b30817c4009be0a98bb61218849a121261f84","blockSize":4194304,"blocks":["f24dc618f248b5f66f60945e518b30817c4009be0a98bb61218849a121261f84"]},"offset":"10370177"},"shallow.mjs":{"size":965,"integrity":{"algorithm":"SHA256","hash":"f24dc618f248b5f66f60945e518b30817c4009be0a98bb61218849a121261f84","blockSize":4194304,"blocks":["f24dc618f248b5f66f60945e518b30817c4009be0a98bb61218849a121261f84"]},"offset":"10371142"}}},"react":{"files":{"shallow.d.mts":{"size":86,"integrity":{"algorithm":"SHA256","hash":"4781142e27cfd19d75a2c0ee432826153fcdf670bdc52631a6078330c9133e6f","blockSize":4194304,"blocks":["4781142e27cfd19d75a2c0ee432826153fcdf670bdc52631a6078330c9133e6f"]},"offset":"10372107"},"shallow.js":{"size":1234,"integrity":{"algorithm":"SHA256","hash":"e678bd0e2a01e9dd495853f1dc7c75492f82e9afa9bfa7e3fe37f95b21010e44","blockSize":4194304,"blocks":["e678bd0e2a01e9dd495853f1dc7c75492f82e9afa9bfa7e3fe37f95b21010e44"]},"offset":"10372193"},"shallow.mjs":{"size":1234,"integrity":{"algorithm":"SHA256","hash":"e678bd0e2a01e9dd495853f1dc7c75492f82e9afa9bfa7e3fe37f95b21010e44","blockSize":4194304,"blocks":["e678bd0e2a01e9dd495853f1dc7c75492f82e9afa9bfa7e3fe37f95b21010e44"]},"offset":"10373427"}}},"middleware":{"files":{"combine.d.mts":{"size":438,"integrity":{"algorithm":"SHA256","hash":"98b1c3591f5ce0dd151fa011ea936b095779217d2a87a2a3701da47ce4a498a1","blockSize":4194304,"blocks":["98b1c3591f5ce0dd151fa011ea936b095779217d2a87a2a3701da47ce4a498a1"]},"offset":"10374661"},"devtools.d.mts":{"size":1923,"integrity":{"algorithm":"SHA256","hash":"c0c43bf56c3ea9ecc2491dc6e7a2f7ee6a2c730ed79c1bb5eec7af3902729cb2","blockSize":4194304,"blocks":["c0c43bf56c3ea9ecc2491dc6e7a2f7ee6a2c730ed79c1bb5eec7af3902729cb2"]},"offset":"10375099"},"immer.d.mts":{"size":1204,"integrity":{"algorithm":"SHA256","hash":"924fb867403d4a486f9e3474624705756ab8e3fea2493387441704db04614926","blockSize":4194304,"blocks":["924fb867403d4a486f9e3474624705756ab8e3fea2493387441704db04614926"]},"offset":"10377022"},"immer.js":{"size":367,"integrity":{"algorithm":"SHA256","hash":"7000eca6dddfb62048e35e5c6c6b1c8af868f969c6e1c348088848a69c78806f","blockSize":4194304,"blocks":["7000eca6dddfb62048e35e5c6c6b1c8af868f969c6e1c348088848a69c78806f"]},"offset":"10378226"},"immer.mjs":{"size":367,"integrity":{"algorithm":"SHA256","hash":"7000eca6dddfb62048e35e5c6c6b1c8af868f969c6e1c348088848a69c78806f","blockSize":4194304,"blocks":["7000eca6dddfb62048e35e5c6c6b1c8af868f969c6e1c348088848a69c78806f"]},"offset":"10378593"},"persist.d.mts":{"size":4908,"integrity":{"algorithm":"SHA256","hash":"aad0b04040ca82c60ff3ea244f4d15ac9faa6e124b053b553e7a1e03d6a6737d","blockSize":4194304,"blocks":["aad0b04040ca82c60ff3ea244f4d15ac9faa6e124b053b553e7a1e03d6a6737d"]},"offset":"10378960"},"redux.d.mts":{"size":734,"integrity":{"algorithm":"SHA256","hash":"025c00e68cf1e9578f198c9387e74cdf481f472e5384a69143edbcf4168cdb96","blockSize":4194304,"blocks":["025c00e68cf1e9578f198c9387e74cdf481f472e5384a69143edbcf4168cdb96"]},"offset":"10383868"},"subscribeWithSelector.d.mts":{"size":1163,"integrity":{"algorithm":"SHA256","hash":"9eaa04e9271513d4faacc732b056efa329d297be18a4d5908f3becced2954329","blockSize":4194304,"blocks":["9eaa04e9271513d4faacc732b056efa329d297be18a4d5908f3becced2954329"]},"offset":"10384602"}}}}}}}}}}}   {
  "name": "zhihu-browser",
  "version": "0.1.0",
  "description": "æ™ºç‹�æµ�è§ˆå™¨ - æ™ºèƒ½ã€�ç¾Žè§‚ã€�å�¯æ‰©å±•çš„æ¡Œé�¢æµ�è§ˆå™¨",
  "main": "dist/main/main/index.js",
  "author": "æ™ºç‹�æµ�è§ˆå™¨å›¢é˜Ÿ",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "electron-store": "^8.1.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.0",
    "zustand": "^4.5.0"
  }
}icns Æ½TOC    Hic07  |ic08  ;.ic09  Büic10 ™êic11  ic12  ›ic13  ;.ic14  Büic07  |‰PNG

   IHDR   €   €   Ã>aË  ;IDATxœí]˜]Uuþ×>çÜ×Læ•$Œ™D^Ab”ªjíW«“ª�$¥mZÁV?“Ô–¶´ŠÕj­&Dl5ˆµ­´Ÿ ‚Ö’‚ÑóBH ÉLæy_çœ½ú­}Î™Ü!™™ÜsçÜa~¸¹sÏ}œsö¿öÚk¯µöÚ„ª�©£ãakÓ¦+¼Ê£sVœ›aëtˆæ³æ© g@ÈÈÂ+öÁ( TQ1v‚ôvÒÖ–’V�={wë3•Ÿïè`{Ó&ø q5ÎO§ÿL��P6�Ypc÷[´ÆÕÄþ¯3øee§�r`î•=@Ë=3ÀrU¹�:D�ÿ ,Ù�>ÁÚû…>@ý’IýD)|oçWÛ�¾ÕÙÉÖ†Ð§+§' �l!$~Ö²ýSÓ×ƒhH]¬ìX—Á^¬=2œËùÌ½š»žDØô	Ó#Â¶"e+²3 •†öÖ[Áþ=y¶îÚ¿®¥{8cÁØHXÅ
kär‰|àùiœË}„+Uªq6û%h7/}Û™èž$û4„BÚR`)'Gd¥¡ËÏ3c­UüâŽ{Îê-ŒU ¬!» tt<dGãü‚•GW€h•rÏÖî ´_òÉè3R£ýÝIŒ ÌZäAYiK9�ÐîÀs`^³smëºcÃÂè´Áè T7í78Ÿ¬Ü—•“í`¯ í—=‘PÐdO¯	˜�†UVÊ&;í6±ŸÿÃÝwÎÚ>Ú!a„=UT+ùáù7¼x�r~ªœL‡_îõØ/1‰å2I~í@¶´½p \'ó–^fÈ®„³‘üÔ©?Âb’ÈIyÞò®ÏÙé)7³¨{íúDê=…K
ÚWÊ±Èn„Wê¿cÏú©sdlói@(E�PíMÝwÚ™–e~±Ûk¤&­ø$AÌR¾•i³½bÏ×w÷m\Ž�¡QøòBp’! ´,hoêúŽ�i]æº] ö$ù	DÐ!máÈÎ´\×Þ´dV­¦UÂáI†õòä?lÉ´¢}Å‘;íLë»½Â—NŒ·0‰*@8ò
]®�i}Oûþ�¬[#SCáòe´ý‰%£ƒml"¯}Ågg¦ÿ©HÕ$ùõ\;Óæ¸…®Û÷¬Ÿq+:²1ÌMb§ón8¸ÔÎLý–_îs	<ÙóëxVªÙö=Kwß5cÃ‰¦ˆt"ßü^œ;ó817±.Óä˜_§`Öd9âLì#¦×í\ÛòÌp�áñ6Àvã¶e&úš²³-¬ËbYNZûõ
"Å~™•ÝÐ¢uy­™Ž�A½ÔË÷ÂµVºõJ¿Ôëarž_ÿ e	—Âiûò®1C€p½mþ§ÁêÕ4g×ÍÍ©¬¿M){–x™&}úi(H“Öåå‚³pß½Í=æ8‘¸\.S¾5:•ö>bgZfk¿èO’?�@¤„S;Ó6[8â±4ÐþCN‚s®ïiNÙþS¤ì™¬]ñMFô&X“Jk÷Eß²ÎÝûÕÖ>9ª:VÁãÀ±Ý¬tóÚ/é‰D¾Ä'•’`zð°­c[Ã•ïÉw&VlS´@I[é–3”ëÝ œ÷�XjîðVåä.d¯ P·A™³DÄùð| ì±ù[ë -ú…Ÿ“ØªÉº�y_„AŽMCB}N>SÇðÉÎ*]ÎoÛ=gú"™òK¿æ¹Ã‹ÙN]È^^$¥îÈ�‚eFÑˆlÈ¦7+Ìžª0³UáÌ6ÓšmSriB*to•] _bt÷kécèòñb�Æ�.y­Ñ—XO;@&Eæ|u*{yVvjá¼ç�,Úƒé�ÛrT+î´ìFò¼n�æX]¨v!��Á"£ì„Ÿ{¶�K8xí«mó÷œéšrcÓå}yÆ¾Ã>žÚçáÉ§=<ö+»øÈÙ�‘¹†P³Ô˜á[N£ÍÅî¥ D ˜XZÂ~Ùä¥¢Nˆw= ·ÈÈ¦€Å\¾0…+.JáÂWÙC*;‚É=I’žûrc;‡ïEÃ€Î…çØæÑy)ài`ÛÓþyÙ<ž|ÚE±4f	Ž£ItN0¤ù„k&\)ÜÓ‚•çjmm#e7€½“4ÏøÂ�b¥²ôx�™­Þ¾8…ÎK3¦ÇWBÆ{ó��Ì±Þ‡„Fœ¬Ÿípñíñƒ-eîÕhÈÒö	4Âðó�«�0ƒlbí*å/´5ÛoRN¶�Ý¼NêÜ_^Œ¹ž>�sfÚøãwçÐù–fOSÇ‘nÈ­øj€†å3Wj9ÇÏuÌã¹Ã¾„on*bÿ�)Y2Âj²öE£åAR<Œ÷…ÆKˆ =­œ\ƒvo¶	t‘¤ô…‰_‰T÷=ƒŒ–ÂŸ¾·Ëß–ÅÔ&uéÑ4/öëA `¢ž~öt{o–-Éâ«ÿ�Ç½‹ðŠ€¬…ñr€ŸæÀÜÖ€*ì¼<â�5NÙZ·<‰î7y=Úý#ªÕX$TE¡bØ‰Áõ›—¤qkgfÛCÄ‹`Ô‚ô“AOÍf´(|êý�xû%i\óí^nÒàfÀ¯HÇ Ÿaå�T7!·ŸàôÁ‡y¿f‚ 'Óâ!>×&Æ|ÖžÜ…JÊð/sïž6ú×jÄÒË2‰"~8*›í¾§‹ø«§ñÂ<q<½~h0¼FÀmff3rÏ¦ì"ó™šif%œ÷6Z‰e­!Æ‘Ñ&sñ·.Já¶5âœÖÐ|;iÄGðÆ¥ö7ÛñÉ-æïœŽ©Q»V´¯
IË ``Ã›Âhù¹‚’~¨j FÛø2´Ør­f™Æ_�Š¡W,1>öÛ9Üò¾#Òë“J|%ù_Ú‘ÇŸmîGKVVÃÇOŠP T	(Îz.ÒhÝ"éü¨	çŒœÍLØ ã¦„àb™aÛ„üp®~Szh\­òrÈÅG7÷£9£‚ëÍ�HÜ¡g ýóMO8· 2Óp£${ŽŸ‚ÅÛÒ °ö¦&¼a�c4�e%ß+E¡|zëÀ�0ˆ'eÔ!wôFö àôQ`Ä
I÷ g\ÛXÈß½øæï½¥yˆ|1`’œB¸¤�¼XÆ¦ÊhrhläGÍá ù³B£±F ÆsÌ/¹�ÿþî�5nD~=€Ãçïï/ù#Nb Kä²�áÇ>Œ³ HÏ²åyÝMÍ¸h®müìõB¾@Ô½`ó×h²Q/Ì?¤çûYÀÏqÍ´À¸€wÉe|á¦WªéùIð+yuK>ãH‰«wíb˜[â9ÜÈµ@Í›]Œ»£ŒOt6à7ß�®+µ?’;UðØ”A©êLº†í¡jM~O?ã]¿–Æ‡ß™«;µ?6¡%Eð%ÀVuºƒ©zÄ&’ HI(÷¬éÊxø¤ÇÔë’
‡±ÎÈªS;}FñÃJl£òœÙ2åû‹e�ÆÇ¯ëX é—�‘‚¯e¨Âø/þ€~ÀÉ×È%\++YBºâá{ÇëÓ‰wïŽÑå¿ûì4šRêô| Q‡W@óQ–œÆ‰¢äF\hkTøóßi8iJV=AIœ‚�s›m|`n}%	¬Œõ·
>ãœ¬…»®n9µK8�] äæúóŒß‘5‰õ®ú+«n{}#æ·Ú(Œa(“„ Kq>}A:ÎKá½—eÐ7È51�Uì†Ÿ¼j¦…½5[×†ß‰ÀáP¶k§û1’:yÐ£ˆé‹)Íq´ ñ™E�èœ›1äÃ¿•Åôf2‰¯TÏ �3Pd,[’A³Ä'ˆú˜€•ýe×ÜÑ‹Â>�[¨ èÔ±ÒLB²Y·jCym‡Ï½.cÐgÜñÆ&|ò¢3¤H'™=Õ2É®’–w¶ØÀxÊ\¹…÷wd†VäLx¡óJÈ_~GŸÔ¾Fº�`wÓSÈí*´¹6p´ÄôåÐiÔç2ºKÚ<_>3…¾­7�ŸBß¡ H[]wU­�ï%E]ª;nËÙ•LkRÂò?ùòZVù’áã V	hÝFÈïf^`aÁÅvtyè)3ÂôŒÂ¢6¿1;�%gª"
%GA2I6�;ÓÂU‹ÒøÎOŠ&!6Ju¯�–Hßû.zÿDèü^Hþ#!ù~D~DŽ¨pIûv€l�Ðû3�·¾:‹{ßÙŒÞ2#céˆé°§G=¿Qyç¥iüÛÿcuÄÒ'EŠKŒ×µ«jä¢Ú‰B¾N~%Œ›&³çãw÷ãŸ( 9E†|yK|Òë…÷áäDSÊá7�çà5gÙ(”â³�â ÿ<àm¯“°Öòãê…ü_#_ÖžL-›€M
_×�û-šã¢Þ##ðd�ßNÙ„+_›2érªž@‚<bõ_ñÚ`Œ«gãÏù•Á¯®~6KØÞ|^jLÓà%§Œ¦‰+o·ê 7(+ªkÞV][ÿ^%ùŸï3½w¤äË÷ºûo¹ÀÁ�77cÖÔ ©GªÊ£!S’eæÌ°ÌŒ*Ža@Å•êõ†ö�E[�ðôØ{þqä´Ù¬–v�fíŽ– _üjE7ža ê`Ôœ·×oqQOÈWÀ�O·ç´Ù,•ï�ÅŽ´þëÚ�QÐ¸M¥ñd]ýys‚Ÿ®7ÏŸWAþŠ;ÆFþ¥j?êùc�EM·ðU62©‘]Ã¸j ùsaÊ±ÌjÝ˜7QÈ¿¬JäW¶�Ø ²nBl’j·gUÀTîðgO³L-úEügÊéöÏ¯ùë«D¾ "[<©g´‰ ûî%Ú�;+,ÜP‹˜v^çÉX§J^hí'‰üÑò¸3Z•É«H´0•º˜55aÅ½æ4Z.¾i[·ß78T)l4çõ"ò·%�|At/g¶©XfTU5£lŸ©S(öñ?
.mÞéâÿ±ºµ9ögKÁÁù½JòÇhí_¶ÐÁú›â!¿R ¦N	ò(­ââƒ%NHFÈÿ¿�.®ÿl/òeÑ:
wÜŸÇmßVêœ¢bWDþƒO†ó|œÑ�ßÇèX˜ªšÁw*47ËÎ«�ê_2I…MÄK¾�Ýg{Q(12N{˜ÚDøü¿�Z*ÉÿÝè3óm¹f=ò/JaýÍM&â'ùQ�!“¿«=¬VŸª+hFä?¾»‚|Y˜'Ï2üˆ$	5"5jÈÈÃ‘/05þH~%ä\uáÄá°�†ò·ìvqýß÷½„üÊs!ønÞ|çS8&•”©ÞÆ­eÜø…
ò9ÙäW†ˆ“ï
CÁUŸê)`ë×ý}Šú„ä'M„/|/�Ï|sÐ|WŽEä×ó9ùäÊn´»|Â5€ŒQSq¾z¿'ªïù.�ÞÞcª‰dÓ¤`�‘|ñßóð4cÍµ�øÑAÏ—ßù]ýlÊÐ®'ò¢ñâ˜VWU ¢y¸ä
ªqÁ‘oaz™"‘ŸýNÞ}#)«'BÐ6…°ö¿8Ø­ñ¿;\ó[{ôä¯¿¹ÉDæjM~Ô†G9ùÓÀ¨·ÊüXP­‹gOÊ	*…ÞÒÙ`–—›Fð]i´)9Â÷+í!ÂS/äW¶¡´©ú¤Ï¤�¤Þ~µa(5pó{ræõß|{Ðôî‘”j×a„Rˆ¯'ò‘�K›ÆqþêzÃÆu+¨æG5�ý1
ÁHg&¶�ßÇ&�m¼ÉÈyåÞ¤MåÚªmT}p,ÂóÝ>zóÕWYÃ…àKŒjép0ÒžåÅÉ ?j;)›û|—oÚ¶ÚC@ô )¡nŽUó1
�^÷’×¦°î¦ñ'¿²í¤-E0Å[™hZPdüòÙÀÇÔ¥ÚB`‡äKÏ_›ò+ÛîÏx(ë$'0‚xìâDµ„À® ?)=8ÄõWfM,I¡’ÇþønÏxã\xºB`Gj?�äG»’H9=éLQ†UµQõ[5Ž–aÏAOí†�8SÃÇ*ùW-Jù•möË}ž~Á7�*Ž [<KÃ(ØéãÁ­%óºåïG#‘µ¿$ó³	#¿â¾.”O½”l¬ˆå–£a@.>JÛBB„ 
ìˆ“g­�ŸJ&ùÑþ	¼’”ð¸Bì±Ü¶\¬ôªmÏøxbO`ÀÄµ¾}¤BP™Æ%Q½$ªýQ[ÉF•ÛŸõ!­'Z#è26<Rªim€	A4‡6ä/¿�îhG}û‘b,™À•ˆíö¥qeYÔ›KÆ�mó:BðÉ÷7`ßam²w¥ç'™|-5³eí¶”LÆ©=cËÞ®S6Ì&Ì÷>T0‘<cÙRm…@ôOÞ�3›H¿}qº&	œ§ƒh	ù×T4³Éi[ .ÄÚ’´Ñ”%|ãÁ"õÖV¢Ê\Ò¨¼<cRÅ¢Å«I„É—ä—ÝT4aìS%¾œ.bm
£œ ’õÏäcÉjMAÇÄW)åàú¾ôyîÓFƒÆÝ\±÷Q_R-äž�EãŠÒµk“T™`òu8,IEzK.^Õ_óbÑÆmß0¯°MaâÀáó_}kÐ¸k5LÕä4¢~E|ÿ±2¾÷³’ˆZøê~¸ÌMzþÆ'ÊhŠ±.àpÔÌµ/Ž—5ßÀGõ¸IƒÉö��¿ü—Á¡Š"µBÍ r<ªñ‰;û‡Ž½’e€Ã‡ôö�¯ÀÑKÒÇÉPÓ	‘Ü¨Ô¿}`sw_°~/îiN’á‡‹\?óÍlúyÙ“µk>#Ë¶­‘ð¹ïæMñDñÏ×ÂÚM¼p�êÝ?*à+Lrëx´Ã¸íØ˜!£ö~²Ý}Å	�’ÿƒ-e|êëhSÖÇã# Rö$ÜøÆèÅ“{½WŒx!ù?ÛáâÃ_îCÚŽgÙ÷H1nNQ±tÅ(”¢Ò²Ô{Ëž‰¯	¼�üŸnwqÃ½Æ°G¸L-.Œ«W\‰u÷j\{{¯)Õ	ÁDš0«Kð_ÿW2UMJe6nòñ®¤ª˜Í&eã.’;pýçúð�Ð0Œ³ÐD-¡Cÿ¾,M—ßï}¡Ï„¬u_ò%0Æ®Ißœäãç �J£K#ýÉWúñ·‚Š_fk¶:öza:œ$u|úžÜzg¿I˜_òƒ½n‰0¨”'É@HH0DâõŸ½?�knïÅ¾CÇ‚Gõ¤ty�Þù¼�¥·õ˜M#dë—h¹ûxC8g¦‚,=ì1)(	¸(i4iœiM„‡ž,ã]kz°á‘¢éE‘6Hr I‡KM"*sü÷üE�Éí“ÄŽÄ\¿ÙÃG6¹ã£R{l)[®81Ê6
!÷üOýXùù>ìx.Ð•±ýÄO�goë^üÛ^Ü²~ %�ÍÒôDÍnˆtÀ9ï¶‰±°ÞŠ’SÓÇZŒë¸döê‘¬ž•¿‘3[ÑEŸ‰R¿jUýÐù	Øû‚o_î{´d6Í�g5êWf	Ô?e3ôÏ™=9lv— H/—Ê^¢¤}ù?ó¸ÿ§%¼ÿ²®¹"cªhGˆ„AF³¸nƒÃºƒÑ²­hÙ›Œó÷l,˜-Þ$óXz¼<’G|	çÌ¼�¬<8Wkk)»,ûY%3o&êieO’K4¦·XxÇâ®~so:×9ND/wb„‚NŸpAå:G©Úõèvßýi	?ÜR25|$ÿQ´Vb‰šØ" ýÛÅ	IíËm¶œ)‹µ; �y˜`™Ö� Î”çØX²(…«.Nãü9öK*•š°kXEädy�¾÷rÃJ¡Ìf©öŸ(ãÁ­eìØï²%®Mídš¼|å4X¾;ð¿»×Íx£±G6’•ZÌ.´ÜHºWMÂ¨„–åõ/žõÌjä/ýGsÏ°°hž�×ÏwÌ†K²c¹$YŒE¬{ƒB«�Ò´[öºfj*ûøÉr-S¾5Ô8ÉîõÇÀÌLVä<,¯M_˜·òðb‹œÍ¬Ëu¶ÇG ³9s8¿ãK6­HÏœÖ¬ŒÑ(»˜œÙf™Ôð©MÊxÓ²›QçAQ‹î~�#}º´YÏ eY$7_âÒ(BzÚ¡¡Tó$ÌçGfR)øì¾aÏÚé�Kþ	í™�'ÚŸ;ôå4\È^A&,5Ø¹¾z0D„d±¹`¿JÓ+õhì?â›¿#	Ññc½qÛVxŽM¦ä�XóÑy"Ã´Ná“Ý typÛž9ÓŸîíŽU°6­!+ŽÜ©¬ôç<WÜ°‰F,±Äï©µ“…^©â½Èø3„×‰z?˜5,+EƒwbéŽU,›˜ÊvÇÀ9×÷4§,ïWd9ÓY»ÑDqš”Cì»‡Ê¾}î³w·ôÊA™53:¶ž½»µ„R©)Ä<ÞAÊITÂ©á–øË†ëŽ‡%%'èýb`õj:ÿŠ–2rÛ”rÎd_,Ÿ:&qÌš¬4iíL!¿pûYëz°zµðËÑæ~Œí«iûº9ÝÐÞ­dgIl¢ŠŸ˜DC¸N…[ÃñöÕ–4ÖÎñS¾N¶°�üöå‡6Zéæ+u©Ç©ºšLbXû*Ýjùåž�»×Í¸*â8zûx¾“å;+´;xTÔ†1'Qßªßì¶<g¥1øÇÇp¼ ¬!�N¨_ÝÝú<w%ÙRõáàœÄ0˜R#¢ú•ï~×pÚ	e8®ÀK�<QÙ»îšy¿_ì½ÍJ·ÚŠ·ìç$ªáL¸ó‹=·í½kÖýÂi¥ê�ðrn_Â*¶°†¼ù+¯³2mË½B—KDõ»'ü+ÌìÚÙ©Ž_ì^·kÝô•XÅ6Öò_¢ÊOâ÷gÂ*Ö€ÛWtÝogZ¯ö
]Å¸+à$NÌìÙÙi¶W:zÿîµmï‹84þžà$ó|bóÅU Ý}¾Ï+öÜeg§
ù¸>Ã l8ñ„#¯xô®Ý½—žŠ|Á"¡³Äí+ŽÜn¥¦|œ½AhßõirŠ˜°Lõ”c‘Ó ]ê¿}×úi·çžaîåÉŒÀÓþÀ*V»×M»Å/õ]ËlõZéf‹äUëF&1†à>Ø3\�Õã—û®1ä¯b5òÍ'FuÂÐ‰0Ù�ó8�ûŠåä.c/í—=IÔÕ_.Aý_Y)›œürþÇTÊÿþ®{f=5ÜÑs*Œš°ŽŽ‡ìM›®0uàç¯ì¹Qæ–Ó8K»ý"¾Yú0Cˆ,=³²R–ršà»ýÀ¼z×ÚÖ¯çf¤[�¯¾öà•ÍýA/·ìÆY¬KÐ^^âè2c�psÂ´%&KQ›4.Y9gç é\~yà ÖëBñ‹{¿qæ¡c3¶Ñ¯í8=b*ÔÍ‚ŸŸÆœù�®ÔÅÊ™I1c¿ö]-ËPÌéã$2,'Ã ´£d{`¤1ÿYŽ"+Iáè­¾—Šwíü—ÙGÌwF©ò‡£
0uvBm¨¸ˆù+Ž\ÂÊz'´ßAÌ‘�i&%>$-±	€å¡Ã0Ã+Ý†¤`Ä4+Œ½)°v¥óô0h”µÉýûÓ_kÙ}«³“­$b{jCïäg¯˜::¶†�A¯Z~àœÙoÔL´a>SnhŠì
‹W0(ÜÐ ]Ì´àÝŠx›gÙÿ³÷«mû*?Œó—Kùªôœÿ½~´Y¦»l    IEND®B`‚ic08  ;.‰PNG

   IHDR         \r¨f  :íIDATxœí}œÕµþwïŒFÒ6¹­�Á˜¸:6à%¤–¼„$§RHòþÆÉ{�H„šNR ”š!”„fŠMqã²n[U¦Üûÿ�;3²vYÛ»kI«‘î÷C¬·i¥™û}÷œsOaˆ$CøÜ`Ë1·ïw'´¬OZ#Ç43;s(ãÞ! ¦1`º%!’,É€: I0ÔÌž÷¡Q�$z d$�†zÈ,Û	°—¤d«ÃËÂà¯Ø;»·nh�˜éóûlîBËVB¢`C„H´­çx…ß™1¯}”w6 ŽcÒ8
‡JÆÆ1)ëY,É�A
��to¤ú(ý¯ih0®¨ÀÑ�ô‘q„kG:i!ïaRløKRŠ'c�¹ñØ3ë1bg¯Ør«´ *bPÙ°Pò¹=Ä—-;%¿ÓOüxûÈX�w4÷Äqà8G1#6ŠÇ ¥éÙ€p!á… ƒ„Ì¿O¶ë«»­¡@í
j_ÿ/$£µÃ8g$Ü3,0fÂsºH¶C²'ÁäãŒ[�Ù¶|jÝÒ‘íá3Î�û ¹ìä“±ŠÝi*“%I2òn¾ŒMu·ŸÈ¼Ÿ±q<VID÷²¾JK¸Œè-éÿ’$¼rßŸFÔ ýÿH$�’1f2%	%Òé†ôÜ-’±Û³uµ‘z70§ßõ\A¨,‚�ùtk‹ óM§)m?Œ	ïlÆØÙÌˆÎŒ:H7)ì]„ÏÛlå†T>¥/0·ÀÌp�:/J)ÿÉ[Wß<feðãç´ò¾nìp‚Uñ[?ê…ö×Ô‹¶+¥ø"“h1â#-µË{²ä]ihÂkT&¤”`ƒ4™‘TÖ�Èµç“dŒ_³ú¦1O?ÇÐRB0¼°p!.Ë›FÓ.h?†ø¤÷An51Af•ô\&Á¡œ0�ˆ@J!c†Iñ)awJ0ã¯ðøÏWÝ<â¾]®­ÿE¢Æ ˆê·2¥€Ó.Øvš4Ìor†Ó”jR€ÒcÚ¼×ˆ<$ù	‚�<Ö¨bVBâ>çòµ75? ~¤EÃujP~PoÖ'þäóß˜fÉ…àæ¹Ü° v|À£°ë°['Å…
”/ñ+ÏË|í-®êË�r¡Œ$“ÁÈÜ?è¼1óˆ/3Î¾ÉÍúQÂîðèuRŽFM@É¹a¥˜çöì�BþÐqŸ¿zÝÒS²Ê-XDû`y¬�ò€zS�ŸaÛ{aÄ¿o˜‰#…›†¶ÇÀu6žFÍAJáqÃ2¸YÏÍ<Ïþ¯UKÆÞÙ—3Ñ€À¬™=_ÆºÄöËÁã_£Œ+á¦)“‚{ÚÔ×¨ñƒnÖ*Zàæ®l4G_ú4å”Á%`åôM?ïÍC„¿Á°šNN§¡Ü|Õ×ÐAY«Ü�<Ödxvç#ÜÍÍué/ûGä-%–H (O=½œvAÛÇ˜¿ŠV³°;=0mîkhìäXM†ôr[=aiÍâ±(äŠŒâïÂêl“^(Ã´y[ÿ�Yõ¿D³pº4ù54öÆÅÈfÃ¬ÿý”yÛêïÓLæSŠ+Ö�÷Z"k¼Å´Rõrí¤ Ò*íëkhRH0.ŒøÃµ;þà8]ç¯[:)[ìà`ñH,:oçË0¬Æ3<»�ªøL}¤¯¡1(‹ß5¬¦gwÝk»�]·tR{1ƒƒÅ1)H•Z™wà…[÷�âïÜjÈÏ4ù54†eú›Ä%o<Ã2ïšxnÛxEþ"¹ûþ$¥\ÄeõÅ¹y¿aÕ-rù544öÌÙv—[�ÇYÉØ½Ó/Ú4I¹E�}sdê�Í`¹eF¼ñPE~*”ÖÐÐ(.¤py<e
»g¥—³OYûëñmûº‚xrËš3Ü?Vã¡ÂîÔä×Ð(7‰c<V?Ã°â:øÂ—±ˆ¿ªvhâ/úç’3Z¤ÅS©ßòXã	‘_›ý%óE Þp‚@óo±P˜ª¤8Ÿ+Pr�¬…2üA:�Û±¦3En§K-’†ò444	ÆL‘£À`ê}S7ì¸‘,qÅÉ!ˆÀ ¡¥E­­Ì›zÁ¦›É1—xÙ�®ê’¨¡¡Q^H¸<1Ât³Û°fÉ~—åx�‰üó¶¾Ÿ›ÉÛ¥—õ“|tO>�a qÁŒ„!ÜÌV/n¾#ähñ úM9Ã�ÜH<Å¸Ù,=[êV]ÃêoXÒk“�G­¾iÌ†Áœ0 V‚Ñ3#~#�5ŒžMÝ{uEŸ†Æp‚1.=[ðXý8é‰Å*/‡¸:ÀxÀÀ”õN]¿å»†•úÏé¢ Ÿnâ¡¡Q .zv—k&RgLk˜ó-PAÁ½cï?¤ê‘™7åÂíÇ1#ñ_Âé¦¶Çšüâ¤pz<‰…ÄU_hLÙÞ~o }üfo‚Ñán}Ä°Žñ” èÝ_C£Ò@�´�XƒáÙÝÿJ™Í'==ÞÞúîÙPçýL´;›çñ¦c<»K“_C£BA3q”¸Úánû´
îÅØ½t'=øÂmã=°ç˜aŽ†ŽúkhDãT@8Ûìxòˆu×Öo	»q!À¤ñ=#Þ4"§£þ•:™9Á­T³™íùï½µëß2Š¦Ïßq"$HRséé„�H€ÚsÉ¸)áæN~õæqÿôƒùo�EØ¿0ã2ÕÓO¸Î"fÄ% :ÛOC#" ñÚBwÃ"µÏÏX!d„©„Ó.l›Ãë!é9Ô·\'ühhD‚1&=ûäUKÆ>Ü_šð[ˆ=c†ßˆLJ¹€™	Ê(*ûÀB�b@Jâ°drA!·wo„M>.Üz”aO@�ß¯‡tjhD4–Ü“Â=zõ’±Ïö­è×´gR|Í0ëêATÖ—ª¡¡QdaÄêM)ñµþ¾»Ë”aúy[&žcŒYþhsmhhDT2Ì EÖ‘Ö¬×—¤^)´ò@‹ª „)Ï1ã)K
O…þ‡ó•k¡©4ó4–…¦1{yÐÏÐÏ†¿§@äÁ¤p=ÃJ%bÈµÐæ>ôPž÷½ïï\iN�¼õIÃª›%œ´Nü‰ ÔN„%›�"x¨Àt0´ëûdÚ…áÝ�è…bap¦Ä /�€Âç§'Ñâ@JÁcuÜ³»—¯îwTa× ³WâÏä¶c¥{»p3ºÑG¢�¤Op=	Û\—n�±üÃ2�Æ$Ã¨FŽõ	ˆ™ô`ˆ›þå\	G=€¬´÷ìèèÊHØ.`;i["ëøŒ§ß¥ç0‘ Ë�P(.Æ8qš±·OiÜrôàñ�ó½zùyŒÄ´˜—m×M>+áL;.9eŽ'‘süïÕ'êâãG˜¶¿�	Íš›öe`ÜŽæÇÈŽx°LŸ¬Y¶ëÿ��Ýmmí›¶{hë�Ø°ÍÃê�6ïHç$:zBábƒaìzÍú¹2 ¥ô«Ñ”¹ö³@ èÂä„ë“‰ŽÄ
n&&I/KóÈuòÏ0!4ç½€ˆ™ÔÎ�ªã˜8Žã°‰1r �éû˜¼¿‰Ñ�´ÓÌ[	Ùw—;´.öz]Û;%Votñê›^~ÃÅŠõ.ÞØ*Ð™Ê’¨‹ûÖYy·Ac˜ ©w —nvM¦+;sCëÄqßœ;÷!cÙ2¸ÖÎÄ)ÜŠO’nV›ÿÃ åoÓ$HÊÜÎ9IŽ)û8á0ÇjaÖcš8Ì~Ú<„£�…>}}¾¶'žû™`½Ÿ;Œ„		ÎøQô°pÒáþÏÑk'KaùZ�­tðèJëÚ:z–ï’h1.0"¿df|ŠÕ„S ÜEÜ7�“Õ·s¸Y×Íy,Œh”Ç¼@OFÂñ€T=Ã¬É1Ì�Ã‰‡ù¤'âBøÄ.KA‘›w¬¸�ÅÂ×¹;‘…‡Œ„iÿÑû�ŽãÌwÆ‘µ%žYãâ‘m<ü¢�UozØÙ-Uü€\—ð½kÃ < /’ò{áœD@Üö‰©ó¶.3bus„Ý££ÿ%FH\
°‘�Œ³§ÄpÚ‘N<ÜÂ!Ì|`�@®@ø{á«D„¢@‚@¯±0æ@ÖÁÊõ¾Ü·ÜÆò5²ŽÇˆ:^P¶Ó «ž{NúáÕ‹›çª"ôõIó6�3$_Í³Â=�b#$D&çØÆ�â8m–…³NLà˜ƒc½®:‘^ñ=p¢å6;|¡ Ñ®OîÁÿ™ÃƒÏÛÊm G’º[ß×(¤7©8ˆúúM}mñ~[”©oxÆÑÜŠ7þIþt-ƒ?íŠÝ©ø¡š8ë„8>xlB™Ì½HšóU‚ŒÆèAïí¤Ã)v`a}›‡??–Ã_Ïá•7]åÆÔ%˜ºZŠŠ,»’›u°sG¸Ã÷õ¹<Ž›õpÝ¬öÿK@üÎ´TGd'Ï´pÎœÎ˜m!øõaBMáyz5"€öEnLkà+ªÃ§ß�Ä=OÛøý²þõŠ£Ä°�ŠQµÔÈ5Ì:Sºöñ� 0:œ-…M7HoÿE@è«ñ)àuú;,µÀO˜aå†x˜aW‹W½oV!íú9!®<gãÆ»3ÊM ïQ"Ós
rýt¤Q�8.%’ˆ#ÕçSßýjœí?b3S —cq¾(°G§þ{’˜3³ñ#ì×—
¡ZA÷>cãÆ{ÒêH‘2é(1ˆ±k¿ã¹N…©É*³%xÞ@`%=oøÜµ,2èàæÖÈú1‡±C/Üq�ïEp£R ‡
Z¸éîÊÌ˜Ã‚×áýÇÄƒkti«b¿˜ ’
ÁÎâê¿¦±j“‹Æ‡Êyré¢np%DþÃ‚[Ã€9þG#Äº¸ˆåQðZ(cR:]Ò33]iOãuJF5†|–Oæ~ªžã’³ê1ÿ=uhªc½v5mW!ùCké£s8ù·Ü“Aë#YlçÎh‰ÜhÀIùä'B«]>pte�…@…¯<#aí`°v ñL‰‚¬Y!Pµ@uàbªéIL1cI.Ý´_7¬1¨…žå¿k–…KÏ©Ça™½v±b%çÔ"èúy$ €ªmhù@÷'m¬lw«2½ÀÜw{»U½.;ë€t£Dæ@ÀHK$70Ôm`0r€¬©´7Æ <:	0\»gºÉŸÂÒË�	 gþr×§‚›ï~¬œžìÜ«æˆ~¹ ÈÏ€7z~²¢K×dÐ#¤Ÿ/`÷ÉXÜ›ÐÒ}	Š`½Ðu°Df ~=”(«Á¨k€1ÁËà,3Åd“à·ýî—	�IJUy�‰ÓÞaá²s0e¼‘Ï—×Äßw¨¸^@þû7Ù¸èÑN¼Þí¢Ñâ¨£l¨}ªÂ:²À«—è8È6#Vn�Y"@QQ�6²I&FJAƒ?¤Ÿ}¡±[P®;%óP4ú¿>^�Ï¿¯®—¹¯¯Þ¾#ä‘ÿºWÒ¸ä©nxRbT‚«ë\´HÜ°ÇJì¨“H=Ï`µ3ÈX•‹€”Œ8/FR³ÀF?Sco&ÿŽ.‰™“Lüà‚FÌžjê]¿D;?yOßxºW®H£>Æãn)bÔ,øà n°ó(‰Ô@¢�Õ€% Á$Kr0$w�žjôŸÌûö‰³OŒ£õÒ”"˜¶«Ã¦Å÷ùúR~üB)+¨,5™o	h?Bª“æV3#è�	'ÞHGª#@.@Õ¾Ù¡ƒÌz¿ûŽÄÂsëñÙ3{›üÅ%?-Æ¿¬Ïâ;Ow#²ÿÊu‘™/lŸ)1ê©à„ ƒLª‹ËFp)Ñà—¨h‚ÚZõd¥JC½é«)E~U»Þ'[Mcßüžßébþc]ù¼‰²¯Jæ‹€Û´. yõ68”dH$9cŒNTõðÏ>Á¾Žn‰é˜øÝ·R8õíÖ®^m)•L¾þT¶åâFé�8@n,Ð3Uê
¨ZKŠ4Ò^×�wÁä~°�2Ï~ÿ­fLôý}½ë—Îô'?ÿŽ7²x`“�V‰~ƒ£¯/égVüë×ÆlŸ�G·Ä{�Žcñ‚&ŒIùGOšü¥‘?ëIühEZmµaq3Ÿô”'�ž •[P}V€- äßÞ%ñ¡ãã¸ö�*ÛŒ|~MþÒA•žøëúžhsÐHÅ<¡ È‹ 	€[GE¨Jhwþ.‰³OˆãšÏ5©&œa£K�Ò/¾;6äü(T¥]lÏOÎ�Òˆ+îî;j~‰‡äßÑqüßgUô_‘¿
ov%�O×¸Ý–x¬ÍAÒd*Pq`€=:¨.¬BðZ'?µ©>u–…«?×¨†XÁ�#4õÛjccÚCŒÊy+íª3ç·GJxÔÚ¡
Ý ^ËÑ~iuÌÁ&~ñ…&Õ§^µ³Öä/+–m¶‘ó*¸lZB‘ßm�þi@¥¾Î!¢&€{]Yÿœÿú/¥Ô0mö—¡•õ¦B]á3¹ÛŒUxM;9cS×¹	ãFúG}Úì/
~;rRíþË-é§S«±Ê}‘CGM	 í4”dBsí®ûR¦`èsþa„#€­Y	ñÔkÕ‡Új†Lå¹ê³Mxçô˜Šh(¨-ëÁä~ÿÄJ£4€ ï`µ¡
ßRÿ ¢ïì‘¸èÝIUÖKf¿&ÿð‚"ÿ�AÎEÅ»,žv"ô£^'Ã·?Z¯~*ú—0àú¥©•U¬ƒ€D8…wT#Ç�ç5ú£¶õqßðÞ“‚�£<?M¸RÁ(7Ä©Î@M@Æ–ª‡ß¤ýü ŸNñ~„YcÂüTtóP‰p5²¥
ßRÓ¿G¢åÄ8ZNLhòWÂ ß#M¿í*ÌbÝÕ9D„Wõy¿¼mœ�ÿwnƒ?DÂ6«Q­°SÆ[~€J´¤Ÿëd0ÒjˆnÕ¡j@q¸ß:§£}?3
çÍµ‚p3�ÞdbÖ¨²®¬ÈûÃ8ß^­��ªT BÓŸ*ü>pl\Õõk¿¿òúþ§ïoÁñdÅñ‹ÑÀW,JP�ÍA«Q Â¨óŽïüg}ðÅªïÈ#¼'çNN`B£�ÛP9ÄÈJ‰™	©,WÃˆ«U' dFR7ßÏ½7‰‰cƒ¨¥¬*�^ ûB§Öøìô$z¿.  (QI7�Ñ„WÅcÕØªªÞ™ùDþY“Mœ÷®¤
üiòW6‚)ÞøÜÁu˜Òd í, Fƒ_m��MJàð”‰‹Þ—Äø‘\Y–�°Të ¢¶ .9»I]ß	„“FÅ9.=¼^õN_›3(: ÎÀ¥G4¨×6±ÙÀgÏLªÍe¸Å©ØàUUãO{gYê¡zFdöSaÖ¼éIå
t¸Ãã
° 0I–ãÇ7aRƒ¡´ˆ>?ï´$fdªb²j
(WÍ[¡G-½>û^|Wl«"(ÌÚ´ÓÃÆ4ì`ðÊ<œ“»§#ñã£qæ„¸ÊM !¢µEåEg$‘s+¼n¡€vÛ}ú‘Ž98æ�šªŠwVý�h7ï¸à'�ø÷KÆ¯â0:Q¶1ÝœN‰°3+ðåC’øâ¡uùA¥á÷É
øðñq~Pirªd}UÅÛ ÂS‘Ïg‚á�zû�ùÏÿI^xÍEª‰Š7€QOqXm¥“ù�Ièâf7âªcšòIcù¢¥+à‚3’~0Õ^-»ÿÜ™15Íô#ÿ‘W5Fþ+ò×3xÁ„^*¿õ,GÝ:¦šqÈ"çáÁ� -yÂ ~3'…oQŸŸ’Ù—à¡ð¡ãâ8ô@»:N˜xUô—çÀ'NMªÏ+½¹„F?äÝ'¿K' 9ø„ÔJ†Ô‹F6èÊž¡v€~žHO�W¢Ë‘8y¼…¿Ÿ>-oK(³Ÿ~¦¿ç­ êýÑ9	díêˆ˜Õpî?{jsgZztw5�¿OçP‚úõ‰6Xgf‚„Gó¬=@¸€eìÚ�]È÷{(4á)!ŒL}:â£¯×Ã%‡×áÃþë*ðùw‡�ð9!Ž›þžÆöN‰˜Yá�«Y è~Ð�ýÄ)	5äƒÌGšì£QÙäß´ƒ~{ PÀpš^ê6=ã c<`ŒÞè��ÓNþ<�&0Ð”!©vtZÄÐ¸É0¡ÞÀñcc8ó€¸Úñ�€Ð-S9hNq|ð¸®¹=�‘±
�hTí@jœu€Éûx÷Q4¶àšü•Oþ�ƒ#¿íî´Ë[€‘eH­Ü×€³ß“À‘§šxr³£ºoÉ
lÌtSÛ÷Ã~Iû%¹úøÎ1&Nk!eíbºìúCñåÏ:!Ž_Þ—Q›N”#‚f”ƒéœÀïH !Ét{ï�ã?Ú¿b0äïObþäÞ?ü-‹·�lÀ§7æ$çIu~Oƒï©Ûð[^Kà*„AÀÁ‚Þ™ü<æ�|ÎFc°þ¢ˆÈiñ4%9>r‚ïÃEX„k‡üWîùœôÄ,`Á-]øù�éüß¢F£õ&Ë“ŸO‚àõ!þ¾¬��NBA‰*xdwÿ¬T½ý;HýU:ùßÜ�]È ìð”ªcøßßõàº»Òêo©cÄRáÍ"�¾¡«yú¬8Þ6Ö€íDwŠ¤ Èä:ýV>[£rw~òù‹Iþaô�\Àïÿ®7Þ“QAàR·~cÁškªg˜sxL¹¢Q>GN èâ;0º‰áÔ#h`[õ•hV�Ù_ò¿Eâßûm7®¿+Ç-ýÑœžÿÔYq5jNÇ ÊZXÔæûÈ)14ÎÐ5ÿLþóJLþB2ÒÌÃÕ·§±¥½ô‡y°éwh6‘í9€ <R^«W@F£ò|þ•e ?�þ&u€nH@�{Ÿ0&6RBB² '€N hâT†Ü - ¥-¦þEW7"’V}(‡ÏßèoR.a7|%…ó«AË‘§/ãøbSmÄ¢†HÑ‡nvÎ‘˜¶¿‰Éãý†j(Èˆ:ÊéóïŽü7}5…fÄÔß,×šà{Ž>$†QMn«£% *ûOâ¸1¿¡d%·ÊP)ä?þPŸü”^.ð`¢Ñ~#8Ž˜dª¡¨U¢Fêåá©‹š~hT�Ï¿mxÈŸFò‡P©À Ž=$æÏ6ˆ˜	 ëJ7yd©­/ Úü¯Ÿÿ§Ã³óß8Ìä'„„Ÿ5)††W¯%JF}|€¡r ü/÷«ªqò— Ã¯ÒÍþ¾7¡MœŽš[Ê£ fNŠåË€5ÿ‡÷¨¯\çü•J~…`Žhd8x‚	Û‰–À#Õ÷Ïf¾-²ŒUCþÛÎ»¢+×—�ü$þÉ8°¸’È�]=)è£
:ÑjI™—J™r¾žàßuíÿcÀï'xù�òünüJJeÞU
ùC„‡Ó0`E¬CP$@µtò$Rõ\¥]ú_îWU›ä?/ Swþº8pó‚ÊÚùîø“÷3QŸð›F<2@®ßý‡Z3k#ù×»hª+ùëÉì_�RÍ7*‘ü„pENÇÑ@Pâ4äš eºSö7üRL >ò×ù®\òB²7Õs5‘Ú‰Ðô H �üª‰cü—«ëÿKMþÁ!œD}ÐX#R¹ <*À„Å0~”¿DE]‡²ˆ*áy¸ÈoDlç/DxßÆ�¢d m´ãW» „-®Â™†²wþlDÉ_ˆýFr}XL„>?Íþ#u¿VMk×·ì¸þ®ŒÿÅ`Lõ°�ókŸP7%Ú¤1^–Ü@PùY5ÁH&:^ÙPmÔß5”¢½[â‹×vâžgl¼¹ÝÃ÷>ÙàÇ:ÊQîµó_Ù�WÊtÔgìüK¤ptDw~|¤¡!V,:¹ P£à„Tä7C¹bÕGþO_Õ�®tTéú»Ó¸ô–î|¹i©“×ÇìeCÍ~{—ÙUòB‘¦ä(¦¬:T>*^ ÂJíŸûôP5ä_á(‘£\òQ7ß[ �ß(0û_*ç9¿-Uvç’‹£ëó÷	 ­Su¿"°\+_ (PÒ…åùF�¸®"Gº€ü�»HG‚7²"îü¯oñð©+Ê›áGÍ3’K4áèéÕA~õ« ´eíÓ�@c�Oûˆ¸V{'�ÄüÀì/$ˆBøöÒâ‹€ìüD~òù_}ÓU×Ø+ÓÎß�ÿ�ÕB~æ0¦‚h8iPù@Øö9¯tà;ÿü«;ðð¾Ù¿»7�%OãÛE´ú’íf¯¬ä§�q5‘¿ ô^È
�ÉV�­B+ jÈU@þ~vþÝ‰Àâ"¹ý‘_W-#ù«jç’�î� D‘ D\ Bòw*òw˜ü…¤íÊ5Ñä/’ó�p#`DC ( Ñ&wFâ3?ëÄ²ìA‘?DßÀ ¤hò—"¸õI™‚µh@A÷Õ(\ÔÝ‘ŸfÉ�ùß"Oã›K.šüå�Ð"�„ ÐB§D˜ü÷/ß7ò÷�FŽ¥÷¥ñõÅ]ù¯ïNBò“¯OG}Úç/Xð‘J×£R¯P‘#OVâ³×�ü}-�_ÞŸÝ£’Ÿzø½¶EüÊ'˜…-«â ¼ˆ!y*]YÃºðtNâs×tâ¾g‹KþÞ�A†_=�Å%7½Uúîü¯·•�üÙ*Žöï	áÚ¤ñõ•¾N## ¤ áLÀJ‘�^e[»Àç¯éÄ½Ï”†ü}Eà×fqñ�]¾X2îüëÊD~UØCI>uK.®-òË‚ÓqgTL eíL‹|‰¥¬pÓÿáüùñ\IÉßK~÷PßÐ¥TÆ`ÕF·¬;?‘?�ÿf"ÿ´Ú!!(VEk5*£Â+¾X‹«½GªÙkF˜	S�˜^'Yg�Çº¶\q[�*Q–A	U‹ÈM"ðÛ3ª-õÇONà×vaý0ìüDþÙSk�ür—õEkÕ`ÑHªx pÆT4]M†©ð¹ ª`	À×>R!%~ò§´B)E@ÍMläh}$‹;þ•óËl‰ü¢¼;M’¿ 9Ûþ²HØÖQpwŠUG::é@”òõ³êqñGêTá	C©C$0VÌw;¨)½†r�?UÇqËÅ©š'?�vÕTÇ ŠhYAÀ­íþZé¦^óp‰€ò’dùv~
ø½cªYÓ;¿>¶uxÈ¹2_³QéàQÉ¬"Ø´Ã‹L]À°Š@iŸ^›ýý \“›¶{*¢�KdŠ’ ·”
Úçß‹ ì�*þ•òõHÃ¼y§•£DõRD€P®À`±¡£ý»G¸&7íô"U	 óõ˜É°~«oDåŒµšD@ïü{F¸ã¯ß*ü¦ ‰WGÂP!‚ÐE]³ÉUyÖÄ¨p¦jÜ��ü#êu´¿?„k‘âTk6º*+*ë3@W“z­mi—ØÒdµDå
G\z‘ÿk)?Ú/j7Úß/‚µ¸q»À¶NƒLÔˆ¬ÏH€Êd@&+°v£ˆô€Ð(‰@H~ª<$òÏš�?«¦|ÁZ$5“ó×jT–gdn%uç€W7º‘ñ›£,}w~MþÝ#\‹¯¾)Ð“£tuD‘† èê‹¯»yAˆ2*90Ø—üoŸ¤wþ=!$ü¯;Ê:ŠÒÞ!h@è¯¹ª9HT2­¢f	ô·óS=�6û÷�©Êü<•^w‚F‘ uh wxx}KÐ(B:
"°;³?J&m¹!ƒ5¸j£‡­íBG£äžFêÖ†ßZ{ùZ_ ¢2‚9
" ÈŸÓ>ÿ`ž÷/_ãªµ5K)R/—¤ÿ×ËNUÄ*Eò;£ø¡uôøËvEö¨Ø"E!2­’q†¿â mG§âª’E ×QßÅ:Ú?ÿŸvþgV¹»‚D‘€0ðævÏn@TR.+QB³”Þù‡„pí=µÊÁæ�žÊV�’ÿ9mOj¤vµ¢"’dÇR}Ô·Oxt¥£¬¨¨Õ¨DR Ôq ÅðÐó¹|ëëjD)E ù/NaæÛô9ÿP{Uæ¨µ˜ŒóÈ™ÿ„ÈÑ‡.2õ|ùÏ¿æTÕi@9D ïó“Ùq
GL2UÓÐ¨E¯+Éü_»ÉCœ* µ ”´ˆ»2BMÜ©vSÂz~:ç§ž*Ã�fèÂž!ãþå95&ª–h$_6¹	‹ã�çœüŒjF1D ßÌ£ÞŸØ3krmwï-†ùŸÉI<ðœ­Ìÿˆ�®Ì#’Ô	Ý€ë<ñ’­nHµºÅ�p\W#µîþ*5ðŒùf¿&ÿ� <_|ÞÆê�žZ‹Q‹þGZ Üð†ÒEŽF`Ë!yò³úÞLìÑfÿÐA×”.÷_Ï©Í(Êk�GY…ëâ>gcóN¡’‚¢„)¥„3›ˆü7á¨×ULá_ç×7{øç
õñÒ_)%"+ ÄuƒE	4	G}­` "’¿!Á±x�&± ƒ�·=šÅŽ.y1�¬ ì†[Î*3·Úƒ�äÏ§%ê7}µ¶¦ô–Rú×–®óŸ£³ÿè¥þöE¤)C‹ŸnÂŠõ.î~Ê·J=³ÒE€f(’ÖY7~¥	Ç¬~Å‚Èþ—Ç³X³Ù�tð¯* ©ò¯È*_¬š*‡"_ú`q†ÅR8îð+êÈ5N�g‰ß>”EÜŒÆôß½!òt¡…O�˜'_uðÀr[ùÀQÊì‹Ð"ýÆÙõ¸çû#qì!1um´Ù_È`HííOäTç
@WC!Zä@!˜Äú‹;ÓÊ×U“YªAž�ð(”ÞûAce®Öš5TRò3?…ú†»3‘êû¿7TÅQV@’á_¯8* ¬€j¹CC€"„Ï¦+"€Ûþ™Sõ'Õ²ûW� Æ®»3­*´è†E=@3ThòÜzgZâ†{ÒHX¬ªÖUÕ€²Ï¬qqë#ÙšIÒ(�ùó½¼²Á«Š£¿ª€|‘PŒáÚ¿¥U’†�bdý½±ÕÃ’{3hL0•�ZM¨* eNÆ�×6{¸þîtM»ÅcÀÏnO£­ÝŸú[mË©ª LjL2üò~ßd£¸@µl4Êä”PÚÖæÐTíœÿš Îè‘øþïºóä×–€Æ€×�ôÏU)�šÖ�çùuÕˆª ‘¾©Ž©ŽAx8«”¼š7å9F½éžž|ÕUÁåjµ"«R òñ ‹áŠÛz°iGà
hÐØÛºþq2¹�×Ü‘Vîd5¯›ª ˜(ùþº'ÿµ*¾—E2ýmøî/»Ð•ñË}«Ù}¬Z PÐ&UÏU¿€_ÝŸÑA�™þ?ûk~ÁQnd5þjF Â›J>Üå·öèS�½šþO¼ìàš;2HUiÔ¿æ€Ì7*Þ sî’›ºÐ“õ#ºÕlÖi"(œÚÖ)ðÍÅ]�RªÏka�T½ HÉ)‹‹J†¿³´[	 Ýô¸¿{�¤u Ç¾z}Vm
Ò}k`÷¯ ¸ÙÀðûeYüüoiÐ m ´�éOçýÿxÖFªüþš ©:ùv?¼5�»žÌ©OÂ QÛ~ÿÒû2X|OFmµDþš€Ðä�Å€¯ÝØ…§W;j&^­Ýtÿžj×§cbê'Q>M@>(ŒuúÂÏ»T¥—®¨Mò?·ÖÅW®ë„ÁýÊQ- 5¿j�aÃ6ŸûY'vvûQßjÎøÒèmö¯ßêáó?ïT§B1³º³ýö„š³ 
wJôxz�‹Ï]ã/Ý? 6Žû¨´÷¢ÿëÄº­žj([+ÿþP³@ ¢øyèy_üE—ªþÒ"P�P-ã°³[àÓWubÅ:M	VóAàš€PF52Üýd_¾®ÙPjxW¨VŸŸºDÍ¿ªÿ~ÕQÇ}®¾ÇZ 
Eà¯�çÔ¡�*& HÕ�Ó�ó®ìÀ£+eõiòû¨y —40ÜûŒ�óÒ�­B‰€>"Œ>ùWoôpî�ÚñÌj)"•õõÛh( í
d	<ñ’ƒOü¸Cõ¤¤E z {I÷nùÿQVmôü,?Mþ·€?ICC�v‡õ+×¹øÏtàÙÕ®ÎŒè,Ÿ›¼î{ÖV;[»‡ðëŸó9.¥L³µjô$´ÿÝ£!É°e§‡Oü¸]-$3ˆ	è«T¹PgùÌßùó@Ÿ¾ºYÛï¥­¸·N:$î“ÐÍ´'ðÐ‚¡d¡ŒÌ¿º×Ý•V1�Z>¥c>×ý¦ßº¹K‰6µòÖ÷ë­`jÓG7‡DÐ@¿ŸŸªqÐÂ±š°ËÔ¢úÒ/:ÑÞ-t\ Âö²|v_›‡O^Ñ¡†ÄR�Ý¹(K‰í;9ý/ð´ìa0$ÅZÉáœË;ðtP‹O_µaŸÜCDÿÇ36Zþ·�¼h«ÓÕïAß›ÝA’ Hð4ãÝú0``�%:!xyƒ‹�ý ¿¸3“Ç­MÌòB†&?Ò9©¬³‹®êPÁ>JïÖgüuD'—]z�üÀOh44	Â÷~Ó�ó®èÌjk < â“½J×üÙ5.>z9‰qZúâ1ì(7HH»L)åZÆLHÆ(´¥ó82jDÃ?–çðüë.þp=>ù®„Z˜¡YªOVKÓº‹ˆŸµ%®¹=�ÿžQ Yf:¹g`äP¿s¬á�|µôººšüƒt	(±„Ò†¿±¤Ÿ¼¢+×»½N
´Z¼kúú�¿dã¬ÿiÇ·¥•Ÿ¯Î÷urÏà %—žM×˜Œ‰UÒMSÞ+‡C^�J81ü áËsxf•ƒO�–À§ÿ££šüËúªú¢v�îê×g0`íf×Ý™Æm�æà¸#ý2^,¨å±Á¤›`XÃ½pÇA¼™a4@¸Z †Õ_Ð£öãSÆ›øÌ™I|lnR�Cæ¥kœøjÖ²äÞ4~y_mMIFl]¨5dH	FP¼nÎáì ó^KÄÌ†—8·Þ&ENÀ> < 5ë GN1ñéw×áÇÆó:LXÑvÖž‰Osh°ëÒd°j£‹†×I=Å€”’™	&ÝìYß|e ±iný;·ON—Ð(†P—!:’š=•,‚:œyT<à¢…ÀGx^¿;+ÑúˆO|Ð™°€„¥Ïõ‹éñX£!œî{W-û&À¤DÛSŒ[§KI‡Eü[µ¸’þ‘!]Oj>ùÙ«;1kŠ‰O¾+‰÷Wß+$@-Å	ÂÝžÞ3	%½ñ-íz4‹?,Ë©\">�´ÐÏi?¿xPçíûË)Lí{¨‚=.ÜUG&
ñoÖ,T–` tEŸÍUÓg®¿+ƒsæÄñþ£ã8`Œ‘¿Úá7ù¸¬‡pï��=ÂËoxøÓcYüù±,6lj¢35ì£ÿÅ„”ÄqáÐ´lñ0}EÝ†Ió6�3$_ÍSKˆÐ÷§–ä97’cÎá1eÌ™i©D–y1ˆp¼ 09ª0 ÚÞ#qÿòn"‡¿â¨ÏýDž]‘F©€1&…ÝnÇã“×ÿbÄNk‚ÄÔy[—±º9Âî`´i”Zh]ONª‚£éLœv¤…SgY8rrL/†P¤ ArX…'ë¨`Þ.ÃF!cK<¶ÒÁýËm<ô‚�u[üÃ{²Žè½jâ—Rn5ra÷ücÕ’æ3È 0çÎæ²eÌe��3nÍ‘èÃ*Çë©u×ÀrèóUoº*«ðÆ»38ô@§¾=Žc�áˆI¦ªlSÎYÁï«ŒÄÐ:QP›´ìÄ­•pñPÎ§W9xüe>—ÃÚÍBu^&Ò7Öù©déhS¿<PÙ¾,ÆÃcôùìÏ<mšÀCê›ž‡‡™›þfï¥¦QŽ`!!n1Õ€ÈðÜë.þý*}1ŒÍqÔ´Þ9ÍÄìi1LÚÏP®ïs—Â�Wµz!ï:Ù É]øo¥YÁsç–´X
ž”N=(rO#×þõ²ƒåklëÈPSŽ¸Í'ò‡¦Q^0Ééö0&™€†Wº(&@&',XŸLt$Vp31IzÙÀàÔ„;;‰�ãÙœTŸS¥Ûþ£9fM‰áí“L<ÁÄ”ñ†Š–Ç
™¸„þu_7;¯T	ÚÉ·´K¬Ùèâ•7]U˜óÂë.¶¶u†O"A~=™÷a‡eíÛ'¤`F‚Óù¦+;sCëÄŒ²	Ô÷Z¤�VæM�·íJÃjºØËµ»Œ*„4*&§€@™†Ž'U›+µ-£É6ãGqLÝßÀ�ÍšS\÷ÉÑÜÄ1¢�«à�¿
Ÿgo á±]
TJlï”ŠÔ›Û…j‘ÖÖ!UãJÎÙÖ!U1NO–š¤0µÃáÃ€Ÿöë+RJ×ˆ�0½\û•«—Œ½$ä|o’3´
§kc:¨Ý"0™ÿIkQ)qæ¥7\uÄHâ@D$ÂÓÏY&SÙs4}T#Gª.¨ïÑƒžÚv¤Ê¯·=ÿ„¢½[bG·@wÆÿzÎõw|zÐ"‰þsP§$ú7=w!áµO_y N§KJˆÛz}½×OµHcjÃ–§«a–pÒú4 (ô÷Ug·‚X@þ£�Š”áçêQàô}ÿœÞo©Z êÑwgžG£Â!¥à±:îÙéå«×®x'–�â†ßÊûù-�I ÎÿÌR{l‘@Ht"8¹ª9<{g~µ¢óƒoä2P�,:} „zÐ¿ékô=ú™:‹ÁŠù¿†èoÐóÓ#ôç5ù£â2eÿ1ÎÿHäŸ;÷Aó-Ð:Ã¿ŸÜe·º¹N›q:¤Ò÷8ÊwùP$ÂòÙ==D?–‚F¤!7ÏîÌÚnN™ÿËN>9³+Ò¿ˆ	,”üÕ¥Í/KáýÉˆ5¨Èá0½h�¢@â²â¶uKx™8®¸ ß£>ãWznš*õQ †F¤Á¹çöxBºWõûÝ^ŸVÀÚšŸžw7·©*C7\ÒÐˆ"¤ô˜ÕÈˆË¯Ý²ÿ“}wÂ[wø•þÉ€!ðSéf‘¢¡¡QY`ÔúKr?.äv¯ŸØmÕ ¦\Ø¶Ì´ON·n¢¡ÁÆžÝùÐê%ãNñ9ÍÞÓíßÇ?§•N€%û®ô4	Òa�h@µý–ž-�ý?õ•súçzÿÐzŽGþÂª%cöœÜRk &âúD@C# ÄŸƒ¸»ê¦Q�(ßŸr|úÁ^¢ü’™œ}×ËumcÜâ”QT¢W¬¡¡QG¹Å‰³Ä]¿Øo÷Ø½ P´°ü•%Í¹PuÕÙ�â('®Jç2ÅÝ¼%ò_ˆ½Dø%ÃB°Ù›`t¸[5¬†wzv—`,Ì
×ÐÐ¨HHÏ ÓßîþWÊl>ééñð°ˆbwoþ…Ø‘™ÄÊVöôÌL.žã2#¦»¶ihT(ßß„p©�ÛX@œ%îî‰ü„��ñ…BSÎßt©™õ¿žÝéR�I±^º††Æ¾�jµ«Éô²í—®¾yÜBÎîí÷fÊ·BPµàš[ö¿Ü³Ûï¤?$¥Ð‚ â"qÒÍuÜAä÷+{1 €ý }y&ýjAÉr’ÏN÷Fn$}* ¡QµþfÂv×F×“óéK>W÷lú‡x0o--·ò7–4o®{¡(ÄÐÐ6ìâ ð¼×-·¹¥åVcOQÿ¾|ž?5XvŠ;í‚¶ïðäˆÿ¹ê.¢ãå‡Ëã)SdÚ¿»êæ±ÿrs0O0øã¼e'{äcÐô2;oäVÊ„”ƒú£û	—¸G$.*¿ÙÉƒŽË±ÒO²––VÞ:£EN}cÛ�DêÃ^VwÖÐ(¤tyb„)r·­š0æœ…ä¡ïå¼wbBWHJ2èHˆOy¹Î‡ÕÉ ´% ¡QJH)”Ùïå:î6ìO]64ò†žÑ·h‘ ,Á­×Žë¹öÏîy‰D Rhw@C£�Âïíow½ r-›n8 Mì¯Ìw Ø·”Þ°ƒÐ¯§¶Áí~¿çd^äñ:& ¡Q
³ŸÈïô¼ÈDÏ‡çúéð3X§ÛOðB&žÛ6ÞJš­F¬áa·»€ž.¤¡±ïÈow>jgº[Öÿæm›ŠA~BqŠzTåà­ÆúßŒÝdï=Âîü›a� £AWO„ÓÐ*Ô„×ˆ�4E®óo†ØúEþAžõï	Åí÷ªÒ\iN�ºãF3Þx¾—ëôh.!˜î0¬¡1¨º~Æ%�7"×½dÕê‘ŸÁ2ækçQü†Ÿêršƒ)n»Üˆ%¾áB
š<§gjhìÒcÜ2Èƒö¼ì×,ó-EÕ…¢¨ä'”¨ã¯ßG€^ìäy[>bðøÏ¹‘ØOØXßÉö>TV¯Ç­&CxöfÏÉ~aí-ãþäoªC?êÛJÛò;(IœôÉÓ+q£a5ÍN§á1TVÒ¿­¡%HA&?¸•âžÝù „7Íâq«•¿O=:K„Ò÷üë’>hNÝ0órn$.¡I4yˆÎê¹µ)%¤0ÌzƒÜ~)Ü­êùmÅ™!äöåúQ¸˜:oëû·þÛ0G§B¸Í./ËëÐÐ¨°^œ™�ÕÃs³Ï{^úÛk—Œ¿Sñr¡T.t©_C§þìŠŒŸÿf]ƒ—\ àëÜªO‰\»£7«…@£ =êÝÉã)&œt;$®è62?õ3ûÔf©;—ã•”ìWA«¢ƒæm;Ô„ü¾a$Î"#@8ÝŒ:™¨#C=’L£Ú"|œÇ�Ü^¶Õ•ø¯×—4¿¢~b€m¼Š‰a"™dª]qðf§Íßñ^)�opÆæ0#!Pæ‘ŽhT‡�J„1x¬�¦õ@@>Â˜øáªFÝ¹‹øjã+ûô­áÝeÉÜ¡J¦ ˜aÚ¼íg2Î?'…÷^šL,œ.
ŽRR¦†”j«@#*íù¥">ç&�5BØdÝò¿	)®]³xô=þOI†Ë|·x¸^heª�é3yÞ–˜4>Ï Î6£-áe Ý]U—I-Lz¦v{“™	p£nn»-ÿ£”ìÚµ‹G?šÿéa0÷+W 
/Ê­¡E0ùüÍ37Z“ïaÌ8Êˆ5A‰�—Sm�É•Ü„Ê{/µàÓƒvy2Ý©M>3â`FÂé$)xZJy·^ëÚ[ö{ÁÿÉÔ�Î
 ~ˆÊ$¹„Ð4j¹Õ˜Üô®c¹ô>ð2Ž)<ÖÄèÚK7)_—ÑPs
#ªáæå6hh£(ŠïŒ>	Ïc �žö átéWI!þ
füyM×ýÿÎ'ðô]Ï„Ê&ÈBÉç|Ù"–O†8è¼×±Xã,ï$.Íã ÅñÌ0Ç`TwäPõ¤ß±\ztãü‹N·NAKÑ¡ÑÁÉòâp´•øà`SµlÌ 3,Ð‰•gwSÒÎpö¸€÷æ?Yý¨gVÿŒåÂg�»PšËhýU ñ£! }rZV‚µö1Ÿ¦ž»­IÆål0Ìå`³¥SØxÉ�äÌ´”B“!@â@Z „�Üµàßå9nÕ¨X0uêì<ø7y•T²"%Y˜Òµ™”	lb0VIæ=n.CZ<»ú7c:Ÿ�šsª¾ü%ÊÝ¯Qè{„ØÊçÎhaË.ƒ×·ÒÔ/É¸ØÙ�2b¹I€˜Î'ÈIrš¤d)úFÿ–#ÙqZjŒ6‡1¶�èdLvHú7cÛ8Økž`kÈµ^<þ�5tîð
R²¹—ÁX¶²U¢µeXŽòöÿ¼Ã©ÜEÐG1    IEND®B`‚ic09  Bü‰PNG

   IHDR         ôxÔú  B»IDATxœíÝ˜Tå½Çñß{ff+lawAd±×ØbbAc®ýª71š¨	‚šfºM5E¯“hôjb ±aK¢±ÄX‚š˜X£Q#ˆ,X va[gwæ½Ï™
Ò¶Ì™Ó¾ŸçY��y™�=ÿßy«BmÜ‰¶´¤¢q#³£•ê�4ÒJåF¶ÌJeÆšþÏR™•-ïÿ¬2É”£
¿ÛÀ_ÖªM²�Fê´R§‘éèÿ¬Nkl§±ê°&÷çîÿ_m¤+;¿aæèøÞ…›ñ»˜mÏZUéôÙ�¤ÌN’ÙÑí(Ù­Ì6Frx’•²’],™ùVšïX3¿ÏhžI8_7ª•ïFð hÂÔæ	)'3Å*»·dvr½1f¿Û a­}W2óŒÌ¿%½`óHÃŒš¥¼zÁB HÁO$2;6;EÒ3Áï6@>YÙÉ<&«Çä8�üG ð@ÜüG ( 
> l� ð Ùú3-ÕE%}Ÿ1²Ÿ“Ñ>^= D’Õ³Ö˜Ùé®ä­oÍ©jö»9QD È§)6Y?©éHcíç$s¬ŒŠòúø 7ViÉÞ+kf/|½öÏzÌôùÝ¤¨  äÁ¤é«v1ÊL“µ§cFçã1 ë²Ö®�1·X%f-š9Ê]a€a  ÑvgµÕf3=§åîö�Ù}8ß À Yû¢•™�îNÝÀÁÐ iâícÙÎ¯Ë˜/©rˆ¯;  ¬Ô*Ùk2¦ìÊ×gŒXÎ‹:p€ÚæŒ–‰)Û{®¬=ÝS2ˆ× à1km·Œfõš¢ËßœQõ:/øæ 6cÛ©«vu™óeu’1Jà5 øÄZe$Ý–Í&.]<{ÔË|#6Ž °ÛN[q@Bæ|½‰× TV÷gd/Y<kô~7%ˆ °íôÆ£Öž/cðç[ È+kŸÈJ/š5ú^Ù÷ þcâ´æÝê»Ò¼Öë ˆkõx_Ö|á�Ùµ¯úÝ– ˆ} 7½uT©Ò[éLŽÕ€Èë³ÒUÝ*úéÒ™•«cñ Z§þÍ•Ÿ7Žý©¤Q~7 PP«dõÝ…[×^§M6Ž¯},ÀäÓ›ö“Éþ†|  æ¬}QÖùüÂëkŸVÌÄ* L:mõhSÔ}¹¬N5&^ÿv À†Yëî'do²½¥ç.ºiäŠ¸¼Nñ(‚SlrÒ¶M_3ÒŒQ…ßÍ �µj“Ñ…‹j¯ŠÃ¡C‘ õ§7lŒ~-£ün  ¬^µV_h¸¾îqE˜£È²¦~zãdôŠ? `ÀŒvpkÇäi�ßwkIT_9á{n4Æü—ßm „—µö¡ŒSöÙ(4d¢¸…¯cô;#3Æï¶  ÂÏÊ.ÏZ}2j[
G' œhõMß•ÍMôãÐ @^2Ò�®®½Xw÷À¡Ð‹D ˜túÊñŽÉÌaÿ~ €§¬}¢Ï)ûd†B ê§­ü/™ìmFªö»- €x	È&>Û0«æ!…XxÀY65¹¯é"+�Ã¦>  6º¬!Y÷}]gzÃøê‡2 Œ9Í–�L5ÝkŒñ»- €ø²V�®î­=vùM¦C!cÂ¸�¯SÔ}¯¤}ýn  ’žÉ¦KŽÛ6Â&l“ýŒ“™kdêýn  kXÙ›Mºèúš%ayUB³à¶SWíjLöï @Ð™z·F¹µJ!Š€‰Ó›öMXû 1ªò»-  lŒµjÉsøë3kŸQÀ¾`òé�Ç$mv.Å tÆ¨Ê­Y“¦5~’z À¤é�'ËÑ]2¦Üï¶  0 Æ”cÈÕ° l ˜4½ñc5GRÒï¶  0F¦Ø­a“¦5ž©€
d ˜<½ñgŽô36ø „•12ŽÑuõÓV|G¸I€“§5~AF×úÝ  òÅZsvÃ¬ÚÿS€˜ Mø³ŽþhÚ3 ÀPX)+«fÕÝ£€L ¨?£qŠ²öcL‰ßm  ß¬µÝÖ:G/º¾v® `Û©Mû$û�ô»-  xÆjuÖ$>²hæ¨+î`ò´–m¥ô32¦Æï¶  à9«·m&uPÃU‹ä#_ÇÚÇOk+¥¦ø bÃh¬’é·úl[M,{ ¶ŸÖ82cô¤‘vö«  øèÇê°³êVÇ¦`ÂT[’1º‡â ˆ±}3ÒÝšb“ñ Z'å4Ýi¤)n  ÄZ?©éz·6ú¹þ„õo5ý@FÇúy "#�š«�…Þë+ëŽû³Ñ  kmd²æ#¯¯}ZR°B<aj³{Dâí  Ö•«�NöÖ­?ÓR­¨€”Ó;KÆL(Ôó .fbqIú·‘
 ýü˜
ñ\  „–1ŸÈÕÌB<•×OPæÊ�•Í<cdÊ¼~.  BÏÚŽ¬I~Øëí‚=í{–-SÖ÷§ø 0 Æ”Ûwë˜Ól¹Â Ê3�×°Ù  ƒcŒÙ¥¢¨éçž>‡W<izãÉŽt«W� @äYç“gÕü>4`ÂÔæ	I§ïcTåÅã Vjî5©½ÞœQõz(† ’Nï¯)þ  �‘ªSÙôµò@ÞÀ¤éMÇcÏ÷ã GÆ˜ÃÝÚš÷ÇÍû¿Ò+Æh|> €8³VKÒÎù<:8¯= ÙïRü È/·¶º56¯�™¯š8­qû„±/™â|=&  ège{ú2ÎoÌ®}UAêHH×Rü ð†[c“NöŠ|=ž“¯5ÿÆè�|<  ð~Bà°‡ ˜ø @ø&»€‰  „oBà°z ˜ø @8'«€‰  „sBà�{ êÏhœb¬Î“ €¡³F‡4Ì¨{¬°= Y]8ä¯  Ã7ŒZ<¤€ú3V~ØØì“C}R  �Ö8û7Ì¨yª0= 6{þ�¾  ä×kò { ¶�ºb²ã˜Æä÷ !  0xÖÊfÚañoë^ó´ ‘�{àÅ € pkr"k¿3è¯ìÝ"aæIJö‰  €gúº­¶Y2«îmOz 	ó-Š?  �“,2æ<Oz ¶9«qËTŸ]dŒ)RÓ  €g¬µ]=2õíp@2c¾Mñ  ˜Ü],ûÕÿý�ü¥	S›«’NïÛ   ‚ËJÍé®Ô¤·æT5ç¥ éôM¥ø lFª.*éýÜ@þî€€‘�:ìV  Ïéäþ½M›0µi‡TÂÎÏK«  €çYc·[4stÃ°z ’ŽP’   ÁØÈXsêæþÞf€5Fö´<¶  xÍØSr‡5 ÔŸÑt°ŒÙ6ï  ž12õõg¬ÚoSg“[ú;°‰ üU[aT[á¨¦ÂÑ¨‘ýŸG–•%¥¢”éÿp�4*N)÷ÿ2Y)ÝgÕÓÛÿ9Ý'¥{mÿGŸÔ•¶ZÝeÕÔ–Õª¶¬V®Îje[VMm–o9pÖæ†ð7zLðÆ»Î²©ú¾Æ¥Æ˜Ñ^5À¦¹…z\mBck�•ÐÕŽ¶ªMhL•£ÑUýÅ¾z„?gs5·Û\hlÍêÝæ¬–­ÌèÝUY½½*£wVeµè�Œ/íÐÏÊ.oHÔ�×u¦Wƒé˜”Yy4Å(ŒñµŽ¶—Ôöã’Úië¤Æ×%4v”£Êòà¼é�ê	Õ�Mlôï´tX½µ"£%M½º¤O¯-ËhÁÒ>½½2[Ð¶qddÆLÊ¬úØ"éÏƒ
 FÌþòÍí‚ßmbJÛ�KäŠýä­ú~iQ4_ëªr£ª‰Ií61©£÷)~ïÏ;z¬æ½Ù§…Ë2zui_.ükqŸ¯m¢ÈQÆØ` ØàíEÝ—VŒ¨êÑ;’áyë€ˆ2FÚn«D®à»Ðýìþ>1¨38ã£7£\ïÀK‹ûôâë½zéõ>†€á²ZíH[-˜U·z@= UÝÎ'e,Å¤ï�Ò;iÏIIí2!Ù;{/¤Ò.Û$sŸ9¤$÷gÝ6^XÔ«¿þ;­çè% ÅhdÖšOHš½þÿÚ€úé�wé¸Á=?n�?h×"¶G±¦ìVè1û(XÙf5÷Å=ò¯´žx%­^ò °YVúcÃÌºã?øçë_­.´Îä%M�’Fmþa�ø©©0úøžÅúØEÚÇ¢Ü¸>
¯+­\øËý� ­“¥‰ÀY»ráÖu£u¡Én2 Lžºb%Ì~ ž¶�Ðá{å
¿;žïŽï#8Üýþ¹°W½�ÖÃÏ÷ä–!XKÆî¹pöè­ýGëÝ»XÇLáÚ¸³õ“:lÏþ¢?iË�/uƒÿÜ‰•ûnŸÊ}|ïärÍ{«O=ß¾Í~€uÌI› 2rÿKî,ýOX¢#ö)ÖèJ¦ë‡•»´ÒýøúñeZÒ˜ÕŸÿÙ£ÛëÒ’&zS&WÛ¯X÷�ÖÆø?b(™�ŽØ«X§Zª½êÐ�*kÝ9½ºyn—})íws ßç¬ ÿGœ¸wøîr³OTšÛKñáöÜúh—î|¢[­LD<ç¬s»Ãø?â²Vÿ´�•êã{²H?Î[/Ÿwbyîãî'{4ûá®Ü¼ Nó Öíïdüå.Õ;~ÿ}ö°ÒÜ8?°Æñûç>ÜM†nx¤K=ß“[U D}ÀûýžŒÿ#‚ÜÓóÜ»ý,ÉíKlÎòæ¬ny´[·>ÞÅð ¢ÅÚ•]«ëÆ/½Ót¹¿}ïŠÈø?¢dŸíR¹»ýÃö(bï}IO¯tßÓÝšñ`g 2¬qöo˜QóÔ:C Œÿ#
Ø9¥¯W®Ý·e6?†§8%}â€’ÜÇã/§õ‹»:5Ÿy9“Íî!iÝ `ŒÝc#G ¡˜Ø÷µãËYÆO¼kQîã‘Òºâî½¶ŒÍ…RÆ~XÒ¯×í°fÛ›"lÜ;ýoŸX®½'§ün
bÀÝÒ=âÁ¦õË»:ôúr‚ ÂÅ­õk~ý~?©±;Ð€°Øy›¤ÎùD¹>º……åÞ(±wQîã¾gzrAÀÝm…\­ÿÏ/ÝÿL˜Ú\•Jô5ûÚ(` ªG�÷ÉrýÏGK8��àI<ãÁN]{§ºó¼Á`&!Ù")[de2’“–i†j1<½™dõ³«[r= Édv÷À` ¨#�zh©¾v|™F–rDp¤’Ò�.Ëí3qñíí¹á�Áè©’z«­2ÅVY·Ø§Ü‚/eK7öV&mþ$ÓÓÿ9¹Ú¨x¥•“áç›–R¯;ð¯\ 0Y»óÿTªOê¢Ï�äD>Ú–£]õÅ
=9¿WÞÜ¾ÑùYGJ�²ê©µê©‘lñàŸËYeŠ¤uŸÁJY)µÊª¤É¨¸Éä‚ðAÙ„Ùá½ `e'�4£F}ïä:f¿!\!Ÿì¿cJ÷ý¸:·«àÕ÷t¨³GÊ$¥t­Uw]ñ—W›Q:Ro­ûaÕf­RmRq£É‚d§GÏ‰Ð1V;¼?	Ðôÿ
÷�žs?Q®ò¢)Â'•�Î8¼T|¨HŸþc‹—¸ø…Ÿ¬ØWé~XuÔ[­’F,2J­æg*öÌZÀXw€7‚qHËÏÏªÐläƒkï³úÕ¼N]ýj§:Ê‚1Á*=JZYmUÒh5b±C�@Œåjþš `�a þ¾!MÿÓW�+ÏíÀ„Q:+Íx­S—¿Ò¡•=Á(üü9ë-u×fUúŽÑˆ×™'GnÍw?›	SWl‘J˜wünâË=�ïgÓGjÇ­Ù¾á”µÒm¯wëâ—Ûµ¤#D{d¤²¥Feo%89Vz3vËd2iXß|õ¸2�}lß„V[oV§ýµU�-ïUè$¤Îm¬º·°ªzÑ(ÕÎPp\¸µ?i­¶à[?Æú¯úR…vâ®!öf{FŸx¬EÛÂ½%p¶XZµ—UÅ«Rér*B¸µ?éXU± 
é¤ƒJtÁI#TÆê>„Ø£ï¦uú­jNo¬HRÛÎV}#úW¢Í­ýI+SeØPUntÉ´‘:t÷"^o„Ú¬…]úÖs«scÿQã	dÊ¬*_12Yb@T¹µ?)e«8…ØågV¨¦‚
Â+“µ¹Â}C·¢¬§®H êEÎˆ.[’´Æ)¡ ^:ïÄòÜ? ÌVõds]þ¡œì7}#¥UûXU¾,µÜ£Ç–$Ù¿›�èžÜwíÙ•¹½ü�°»r~glŠÿÚ“Woo5êŸî™1„€(1ÆT9Vªò»!ˆž='%uß�ª)þˆ„»ÞêÖóâ¹™¾ÛÐºc';Äœ[û“²¶Šm€‘O§¼Tç~²\I¯<
è©Æ´¾ðd[¬_óž1R{§Ííˆˆ°¶*idè@^”I¿8«BÛƒYþˆ†¥}æ¯­ê÷2ÿ¼è˜h•ì�JV¢À­ýîà, Ã¶U�£_¯Ô¤-¹íG4tõY�üxk ÷ô÷‹;�è;F‚-q¬“ 1ìñþ»PMñG¤¸Ýþ/·°Aþ:RËnVÙ¡(üL‰ã¦ ¿›�ð:bï"Ýr^•*ËéDtÜ·´Gw/éñ»�”-‘Ú¶# „�5–! Ý7ÿ§L_8Šƒ|½Í~.z±Ýïf~R`ï›–¡€pËMdGvJQRºâó:lO&û!zn{£GóZ™õ·9í¥ê—ò-�ÜÚÏ-ô~þ3¿Q©]'ðÖAôtg¬.}™»ÿ�H×Y¥+¥¢V†ÿÂÊñ»�Q#�îøNÅ‘>äçÍŽ¬ßÍ�öm™f ÈèJGw~·ZÆ°ÌÑÔšÎêó:ünF¨ôVKÝ5„€°" `³¶åäîüÇ×òvAt]³ K�Ý³Áê  ´¸¢c“ÆÕöÿ±5¼U]ÖZ]¿°Ëïf„ö¬€tÁ)Œ¸ªc£¶�Ð�ß©Ö˜*Þ&ˆ¶çVöiy7cÿCÕS—×o
„+;6Èë¿íü*ÕT0ÃñØøC×]K@ °ž-ªÝ|^%Å±q»þK¶\êcO°Ð! `Õ#ŒnùvUnÖ?î²¿†Õlü3\ô„Wy¼gD©Ñœo3ÛñòÈÛtÿçCOÃ aC @NI‘tã9ç‹ø¹Ÿñÿ¼è«�²	B@˜  TBšùõJí²Ûû"^Úz³úëò´ßÍˆ#õÔ0i8L ÐU_ªÐ>Û¥x%;/®Ê¨—ÕyÓ[É‹&€˜»ès#tèîœê‡xbí~e¹”„
 ÆÎ>¶L'Xâw3 ß¬èbö> Â… Sÿýáb}õ8î"ÞèÈ¯Ližž" ÄÐ�»¤té´‘~7ðÝò.Æ¬ó‰€p! ÄÌn“ºæË•Jð�´‚ýÿóË‘2œ”�qOô›ñõJ3áÈ¡ ÿl1o®°  ÄD*)ýæ+•ª*g�.°Æ[LÌ·+Bƒ —œ>RÛ�£oX£;ãnÄÎuùÆ<€ð  ÄÀ§,Ñ±ûÑ/¬­$!�/ç˜o‰nBUXðî�¸�¶Nê‡§Žð»@ �.á˜oNšaÆ°àÝa•åF¿ùjEn¯ ëSÊG^e¥D= aA ˆ°+>_¡1U|‹��C@^™>#céªCD�yD©>ºëý€MSÊ%0ŸœÞoaÂ»?‚&�Mè'”ûÝ ð˜�_	NV@Ä%¥«¿\¡$C›ÀfÑ�_† *€ˆ¹à¤š8†ês ò‹€p! DÈGvLé”C8Þ¨Ý«“ªH1i-_’«y-Ã„ Õ#Œ~ùù
¿›„JQÂè€1ì]›Y©x%K Ã„ —L™ ç°-	 ùPÔläd¸…	 ŽÜ»X‡ìÆEŠ£¶âg'Šyÿ… äF”]ÈV¿À�mY–Ð^5I^Áá°RI/aØ Bî‚O•ÓõÓ1ã˜<;É6w ÝÿaC ±}¶KéÄ¹pÃuÌxNËŽâFŠ BÊ=àçÒi#ýn	ÛU$T?’ý3†ª¤‰ F€�:û¿Ë4®–o�/ìÆ±ÙCQÛá(ÙÉû0Œ¨ !4iË„¾xt™ßÍ "å“Ûk§JzÃ1Ò•ÒV€úéçø�¼ðãñ³5'M(Ñ1;ëÓS˜‹F€�9|¯"íUÏ’%Àß²HÍ1ÚQìHìÚêè7O(WEó Â† "©¤ô�“§¼ôýÝ8J{ ¾¸C™¶Ñ?dRYnôõãyÝÂ† "î¸ÿ–£ø–^Út‘ŽÇ²ÀM™4úÖÎëÎCr‡ÜùIªIH¸…ÿìc™øÂ÷v+ÏMpÃ†}sçrU¤Ö-	GúÉgé¡@H|çd~°€BÙ¹*©ï³,pƒö©Mê+;–nðÿí=9•;›á@ ÉŽ‡ˆK€BúæÎe:akŠÙÚÆ–:ºý *¥6Ñ=rþ§˜€8ïD~  ?\ûá
�ÿ@Ww\•$¤;§T©¦dÓ¯‡;\yê¡,ÞÙ÷Ñ�RÚ}"Ëþ ?Üó�u=fåtÇûõwï÷¯Û¿B»TìZô…£ËrÛ•#Ø ÷õ¸ûüpû_»õýÛ•è1ªzÉH™ø~~°û·õÀïêGW::ù`z‚Ž `îÂÝ?àgñ_#ÕnT9?žËþ{|qn>Ä`}ž^€À# Ø9Ÿ`æ?àwñ_£d…QÙ›ñ
;W%r]ÿCáö|zÊ†W  uð®EÚq<ƒh@Šÿ#UÆd8àôú=vø(•&‡zÎ:ª”¹ F ¨oþcÿ@�Šÿ%MF£þiät)’Ü~¿Üg¤®Ø·BE‰áõxäz¡ ¨ �ùÏÝ?¼â¿öœ€šg�R­Š”ê"£?R¥i“óW´Ï<¼4·K ‚‡oK �q[þA-þk8}FÕÏ•¼«H˜\‘ÐãGŒÒ![äwÓ±1ÕŽŽÝ�•‚ˆ 0“Ç&r=  ‚[ü×0Ö¨rž£‘Œ¬UhµU‘æ^ýÞé~ùæî€à! Ìç�âCñ_[Ù2£š§5)T¶™ÐŒ�VhÎÁUëî“×çÙ‚› b‹¹ q'Ìµ]e@˜Šÿ©N©ú%Gé
«öIV½Õ
¬ñåŽÎßu„NžX¢aLòôÐæßçElÒDÈ dú¥J²ò]ñ_[Q›Ñ¨ŒÒUV«'[õ�T`Ô›ÜQ¾gmW¦¢÷ÿºC›Û�KhÁÒ¬¡	† ¢¼ØèÓ³\sñ_[Q‹»RÀÉí�ôùÆw‹RGìZ®—Ž«ÕÙ;¾ø¯qÆáq	= ñé)%*áÄ_À37ÏíÖ�ç¦øpß ÷#SdÕ]'�ÝÙÑÙŒÒYoŸw×ê¤ŽÜªXGlU¬Õ$súøí¸ý‹uÙï:ÔØêñ?B ˆSåîðòÎß�â¿¶DÚ¨|™ÔºÌêû'ŒÐÄÝz`Y�þ¼¬G+{†¿„À½«?hLQ®à=¾XcKƒÙÁ{â�%ºæ¾N¿›@0|x‡”ÆÖó‡»BvûÔÕwuê[¦\×Õ¿Ï~cwVK;³ZÖ™Ñ2÷s‡û9“û³·;3z·+«ê"G[•9Úª<¡±eŽÆ•¹ŸçþYYB[–9›Ð7€à   >uÇf^¸in·~âó�ÿÆüü¹ÏŸ?ªTu%NîcÏQÑ¿$oUãä&þ}^¯ßM‰=n;}V^btÄ^,ýâTü×³Žè¡›ÀMO0 ÐÆÒ? ~Å�‹o�_8lÏbU�ÁxEÄ |vÊ!tÿq-þq©„tÂG¸öù� à£½ê“Úf4;ÿ q.þq'L ðÀG'|”  _®¸+´Åíàþ;â`â˜„vŸýI�AF ðë…7ÒÑìûäíÎÿoïŸUvî¿cÎ£ÝŠƒ£öe´Ÿ >9`çTn €øvûoÌ…·´Ç"C ðÀ'GíC÷?0\Q,þq
u•ŽöØ–a ¿ |à.û;|/6þ†#ÊÅ?N!€#ÐýC ðÁ;ÑýÃ¬‡Â?áo0!àž§zUGìÍ< ¿ |p$“ÿ€aÝù_rG4&üt¶ü�»D·Çp‹jG{NbÀ ºÿÿëCÑýa¼‡nÿÿÛ.¨Šü®yGÒà@�}dGfÿC1ãÁøtû»êÇ&tëùÑ/þ.€? 6e7Æ»€¡Üù_vg¼ºýo9¯J£FF¿ø»ÆT;¹ÀƒÂ" ØÇéþ%nÝþn!ŒC·ÿMÙ•¡ÑB# Ð¶[$4¦Š—¨8ÿ[¿¿âï:ˆ PpT£:˜780`q-þ•åñ+þ®}¶K©”N€‚" ÐÁ»ñî‚â?	ÇÝ"�kd! 
¤¤HÚoûT¡ž-Š|q“TX€q“­›plÅ?ÞŠð†GADI*��ìÈØ”Ž×:ÿíÇ%4'ÆcþÛÐ�,�Â  ÈÞÛÑýlr�ÿï:b5áïæs«TEñ_ÏÞ“¹V
  Ê‹�¶ÛŠTlÝþXÛ‡ê	 …B (€MNÊ¡—XÅë]/ë9¨P °‰XÅ2aL"–!ù� P tiëŠåÁ>Lø0®™…A ð˜1Òž“ÓÖ.þq:Ø‡â?xôšÀc;o�T1õÈ¡øc è(f[xlÏI¼Ä€ëººtùïãsç¿ãø„n:·JeŒgƒ �í¸5 pïüãTüÝnÿÏ¡øÇä±,�öÀcÛ�#  ÞèöÇPl?žk§× Û�71b,nÅßíög¶~l¿Àk¼Â¯gMÑ‹…˜Šcñ¿å¼*�(eÌ?¶ÇÅÓkô x|ØG= Þ# xˆñÄÅù0¶ÆQ)‡¨zŠ à! â†â�|b•· Ú� ˆŠ?ò�›(o ¼za�4¾Ž—ñ@ñ‡&Ža•—¨P_Çñ@ñ‡WÆÕrõÀ#ãjyi}xi+€§¨R¡ QGñ‡×ðÀ#t]!Ê(þ(„’"q˜’‡ a QEñG!q3å€G»Š†õùÝ„@¡ø£Ð¸™òÀ#ãj˜½vOÎïÕIÿÛ¢ÓÑªÞŒß­ñÅ~ À; %¥š
	³¿ÏëÕ™W¶¾÷ëÏÿªÿ×quíý�±:Øg—m’šómö	‚±£(S^á•õ@m%/kØïüÝ‚Ÿ^«÷ÿ‰WzuêÏÖý³8Ýùÿò®NÅéT¿Ï©Ty	!>F�äzê^YT�àesñwïü7TèŸYÐ«i¿ŒW Û~«& x†Jå�ªrî¢Vüã(þ®§Þ! x€ÄÍâ§·â¿ë„¤n9�1ÿ ª¢GÕ3 ŒâÙâ‡Çâã¹•QJÏ]U�àûâ€xÃF»øG9\uOg,‹y1E&¨Üï�»²
ùG ð “ Ãá¹…C/þQ—ÞÙ‘ qAñ�ªrJ•xU=PM—U(Š¾
wB€[üg>Ø¥¸ ø‡½ªÞ  x ŒõÃ�öìký»;�¿ÇtCÀš�ƒÂæçˆWñß}Ûdÿ:ºýC£¢ŒRå^U0šì;ÿéWä·ø¯=Ÿ l›¹wþ¿ùS¼îüg‹M~Âf7Už  x k½xTä«Ûß‹âÆá ºýôªzƒ à@,‹˜B@ÜŠÿîéö³R†k<A ð õ?¾Å?! nÅ?×íÏÞþ¡Æ€7 Èf½xT„¥ø9Ä±ø³Î?ü8˜É Ð/.îó­ø1PüVex‚ à&£øîç-¾ÿ … Š?ÂŒ o ¼@€¯^y³¿øwö(0Ö„ ?	ÅaWÉ	«ž  x 7Cð³øŸvyk ŠÿÚ! Ð½D—TO <Ð€ñÞ8ÿö®à^-^XT¸¡	Š?¢"sh¢ˆ àz 
/Åÿƒ! £Ç»¶Rü%é¾àÿ\‡Àé^/Q(þk‡€Ïþ¬Õ“ðã9í,õC¤ ¼A ð = …Æâ¿ÆËoä?¸Åÿæ¹ÝŠÖùÇC Þ  x€€ÂX°4ÚâïE ø#ªÒ½áý2€è(Lñ?õg-¡.þÃù·Püeô xƒ àV¦ø·v„¿ø¯N¹lh�†â�¨c€7 è¡»ÊÛnÿˆÿ5æ/qƒM«Ú:þo»è¶ŽX�ùçNõ;·Rål+=éèý¼À«#Ð-ä;ÿ–ÿ5æ½Õ—8é	pïüox$>ûì9é?§úQüc§½;º?ó~" x ¹�ã ómEkVŸ½<šwþê	øô¥›þ·þ$f³ýÝâÃ·ª(þ1Õ¼:ú?÷~  x EªÐFW::bïbÅ©·cc!à{7´ë¦ÿ’"¿[¿pSå€x³zãG§ŽÐ§§”(.Þ^?¸ÅÿŽ¿Qü/Íôªz� à€wâšÛ-Å±Å€7’=n¬­lcÀë`Œ4çÑîØ„€Ã.X«É¥tûck™Xíz <…j‚ìÂSâÕ@ñG\­b g if" çâ6ÜùãƒRõÀ#«Ú˜´R¨ð™CQ°÷ä”n<‡ÙþX×ÊÕ\K½B ðÈÛ«2^=4b>Õ;ÿYß¨TqÊï– hÞ^I ð
À#ËšxÓÃáE·?6ei7S^! xd	oÚ‚#„Å›C ðÀ#Ë ¾ „Å±”ÞTÏ <Â›Ö?„€à£øc –42à€G–­Ìä6°€?ÁEñÇ@e²Ò»ÍÌ§ò
À#=½RK}EŠ?ƒño <´Œå+¾#ÅƒÅPª· Zü.cWA@ðÅCÁ5Ô[ ½¶´ÏË‡Ç üCñÇP-XÂ5ÔK -  
! ð(þ®¡Þ" xˆ7oð
gßíSºá[ìí�¡[°Œ / <ÔÔfÕÂ©€�C(Lñw÷ö/)*À“!’ÞZ‘UwÚïVDÀc¯2†H„ ï‹QÒÃ'Aäq÷ï=€Ç˜\„€ü£ø#_BõÀc–±0ÈùCñG>±À{tÒyŒ!€p„ c¤9�vûÝ”Ðúð)ÝxN¥ßÍ@„ÌcøÔsô xlþ’>&²„À…§ŒÐ§§”øÝŒÐÞùÏø:ÅùÓÜnµ¤‘3 ¼F ðX_Fzù�^¯ŸyÀpÀàÑí/<·�kf! 
àùÖ²†!`à(þðÊó€B   oæp!lÅ^ú'= A (€g^#Í†!`ã(þð~Ø”^ÓB  @G·Õ¢wX6„€õQüáµ-îU†ùA (†Â‰ð>Š?
�9S…C (fµ†;|æ�x/t×ùÏü:ÛûÂ{Ï1dZ0€ùÇ|æ„Yœ÷	X³Î¿8åwKun×ÿS8¨P ²¼9«K™fq Û…ôô‚^6N+ @=þ2É6ìâ(þ(´Ç_âYH€" DCB Å~àYX€onÑÙSÈg„W¢(þðÃò–¬¿Ë0i! 
(k¥¿ý›.®¨ˆbøèN)Íú³ýQx?Ïµ±Ð öó "%J!À-þ×}�âÐý_xIž3ÖþJ ˆd0Fšóh·ÂêÀ]ú×ù~èé•žœO@¡ÑP`�­Y½°ˆ}®£&Ìû¸wþ¿þ
ÅþöŒ¦¹,À<ÇLÀ(
ãpÀšnÿTÂï– Îx–k¢ >àÍ]aÚ6˜â� èNKùÀ Ÿ–»0]ap÷öçÎAðØKéÜ À'¢Ë+Ò‚<àÿßÒí�€øÓsá�<v ŸÜÿoú¨bXSü9ØAéþôEfÿû… à“¦6Ë¹×1¤°W}’â�@™ûbÝÿ>" øèO¬ˆ… LÜ{rJ³¾YÅ�?åþg˜üç'€�î}ª[½l}~Ntïüg~£R¥E¾<=°AÍíVséþ÷Àç€G^ Ç…Ãnñwïü)þš»þÑ­LÖïVÄÀgwü•É€qRÈ°ûDŠ?‚kÎc]~7!ö >ûû¼^-[IŽ“B„ ·øÏ>‡nÓ³¯õê­\÷üF €;ÿF/@ÜxÖÿòbãÉãÃu×¼@  $ d­ß­@B ÅA×ÞeÙ-  9!ðñ—Ø#Žò(þƒ»žìQ/'ÿ  nc2`låcŸ€]'$uÃ9Utû#ðæ<Êä¿   „»æ’&&ÅÄÕpö	Øië¤f«ReÅyo�WO¼Ò«Eï°ùIP äº?uúÝ„l8À-þ7�[©‘¥LøCðÍø3×¸ ! ÈþÞ­ÖfÆÙ`B ÅaòÚ²Œþ1Ÿsƒ„  î¶À³a|,î¶Û*Á�?Bå×ôp `núKWîˆLÄÛ¦B€[üo>¯Šn„Æò–¬x–mÏƒ† 0m�V¿ÿ;aÃ!`Mñ¯*gÌá1óÁ.öý @ Í|°“��°^ ø#Œ:º­neßÿ@JúÝ ¬oiSV÷>Õ£ãög]úCÀ–£�tP)wþ�v©‡¹�D@@ýê�t™á=_8ªLÕ#èöG¸´tXÍz�¥AE (wS ß=Á\  áõ›?uª‹IÍ�E °ÿ»·“=³„RS›Í­jBp ìÝæ¬æ0y@]uO‡Òúh€ô0�@Øn^nœ!Ì # „`Íõ3‰@xüâ,e@\÷@W. @Ð½º4£»Ÿd×¿0  „@{—ÕÕ÷Ð  ø~2§Ýï&`€ !qóÜ.½¹‚s´×£/¦õìkìú€�ÈZéâÛ;ün lP&+]t;wÿaB Yº~fé@ðÜ2·Ko­ÈúÝ d~xs»,óHk‡Õ¯˜§:€�YôNFw²E0€ ¹êÞÎÜQæ@ýò®u²Ê@@nJn|„-Ãˆ B+Û¬.¹ƒÉ6 üwþ¬Õ~7CD ©ÛïÖ‹Øh€¿×¡_ç:V€�'ï>¶ àÓiôD† Ä^_žÑ¯ÿÄ� 
ïÂ›W3)ä !wíý�Zü.Ý  
»'ÉCÏ§yÉCŽ r½}LÂP8=Vß¹�‰Q@ ˆ€-îËMÆ ¯]zGGn%Â� ÿ{{»–4²' ïü}^/7B ˆˆ®´ô•kÛr‡@¾5·[}óº6^Ø! DÈ¼·útûqðÀ7~Ó–ˆ@Ä\s_§^y“�9 äÏ­�uëó9‰4j ãžøÕkÛXŸ /–4euÑml=E€ˆþÀþäV~`�»ÓèÙ×´)M§b$ "ê÷Otë¾g82ÀÐ]ö»Í‹êU€ûö¬ÕZ°”]ÞýÏöhöÃóe€ˆïxÖ¯ZÕÒÁÌ] ƒ[QtÞLvû‹:@Ä½³*«/ÿ_›2ì` V­¶:óÊ¶Ü¢� Ï¾Ö«ÏaR €MëÍô÷6¶rÇ€­ãu'ÀÆ|ï†Õzéunýã‚ #Ìn×óüpXß�té®°r(N 1ãvï-m¢{Àû{9­‹oïà%‰@Ì´uZ�þ‹Vµ²2 €”[*ü•kÚr»ˆ"^ 1ôæŠŒÎ¼²57á@|-oÎjê/ZÔÃ6ÿ±D ˆ©-îËm ž:{¤Ïý¼U+Û¸õ�+@ŒÝ÷t�®¾·Óïf (0w_�/]ÝªÅïÒg€˜ûÕ;uïÓÌüâäÂ›Û9Þ (·åç¯0ÄÁwwêö¿²' øOwà®je�  ânšÛ­kîcØý@Ž{Þ÷ô_¶jþÆ�(ºûÉý„-Á± ÞÓÑcõ¹Ë[ôúrB %¿�fÕÖC À:Ü£ƒO»¬UKÙ-ˆÊ._½–�~°> Ö³¢5«Ï^Þ’û ¼žYÐ«³9A À-[™Õ‰µh	ç ¡ä®ì9ý—­¹ù=À† °Qï¬rC@³^]Êœ  Lî{¦§»oŠ?6� €MZµÚêÓ—´ä¶|îÿo^·:·¼Ø 6«£Ûê´Ÿµèñ—Ó¼Z@Àwöüþ�í~7!A À€¸§…}áª6=ðÛAãåû½Ú9ÛƒB À€¹]Š_ûõjÝ<—mD� ùúoVëŽ¿ñs‰Á! `Ð~<§]—ÿ¾#w×À?îðÜ)—µÒ3‡!q¬,}º´ëèÒ×~Ó¦^ ¾hlÍêÄ‹[ôìkä…Ásk¿ÛÐ2„¯ôççÒšúóÖÜ]€ÂYøvFÿóÓ5¼MÇ�µ8’aàCæÞ}¸w!îÝ€Âìî÷©‹Z´¼™Ÿ9‡évŒ ÃâÞ…|â§-Zôw#€—î{ºG§þ¬5wp0níg yñnsVÿó“fýå_ì ä[_FºäŽ}ó·«yq‘/-î$@æ  /ºÒÒ¯nÓÅ·wä.X †Ï^;å²Íz¨‹—yãÖ~G†9 È¯Ùwå.Xî6Â †îù†>óÃf½°ˆ­¸‘gÆ¸“ ™€üs/XÇüpUî`ðf>Ø¥Ï\Ú¢æv‚4òÏÈv;†e€ðHS›ÕÉ—´ä.d ¦½Ëæ¶Ý¾ôÎe©ýðŒév¬e ¼å^È>÷óV­lãjlŠÛcvä÷›5÷E&ÓÂ[níw$‡I€ðÜ“ó{uä÷Wé¯ÿf×2àƒÜI³WÜÝ©O_Ú¢å-¬ïG!8n °ì€‚hé°:ãŠVýðævusƒä,iÌêµèšû:9_cÜU †I€(°[ëÖ±6kÁRÖ
"Þîü[·Žþá*Í‹É²(4Óíd�óFÁŸ±÷æŠL.üúO�±-?îÌ~wÏŒïÞ@oü‘5æ]3ajó„T¢ïuŸÚ hÇñ	ýâ¬
MÚ2Á«�È»ë=ºè¶vµu2)þéÍ$'�hõ#›zŒW_ø&™�Î:²L_>¦L©$ßD�»]ö¹3VëéL„…ßlûÂ¶º*GwšŒ‘ünâÍ�íN‚:êÍzùÆCÖJ7ÍíÖáß]EñG0X-rk¿» ¬Ñ«~·X37À=Yð§·uäÎ Âì�å}ê[ô“9í¼ŸÖ˜ÜÜ¿\ �µ Ê��téã¬ÒÝOö°4
¡ãŽï»§÷¹=Z/.¦GóŸšŸ F �³¢5«óf®Öñ?æ"ŠpèÍô‡×CÏ_•;½�S1Dkj~nº•uÌ«Æ¨hþ’ŒN¼¸E‡íY¤ó>Y®	c˜¯Šàyø…´.¹£=·±dnÍ/ ôõ9¯¦¼il�¼�Öc/¥õ™CJuö±eª*7~7	Èmâó£9íœ|‰Ðpk¾ûù½+hýôÆ#UúÚ*`€ÊKŒÎ8¼TS?^šû5Phogô«{:ôçç˜­Šð°²ËfŽÞÂýõ{+®�Õ«2ÚÏ×–ÔÑmuå;5û‘.�qx™NûX©ÊŠyùà½Åïftõ½�ºïé^n„�íïþw½¿åŠqg B¥µÃêçèÐ¬‡:s	�rH©JŠün¢è­Y]}o‡îyªGY¦L!¤Œ±ïmÿï¼¿*ÀüË·yØ[ýÒ;;ô±Vå6]òeiSVç_¿Z‡}§Y*Åa¶v­oðtòÔ{(a^ð­U@¹Ýùn�@%“1ÄÉ}¿ýs—î–½(Ö8û7Ì¨yÊýõû³§.´Îä%M�’FùÙ8 ŸÜá€“.Õ´ÿ*ÕÕïuxõ�ù½úí�úû<öìG´X«–îÕµc—ÞiºÜß¯3}º~zãÝF:Î·ÖI8Ò¸XgQ¦ÉcÙG ëÊd¥ÿÙ“;�âµe^D’•þØ0³îø5¿_÷Ü5«Çd ˆæÞ=†Õý8h—”>q@‰ŽÜ›eq·jµÕïžèÖm�wåÆú�(3V^ç÷kÿ†y ˆ“êF'|¤D'X¢I[Ò+îö¼î†Rnáw?3©qÑ›IN|cvõ{« ÖÝA…y ˆ©=¶Mæ‚ÀQû«¼˜�…¢º~ß-úø{wîÎˆ+½Ù0³nÂÚ¶Þ•Žy ˆ3w3¡Ã÷*Ö±û•è€�S~7yXzÿ3=ºï™n¶êEÌÙÎ=uí?I®ÿw˜€øêìy®€;DpÄÞn(Ö^õ):Bau—ÕÃÏ§uïÓÝzr~/]ü€Ë:�éÖ»¤1 XŸ»„ðè}‹uÌ¾ÅÚy›õs3üÕ•–}±'w·ÿØËiõöñ65þïZÿž†y À&�®t4e·"¸k‘>²cJ#KéðÃ¢w2úÛ¿Ózâ•´žzµWiŠ>0àñ×¯\Ì Æ1Ò“’:pç"°K‘v��Ìýò¯­ÓæºôÝ¢ïÎÞ_ÑÊ²=`¨ãÿ®öekî–±ll†»„ìù†¾Ü‡{:¡Û°ÿŽ)í»]JûíP¤íÇ±¼p8'>þ³¡OÏ½Ö«§¤õÂ"nñ�|�ÿ»6x¯²ý´Æ‘Yi™ŒFíÙ ¸ÊKŒöÝ>¥}¶ëÿØyë¤’d‚�ÎØöµÞ÷>æ/és·.0,¶½¥X[6^3ºýƒÿg£�•õÓo3ÒIÃ{b k+NI{NJå&NÞ*©Æ%´ÓÖñ›TØØšÕ‚¥™\‘_¸¬OóÞêc^ €Ýÿ®�^y¬ÌmF–  äQO¯rÖÜ�µ¹;ºnØ~\RÛŒNhË'ô›-oÉjYSV‹ßíËüKû‹½;žÀ{Y%nÛØÿÛøÕå,›ªÏ4.12c¼j€M«(3;ÊÑè*Gãë[“Ð–£�©rTWé¨¦Âñm‚;	oe›ÕŠ–ŒÞY•Í}¼½*£·Wº¿Î°·>à3kíŠ†dÝ8]g6x´åÆû¯3½vz“Ûð5/`ãÜ;å¶ÎŒ^]êžP×»É}
Ü0P3Òüç³£Òb“û(JJEI£â”QQªÿ×îŸ•™Ü!I=}Vé^)ÝksKézrŸm®·¢+mÕÒžUS[6·}îÊ¶¬V®Îªµƒ;x è¬qnÝXñwmrðÑs›, ºw›³¹ X§†oÂfú­©ŸÞøš‘©ßôß  �aíâ…³êês‡ o„³éG0VÖÜâAÓ  €G¬ÌM›*þ R_vÓ]   8¬{ë®Ô�›û{› oÌ®}UÖ¾˜·–  Ïé™…³ª; ¸¬Ìì¼´
  xÊJê¹P Hw§n°Öv»U  À3Öª¥/›œ�· ðÖœªfkœë†Ý2  à!û›7fW·ä- ¸ÒÖ^F/   ÁäÖèÞ¤¹r À`É¬º·�1›�U  
Ï­Ño^W÷NÞ€+ãèîÊÀ!µ  x¥/“±?Ì* ,þmÝkVúý ›  <ãÖæÅ³G/ô, ¸²V—»›öë  @þåjrV—öë Ïª{N²öë  €Œîi¸¾îyÏ@ÿW™K†ôu   ¿Œ3¤š¼™Ó 7nò´Æ§d´ßP¿  �µz¼aVÝ”¡|íÐz Ü¹ †^   üd‡x÷?¬ ×äé��HúØp  žµz´aVÝ¡¢!÷ ¸z3ælk•Îc  €ÁqkoFú¢†aXÀ=*Øsõp  Ž[{_ŸU·@~ WÒÚï[«%Ã}  °ynÍuk¯†iØ`Á¬ºÕÖè¼á>  Ø<·æºµWÃ4¬I€kcB   Ážø—×€u&Êöäëñ  ÀûÜ;Ü‰ž wB ¬®È×ã €µX]1Ü‰ž WBæ"& �_nmukl>3¯€	�  äŸ5æ«ù˜øçÉ$Àµ1! €ü°Ö>Ø0kôÊ³¼ö ¬Ñ›Iža­Z¼xl  âÂZµôeS_ðâ±=	 oÌ®~ÃÊLóâ± ˆk¦º554ÀµhVí]Y™+½z|  ¢,+seÃõµôêñ= ®â¶w‡Àg¼|  "ÇêÙE‰šs½|
OÀ¼;Mº7“<ÉÊvzù<  DiÜ¿7›ü”®3½¡ .wìÂXçË^?  Q`�¾èÕ¸A€ká¬ÚÙ’½¡Ï @xÙÍ¬»­ÏT� àêHÔ}ÉJ¯êù  k5Ï­•…z¾‚€·¯3�ræ  ð¹¹rÖ91W+£ \¿­y…ù   ¬Ë­�××ÌS4 ¬™Àþ   ôskbÿ\¹Â*x p-_óMku�Ï @P¸µÐ­‰~<·'‡Ä„©¶$é4ÝoŒõ«  øÅZÍíËÖýÆlÓíÇóûÒàrÿÁ	éxkí¿ýj  ~pkŸ[ý*þ¾ö ¬1~ZãØéY�õ»-  xÍÊ.ê±æ %³êÞ–�|ëXÃ}²&q¸¬]éw[  ð”[ëúŠ÷»ø" ¸Íõï>ãe­õ­+  /¹5Î­u7T-R " ¸^ŸYûŒdN²îŠ  ¢¥Ï­qýµ. \³êî‘5_õ»  ä“ÍšÓs5.@ \³jÿÏZýÈïv  �nMk¸¾öfŒï« 6fÒ´Æ3�ôc‚ÛF  6ÆZY{FÃÌÑ³@�.®“¦7žldg™b¿Û À@YÙI§5Ì}§*ÐÀ5iZã!Fúƒ1ªò»-  lŽ•Z•Õq××=® | pm;uÕ®ŽÓ÷ˆ1f´ßm `c¬µ�J$qO¿UÀnà†,ž=êekôQ+Ûàw[  ØØÊí†âš€5&�¶z´SÔ}¯¤}ýn  kX«çdKŽj¸~d£B"TÀ5æ4[>2Õt¯1:Äï¶  `­} 3Y÷É·¯3�az5B1°¶å7™•×)«Ûün  Þ¬ì�«ëŽ[ñeÀû¬™tzãwŒ1?2F	¿[ ˆk•1Ò�Îªý©d¬B(Ä _ýé�ËÑ�FÚÚï¶  ¢ÏZ-ÉÊ~fñ¬ÑO(ÄB \ã¦·Ž*±=7cŽô»- €è²Ö>”î.:ù­9UÍ
¹H€~	  <Ók¥o7Ì¬½"¬]þ ý  ä»Ëß::aÑŒºFé•�\ p1$  È¡.ÿX€~	  †¬7j]þ1
 ý  †�h—ì@Î›¬ßvå92Ùï™2¿› +Û)«‹×]¦ÇLŸ".à?&�¾r¼1ÙË�Ñ§ün  8¬ÕÖ:ç,º¾f‰b"V`�I§7jŒ½Êíäw[  þ±Vó¬5_Yt}íÜ¸}b r €Ø²Vm’~Ø°¸öê8t÷oH|À0,  ñëîïËÚ¯½1{ô»Š±Ø€5 €h‹swÿ† Öv¢MÔ�l:Y²ß6ÆìºÁW *ÖÚ—e�ËÚknÕ�&ãw{‚‚ °“Oo<Æ:ö|#óÑÂ~K  ù`­æJÎ¥³jâ]`3êÏXùac3çZ™ã�älîï üc¥¬±ö�Öè'3G¿À÷bã 4iúŠzcõcÌ©’Rý: @AôÊÚ[²F-š9º�×|ó ƒ4~ZãØbÙ¯Jæ‹Æ¨b°_ Èïr>kôë´Õ•KfÕ½Ík;p€!ª?ee…J2_–ô5#3f¨� <+»\V¿ROâê†[jÜ5ý$@lsFËÄ"›>EÖœ"£òñ˜ €°Z é–´“ºùÍU¯óú Ï&ŸÞ´Ÿu²§Êê$cL]¾ bæ+Ýf�n‰úé|…F ðÊ›œ4iÕaÆfO5²ÇË˜rÏž "6®odÿ�‘sËâ­kæêB“õ»MQD (€	SmIÂiÚß1æPk³‡cö•”,Äs@ôYkŸ5Æ™›ÍjnÆÖüã�Ù¦ÛïFEÀu_Z1¢¢[æ�ô1I»³Ç €8­Õ—ô¢¬æf;wu‘þÚxÍèv¿Û7€ 7½uT‰í9Ìäzt¨1šìw›  Ïæ[kçfgnÚ¦[:³r¯°¿ TæÊ�•Íîoev16»�dê	 ÂÂZ-”lƒ5ÎkN6û¢ÎSgÔÎ÷»]X ,N´‰	å-ã'SŸ�­·R½»èÀÍ’ÝÖSâwÄƒµ¶[2‹%¹;î5Èš“0i%Þl­|‹wÂ� §7o“Tï6Y9£$U:Ùl¥Œ©´R•û{ÉV™Ü¯­Q¥¬­2ÆŒö»Ý üe­]!cZŒU«¤V+Û"™Ü¯�Ô"k[³ŽÓj²j1N¶¹O©7_ŸYý&ß7…Þÿ÷��Æ5    IEND®B`‚ic10 ™ê‰PNG

   IHDR         +ƒ   IDATxœìýit]Yvxþ÷9÷Þ÷0 'p&ƒC�Œ™1Gd2rNeÊl1mK)¥;e»[Ëöêþ\V}î/íÕµ–³–Õ¥Õ²×ªŒê¶«$UÉ–ìŒÐœ’()ST1OœgLï½{ÏîµÏ½xàA20ãÿËD ¸ €‡ûîÞgï}DtTp‚S�£‡ ã§!S—!íÍ?’ÎµT€](FÞ©Ð¾É‰pêÐá'$Üé�vìëï÷öwú6{)6uÐÙç7:- ®¡‚�F€fN5SH
	…K|�€Š†:MEµQ~™™(2 )ÄÞ�D v»	 GÄ¹ê{ã#€ˆˆhÍ�ø_Õ`×)S ¦Ú ‡J@Gv»µ×ÚQ‘–é@`Ï§-{?
m;‘vðÒÕ°×.‡ä­üuHq.	é¹Üçç¤÷ê»¯ý›ýöùwäøqu/�z5™èísÅˆi»o!ìhv¦­=Ã‡µúÊ)(AqÂ.h„5Dwt ¢®¿‰®çŽúM¹‡'”cêwö¾•6}ê%M§0�zIR‡NêàÓŠy³Q¸N¿w2ì‚‹`¸ÐbXDÖAµ�T/öZ4qŠÄ^kÐÎy	1Ø÷PM!â%¾ÖÄ’
M4U/‚êëØç#ƒ"c€ˆˆh�' ,ÐW´È(TÑÑ"@:ÉÁ’¹Št Z ¾F¡N;¢–0Pû¼<8éˆj¡åç@è@eJE¯x$WŠ+
¹àTÎÅ´Âw
òÐIÛY³èÒéäÒÓé—V§í7v^AçnRJ*³×m7}¿LU˜  Š´ü[¸i•ÿU£gø¤žü·Gò;MŒüÚ…Áõ—;£…×õn�nDÖ	dDE‡%èœ¬Ó C[�·€<®äg
M[¹'ª�Š¨¨³×v»~¿V·QÝEuœ›s\ùù]ÇÎ²üå­Uª
("AâkµÿÚåEõþ ¢öŸx+g¯å¦ã´ú|t½_ËƒU@ÛP×¶
E˜Ð+^är¹äWrÈE�âªJvÑåí+A.^ë½~ùüÿ¸iüŽ¾•ãêŽœ†·êLàUôOkÿØ‘«â7½Ð?U¢åŽ ­Í@?¾	àÅËÛ'NÜQ–ùÐ1Í¦‡/÷hÑnÚj¾I&¡“!)²\Cæ|Òm t6Bu=P¬W‘§Xœ_ç4l°Û¢:*Ù@ê²&ÄU÷%ØSqõ¶ñtöñyºëyË>VñÈ[|¼ëíêøòÈî�Ñš×Êµ„2*(ow¬ºo—·ª÷ßòøîcíµ¯oÎ,=XãAÑš :“­ ¸ *—‚¨U\pp¸ È/9—^€ä×C!‰mäE[�o#KZÅD§ƒÞF«yyxêÔKÒ¾³vÎêºïÅ-YÑýƒà…­L ÐQ•…½xë>þ¡ÖµprìHñaåf{Ž]JûÒ*SÛ‚bL�Ž8øÑ µ€~= ëà0ñÔzí‹º?¾¨H
ÕLDRq)àRˆKª?CÊÃLp~Sð?û}t½«ûcÝmUBàVÇÜòs‰ˆˆhmªƒ÷®·»Þ_¾ûæ÷Ï¼-·)º“ uÂÀ2 .^ïhè”]¡ceÀxµö�¶UØ¬’ÃÙ‚ÐFÀ5 WTpÞ#&ÎKá.IçÄ%ïùÞÎ›§>¬Z ª¸Úø‘ËÎìÓžaÜj~€É$Zõ˜  Õ»ÂoŽßí
ÿ÷²öæÍÍÎµ¢·‰ÐIÚD{‹Ü­wÐÍÎ»Ð|«(Æ‚`DTF!t½Kû¼K{Ë¿ª`õoVñfËúVgípÕëò}ÁÊîÊ>9{®±*ýX¢_=›Ú­ú[±:ÿ[�*¸á{íþXýs¸éˆ›žá‰ˆˆhmë^!˜yÏìÊømbb¹ùcÚ½š2ªcb'cýïÄë+pqâÊ7­Z@f^Ûå�-–”_4t¦:ã6ƒà¼(.X" —‚ê98÷>àÞ,\ûŒ/ÜE—ÈT;ïL‰LûéÓSC}×¦N~ãñÎ]Uœxñ†oš´z0 Uâã¯ðïý¹ƒ¡!;D°Í…°¶)d§@6*°½PéhÐž8m?ÓC*.\bsøªçµrE_oXÙ�Eø10SŠß½Ì› ý£0¨'""¢Eqû„À‡|ÆoÙ"GµÐa¯,ÊŸÛ'PVT=ñrÉRòX ªV1PîB 2­ö¶È¤†b"çá¬@ÞFÀûÐðŽøðÞ ×·O~cëämï#+ha€Vªê¡¾ug™ÙÛ­ðCÃ¿Ñyì!ló�íº]€�’4]Ú_þ‹!ŠrîÌÊ~àÛäÛ¢În—«ù]�sñÉ¬ZÝ/Wî«F:â#""¢µf¦_Ñ–7f;ãûâ«ø¾²JRÊª_Ôo:ÀeeKeP�+Ð¢sIÅ½í4¼TÞqÎ½§poíóZ}–MÞs…Àœ%¶ÐÊÄ ­@V¢9
¸z•?NéŸ—~ô hˆj¯=â’ÌZúãM|ºªKøË©}3øeÀ"ÿîò¶zZÎôU×u7/âÔÉ�òºÉ*ð«¡îæª�ºuÀ>¡ª@(ZL)0	¸–ÀMªõÎ©àÌ½V”×œÕü »,gpn ­(L Ð
Põ³ßÁjÿÇ[á—r(MµÂWûCa½ú…­�ëúõ¸ÛzE¿^åŸ�rCDDDDó=XMI.G'•õ³["ÅÝ‘¡^^$‘Øšió\£|½PõL¦Ù�ˆLÐ²Æ€…–7;©~ÎzúÏŸzÕ‡q(^zÉ†ç-Ä
¿­îÏê+o—eiUeÁ­Võø-IÅÀlµÀÌl�òº®ž#ð1*\xGpû
�cÇÔ¿
xàUl8t8Ä]¾‰p§­©DK�	 Zfª,ªMa�Xo}ÝûEm`ìô Àt ^±â7Å~ÅV¯ºãã¬ð—üõj¿ý‹ò‰ˆˆˆ–·ª3VÌÌ˜—
qís�\Î§Ðë’ö^ï\íw¥õ¡;
Ìì&À„ -L Ð²êë·	þG†álŸÖ¡Ö¾pò’ß´'ëqu»ß¼ü€“ÎÃpþ°½O%ì„$ýPµþL4ôÍÏ
?"""¢[%ðq*&áª
Í'òNP}] ßê¿óÆÎáWož?¥räëHf®e/#à”óh¹`€–_ÿ¿8Û_\rƒ�fÖçóÎHÑÀV< !<¤ÀìIšÃ©erË)ý¶EWø‰ˆˆˆècTX¢À×òéK(Þ‘¿U‘ïàUßÂû¹„ËYgj¼‘dW¿û›c·¿üå¼ ZzL Ð’Nñ¯ûú7œ{9¼òÊ§lµŽ=ÿìôFWøƒ.×‚øƒ@8 È&ˆ€ †œÏ[å/'Âp…Ÿˆˆˆˆ B h!í�+‡êu@Ïªâ‡^ôU…|¯hßã7ÇÎÝø/=ú­äüÆÜÌ¼ î"@K„	 Z$UÆ³|ØÝzµÿ¸ºç®%E� è„.Åþ 8(ªä~IšÛ\Ö_–hå“åŠ¿…õñÏÌ…e?Íc…@¼Èxˆ÷bÕI/ìuh�#äSïp*@¾ç´ø¾Âý@½¿ N®çÞ]gãÐÕÛoU}×ÈDó(áO“k’¿õöO]~UNá›^úÊMSüw½{z»Hó!Ú�ÀùCpº]ëè‡¸Ahè‹ƒüòéj¥¿LÖZjVTÝlö¶ú‚ÞGDDDDw,Ž�–™Z}¹¡B Î†Š†6+ÀŠâäè-V�*ª‡Ô¹q(Î‹†÷¤SœòEö7»Þ=ýÝ·€·o½‹À«¾gø°ÆYßTî @Ž ´@Ô¦è×AøMÙÌmÿú�žljx@:“ƒ™Ê@Ç%[Â}*ò hx‚Ã>hŠKã0›Þ¯Å´ª"ˆMìw¸˜£�'jë#"""¢…,;`¯C}M*‚D|SìºÕÚRµè è\Ÿ†âU÷7¢ú·pîu„ü}½®­p­ð›¯½ý2}·×ÐD 4ÿŽ«›™æÿÎ�ÜkOíët—=:®YëýJÐ‡ú€ƒìQÈ6q2È BŸöØI´ÜºÏ¦öq°´ˆ'Þ®íùø8&"""¢Å�Pÿ7.Ey‰sl^€´<A\¼êLÁ¹k€^× W}Oƒ¾!ßÓNø›×ßÛò]¼w¼*W·÷Ûÿg:´ãÇºv¸]ë Ñ½a€æƒÕBáÃ²•~ùü@§ÓÖf¶É·K:-VÅƒìrÍa±+VN¥ù”ûe_üº""êêS,Wû‰ˆˆˆh9UÄ¹*!n&P^°z±yIOY Åôe;ò-�þm÷7ä;¢ú¶†öù4Í.ÿà×7\ÿˆŠ€øŽÅÿi5a€æy¢?pê¥Ú7nã×wO8¯Ï�;ÅnˆÕ~ ¬“¤éâjÜµ ,cj=þ°ªªîG)Ëü‰ˆˆˆh™WÄkW·`mV¯s;6Ë*Ø.êÜuá²ª¾åÅÿEÈ;Ú·aóŸ÷ÿ!s¶<tì{¶Õw yÃ ÝƒjZi<ÁÝº7iÇÏ^n4¦‡Õ÷l„¶÷ªâ	AxF�Ç’æˆÕFA;Så‰j£üËò&…Àúû¹ÒODDDD+{^€m÷'ˆ×¹bû
Š$")$í�ïÉ§/œTèŸ‰Kÿ¯;ø³Ó“rå�ÿ°îòm¾ôìÐkÎ	 »Ä Ý%{ÉÞã¦.7%N-ý†tº�Øø+g6õ
žöž¸GT°]\²NB¾N|£W|Z®ðÛV~±¯?NôŸÝÄ¯|ƒ�M""""Z-óª�ª-àÛJ0¶¿Ú¬€Ö¤:ECqETÞQ)þ¦ðþO'CñísÿnóÙî¯xäëšÚ®Z=ÃÓzòò/³Š¶Ðc�Ewà#ö'=ú­dïžÃEž»T¶ª¸ý‚ð44<í\v¿Ë† í@;ã³½ýe??§øÑšÜEÀæÌÌ
H IÚWBçïà’?SÁ·¥?}ß'ùå×ÆÇ.á%)îúZ�¨KÒ}ƒèÖ+þp6Ñß²�§Ži�¯Ì=ñlÛ{hW®xÆ¥ò$$<äà7‰¸aU]'.B«\é�ù&ñb[ø¡+JDDDD´êY@ÜãÊ‚tp]]Û®Wmˆ°¹X.ä{ ŒªÊ³ªá¬$òÝîÛÛ{Îýé»Àës¾ä7ÕzéU«rmç€—¬´–I º=_„»Í"îüÚ›ÍžFßpgÚ�hŠ�¢î\þŒ(žpIÏvçû ¡…Ð¹n•ýyì{ÒXÓïÙÛODDDDtÓ¬€Âò q–HâÒˆo t&ò©wTð@ò§ŠðwÒÁÛi³¸4Õš¸üöoìž¾ýµ<w ›1@7;®îÈé“8‚2“8»âoÁ‚þÃù³êüc9è\²^5Œ Å $=^$�†í²×ßJœìDT.öó1GDDDD4«LØÂ›µÈÆÝ2X%­­¥igª€óWr9„âTÿNBñWÉŸäuNà˜úC°Š€i=9v¤À	)mUŒQW¦ðE{ÑWýüòù�NÒvy:
Á^…<$�g$„G}chÄ†ú…|¡3n=Må@@Nó'""""úø»(R—ö‹K›Ð¼ƒ¢uõ’:÷×
ýS�~Š×B§s±9�\:õ?n¿áë	Ž¿(8qó5>­ML ÐLŸÿ!+ÑÇ«8õÒíúÇ²åçßmºäïñŒª{HœîUøQˆ-\ÒÛ™lÅß¶ôƒå)+®ö³¿ŸˆˆˆˆèÞÕ5µx±Ù q¶–*B>	.ô¢}M4|·È;’‡ð×ïü‡�3Û:®N½ŠS8\à%K(0	°Ö1°¦ÕÁsKƒŽ}/Û×³yC‘è€$�9ÏzØ7‡šqPIÞ‚S…ÂÚ´Zñ·}M0;à�ˆˆˆˆˆ>æ%;‚Ú¾Ù±"Àæªßã%iÄÓW¦¡új€ü‰@ÿRÅ�ò¹œþÑÛ£gñŠäs¿Øqw«Š_Z;˜ X«Ž«;
¸÷/ýÈ¿6²¯ÓÝ´í«§h¤É <#‚ýY/"ÃiÚ‰FcQRQ®øÇóWü‰ˆˆˆˆ¥" Ž	Hçaó4·ø?L«È%Å%ù¡¨þQ‘ãwÞüÿlüa÷õÿÞoÿ(ÝúÔ¾âk1à|€5‰	€5åö}þ;¿öæ:/}~�:yB$|AT÷�ÁfœKWü[¹ŠÛ½TÊ•~Ç2""""¢Å'ë€ˆŠª“¤‘ˆoÆð.o]m‰È·äwÔ…?÷­ümÉ’?øõ×ï46 Õ‹	€µäØ7ý!ó=Ã'õä7ïÌô;Û?Õ//xq/(ôIq~; BŸm?b“HfWüã`’ê‘Ã""""¢Å7÷š<ÎpIìÆÕbÚvàžPÅY *&*/O��þñ{/ÉTýŽ|ý/Ó©ËGä^*ðÒWfvý¢Õ�	€Uï6™½¯kº»8;"E¶ÑùâAU÷i‡pTÒž½’ô@m¸Hgª£q?RåŠ?Ñ2®qœK{S$½Ðö5„¼ý=8ÿŠX„üûâôÌ›~Ó%|C:sc†«V³d©ï - U9úÂËþüÆÝ)»ýf¦ûïiŸß%>=ê\þ)yÀ›¡:?XLÅˆ¤O(uÞ€+þDDDDDË‹]£«“Øž«jƒ4�|Êv°�îSÈ¨ x>±a�ßº¯¸úòëÀk3_âÒC 6œ{9¼ò²ÖZ°¤ß-V ¬Úéþ�{l;öNO_oº)x¿�'Uð€|c¨! t®Û€¿Ž�•¸% {ü‰ˆˆˆˆV–rd·-ëÅ�ºÄ%.ˆy‚¢uuÀ+|ªáŠâ�‰ÉÎÙ÷^Ú1ÓW‡¶
ÈDÀjÃÀ*ü�œ>é/´FýÛÿó®ÖLöî¸º}ožyÎ}‚g n7 ÄgC6ETÕª…Ú€ÖO¤q‡®ø­Ô±@Ä.-whÑ¾
ÈyhxŠ?E¿ó£Ý›ÿrfñPUvþâ[�õ�‹ÅÉ±#« «xÅßú•+#¾³1íè^À?	_vâ’¬ß¦úÛ	À¦úwÔöµ;3ÑªI(4œ•ö§â3g;hû:‚†ïBÝï ÅŸt‚¼Ö—L�;õïv\ºéË°"`Õ``ÅSÁ1¸C€ßpá•’×yðg¯OõæŸQŸÈ£‚d›JØäÄg6)TCÕÜF†ˆUý³ÇŸˆˆˆˆhõ±€XC€IPÇA‹¶¨;«è¼u-^îi5þëßþ‡u—ëÏ<z\“ó§`3Å
¼d­lXÉ˜ X±êI�sÿ w~íÍfðý#$›ÅÃù,4?*éÀ6ñB>�–	àí4`;‡,Ñ7ADDDDD‹EUUÊù §ðiÃ%}eepgâ]¨û~_á¿ÓN:g²Æ†K¯ýiÝIB+wX±«þ/¹#ÃÇÜI›ÍÑµ…‡—ž}	äÕÖQ…;$’l‘a›bØb½þ™Ä?XÿDDDDDk„íîÛÞÛ ƒÄØ °øÞæýa‹Šû‚†ü1Hx5-ô•0qæe ß›ùü¯kz'qòò/)«V ®ü®4±ÿfn¯ÿ¦¯žîLeSün/úŒ:|JÏ'�‘,úh_·I ±5@ âØçODDDD´Öi
)ìMÉmÓ ä­Ë-�þ‘|«áÏ¼Ã›×:zöìoŽM|TlBË +Éqµ^ÿdf{ýmk¿žžä‰àÜ—Å¹'ì°Þ%�~¸¶½_×tÿê7Î’"""""ÒÙA¼ˆË [+´ù Eë:T. ú¶†ðç.„ß™šÊÿ¢Þ20Î@œ�3	°r0°B§üïüš6é™±"—‡œK�*ôË.I÷Ç‰žù4TÛ¶ïg®jÓýÅAÀU"""""ºMÈ�w) HD2/I´˜BÈ;?Èï„—“4ùîôôº3oÿ†LÏ|.w	X1.{*8
ÿô©wÝïõþÂü?‘%.ùŠ8¿'m«ýeÏC5�gðODDDDDJàbì šÆXÂöŒ±`±FŒ9TÿUhµÿq’^8Üý©1V9
û.0/sü­¼)ÿ›3éÛùœý‚8ÿ¤Ï†òI[ùoÅ±~°?\N÷'""""¢{	ET!V`»Hßhº¤Eë*T‹o+ä?» ¿ßÖ‰½ý»ÏÜICË ËvÕÿeäÀ€œ¼ü†à¥¯ÄÔÛî_¹¾IŠ‰Ÿòâ>'� ²E’f�XëŽæÐÐ)÷÷û£cŸ?ÝsLRÅV�8‘vC‹é)¨~ Õ¿)4üžú¾ÿôæ¿8?åØ7³#Ã{ôä®+^y¡``ùa`¹¹Å$ÍÇ¾×ß;¸y{ô"òÓ@xÞ¥½ýÐò\Cn½:¾,Õ!"""""šOZ¨j.I,ì�ÉqÀý‘ªþÇÜÉN^;óîù—ÿ¨Ø†– Ë|Ê?Žkrß[gž‡—¯ ò)ï²-ªÅ øÌþ¡¡ˆÛw@bnŽ¿O"""""ZˆÝÔ¶gëŽ	´hAÄ_+Bû@¿…B¿ùú®Í„*Žá.ËÆe<å_üåMNòÃþó
=æ³�-ô‡ödGa‹þñPûäï‘ˆˆˆˆˆ:n±¾þÂþ+pê²ÞÔªŠöõòR�â¿Í_Õ¢uöíßØÍ]–!î°L¦ü}ë­ìÆ)ÿ)òŸsAÿïpþ˜“dÌ²l:ÖJSN÷gðODDDDD‹&.<úr§1M-6±Åb•³üßÒàÖ‡ÆÝŸuô-dÜ%`yàÊñ’¹ÕtÌãnß/üÊXHzöCðiQýüÌ”ÿÎ4´¦U5©úýù»#""""¢%¢¦qqY�Kûfw	Pý=¸ì¿&šÿð¿¾þôÜ˜‡»,%‘K¸êäÀI99vDë>™=?ÿþ—ø Èg î�ˆl–¤Ñc.â”öúÑ²š .µá€°(_óé)…žÂ)÷_ZN^z÷×7|ÿú¿M�àNþàˆâp—€%ÀÀbÿ¼�ëœ^³çë¯…N¶+EÏQuøáßèO5´¡Ež«AlÒ†[6ˆˆˆˆˆhyQ
ÍÅyÛ.0ß@Ñ¾–þ� úÍNÀ·Ò\>xíß¯¿v‹]bÞ`ÉîûÃ€r1?.6åÿØ1�Ù®ïÈ×µížç<ÿ
‚_ñGœ÷i9Ý?þ-$eðÏß-CcÕ±zÙ¹4�ó�«è¯%þµ&Å³‡þ…ö×Ÿb1‘ÅF#-í�_[øÃ^¢)ÿ}UûÆ“÷¶8×ó_ ð÷“ÆºQ-¦ò©¶*lÊ¿ –,`¿?­”]DED%ifÖP´ÆÏþ?Åï©ßo…Ógslbn%€UtÏ
 …À
€Åpî‹—�Î¼P•©ìüç²¯ú¯Å¥?á\:ªùTÌ–ÈD,{ÆàŸˆˆˆˆˆVÚ.1–É 9´hÃùt“8ÿ“ªá_CÝ/ô&þ1‹‰ÊÏQ‰±Ò1Æ¦‹� ‹¼ò¿ókg7;çð‚/BlÊö Kz¡ù¸jè´°’kàï†ˆˆˆˆˆVt5 €\\Ö”¤…íl¦�ï(ô÷4„ÿ‚|ïíßØtfæSX	°àX°�ŽÁ=}íÝF}sÛ±+#©w?•¨þK p@œ‡S±* ŠL ÿDDDDD´*ª,Æ�†ó8ŸÀAîwŠ¯$*ÿÒb#‹‘êÏˆ±+W™eå_eß¯^ÜRLË'¼¿Õ¤Ñ×@ÑB¶¿§üÑ*ß%@¼çø´5Ñ‚ÈËEáþgßÔ?üÑ¿ý`f ++ æ�
Ž½äv¾õVV¿gïÏ]ÜŠ\ÿ‘øðÏ }Z’´+blÒ§üÑZØ% šÌÄAYld1R®ÿ(ÆL•K{ÉÍÌP£yÃè¼ŠPÊ•ÿ£Ç¿•¼ùúýÛŸ|Áyù*DŸv>óZ´…¨h°£9åŸˆˆˆˆˆÖ U(
g¡">ó¡hPù³PèoæEþŸwß÷ýw_9ñ©8P[°æî óˆ óºò·÷‹ÿgZ¿çÝ·÷îN2÷+Îë?‡s�8ñÖc¼Ä	ÿþ‰ˆˆˆˆh�íPÇB
ÄÉb%¯ÿÜb'‹¡ê£clg°`¾°àcë~0–=+;¿öf³™§;CÖøquø%ç‡ã‘ùt"ÕØ^­E±Zm>€$Í¸ˆŠÖ«ðÿvíÖoO'�·ßþ�ÝÓsc®øª\R¥{Â ôã:9zôeôhœÞ%²îPž¦¿ªÐ
ç÷ÅÇhYîŸ”?ó˜ù""""""Z£bLd½ IŒ•b9€ßg1”ÅRSÕGÆXË*Ž³àãb zÏf²P3¨M_=Ý×“¦$N~\¡?ë“ž=ª94oµ%öú3ø'"""""êŠ«,ž
ª($id"	Š|ê�ü‡<èoOu:ß;û›c3Ñ«Þ‡Ñ�cÀ½²”½Ì< Uz“ð˜GþÏîœKvjèÀý	`%-\ù'"""""ºE%€ÅL;Yå\ºÓb*‹­,ÆšY|ýïÔYõ5¾É8ö^±à®ÝœqÚñ³o»FÏC‰s?ÅÏùÆÐ&-¦Š©iQÍ Ž‰"""""¢µBP‘¶óÍ¦ø­«g!îßçšÿoIëÊß¼öï÷_»96c%ÀÝ``zWTp>f�*;¿¦ëR—MDÿ…sÉ?tIºI‹I›øgÅÂ~"""""¢�$"1†ÒšOÂb+çü?LBøçšö=³ókÚœ9ö˜z‹ÍøS½;¬ ¸SÇ�;œxqÎ”;~î­±,éy>û{�â§’lh(“6½rJ€> ‰ˆˆˆˆˆîJ(T¥í’F�ó}È[W.©¸ojÈÿwtŠ“oüæ–ss6°¶lKÐGbÀ9îpêpr,îAYÚùµ³›}Öü¼þS—d_r¾9r[ù/,EÐàÏ–ˆˆˆˆˆè^ˆÍh”• pI6"Îý´ˆþs$òÙ�ÿâúæ9• ¿z2™»=;ÝHÉHÎöñ‹·Ó¬Ýsn{pxÞ%é—EÃ�»æp�¶Ç5Ó­¸ò/Þq{J"""""¢{%¶¸jû¶%i4$é“¢uuâ~G‹Îoç““ðvØõ.^’b6n‹ŸÇJ€aûÒÓm©àëH0
œ{ðazàÒ~¾(A~R\zHÄõhgª¹ È ñ‘ÊŸ)Ñ=³îk¨f
ÑŽÍèéUÅg4t6úFÚ·?»ò»?ÞŒ‡‡à4<¾¡9“ ·Ç
€Û‰}$ñG£ùCÿBû'§ÎÝ—8|’|Y‚~Â5EóÉ ¡ÕFøÇ•"""""¢ù®PHËùFCÒ>WL_±½Úùm¯�ÿ6]l}ûíß�é*�c%À‡à€[R9ò«HbÉúý�¿Ùlµ.<žªþ, ?+’qi¯„|
ª…ÃÌ´®üÍw%€@ª¹�	¸´7u>}*_Ë!ÿ I/Æño•ÕíÇ!GŽp&Àí0p“2côãcˆeÿG¾þ—©×ïÕÏÃ†ý¹ÆÃÎ%}ZE(¦Ûy(Wþ¹ÝÑü‰1WÈCÈ§[ÐNá\6$Î?é\ãÇC>¿ó�ûŽ|]S‹á~üäoÝ0€jL Ì¡‚£ð8wÂJS?1µc·×ôÓªá‹â³ýâ{l›¿¸òï 	Wþ‰ˆˆˆˆˆ§À	Rg;°¹¤W$éyØ‰þ´÷îó×[î;zT‹å,¦‹±“ s00£Ê½€'Iž�ðW}ïoÉ]ø´&=_p.½_Äe¡hyÁÚPWþ‰ˆˆˆˆˆµ Ð"o·Bh"¾×¹ô!ï_
>ýîŽ¶ 'Ê˜Îb»îX�˜ (©Ä~Ë�*ûþwüì•a�Z�üŒó�ç$iö„|J¡Kš¤ûÙ±çŸˆˆˆˆˆh‘+œˆ¤°J€Î$$íiHÒ|:@F¼{fÛ¯\™9üØK®œíÆ$€á6€Ý„jÉûþ½ÑŽ›þ\óË}B\:hÓþòÀiÿDDDDDDKGb7 B‚æmï’T’ÞAñÉãy/ÓíýÿøûøÃr!~\Ýlì'kz—- qåÿ¥™•ÿmÿú�žŽsO@ôœO¾ä}6:ã°>“råŸÓþ‰ˆˆˆˆˆ–K%@œ	Ð‡÷�ç_„Ê/äéÈ›¾zºÏŽ<jqïL%ÀÚ¶Ö+ $þ/}%®ü�þòù�t¼x
Iò“¢8*IÏˆæªE»%Ð¬œö¿¦FDDDDDDË¨ÀÅÝE[|£!Ißç¦?©ÞŸééh±é«úÇ¯œ�‰xø1õXãÖn€Zß¿Ê‘áúg n0è#.—_r’þ”K#!Ÿ€jn{NföÈbðODDDDD´+ ™ÅnÃY,çœÿ)ïäçW×G:ôª�í ®Qk·àÅ=NœÈOaïØÐõçŽ¨KR>ãÒÞMZL©Ó-aÏ?Ñ2f­ý3• -IšMŸönÖ¼óiÕâí½¿|®“]ßðê©ÒŽ‡þ¦UÄ*ðµfmV ?îv¾õ‹3É�°yý~Éð5'ò�œO7j>	„ÂºýÙóODDDDD´2*,†Ër±˜Îy)¾Š€_šn\Ú_¹÷I,&Ä´öJ¬ï£šö�£ßJl{à¾¼¡ÿÀ‰|ÝeC;µ˜FÈ§¦hÀ*IˆˆˆˆˆˆhåÐ`ƒÛÊ™ >ChO¾~½púÿ{ëúú×fâÁîØp�X[YUùâæÙ¶‡ûöÚÒâEõàü6-Z€–9ªVþ‰ˆˆˆˆˆhE±XN$�*4äPçvAŠ¯9àçwLm«ÛÙ‹tÎ¶ðkÀùfUpn&»£*{~õòv´Û?íÅýSIš‡� ›öXð¿Æ#DDDDDD«�" ÚAÒhØL÷¢3õ]¨ü¿\&¿ó£;ú ºÖ*ÖJ +ÛðnV'<üÊ;c>_çQ�ßWN÷�¿û¢kågBDDDDD´z•»IŒõTíÆü‚tÂ?Üùµs›ÊƒTöÆ*ñµ®þ
 Ûæá„„úæÎ¯�ÝÜðø\€ü_ÅeOÂ*ý‹ŽÕþ—å,ý'"""""ZTƒÅ|ª(œOÒ: ¸ÛÉÃ{û76�¹]ì¸­ò,‡ÊÞK?šéëØö+:’&î§Ü/ rXœ/S ’˜bðODDDDD´zXí?à$VœoxQ¿èÅýäÎ¯]^7;®þ™ «7`Ùˆ¾öoö[_¿îùêé�Y¸xª?Èsâ|ŸæÓ9,¤k ‚ˆˆˆˆˆh­RÕ¼ÐÐ.ÄeƒNüs"áïy×yfÛ¯¼3RÆŽcÇÕ¼Eà*ýÆTŽœ†¯³7;ÿååu>K¿ä~Àâ“ˆ·ã48ý#"""""ZÅc¿ "â!>ë‘#@øÇMm|êÀ/Ÿ˜�%ÿÞL,¹Ú¬Â@ù‹ê³I¢›¾zº/›˜|P¡_ç�ŠOF¡y_f¬Êß-EÕ6ï–°J Í·Q\ú)…þXZZìh1dÿØõrw€U˜Xe	 •£Gáq‚—_ÆC_=Ý×Ÿeiá¾è’4‡ÅePµ)�…­üËÌ�ˆˆˆˆˆˆV1±ØÏ!NCIÎùt‹¨|Bá¿d±£Å�xÙZÊQÆ–«,	°Ê ÀøøI±É�¯¼ò©|"�ä/HÒói‘dLµ¶ú¯ÕdGÿDDDDDDk‡Å€¡Ü ä!nçÒ�.éù,D_È¥1j±¤Å”1¶\eVO@«ÌÌ‘#åíoª7yŠÏJÒó�$�„NÐÐq÷‚dðODDDDD´öˆm˜h(DC;HÒl¸´çAhølá;q\“9±ek®«'ðâË¶§Ÿžü†tpT“Ý¿wá1 |^Ä?à\Òk�E[üËÑÚ#€x�@Èsh®3Š¸
ÁçwpõQKÄØÒvxiõÄÍ«å‘½—¶ÚXÿhÇ¾+Û%×¯@õgDÜúÐ‡†Žuü'1Ùcó‰ˆˆˆˆˆh�Ò²@$Ñ�KèL@Ä¯‡àï»<?¶ã�³;ê#½j³ V‡•Ÿ ¨Ê1^ûîkÛ€†½¿tmCZ´?!Àg]Ö·SÄ»�Oµ:¶+€U	,õ=&"""""¢¥&Š·XÑbFqÎ¹´wP|6…<¿÷—>Ø`ñã©ÿÞµãñÇ�¯øøy…*G~Õúù-¶}ðgßYç\ë"áïô¾:Øû¥2î'"""""¢[u ^åwp‚ûá§½k~îá¯]ZÛEÎbÏÓ/®ø]Vp û/zèØ÷²V–îÕ Ÿ—=#Î÷…|ºc“­éŸ+ÿDDDDDDt³X	`Û†C:ß'>{Z5ÿü´Ï÷Z¬gÌX¹I€zÇUl_F{ëÈé“þjcÐ¹k}»ƒó?È?õYßAKÒØ/O$pâ?}U•Ü%ÍÔ¶	�É¿S‡ÿÉu:¿'ÞÜ:²¯xÅö<ÁK¶—`wR`e(·7X‰^†Ã+’Ÿ‚õýC&Ÿ‡o|ÛâD›úÏaDDDDDDtG´z‚í§â·î³ ®c|óÅWþ�œ�?Zm¸¹•Z³pè…Wgî»O:û‚“/‰KŸs.E+¨¶ãÞŽÕd""""""¢cH‹%CÑÎ§"ÉsÁáKÎuöÏu`fØÜŠ³ò ÿ‹Ú$=uâ�6Ž«ÛûK×å!ÿ¼Bžp¾±ÎÑ�qOGq+ðWBDDDDDDK3Ð‰Å’:…½Ç%�u<Q |î¾rñ0Ž©Ç7¤Ëÿÿ—o®¸íWX@¥{Æ}g&Ç íc Ž‰scZLYð_Ný�+ÿ+®%ƒˆˆˆˆˆˆ–ŒÆB ‹)ÕÅ´ÝÜ"~F
ý÷õ]ÚRyèÕC+nW€•“ Ðò{Èc"àW®Œä�©§Âç�Ë9I|È§Û¶‡#$& –úÑŠ¬o±eÈ§:Î%^\zXa•çù;¿v9Vž>uªèŽUW‚rGUŽ|ýdrrì·
œ8ö|ýÒ�/:ŸÑ ?¥¢_JÒþQÕš·lù¿Zý'""""""ºç8Tâ›‰H‚¼sý< ÿ»Cöµþðµ¿þ:Ž«ØÎt'¿q$_	»¬„
€Ù`þÄ‰`}ÿ v@õ³H’çEüP(Ú„<¬�ï‡ˆˆˆˆˆˆV‹5CÑÊÅù!ç³ç�Îg‘a[l8!‡®Ë<`VÁñã³	€cê÷¾ÿÞíäO•§�oìpI3‰½Äšÿ¹úODDDDDDŸØ\9§Zˆj¡Î73ñÍ=ªx>hñÄ¡¯Mlª¨1Û
°¼Û–y ÀË/8+¥8ù�Ç;{†Ñ�¼ñŒ—äsâ’Ý"Î[ä'þWÃ–úîÑjQ—·˜SƒŠøÞïõ>ù\ÇM?³çôå‹UcùÿW–|½Ìï (Ìõ‚+÷©ÃOˆóŸq.
�é ¡c¿‘dåÌ3 """""¢Dâ® !—Ð™€“t�ˆÿ¼Šþ”·wæ¨á“qñËØòM «öT´a
ÇÔoý¹‰mÒi}R‚>ëÒÞõqÆ¢ÓA°d‹·Òÿ¥¾ÇDDDDDD´ê ÎÙ® Z´ÛI{7ô9ÑéOnùÅÉí³â�çsbÙehy& Tåê=E÷ö_ifÓ_ÂßƒÃíXù'þÇªÿe�d!"""""¢MË: »ÐCÇÞ³?ÞÄÄ—,f-ªbÙeº5àòL Ì°ò	H±M%ÿ´øæ£"IòI[ù×jË¿¥¾“DDDDDD´ê‰%B[-&q™¸ôQ¸ð)‹Yël,cÖ;¿Œ¨Ô‹ùÇŽ©ÿËÁñõ‚â!9ä’ÞaÕÚ™´	öÃgôODDDDDD‹AâÿUcÔ*i�I†µ}í�HñÐî_ÿàñkzáÜ!”[Z@ŒX—OR`ùU ØäD}å„ä?h )Eûˆª~JÄo¶Ÿ M^\ê»HDDDDDDkœZlª*ÎoŽ1kÑ>b1¬Å²Ó.Ç]–Ý:2<{ŸÆ“k[œÓ/Aõ‹7¢ù”õZØ²¿õþsõŸˆˆˆˆˆˆ—Ä`Ô[lj1ªÅª³Zìj1ì­bÛåbÝ¡®!	ª²÷ç.ÓªO¹¬“HâCèäyÙwADDDDDD´Äfä°ÕbU‹Y-vµ6Æ²qàÉêàå3p™Ò*Ç¾YÞ—þ1èÞ¯^P¯GzT€í"¾»å‚- DDDDDD´´$¦+ßoom·V}çˆÅ´ýcGbìZÆºË#	°L À¹Wct{ÿ5•!õú¼øÆ3pIÓÕÔ[ù_?7""""""ZÓ¤ªèhŒY]Òo1¬zÿ¼¦½Cq DËXwyX6	€WºÞ�]Nðœ¤�ÃÎg½rU-,Áb	€eóÃ#"""""¢µJÄbT‹U-fu>í�1¬à9çòÝscÝå±ÀÒ' Ž}ÓÇ†eGŽ}Óïø¥+{¼¶žƒèýÎe½'Ð"¦üÑò!cU‹YÅ‹-`[,[hëéÿäònScÝ™Øw-' TåÙ!®êïýÄhêò/AäËPŒi1mSÿ!ª–$àÊ?-3cV94oŠMN‹/&!ÿÂÞþë#å1Uì‡®å
€’âè·�Ö�á$�‡�K²Ð™Ìcï?ØûODDDDDDË‘ØK9 Ÿ´]2$ÙÃ¢á(¤Ø†ã±•}Y´ $KóÏªàø‹öSÒ‡‡#_×ôòÔcâ� ÅAŸöXöaR-7[+ˆˆˆˆˆˆˆ–‰ë,ÈWIÎ‰)B~X¤xh÷{ã<~L/œ;ûÚc%|Y¿øI�¥« xù)§þ�çšHG€ð)·	ZhùÃcÜODDDDDD+ˆ–‰ ˆSÕOIÑ>òƒšqW ÅW–._²øÐÆ3ÿv'Í6‹às@ø¬ˆÖ<öþ‹{ÿ‰ˆˆˆˆˆh�Xºn³ Dó)ˆóÃPý¢sú¥ñäÚ–ú°#Ãk*P=è>¬Vú°÷ç.¢5ý P<îÓ�âBžÃZ bï?Ñ
 q BèØ, ï²þMªÅSÀôƒ1ö�C OV/þ@ÀE°UŽ}³ü7ûÇ {¿zq@½èQ�n©wEûÿ²’@DDDDDDtÇb,[Æöã
°Ýb^õ�#÷�‰±n/n`ÑWØÏ½£ûØû¯©©×çÅ7ž�¤!´:qê¿eMØÿODDDDDD+ŽÔ• Ât.é·˜W½^ÓÞ¡8 ¢el¼¸9 úJ×­ ÙåÏIÚ8ì|Ö«¡£ª…%L,À	€DDDDDD´ÂˆXLk±­†\�O{cÌ+xÎ¹|w}T/îN ‹— 8öÍ²¾ÿ„äG�k²ã—®ìñÚz¢÷;—õBœ@‹˜`ðODDDDDD+—HŒm-Æ/¶àm±o¡­§wü“Ë»�So±ñœXyÕ$ Tåù²¿Aå­·Î­O¥õeù2cÕÔˆrê?­c\94oÙÆ€›œ_LBþ…“�ñÑ:>Ž±r¸Š* z†§mB|I½Œ‰¸O¸¤ù°sIòÉ<öþÇ©ÿ¬ü'"""""¢•NÊ�íl@>i»d’fðIŸvÆêø¸Œ•ÇÂ' ,“!¢'ÇŽX}?ö|ýõ!'Ø`¿O{Ä7­:"@í{gß?­
RŽ°6w—4�Kz‡�à~ñzÀbcû@Œ•Et1ª >ð•êß8!áÐqÍ´è=´xB4l´hàvDDDDDD´Ê©
lö�Ž…�?i±±ÅÈ+Ï‰��[øÞÿW«Þàú»Ö;M>©*ŸTÈh(Zš[JÄsõŸˆˆˆˆˆˆV‰e 6@B1UUÕOZll1ryP;/p€[¼Þ Y$xÂùÆ�Øûß™¹,òv„DDDDDDD‹Dálð}È§
çÓÄbb‹�-F.XœY ná{ÿ+öþ�}]{‘`Döº´oP’Øû_Xúƒ«ÿDDDDDD´j‰Øà;Išb1±ÅÆ#ÇX9Îø­Ÿà¾÷ÿD8z\“žüÒž Ó�Xï9ë/þìÿ'"""""¢µA,Vµ˜Øbc‹‘-V¶˜Ùbç…ž°0_XUŽÛ×VÁqußõ¡óTŸUèHÈ[ÐÂzÿá¹ë­zÿï-Ž11tÄbd‹•/þ`|Ôbg‹¡c,½@U Ü{/jÛ¹ÃÉ’ôëýÏ­÷¿£ìý'"""""¢5Cá,¶˜Øbc‹‘-VnõµFÊÝ ¶J~a ÖûÿÛã¯â‹­
¿Kz79ßL -t¦÷?ö­bbsò$ÆÂÐÂbc‹‘î ¶ÖG�üÁËÖ.ŸÌÿ—´²	xÕðïlêhç° [DR)Ê¾vÿÑZ$¢‹‘UÃ–Pèá}¿ðÎßmÙ½ýì+§^Ò9±õò­ P9z¼êý?¹ãµuÚ“=ïž‡„Q„iØÖbÿ®,ìþ†DDDDDDDËŽ¨•ÁÇm-F†èˆS<'.}þôéëëpnƒ”±õËel½œ[ ÆOŸ´²~ÅKR´'0Ä='¾ñˆsi#äì›´¾""""""¢µ; #[¬l1spòl@Â+ŸÊ-¦?ýÂ¼/šÏs n½ÿ×g‹û]{‡À=,iÏNñY¦!ÕÂú¬”� DDDDDD´g8…ZŒ,¾‘¹¤g'TE±ù†cu™Î ¨ú6ž×cÇÔ¿ºabCkúú!…Ûî]–©Ú@CvþEñbI ¶jÑ>°ók—_}{rÝõþ1Ìû,€yª èêO8·Aþ¶ùþº|zêi(žtD‹6
ˆÚ'""""""ZãÄBiu94´í£Þá™$i?½#}g/¿cícß´#çgÀ¼äe‚¨õ+„†T•§]ÒxD¤ìý×ÐVØ˜C"""""""‚ÅÈ+[Ì,.iÂ7Üs®90øJ5à�ßŸ¿¸}¾�e"æö%A6«èÃâ÷‰O›eï¿µ °÷Ÿˆˆˆˆˆˆã,VÖPqi�s�PñÐ-sB1æ–å0 .ìù,ÂÉËêwö^P´@ÃNçÍ`åÿ2]%8÷�ˆˆˆˆˆˆhV—â�ó�ž¢=¾K]Ø¿çØë§Þ8´çzuÀ­ß¹ îG ð°#½:hý
Nð¬@6hÈ-¸íÑí¨¬@s«u*O oðÈžÓ—6ž* ó1àc· Ôý/½$EâÃ€õ+À¥OˆKzC1U tìÎ²÷ŸˆˆˆˆˆˆèVqÀTq½€<!¢ÏøéF¿ÅÚvÈ|Ì˜×À\Å(s®yÀ%i�õ1¨–Á°mXÿODDDDDD4‡ˆ@Äbçj@¯øô0�©¶7Þê°T3 âÞ„ÇÕmzýL�SÙ©ZìpI³G‹ SZ¶(° €ˆˆˆˆˆˆèÖ¬´? A!iÓ‰¤}:»Ä»7}õôÏÞ·yª/+ð>Ž{ŒÌU,è·¯œ@aÁ¿OîªC0Œ`ýef‚ÿDDDDDDD¢Œ�ãˆ}…Äÿé8}¤/KZÌýÊ‰Š8ð¸Þó,€{_š¹þ\Ñ¡ÞÐ£^t¡xL =!Ÿ:ïë­-!GÈ§m"`¿jþ0B8<<ÔÛœÙ`&¿—/~/Ž¿(‡6ÆÏ¨Švü ÓâA…>¤‚!Õvì_¨R, """"""úPbÃ  °Ø¿ã‘ƒâä~ÍÃ@Y…�2¿ÇÍ ï9sÐ3ÿI�³
Ä‰“=.inr¾á
�m """"""¢�¤V`³ Úê|æá››º'´ÛC8!dßcèÏ	 œ8N^¶	åí l�Êv—4ÄeÖ²PÄ´EÌ_ÑG²ZÕFæâp¾·p;ƒ&›ëCN�‹±¶ÞË€{Ù Ž%À7Ž}EýÉÆø(Tv ‚xÚv§?VV‚ˆˆˆˆˆˆhÍ‰Õöp©Åß#ŠÎ®ûþ½Ñ§·^yé^)�ºÛŠ€»¬ P9ÖUÖÿ×ú$›>ì€ƒ
hˆ½ÿb��{›JHDDDDDD´f‰Æ˜Z5Õ¶…øƒÎ¥‡:YãÁ¿Î.öáDô—±ùÝÅÝwÝðÆ×«ÏÑ¢ï)ÿ…‡DÐ£ù”ÚÄB8Nÿ'""šÒý"Ëô¥ë>Ñüí€|Rc¬�üaU}¸h6zêÝ fbó»ú¢wãø‹rµñ£rú¿}r_1àT‹êCpIŸ†Žrú?Ñ½éª]õ"®|qö"s_¼»ó—¤ûÅßp»z¹Ó¯uãý°û6s?ëûÝõBDDDw½€¨hÈÎ÷ú€szHŠ©Áò•©1ˆÅè: i—Óÿm‚w/m‘]’4‡!ïäPuÖ p·_—ˆˆh5˜y¼ƒgÂú�˜Æ·Q>ÕK¼ioã†·ãë®V¿®cºÞuÓ;gnÖ_û6÷ó¦»\­îßtŸç|Nµéo•Àˆïëú¼™·»ÞwGÍŠ]÷•ˆˆh’¸ BpI3�¸Qí�^ÜHYö/Ú³EÜÝ½ó€ª@$œ:ŽÜnnyãýaÉ÷2æ’>hÑ†ŠQ»La¾ŸˆˆÖ†™ wæsƒß®wÏüçÆcËÀ_ê$@|º/™Mè‰€¹	€ú¸êÝsèÛ7ç¾ÞpûÆàÎ÷9'¨·Á?åÐâú¸º‚¡N
”vq‹ûVÝ¹›î_ul=Vø–÷ŸˆˆhÕ{&T‹±!>íA>}y,hØuà—/œúÁ¯ãúÉ¯#‡œ°{’ÕùM |å%+ý/lÀCÇ5›zïìVQìt7*äª?­
7®rßêãsVç»÷î×öŸ›ÞgkøsŽ)Ÿâç”Ø;©^Ûm©Êýe¦@ºê™Ù Õ»ñ}10¯Þ®?·vã}.«nqŸoñ½Õ		KZØU@a/öv¡ñµÝAg?ÊãíŽØýÀ-*fg
Ì­*¸iþA}ÿo÷bõ ­R?9Û³Û ónO[ÂŽêDââ<^¼óÝ î0 rôÐËRî4 Ò~çôP"�C*ÅA¨hè8ëOÄò""¢çæ•íêýsÞ7÷I®^µ¯ƒàÙ@ynp\¯ì—¯«@$Ûkï�Þ† K�ÞLÐÌ=A#z27çv–HÙÃïeNO¾Ý¶|{]ÏpUo};Mìvµoÿ~¼ŠÜô¢¼öv´ÇÛ…BCùÚn—Á|y;/€v®hu€É–bº­˜j…òv[ÑjSmÅd˜îhü7êdÇl@_Þß:9Q&9f«
fªº¾�ºÚ`¶Mb¶Š N2ÔÕ7V@­ñéN]¹Ó^ÛžÝ¸ß9´mïÕï½¢—íÙîØaÈKU[À¼U œ?µ¡(òK=>Õƒ9 �fÈ§5Ž)P0@DD+jU¿N™Ç`²
ÈgKñËì9«ÞÕÛqE½¨ç¥¢‡ëY`.ñm{�V¯ËÛ³+üv|ý5,0· ¿·Q% RAOÓU	 ùÐ@R
Œ�]1Pþs*nN ”}™ E™°Ûö=Ï&ªÛu"@?*Pß¶D€Î$ ìý�|ög[~}�I(Xr ·ûb÷ÃÞoÛûËcìíV®h[¢"ØÖÈs+	æ´TI…[UÜòÊˆ	""Z®,Æ9BÈUÄ7UÂaýQ#/NrÉyã÷ãpÿªyp> 
´,›m”Ö€ÂÝM÷ÂICCQ@5©jöX@DDËÆ�Cèæö²Ï®é[Í¯‚ÑzØ^˜–+ù³«ýõ´›˜g‚þ‡þžr Çy‡¾&Ð×tèô5Ê—ðMö³2 ·¯aýœûº «ô¿þ¸«JÿÝmËçol�ÛÂsvW/ÜªôNCwUÃìÏ­;aÐ]]PÜ‚{«˜¶Ê€*a`‰‚©0>­˜h)®OÚë€É)Ä××§Ê¤Âø4pm"`bZã×¨“/eõ@UE`—?ÕÏ©þtÿÜâ÷z‹™õšI÷÷GDD´ôl™Ý*ƒ=‘´V á�T» S—ãHž;@|Ç C;öÅŒÂ‘¯kz%¿°‚-.íéµå “ÕúÑ2ê×¿¡¿Xgí•A½}º“i"È’2(·•öx;R[á¯Vòë`ÝVömU~°·N ”A~™pèo½M?UÀ^Û×·Õøåùs»Û<þ½åýÛ9ª€øˆ�½ü×&Ë¤ÀD• Ÿ*«,A`	€K×Ë€ýÞâE^&j:V1P(Ú�o[µAÇ*òºZ¡¼N©Û	âë:ArCÂ-gp® -™nIÒT¤Ñ:×·#p\œ�¼gøÎƒñ�¸üÐ*“ zš;¦þ¯ÚS›%q ºA\§ÿ[2"æÎë¦<""¢%\ÙŸí/W gKûË`±NX€h·U÷F*ìŒ
Öõ;Œ8Œô;lrê“j%¿ô­T¿^¹Oë²ÿ*10Sš?'a0Û¯ÏgÊ’%Z,Éb3m ÁÅ*k°Ê‹ºÕ ®ÄèeAlè(&§W&ãS×¦4V\¸py<àòuûXÀÅkŠ«“ŠÖt9œÐ~×–Ø‰ÕöâmÞ@u»jã°j�î–�X1pã\÷ "¢EŸ”,Ö¶Qÿ€K­Üm½îÛy~âûo×s'O Ç7b©@ù„ö!«ó½þð•˜ ·±=úÆ°6\>½[C8Ñ„XØg…uÜ©—ˆˆe•º»|ÝºØÇ ~v¸^ý¶¯û¸Šo+ú¾\Ù· <KË>üÔúí3`]¯`]_ø¯�üÔ	 [É/WöíØ�cö>ÎÎè.Û›ývg'áÏùþ?"Õþ±õoq¹ðQqî��ðl�\ÏÝ¨)v¯¸ÛK9Ó ûŽÞùzÂxøÛËµIøË€U
XrÀn_�1	`­uÒ§®˜­(g´¦,áP¶X‚`¶b š+Ð}ßoñóab€ˆˆNÚDC?û]+ÿÛ�À•·!Ó]±û‡ÎøÈÀÑC(§ÿ«Ê…ÿËÄ`š‡zPƒ6ýß¾~W%Ñ¼èîWï~]‡¤ÙS\Ñ5¬¯ÜŠN‘çe`f=ù¼oŒ†zF- ïµàÞÞç°~°,Óo¦åê½­LÇdAµBm·K¸ùý¾bê<F�e±Ýìwv/_ôãRÝ•ÿ<½›/<û�¿¿ù¬‚ˆ­MÁúA«p±ä?–þWA}l(l!p}2àüUKX’ 11páZˆ•ö¾óW4¶"XË�%$,y(“Iõ†e5Gù ¬wuˆßg=G€‰ ""šOñ)'î`O6. Šºû´gÇß‚jË*Ê�û>|ÀG& ÎŸŠ×(± |ýlŸî’ûhhh—5œþODDïymÎ
xÙŸóð½z¥ßb¯:@�ÛçÅ^ýÙþ}+Éodˆ�ýæuë‡¬œ10:X®èÛêþè@Y‚~§êûP—‡ÏÞçÙ¥ú[¹7~õs.±;º÷xGoü´9¥ô]ïìÎ/ÌÕsŽ�=¨îÝ¯Û*Ò*qcs>ìŽZÐñºÆ�«“!¶\™¸tMcràÌår�%ìwms
,©`•Ý;ØÇí¾tß‡8Œ°ÞXÏ¸Ý÷GDDt/»XÚÙIÒPçöiÑ>”äù+9×µs_ña_æ# íë?êºV‘!UÝ'I¶ÍÚ‹bÚÖX8ýŸˆˆîI÷tzS—ZÇÞ}¸«	ü±¼kà›úƒ¶š?è°q¨\Õ�¯ëÛƒå‹â³U\ëÓ·×ué¿Ý¶`1®êÞ…Øù¹+÷/£ ¹¸UB$Nâ�ottógêÇ¬$°ä�íÐ06lA¼��)›;`3¬ZÀ¶-´�ƒÖ:pÑª.k¬8wµˆ¯­JÀ^Û B;¾“ ®œ'PÏ°·g¶’¬²l "¢»gYoU[Aî|#¸Ýšw®3àM;ª}ýã ñ©
C;®Å§­�_CÃ…ó[n“Oš™{®¦ÿs¤}ÄS×Ìºžiª=åë•ýzx š±7ßVtËþzèžðØ[é¾½X�~|½nîí²§üÃÍüûUTvãÖ€7\Ž+÷«E÷Ï÷ŽŽëª¸q•½»z VjTl…¾Ðhí=ò¶r(¨8%Ì& ìöÕò¶µLN—ÇÕÛZaÚv5h—³ìå ÁÙê »}«¿""¢Wf’D—57=&…nÝù5=õöo 5´ãdÕÿ_op{Ç	 ‡à„„“ßÐ|ï¯ý(“É‘Ýªþ�"ŒÄ#ÊB<FþDDt÷ýüÕ0¸™ ¿*­·òj[‘µÀh�`ûz�­<6­sØ´Nb)ÿ†!�Á>Ao†9¥ÿ�jË>{ß�>9Õèlhîíb ¿\u'gêñrgÎ¯³k¬â]dlìñ46"±M¤�{´:I|l¶«Ç¨µ\›Pœ¹R´Ö�³—Þ½�ãýå,;.¶%tÏ¨wˆEœœ@DDwÇbp{‘ø_Œ@q(K.¾¶÷×.½qòßiÇW‡ñ	Qï¼àåz‚ hßµË=ÓI¾·á úBÑR„‚½ÿDDtG+ý±w¾ZÝŸí£/Wúm…]¹Å^Z­ô÷vlpØ¶ÞcÛ��1Pó³Òÿ�RV”SèëþüÛ®êw­èÓê® ˜S1ð!Õu¿­ØÛã±™ÝþÛŽÖpæJ ï]ðxï‚½.g	ÄyyÀD˜j•»EµË€ëª¸Õ‘œ@DD·™âò…ö8ààö6¯m8H«+–¿å,€[' 8ú"ðJÿLäE¿¸b?ÄíS !‰[²ú‘ˆˆJÝÁt5 ½ìç¯&ö×Ãó¬ŸßªÙûm ßæa‡�}|Ù±¡|m+ýC}e€`�t¶‡ÿNÔ�Õm{ô¹ª¿&Í©˜§j�áþrÖÄØ¨‹�k›!`ÛÚ�Akxë\ŽwÎxë|�wÎ¼{¾ˆíõ•pÖ&P'Ê©3[Drn Ý Æà A­` ÀþÚû'òä¯\±cŽ¾ ¼òò­/‚’�œþoú’†vò]Ù.‚BG!Î¦41@D´FÝ¸Ò–z+¾™•~�™ÐnÓú{½M‰åÕ¶}›•Wï¨‚ÿ�üoJ°k“»‹žýÙrÿWögnÝÁã÷V�µ[V
TÛNÚ'×%ýõ¸aG	øÖ9�·Îæxû\�wÏ‡øÚ’-k'(+âËtµ³@�ÀŠófw¸qøÇ­Qj1xYê(NªØ®êvZÌ~C, /¾(íÍ?7óTz½¸íðé˜Àù�Ûôÿà«ºJ^_­!7õòW‘”•OÇiýU	¾õöç…õ@ë»Ç<vmLb°¿m½‹�¿•þ÷Ú ¿LbbÀ’«gŸA?ÍóãüÃ*>ê
Èû»6•-,ìÔ¸ò?1¥¸8®±*à½óELX‚àÍ3åÎ6½)ó/Ð,¹P'¬šÆ²u2¢NPp€ ÑšÛ q7 ÕÂùF‚Æ€ÎöÂål[Û`ó�/þû9»Ñ~d@6ÒžÝˆ§è*Üˆ÷=©ÚòŽL[!çbÑj´V÷ð—ÛóÕåÊƒ[Ùì4}A3Eòm2ÿîÍ¶º_®öoßà0:à>´¿{¯÷òmöìÓòª¸±B`6(/+_¬Å¶œê•øÒíÌe�w¬-àl«Þ<c»\›R´ÚÀD»¬
°ê€¶�^ªªiâƒn¶2`N‚•DDk‡ À¥pÎ§E¸2*E>XoÐËßâÓnYRÓ
"aÛ±wzšý�/Cä¿Kz×?¨yEçz[T«~[èï‹ˆˆ–~¥¿4ÊÉåõê~Qï�^•-÷÷8lrØ3Vû¶ŽzŒ�úØ#m+ü=™Co£¬öanZÕäÊ>-cÝÛvû°
{ŒOUA~|m»
L*Þ¿Pà½‹o�x#V¸x5Ä‚Ö}i	…zÆìÜ€²-Æ¾f=?€ˆˆV1…M È}:�‰o Ÿºø]hø¦Ç[¿óÞK;¦êX~&¶¿£] œÛ>@_{oT [ ÒDˆ5±äŸˆh•êXê~{;ó[)¿õõÛ‡mÛ½¸²ßg¯- /Ë÷mpßæuU öò{luñø[±$‚-uÿ�[­ôºËôg+4VX _ÎÅ˜ûI‡¶{¼{AñÖ¹ožu1pîJÀ¥k“mÄ„AÝJ`IûÛ4±2ÀWÃo¨`B€ˆhµ
6€IEÐ•-šÉ(Žë1–¿� *x±ªòT`ÓëgzI¶S; Ú«¡�Ø¯×bWÜ"|SDD´ê•þrà˜”ÛèÅÁ~³{ŸgI¹eßÖQÁÎMeOÿîÍ>Nòß8Tø³Òÿž*°ù°©ý±¿ù†^~þ´*çÄ3ïýÐÇy_�%Ñÿ¦Ú�TÎ\xÿbˆ³Ê™E|_œ åÂ?›\ˆ;uU “ DD«‹Ø€(có�[ù~/;,vßôú™Ëgñ¸ÛÇA6zû
€S³OQÃC½Íöxk;4lƒ“¦†¼ñ–þ­3�HµÚß²Òþø—Û”Ùp¾uý®Ô×ö8Œ�8l]o[÷•¥þ»7ùØã+õœ {Ö±ÀäÆ‚Ì#ÓZpcÀß]`ê9Vc‰±,²~Áº™?�Ã;§/*Þ°™UeÀ™Kç®ŒW³bÁ„b|ÊjCµÜIÀ	’z�`×¿MDD+ž³¡L*£kªÛàÝöáþÞïŸE• (cûiPàè‹�Wª›�‰¼×9ÝÈQôªæ–f`+&Ñ
Wà¾êí�ýÃ–D¶žþø<¢èésØ2êpÿ¶$¾ØÿëFúz2ÄU~{±ÿÛ‰¥Èö�ÌùÇ÷ÓÚV'ÁbŒVU7±³€ò[FC}‚û·ùìÛ\€×g¯Xe@�¼—ãÕ·s|p©ˆ[¦¾Úª0¶”ÿB=Ä“‰ "¢•-^Niˆ¥ûô*d‡SÝa1<€‹vÌÑC�WnØÉæ¦
€jÏÀò‹Ÿ!É·Âù-V]&!·´¬û'"Zá“Ì- °àg¥þ¶:ØWõñÛ*¿MòµU~ƒ�û·'¸oÌÇác·b-‰P—7³ŸŸèîÿ.q‹-þ,g•«ùÀ@¯Ä—nW'4& lw«Ðy÷|+®O•6dp|¢l°D€%ìkqN ÑJ·eRu>°y±UBžÝÛÛÍ·I ¼‰{Ö_®z]!;D’1—„|:·µœX£ÆNM"¢¡Æ»ƒU ��\cð¿i�‹�þá	önIb0a‰€þ‰¿]ðo,¨pÝýü\å'ºç¿×™¿Ÿ®á¶übUû·yl[ïðÔ�—'Þ:ðÃ÷¼úv'¾Ÿ*0ÝV42‰-õq”t]Àö "¢Âú*cË¦ª†ÂùF¢!Œ©ÛCÓ÷ÔGÅØþÅ}sÚ nª èÚ3PPtYïÒÞLCÈ´=E|ÈH'""Zä«ýÖÛo¯�ó4Øj¡­&Zÿ¾­	n·^ã4ö³IÿÝê¯ŸCìy§.ñ¯Ö‡ÍÏßïMo|øŽÌ×;
¬vÃã¾ÍŠlìØPàõÓ.\+çXëÀµÉ{Úßm¹¥ «ˆˆV»&C€Ká¼ÏŠÖ•õRäƒÕ3ˆvÅö¸ù©¥Þ#°Ú3pÛ±wzšý�/Cä¿Kz×?¨yEçz[T«D[ìo�ˆˆî¼·8üªWû U­ô×}Á‡Ø™àÁ])îßaÛõyŒ”«ýƒ½.®ÞÊMÃÃ¸ÒO´¨âŸ`×ßá‡%Þ,Ð·6 {±9ïœ/ðwoøÞ[œz/ÇÅk¶®c³<Ê]R«ä±¬žÚÁz8áb|WDDtOìt-šût ß@>uñ»Ðð?L�·~ç½—vLÕ±ýL¬Ë] lÏÀãêôµ÷F²"MÛd6pm‡ˆh™÷ÛÅºü�öìj3ôÛÿ^üõåÿC;<¼»L Ø´ÿnö¹6`f¥¿š ÎU~¢å57 Nè{ÜÅ£Ô¹qâ�û·{l)°yX°uƒ‹»\º®±*àÚDÀd[‘eU@Ü=À*ºvë`2€ˆh¹²„nPô@e‹f2ŠãúAŒíoP% TÊ=c56½~¦ÇöTÁ¨öj(Ê=ã5ÖäÉ\ Ñr�æŸÈÛåª¿­èôîÛâñÀÎ2Øß7æ1ÔW–þÛÇnþMìîŠöø-ï„@<|De€íàñð‰É€ÏL\WüÝ»9þö­ûfo�+0ÕqÔ“¤:³…`}n©L-›«mÔg+7¹•ó÷B°ÃbùM¯Ÿ¹|V«í c¬‡Êêl@¹G`4<ÔÛl�·¶CÃ68ij°=¡bò€¥ÿDDËxšœÞ#Ø2âc€?2à°k£õ÷—½ý¶¸~pî©<ÖxÅ+ûrË°î)þD´rÜ8Õ¿»* \ÕGìi/õ%ÝÖõ›Öåqè›gr¼1Ä]®N†¸Õàµ©Ùs‹µ	p÷ "¢eÇÙ¡JÜÇ¹	Õm€Û>,½ß?‹*PÆús[ â�ÕÛ¶w sº�¢èUÍ-­ÀVO"¢å4Í_Wû-Ðî yâ~6	ü��ïòq˜Ÿ%ì‚ßÖ
p#«(§�×ÿë¼ˆVºz8§¯ªn—ÐÛ<ìÐ×Lqx§Çµ‰ï\øÑû9¾÷VŽSïæxûl¹{@–|ÈîÕ€B""Z|ñ²MC,å W!;¼—íyÚé‰«;íŽõ“ö,¿Hð’|+œß¢@*!Ž‰åZÑ¯èuòÙiþRMóî—ØÓ?Ø“Ìlå÷Ð®ìNb2 ›}�<î[žÖ»Wü‰h•Ïèª°’~+õO`]Ÿ`]Ÿ6 {·»6ù¸CÈ–õ¯½ŸãÂÕ€«SŠI›0¥hçÖ&`-FeE@÷ÐÑ8�`‰¾_"¢µ+Ä»:ŸºECØ–M7šusØùS¯:àp1› °w¥ëÓ›¡×²C$qIÈ§s@||¦àe"Ñ¢¨Wûãb›”åþ¼—+þåŠÜº~‡wy<dÃü¶'Ø2ê0Òo½ý®*ó½ùkÚ`¯;Ù[œˆVç9Å®ûì¢.¾ï†ci90pã�à‰ýƒÿwÏ|ï�ß}£ƒWß-01m+Mü+)‡Ú×®qÕ’|‡DDk�ØŒ>h©p>KTÃ˜j{g[t >ª}}vàÓL@Ïp×¹ºè²Þ¥½™†�i;•ÇKF""ZÐÓø»˜ž¶Òþ`'örµßöùÞ<âbŸ¿õòoßàËÀž·%Upó4[íŸÓ>@DkÒíªbà®Ëû­ÔtÐat°¬¸›blÔaÃ�`l´Àû\WLL•ó&¦Ëª$«Hªª V-&ö‚ —ÂÁeEÑÙ\>‚cêñ’C;lß×RRï	xò¸Æ’€mÇÞéqc‰K K Ä¯)–ìå@"¢ÅXñ·³¸*¦huÊ÷�öŒYÀŸâà�½c>ù³•~ÛÞïÆàÿ¦iþìí'¢[�wâ.ÐåIâV	Âþ^Á»ìÜèñ©‡ç®”s¾ûfßy#ÇÛçBÜ=À†Úy(VT¦qN Ëˆˆ�ˆ• ”×yq©�×	°egï•�·�+'¿qÄ*úmEI|%ž÷ü÷p\]óµ÷F¡²Uœ4âlh^2-Ü){îŠneþe“n3³¾\Áº�åäþ�Õ4K Øn%ºî–«ýöE9ÍŸˆîõ<Ô=+À.(m+@ j/c lõØ¹¡lØ0äñæ™§/¸<¡¸r½Ü=ÀÚ•nUÀd ÑB²…þx1Ø€×ÚžÆq½†RV |.™™¨À¦×Ïô¸$ÛDwÄ	‚¡(÷ŒsbâÁ½»DDkIÜˆkfŸpÕ¸Úoý�Sô:Ú‘à‰}6¡Ûúyö	{}·šæß½ÚÏþ~"š‡ÝnW9dóFz3<¸[qe"Ä$ÀwÞ(ðg?hãµŠX`E¦V�Zu’Í³—¦DD4�Ê²+±B h!h@°±‘¦·�z÷Ì{À”f±2~zö¼><T4Ã„ßÑ± hø`LÙ©Ú‚""š�ós}Öµs´ü¶âoåþÍ´ÜªoÇ�õë÷möxhW‚'ögØ¿ÕÃûv°­jï8…›A?-Ðœ€ÙY�v>îwîvÂcÏf�CE<‡m_Ÿã½._W\ž˜¨+,àÊÏíþÚDD4/âv€¹]f"²QDÇ†×þ°N XìŸL]ž=ÅëT£¡N6Z¶ �clx—þ‰ˆ>þY°”l¹ê_ŽÌnçˆ/v®íp8h+þûSÞ•`×F'úÛ¤ÿîæøµª²ÜîÛDD]·„ºÅùÆvyd�ÄV¥‹×ÒXð×¯çøöÛxãL�©V™­´j€z^IœÀŠ "¢ycvµ]Z*¡G‚ÛÅÖvëj€ËvŒÅþ3» ˜:iŠd€½¤ÕêÿüÜ#"¢5ª»÷µc=þy¹âo“¶mª¿•ö¯ìÞ˜à�Ý	ž´ÿm�®3t¹ÚÏiþD´ª—ªÿÄŠ€*ˆ·$kMêkúxNÛa³K††úß/ÇCÜ9àòõ€ñ©r×€80°»"À*ø&"ú¬@à™#
éYÖ}DÒÞ<»ºïÛ>-R7ä CMcÿ¿‰3 ¸¾DDôq&ûÛ…­•ÁÚKý=¶y<s0ÃÃ{ìÜ�`¸Zñïþ�­šY?mùE9‘…ˆ–>w¨‚÷¯­=à±½il¸x-à‡ïø+«ø~ož-ÐÉËV©*êƒ˜`€ˆè^v¨f Ä	®¶ÛßPP%…míW²Ø?é\{kæ”�{—xèìEœ‹©¤Ü†ˆˆîê4Ù*W«
øí"×&û��Øö}‚m<Ü™à™ƒeÉægO·–$°.«æŠ-Ýûj-ÃÝÊåm›K2Ð#èñØ¾Ácûz�‘ÁrÛÒ¾ŸãÌ¥çXU€UØçÛŽvž¬¦+.Píš@D´´bï€0È`îg«þ-öOŠÉúŠSÅ%g3Y$Ãâ	y;h¯@‰ˆèŽÄÿj"¿ebmk>+á·rì÷´­øïN°{s™éws‚S®ˆqÅŸˆVXµS´ß˜°pxò@·2½t-àûï8ùZßþAïœ+â9²þ“DâyÓ¨‹’¸ÅUîÌ?{›+àøn½Mðß�¹ÝtýsºÝ}ZiÉ"Zzq@L¨.I-òa‘|½s:Ó`±W‘©h¦ç³BÂ:—ö¤åhévµa}è9·*Ë·Õ/[½o·â¤^°qÈatÈÅ}³m¥ÿéûS<°3™³•_\ñ¯zü¹âOD«a—“º"ÀbÙDWÿ{=vnôØºÞcxÀn~ð^�÷/–»Ø–‚EKãñi"1™Z~ÁŒ‰ƒ]ßð½Üê»ñ}V©PHœÉW#´ìkÌù:·Šöo|_UýÀ¥7"º÷š¸Î¥iè\_—:ßè>"ñ½ÅÌ©©PßÑï›¡]m$ˆ ±âS""ºÚ½“8ÜÏ†úÛj–�B7:<u:ôo¶m³\¬˜{2æŠ?­²Š€êÜXßî¶~Ðáéû3Ü¿-Á{çþòµþìûmüõë—®+44€GÕ;Ô£©îýN•¯ºì9AzW°~«÷•}	Õ»\üÇ@Û"ÁÁ¡ºþ.ÊÆ%·©ˆÁþ­>V%fŠÀn¼DD·KOC Îe�ñ�"$}õû'ë»Š·íÖ1õ*†œJ2çTEDD·>Í–˜nÛ*¾åKËU.[áÚ´Np`[‚g¦xâ@†­£³¹ÔÂæTûisÅŸˆÖÌŒ �-a*Àº>Áº>�]›<Öú{Ê÷½~ºÀ…k“-àÚ´ÍB)«êíï© ô»Væc o]²–€µÓ³T�ý-‚ðîÕþúóâm_% ªÏ�	 ­ yy»þwo¼õûâ—¯ß_%œ}~ýMÎ4ëòêœˆî‚Åô*ÑN?Žw8q"ôíšÉÉ‹ß ö_î—BF��il<µãUìÿwóï­1h¯.bíŒ9ÕFÜçÚÊúmØÕ“÷gxú@‚½[Œ†úæRÙ¶WŽ=þD´Ö*n³kÀÞ1�õƒM<±/Å«ïøÃïY5@Žñ©bfËÀ4)« fZn•¸EÿýœÕü*ÈŽ	 þ ï´©ñmMt&)€®×ñíøñ2è�_[o‘(À��~™­� °ò°˜°Ûyw•@ðÇ ¿%ðÓ€Liùqké­“]ß_ýïÏü³¬ ¢Hbg”éÊ"Cc§¿Þ<�“§.’˜8®§/©“Q	’ äUŠÖÎ8<£ÝØëŸ[ñW„HS` ×a×¦$®ü?²§,ù|‚FZ^žÕ[ Úëz[@¦W‰h­WXpï]¹CÊf{vØ2š '+·üþ{9>¸hm!î`—§¶[€}N=`N"À‚{Ü°Ên—À¾
àmåÞ>ÏE
=e 4Ëà>¾HyìL úüúãqÕ¿kõþ–—ÊÝ{U€êÅuµX"À>ƒÿpmÄ@>øV×qöR^ý=â6	""X¶ÔNâ5`]³˜ t
ÇÊÓö^B*AF a=Tª!ö®V;PQ×tëõ/:Ëø-	ÐßãðÀN�O=œáÑ=)¶Œ:¸™à¿¾F³Uÿúb”§V"ZËêŠ ©&ÿwÛ0$8ú`†Ã;S¼~:Ç_ü0Çüm¯}�£“—	;Ûn¶Åj\³ê^üï*Ã�qz­ýòµþ¡au¯epKÿ»VÚoîWß®Küç¸ÝZÙœïË¢üÙ¾ÿ˜H°›Õ}/ê„…íÞUWX2`Já§€dJÊ×“2SEpÓÀÀ*pËùD´6ˆ­þ—ÅGV2%ÐâÖ'è9tìÕË§ä�v<ý\-Î¥C…‰Ã�ŠíP5 ­qõŠ¿ÖÓýÛeÝ©]xnqqÈßÎM�ïKð©‡Ø³¹nR-©,Aà}ÕçÏþM"¢›Ï¯uE@UÞŸ%å¶�#ÀöõåàÔfZV¼w1àòxÀ•ñ€0­H�V„º'¿¨‚ú¸Ú_ÝõJõ:–ýÛÆXî6ýøµú}]•÷ödÒõåº’1éÐ½]`=‡@ª$@þ�|ºz=	¸à;7TÔ/ub€Ï7Dk\ˆ/ªš)tDµ±îòð°Åþe` O=\kP5BZÿ�/\¤""¬õTÛŽª^ôé´Êéþ×9<(‹þî°�ë‡æöùÛ
UZÕ¼²ÜŸˆè6çÙ:`V7|¬§!xhw‡¨>{8Å_½ÖÁŸ|¿ƒ¿üa—¯4‡FV�£-Ø·þ^ è-ƒü¢Gc õKÕÏÎõz×­‚ÿúÎÝ¸Ú~Ãp¾{rÃçÖC	Ë-fÆÚ 
[šëÓ˜„¶Ré”mñÅ*&«
�VÙ^0gˆa÷?ÅŠ ¢µ¢œP¶ô§º(FzÐ“Úc`:õIo‘@0¨ª)Wÿ‰h­«W¦Ú90Ù)'-ôvlôØ¼Nphg‚çgxr_Šëfÿv§\½±á€ìó'"º»óîœª!w¶mjï�í<ÆÖ9lpØ1äðwïçxïz�‰hY`o³
þ{çööÇ¯_·Ôƒ «ÛºÜu«�ÍÇòØ-
m»õøv½ã@×.6K0Þÿ�X`Ò’ @a3ì¶%¬: 8« `E ÑÊ<@ltòë€|�Åüö‘øŸuêÓŽ†Q•d½@2hÙ4%œ @Dkt%ªì1LçŠ©Ž¨¶¬/÷­¶mýl{¿‘~·üëfSªë/Ä*"¢�1à'ÑÝ›=¶9<³?Å½ÙÁÿúýiüå¥®7¶Óun%ýõÖ~Õ ¿ºÏ~Î
ø�ýó‹í#’3wµk»YãêØ\ƒÞ¸wò! ]hü-�^ÒË‚tÜ’ rëŠ V­Z"Rþákaý¬j½ ì´²f* ò«™ÓÆ:Õb½$q�•òÓy† ¢5µâo+NVfi[úÙ&)Öëß�]6Ýÿ¾ÏJñô�™õT}þ�¸USYòã0+""º;ulz«óiŠé&0=´&€ÖE�«ÿ­ªÏß†^[|Ý·eÓõë/8g¥¥œ«ëí«›s†ÿY¢ÃæTm–è°ù …7ŒƒË*ÛY VtÏ˜Û±FD«NÏ['kPt]�Ù ‡¾T¤5"ªëÅ¥^ã–6�D�¥–øÞ-8»Ð´a}q¢´–¥ÿ‰SÜ7æñ¹Çšxú`‚]›<Ö¸™à?~^=@Š}þDD[,ý�¯NIW j“ò¿w%ÇŸ_ìà//æøÁ•ï¶:�mWZ—¼ë2YåŸ/ÝÛ'Þ8; j™ˆÛVs:ƒå,7l»(²+@vÅ!™ìš5€vûfE Ñ*a«ÿêÊýÄyïŠÎzˆŒXÌ?“ (¦Ú>É0Éúàì
¸esX™$¢U­î±4­Ð™.³¥C}‡úmq8²/Åç�dxdO2SŽzËéþDD4/«þñ´:±¶
Å•¶âR;àµkþì|t¶ƒ¿¼ÐÁd;À§‚þTàmø]U�5g¢þjVohóâîÝUÒ#r«¨†!†°	_ùxYçTs¢j×"ZMbT€KTú,5h1¿}$±?yŸ\LtÐgý‰h!ob§®þÑ*Û!«a}özºLµýMÁîMÏ,'üïÛâ±aÈŠ¡f?7î?]IaðODôñØB•­î›xNî:ß¾~½ÀŸžïàOÏ·ñ£kÎL\k+
(’T�ú®÷µ¶Õ‡UÔm)Ðòþ gó®²«V qh`üáUg¿ØâÜ}"Z q€‘ÂYÀ÷$Eûê O$Æþ‰�":ù{�4kô¹$…v‚�xo1›”ˆhuõúw:@aƒ“âÓÛÖ{ìÙœàñ})ž;œâÈÞtæBÔZâ`ª®""ºw±Zßúô«íVM€«í€Ëí€wÆ'/¶ñ'ç;ø³síüÛÜVü{‰É‚"”/õ�;ªzý»~ÆÁfô”¶+‚Í°ª€t¢œwèTU7&ˆhÅ*cz‹ñC}�|ºaéå Ÿõ+ÐgÁEìý�Ÿ£66p©ï8Ñ‚ôú/4m€_Óû¶z|öÑOîO±s£ÇÈÀÜUÿ8Ý¿žÄ#ÑÇ‡® ó³çÕ&¾}Á‚þ6N])âí+í€«Eâ¬8µ,lµŠûüˆ'åÛï"PWTI’ÐT´­`P«$ÎH®JlˆŸhEÂÝ³ˆhåÑê/X\\èŠ±¾Ïúí]ÉÞ_ûa£Ç�SØük'¢U½ò{ý§b¥†úv¬wØ±ÑÇUÿÏ=šáàŽz¿Ù•%Be'O^dÍßÊ¿­àûØ‘
œ›
xk¢À__ÌãŠÿŸkáí‰weéI,I èK¬Ü_cðç[ñ—q÷¶Ø—y/àûªê «È€ÄfLÍîœÀ�ˆVƒ2¾·X?†,öOôzïFç’a HÕˆTËî[ÿ'"Z5«þöZ0Õ˜l){û·z|â�OßŸbû{ý»ùz[?ž‰ˆæ…v­ü7ªàÿR+àwÞká¿žná×
œ�V\jilM/w�²mË¢~.U}¼Š ©†V[½·l+²Ë@óŒ »f‡UO|Ý½D´’ˆÅô1¶/‡„¤N’a‹ý“<IGÓP¨µÄ?n¶ÿÑê™ð¯Õ…æt§\2²R~+÷ß¿5Á³S<ÿ@†vÎ®úÇ^ÿjÐ'üÍ�îjýzåßÎÍLøãsmüÖ»­øú\+Ä!«M/ÊÊÀ¿~a:?¿ˆ™]ì9Ò—U ¶[€5ÛÇ,ób[Æ�¬ÀŽ«“áü%­0¶EŠýk"Zt’t4qH�>›«e]»ÿ‰hE“ê3öˆ@'ñSÜ·1Á�=ÞÀ³‡RìÞ”`d`îò~Z­H±×ŸˆhþÌðZ¯êo�øæ[Sø/§ÛøÑÕã¹ÆàßÚ±í¸‹Uy,ãÎyTôÕÛqF€íÄÐLoVä=@ó<bE@2-3ÉV­ 1a§q›‹ñbWÅ}û'Þ…žPHf‹]K}?‰ˆæ«×ßúFm[?»®±­ý¶¯÷ØºÞÅ­ý¾øxcÎª¿ûQë^""šqqÉ²]çõŽâí‰¿ÿAÿÛ»-|çr�³ÿfb§mó×5ä�N \•h		�÷YSp•$°ÁaW-	 Àªl!1–È1#C´â(\PÉ,öO4×^'ÒPQWž¥«35s­D´ÂÔ¥¥‰/§û·;@šcÃOßŸá“f8´Ãcãº¹Q¾__¤Ñü°ÓjWžf·ù›È~¡�ÿøNp¦qqÙö«ª§Ò’Ì¨wÐh�èÌö�ÙE ½"�Ü~‘e þ:ù«"Zæª˜>ÎøSç ��ko¢…k§™mk]È¿f"ZYêíúìºÑVýí"Òþm]ï±s“Ãc{R<w8Å³‡2dÉl¯¿õøÇ7û5ˆˆèã©ãx;¿¦ÕÕ¥Mî?;ð7;øÝ÷[øíw[x{¼ˆÓý‡R‰‰ûN¢Z"RUØï šÐ±J „êù1¹^Î°cê
†D+„J¬ P‘f¢¢½^´Ç€Xv <móR˜ˆ–=;[ÕA|ÀOµ,¸×8Õÿ3�dxþ�·%Ø4ìf‚ÿ{ý‰ˆhÏÍqb\,ž)ýg¼À;ÓÆo½×Â_^ìàÂT@ÃKüxìõg,¹lªâ¯Ìz0l—€>�ƒµ©h\ ç®eQC]À_Ñò¥¢¶€q…ëMœh�e$æñ˜w%¢•Á~[|°Õþé(‚"KÃ‚-Ã	Û—à³�dx|·ü3! �P®H±×Ÿˆhþ•X@£
¯uÞø£smüç÷ÛxålWZ=‰`0uè�«ÿ´¼*êÁ€ü}åõŠ¿ôm”-Ý‰hÙRÛYU4ª�D½¢ENœZÊ6¦þ8€ˆ–ÿÊ¿­âÛtÿX6€ÞLðØÞ_<ÒÀãûRlZç0PÿÆ‚þ´«Z€ˆˆæ÷ÜlÁ¼õ•š<(¾}¾�ßû ƒ?9×Á�®ïh,û·6­V°ý©ùXvºŸ#«’€��a› (š@ó,�LÔex¬ Z¶êíWÄF­ïmGl){±¬ ÑJXù Ó&§Ë+Çuý›†=öoIðüáŸ}4ÃúÁò”VØ„ÿø‰e)ª}.Í¯ºtÜ¶•²ÀÿBKñwW:ø?Þoã¿žnã‡W‹˜èñ‚Þ¤¬ÆªÒ2Tÿbêâ`ŠëÊJ€¸#€|«|›ˆ–?U±‹c— ’ŠÂ‹Ô�?œ@DË—mÕ—zA«01­1ø?¼3Á'LñÔþ;6¸™à?_OøïHDDóË†üÕmá§'~÷ƒ6^>ÝÂ__ÎñÁdˆÏª¬ÿÖ*ÀSò
pÃ/ÉÊýó`2Qä½@ã,��RT¿|Vt-Õ…o¬ò·VCHœ¸4�³YŸRmHD´üÄÓWuaaSþ'«Í¡woö1ø?ú ûË°K=Ù˜î('1aÀÀŸˆhaØâ¯¥\ëàß¶ùûÞ•¿ÿAß:ÓÆ•¶Æa}©Ä,È•ÿ•Il0 u[Ç`U	`;êØl�ëåÛq€=3¬ Z^ÔŠ`m“Om$.¾› u€Y"Z.ì|§üW�üdhåŠ=›=¾üDGl`ÿ6�Ñ®UcË½¥—ì®­jvÕh+û¨ÎµS¹âo.æøƒs¼z5Ç¥v¹·T\ø·À¿ú$ž–W¨ø¤ZýmöNh­×Ø`;¤ÕL€˜`€hÉ•�Õ«bC ¥¡*½‰MA
åLl"Z>êàÝû;Ðikúgý·Œz<s0ÃoàÈÞtf¢^”ÇÛqìõ'"Z8u|J«&Ò÷'¼|¶�?8ÛÆ™¸Í_5°Õ¶“«Êþi°€ßæëÄmËá€6ÐY5@§¬ˆ¿j$Zê-=ÄA�‰Ãâ{ …íÖâÊZ1SwD´´§*»h´þ}»Ð(ª—Þ†à¡Ý	¾üd#& ¶Œ¸9Ûù%U¿?Wý‰ˆö=§sT�s­q±ƒo�iáo.åq{¿Þ¤,.å6«L•ð)Kô€¼˜ÞX–v4.
Ü4 ¶m Ã	¢eðÇj­ÁÞ²ÿêœíÂª=ª’‰•°^‡ˆ–É”ÿ</ûýmÅh §\õ·ÿO<�ás�6°i¸Œüm@©Zb*kK‰ˆœ]RÚ9×\j…¸Íßï¾ßÆ©+9&;ŠFRî`\\ù_Ý‹q‹Àu˜iÈìy¹Œ9f·‡ ¢¥æbÌ´™(´‚†Šºrõ¿Ü#€WÑD´$g§jÊ'W´:Šf*ØµÉã¹CŽÚ ¿mÖÍ.û§¶ÊÀ"¢EaçÛÛUSÿÛ…â;—;øÿ¾=�ßÿ ûþûÒ8p:NûgÕÿ*UõÕPÀ¢	t† 7­1øO®Klˆ�¬ ZªÕÿj€€ëEèM\Ð¦ŠdU§Ñ’ˆ«ø Ú`rÚ®[F<îóxêþŸx Å“ûÓ™Üd«S–üsÊ?Ñâ±¥"_Ujµ‚âäÅþ�÷Zøã³œ�,ÐHý‰ 8íÍ¨º‡CÐ-Š¸;À8‡-1sëDa1�Mÿï…H&P§±`&WË‚"Z4¾êù·²ÿ‰–bÛˆÃ§Éâ¶Õßæa^Š9+ÿ,÷'"Z<v…˜‡j>€7®øæ[Óøíw[8=ÐL^Ê•«à…ä`ÉûºÀ*ò†-µJ€j(`»ÀcD‹¬ª½	Pµùp"Ò¶€ =¶c––{2UGD‹zfªç“L·ã)*Nð?°5ÁSûS|áH†§dqò¿©‡ÚÊ?§ü-ÛîÏµ6ÙßÎÙïNøýÓ-|ët¯_/Ðð‚¡LÐªVþi�±5D›&–”C[£ö —Ëd@|Â¯GD´ø,Ö‡À–Ï²DEzÒ€ƒ³�h¹O “¶D´àlp_ÜîÏU	€ ¸o{‚Ÿ|º‰Ì°k³Ÿ	þM]îÏàŸˆhñhWÀœ�ø_ßšÆz§…w&
dNà\ÕóÏàmWäåPÀÖz-EÚPÀ¶=ˆªç-&)wÇŠÿ•�ØZ[¢Ö šZ_À¢Þ"Z³,ˆ·R@;×X2j�þ®Mi,ùÿÂ‘l+—
ì˜z‚´% ü-žzÈªÿöö¥vÀ·Ïwð_ÞoÇíþ,10˜I\õçÊÿf�}(“ q(`£Ü 5H$ˆCcÀ"&Šˆ_ï;kH¡šˆ‹—äKpOˆh­°3ŒðÈ[P§I+�eÀÃ»üä³<s0Åæu~Î® qU¡JÑâ¯üÛËåVÀ;ÝŽCÿ¾­ˆC E$Ã•Š-}qÉ±öC´6jú{ßÜu«øî
@´Xâusu‚¶
uÞþuv=n¸DD{²`Þzø; Ï�L°yÄáàöŸz(ÃgÎ0:èæLù·„"¢¥Qï²jIÛ÷&^>ÓÆ+g;¸Ô
èI¤Læò—C7T8«Þ«æX@g¼
è­ Úuœˆ}õ?Vÿ'M-±/±™¾%¢9çÌNù·’þ¢(ƒú‘Á³3üøS<¸3™	þM–”¯ü-.íŠü-	›«âÂ´â»—;øÎåïŒ1Îl”—Žu›ÑL%@•¼�U$M
XfŠ—~ºÈV ¢Å¡V­¥*û¯Ml(Ê ¼Ð&¢ùVíëäÀdGa»�ö:l]ïðÐž/<�áùCiÜ;Ú.Zír‹?k "¢¥a‹´¾JÞNæŠW¯äø“ó¼?âÇ2›ÉÂ™nôQ• ÕL€öº² üg -.Û
ÐNÙ¡g ¨¢WD<NíÊ¼Lù²Ó–ˆægåß!nígÃþ¦Z‡ýÚéã”ÿgeØµÑÇàßHµòÏ3ÑÒêžúq:àÏ¶ð'VúßèñÏÓvÑ-Õ‘D• ½@>="0Ô ZxVáo›l[IŽ% $ÄÛÀFµ;€íHD4¯+ÿí09m[Œc#‡wx}(Ã'Èbï¿±òQ«°D�Í	 "¢å¡€w'¾s)Çk×
ÛÚ})â–L Ð³µÇ�÷~H&±m#ícŒ?ˆžÂ© Õ$�%âÞ€ãBDóÅùÔ¦ÛÓŠ-#>ùûô#Ú�bóðì3¾%
¬ìŸ× DDKÇ‚±rÏèò¼Ü*4þûÎ•ïLŒçµ3ãÞ‰îà1wò±¡€iÕ
ÐœúµY „®Ý~ˆh!Ä[¬ÀªþÁb["šWváh�¼­üO·ÊQ¿{6{<u ÅÏðÔ�C}e¨o;Øê¿µ	ØÅ&--;k[m–­MÀw.uðgç;¸Ð1ø·¶ æJt×³ Ð \È®°Y D´ˆÊ&ÛjÎ6Ñüˆ«ù¶òß	˜n+voöø‰§øÌÃØž`¨w6Ò��µÚDDDK/nU�“Ï·
üñ¹6þô\¹í_Óöp¯Ú¶¸`Kw= µ* �[æ½å0@)x@´Ø˜  ¢y]ùoYÏ+ÄàþÀV�£6ð…#<v_�ëÞ2ÊŽaðOD´¼Ø)zºP¼u½ˆÓÿß·½[�Áª÷Ÿ tÏ¬‚¤QULÙ8àŠ*¡Ä@D‹‚	 "úØ¤ZùO<0ÕQLw4ÿ?ó‰&>ÿX;7úÙc«ÞR.-¿Þ{™*¯]ËñWs¼?©q`jû¶/õ¥Kí±e ¢š0¬p9�´I»XCDŠ	 "úXb@_­üÛ6–°éþ6ðïs�5p`[yšéeà“õæÑDD´ìzÿ¯æŠ“;øÓóm\n4«!­\ù§�û ‹¾ClèXÀårW "Z<L Ñü¬ü·5&ŽÙÊ>ÿh†gëù’úMþDDËº÷ÿìTˆ}ÿß¾ØÁ•ÐpRöý×Û¶Ý­®ç~µ¢À(úl[@…›|Þµ³«‰ Dô±{þ-ø·müöŽ%øì£>ÿh{·”¿í`	‚º´”ˆˆ–�î˜«P`2W¼v=Ç®8=`ûE÷:aï?Í»�í!@Z€\|»lÀl× - & ˆè®Õ}ü¾êùÏ`ß�¯|¢ Û6t­ü[ðoÃþøs&"ZVê‰þ¾:§OäŠ¿½ÒÁŸ_Èc@= VÍ[Õ0@*¹Ná:@:)�iÎ ZL Ñ]©Wò[Eh�±Ïÿs�føì£ìÞ|‹•þŒ‰ˆ–¥P-¸Z`2qðŸ% ®u½6€½ÿ´ ™§2Ø�m Óe5@\ý'¢Ç ÝÓÊÿt(‚bÏ¶_ùd¹ò¿e¤kåß†F1ø'"Z¶le?¾TçêkmÅw/uð·—:¸–+Òº÷ß^–úÎÒªbÃ ƒí,aÓÿ@Þ£H& )„;-0& ˆèŽ•+ÿ@h+š™`ÏX‚Ï=’á³�4°£*û·�Û< ÿDDËŸÔ3×¸Ô
xw"àÜTˆ»µX€íàÂéÿ´�B„&P4�dªª`5 Ñ‚a€ˆ>RÞgÓþ0ÊžÑû¶$øGŸlâS§»aåßªˆˆhù²€?nÍZ�¯­ÿÿ½É€Kí€`'yg+±ÕÆì\þ§ù~üU�;›`»½@Ñ¸6à‹ê»´àc�hÞ1@DÉ.Û9Ð¶òïâ´ÿÏ=ÖÀgÉ°etîÊ?ƒ"¢å¯Þõ¯žþoCÿÞ™1Ék«ÿv.çÊ?-¨úæ€¼ð½@z½«`vm�ˆæ Dt{U_¨­ü·ª>Ð½[}µòŸa3Wþ‰ˆVdðß½°:Þ±­ÿ
¼~½ÀDGáœÄÁ€ÊæZ(Uq‰	èô(|�½-Hª¹u
Í/& ˆèCþÙÊ~«­hd‚}[R|þ±,ÿ[«•ÿé�qåŸˆhENÿ76ýÿG×r¼v-�o§vzg -ð}9Ðæ (#¢Ç?3"ºm MSí€Nìßæð3Ï7ñ¹Ç²9=ÿ,û'"Z‰Óÿ5žè­Ý¢°
€<&ÆëéÿõqK}giU‹#&b©a•ÈÊ¡€öÀãê?ÑÂ`wÝø{´;Àµ‰ß¾G‚Ï<Úˆÿlå¿®°GÏ�DD+–�Ï'ràýÉrúÿt$V¶ÔwŒÖ–*	`;X" > ™}"Z<¿Ñ¬rA(®êÛè©¶bÛz�Ÿy¾�cŸhÆ·k‰çÀ?"¢•F« ßÕãÿ\˜Vœ›˜h+r(�aüEþx”ÙÕþ`Ã {4¾Ø\ ©« ¸Ð@4¯˜  ¢È®-¨·iÿW'ìYØ¿ÕãÓ7âêÿžM>VpåŸˆhå‹¬
\ïhÜÀª kÑ’±ž“˜ (wˆÐØ‡Âß	Ñ|c€ˆföƒ¶žÿ"(&[Š-£ÿ¹&þá'Ø½é+ÿÌÈ­¼éÿU@[¹
Å›ãÞ/‡ÿYOW¹ò¯3Ç-¨jÒ¬ °€^EÞ«ñí¸ú_Ï ¢yÃ!€Dk\ÝóoƒþlàŸ]ôíÙìñÂC6ñ¿�û·—§	«`Ù?ÑªXh�¦ðúõo�çhYï¿+ûÿëíÙ‰û�i;ØËLÀìúÍV ­a³+ÿ@^(&¦6;üä3eÏÿÞ-]+ÿ®<¶«m”ˆˆV˜zeß^ÙÄÿ7¯xýz�	Ûþ/öþ§ÿÓ"?(«Ý êí íÅWËÿ,8$šw¬  Zë+ÿ…­ükœè¿cƒÇ'§øÂ‘Ý“ÆãòpŽ�?Ñjb¹\+û·€·Ç&s s@Á­ÿh)Y€"NË—º€ˆæ+ ˆÖ WþÇ§ë¾üT?ó‰¬Êþ�ÿ\ù'"Zºc©«mÅ[ãÞŸ(0U(WÍ `ÀE‹ý¸¬ªëJ€¼W�÷ÈÌn œPI4X@´†Wþ§ÛŠ¢ ¶Œx<s°ìù|oE¨æü±äŸˆhÕ­ütp±p©ÐÊâ%žî«]Ùˆ_¨€VÐ=€ïØƒ•×"Dó‰ Dkˆ­êX õ– P\ŸR¬ëwøìc~úÙ&ØUÿÆŽ–þ­žó¿ÍTsåÛ—ÛŠ3SŠ©¢®xAHKmfê¿% !¾ØÛõŒ "š¬  Z#, ·ÒN[ñŸÌË•ÿÑA‡#{S|þÑOH1ØkÛ ÎÏÅ"¢ÕÁâ§z…ßbþkÅ›ÿbï³V/K,õ�$êž`Q
3SDóŽ	 ¢5À.ê,ø·müZÓŠé60: xêþ_<’áÑûÊà&ðgäOD´jÜ8G­Á¹"ö±ú¤Ï -­¸Òos(,!å«Ù uöŠˆæ D«\\ñ±•ÿ „PV ô5%úûì£ž>˜bÃ:WnûTMæê?Ñê•˜.ZEˆ;À-;¶òÏÕ¢Á ÑZ(ýw@ÞÑ¸¥_ü¿ðp†§¤q  UØE`ø3ÑND´zÙV¶úoU ¹j|¨Z­‰––-DX€GÜÀ.H¤{�‚¿¢��¹5¢ULªÀÞVýÛyy{ÇF�£fxîP†më}e•öR­^v¾·àß^ìm^Ò²b×.¶DY% ˆh~±€h•Š;éb§ÅöÍT°q�Ãû¼ðP†Û<²dvg ÏÞ"¢U«{ußVýã€B‘Û€êüoÏDK¢îõ¯v°Å’ 33 º�!¢�…I_¢U¨N˜Ûê¿­ü[éÿ¦a‡ç§øÄƒömõhf?n‹ŸÃ,;Ñš`3a&óò… ´ìX2Ê‚[¦äµ	Ñ¼c Ñ*.ý·çÍÔý=ÀÃ{ü½'xhw‚ÞF5ñßNžÁ?ÑjW÷åV3 ì9@¸"DËBì÷·@½@We Í& ˆV!{¾´•³~PðØÞŸz(Ã#÷¥è‘x!Ø)Êä Wþ‰ˆÖ+üšâ Z» Ä Í+& ˆVëåtˆÃý,À·‰ÿ?ý\žÜŸÄà?"\ù'"Z«lÀD0Y„øv�æB+-õãÑªmP±ãöÄDó‰	 ¢U¶Ýßth�Áþ;S|ú‘r»¿‘þråß*Ò¤HDDk�õýOçVP‰µÅÖj#¢eW_xÍB4o˜  Z%b¿¿Lkˆžvnòø©ç±ôß‚ÿxŒ0ø'"Zsâê³C b@âKœàf÷Z'Zru)JTT´ŸDó‚» ­pq?_öô_�qeÿV�£fxþpŠMëÊ?óV§¼¸ãÊ?ÑÚf ã9pÝv‰	³‹¬DËŽÍàƒ“h^ñOŠhÓzUß	:…b|:`Ã:‡/?ÙÄO<ÝÄØ°Ÿ9–Óþ‰ˆÖð‚j×ê©­ú_ë\k—3 œ·X§e¡~˜J× î@4¿˜  Z¡ìÉÑPÀT«|ÊÜ´Îãñ})^x(ÃýÛ|ØÉË?{›ˆˆ¨, ´º* ˆ–K $åg ÍÎ  Z©¬ôß†þu4ù¶òÿÜ¡_|<Ã}c³—s±äŸÃsˆˆÖ,«ëÞòµ](¦
…:™ù8g Ð’«§6“Â“õ {Œ†ªB –,íÝ$ZÉ˜ô%Z�âs_yíþ%Ø³ÉÇ•« èäl¸ƒ""ê~‰­cåü˜øó§CË÷¦$šw¬  Zaâ‚¾+Kÿ5 }ÁØˆÃ‘½	Þ“Ä¡vA—wKDDk×�+û=^°.4R‡Ž*‚j<†«´ÔânUÿ¿½í:
—ÛÛß1cEô±04 Z�¬¬?·=œ[Àð€Ã³‡2<s0Ã–ÛË©\ù'""º•†S 7-+Èì9ÃvY#ZVl>E^¾ðJ4˜  Z�œ•n: ™	îóøì£<¾?ESÊ²h¹ –ÿ­yr‹$rO"èM^$®þÇ
 >gÐrQU HHQõ©ðñI4/˜  Z!ìÂÌú5;pmR‘¥ÀC»<Ž>˜áÁÝ	{ËgFk¨�'""Â- MïÐë%^rõŸ–%ú‹ê…•�Dó†	 ¢ îÍL½ýS´ÚŠ-£?ñt?þT£ý³Ñ~=Ô‰ˆˆhf5µkùÔVýû«
€ÄU ÕÇøôAË‚V3 r…+´œÀ'Ñ¼à@¢eÎ‚y[­±•ÛºÉnïØèñôý)ž ÅØp™Çkç@šØ…ÝRßc""ZÎ¬ï¿7qñÅ#Ä
 >uÐ²b©P½°üŸh^±€hH¬ô?WŒO£Ÿ{¬�/?ÙÀöõ~æ˜Øó¿¤÷’ˆˆ–«îç« °òÿ>o3 ¬ÊÌvàs-ÕV±÷ß^ÔjWxuC4Ÿ˜  ZîÏƒjeÿåíÞ†`ÿÖ/<”áá=)© “—ÇX• ÑG±ÔqoR¾Xò˜3 hÙ©Wÿ‰hÞ±€h™²R‹éóAã�¿Ý›=ž¹?ÅÁm}�úÀÙã‰ˆˆný¤2· /Î pHê] D¹ÒJK.öù@r@
«¨»¼Æ!š7¬  ZÆleÆ “-`]¿Ãs‡2<u0Áè CåÞÍ|N$"¢»½øë©* l[Y.´Òrc�¿Ë—ú^­NL -cÎI,ío¤ÀÎ>& Ø™ÆV€ ¶ZSõþ3@DD¢ûiÂVý­ÿßæ $q@™PfF™–Lýø³êG­Vÿí¥ûqÉ­ ‰æ[ ˆ–éÔÿV˜n‡Øç¿ok‚g¥8°-A_SÊá¸Zöq2ø'"¢»a«þ=± |±
€Ù‘²DK/–þ³4…hA°€h‰‰n±©ÿ‚<WLL+6®|é‰¾ôdë‡Ê4¸ý×önfðODDw¿€Í pñÅ»j [Êhÿõ KÄ¹ Õ\$"úøX@´ŒØÊ¿MüW{ò`ý�ÃC»R<w(ÅîMåúŒMýOª¾M""¢»eC mõ¿á«• –ÿÓrL°€hA0@´LXÀoýüí¶ÆÃ�Þ—âèCvnœ-Îäª?ÝÕóËíÓ^Êþ›çÈ¨¢Ü jÀf¯5-�¸Ò�f 0	@4ï¸†H´Ì…MþWlvøäŽìKÑ×�¸€•hZ• Ñ½¨ûû‡á†CêÊ÷1Î¢eÃ®u,øç. D‚ DËeu¦Zq±¡=`ÿ–�íMâôÿ4:Eu¬­Ö,é½%"¢•Æ’Çö4“Ä ¿?léqLËæêòy…«ÿ´„¤«ü¿#p�ªÀ»¼ð!š7¬  Zbq+?_öö_ŸÔü?¶·ìûß±ÑÅà¿»“Ï�DDt¯B× « XßpèM]hcõ?-yd 7ø©êËh…h^ñOŠh©U½ÿA�\±eÄãÇoà3�fX×çf&3Ç>MFÿDDôñžrfô¥‚ý	vôyôx‡N(·˜µç>ÝÐb²¾c+ýVúŸL*’)�­ ên1È‚ˆî DK\’i½ýSí2Àß¾ÑÇžÿ'¤Ø0äâEX]úÏÞ""úØÏ;]o7°­×aGŸCOR¶T×D‹¯þg¥ÿ®U¾æp
¢ùÇ ÑOý·�“ÓŠÑA�O?’áó�ež�úoÇÍ×sO­/±àßcg¿Go"ÈUc5«Íh±§RÚ*¿õûûi�Ÿ¸BfJQêID4?Z-±Xâ/À¶Q‡çexhOŠ,-WþãÔþ•Ñ<©ã‹©šØ3à±«ÏÅj {Þ±* >íÐ’õþOZ þW—þÑ¼â. D‹,>—Ù°%-_z‚á~‡C;Ø–`¸OæjâsÍçóO|ŽQ ó‚½÷$èKÊ'¦BåÊ+-ŠzÂ¿ÏËÁ~²œßÏyDóŽI^¢EVô³©ÿ×&½M‡Ç÷¥xú`Š�CåÐ?–»ÑBŠ¬‚Xú?Öã0”º¸3€U¤±âš–ªÀ‚ÿÄ œþO´`˜  ZDñ¢JÊ²þ"(Ú…bã:ÁÑ‡²¸íß`ŸÌ´Ø1ìÃ$"¢ù‡©ÇDól˜?Úlësí±V A¡Š¢z."Zðéÿ–t²•þ¢J L•oÛûb 3RDóŠ	 ¢Ed«-E Ú�²
`ó°Çá�	Ú�`dÀÍ|¼>–ˆˆh!Y+@Øï°¥Ú m»¶ Ñ"²™GÖÐ.§ÿÇ
 "ZL -’¸ª·ýSL·5üÏLñ‰Ã6Ïþ)²ü’ˆˆö	Éž�Ê,³=/õ'‚ûúìHÐŸ8äA ±Z€¹hZÈÇa\ùÕ¶Óü$ÈœÙ D4¿˜  ZD±ô_-	€ØïÿÜ¡�îIÐäÔ""ZÌç£®·›‰`ß`™ hz ¸ -Þ1& ¦«[ùgàO´ ¸ Ñ"ènaËÁ@°g¬,ýßºÞ#±®¼:–o‰ˆh�Ÿ“ê ËFôzÁþ¡÷]+b€jŽw¨ž½ØƒMóÍVüÛC1Nÿ—rø_÷ô>îˆ+ ˆ˜]?ÕSÿ¯O*)ððîÏL±}½‹Áÿœãù!"¢EÞ`¤!ØÒëÐL Œùi‘Z ìHËÁ– (�¼"ZHL -0è�ä¹brZ±aÐã3�døì#†ûgÿ-IÀ‰ËDD´XÏM6 0T»Ø³Ñ¦¦`CCÐL%n	¨ñDðø«v™$
¤S?)åô{ìqú?Ñ‚a€h.°¬çßžèÖõlõ8²/ÅØˆ‹3:ödWÍ ""ZLÚõz$s8´.Áî�¦LåÎ4|z¢ù+ü¥Üi¢Ý:“€³
€à˜q"Zp<§-�˜Ù¶©ÿAÑÉ5ÿ�íMñÔÁ[GýÜ’>áÑ’ìNS6žÙ­à¹�Y|m:´‚"W�-lO£ù{à•/^�¬-hL	Ò6àmëI›ÀÑ‚b€hYYž“-ÅH¿Ãó‡3Ù— ¯i+ÿ‡/Ù…ÑR^†jàƒ#)žÞ�Æj Û¶Öv®a…ÍçãÍv™˜Ìô{èõhÀxKcU$ND‹	 ¢…¢³«+�Ø¾ÁãÉ)öoMÐ“Iþ�õ¿±÷Ÿˆˆ–dF�bSÛ¢V‘8Á–‡×%ØÞ+èKI�¤f²šæáñæhE;WlìõøâŽ_ØÑÀú¦Çx[ãÇb�$oD†Û - [-iwŸà²T°kSûþïó1øïÆç8""Zju'šüÛúIñÎD�7Æ&«mjíéË†´}œÇ™•ùgN°kÀáèö�^Á�þ®ÀOçåÎ l‹$ZPL -Ô¶E™á¾oÄãÓgøÔÃF»§þÛËüñÑ³ç­®tôhÓã…±WrÅÕwZxózw°Ý¸E ÝÃÃ+^ïØ@IÓŸ:lÎMqÿh‚f<v_‚·.å8w)ÄÁÉÖ’w¢°™ ü‘Í+¶ - KŒ�:<¾?Å�m>–¾Ù`ìýç_-ö”d�–õü§8<œâ©)6õ¸øœesÖtÏ�¯Xú\ë(úàñ)ž^Ÿb4sX7èðø�OíÏÐßtŸ²áÉÕöÈü‘Í;† Dó½­�]( ·!Ø±ÁãÀÖ»6º¸rbfzÿù“'"¢eôüe€`Sÿã–€‚ƒ	îðØØ#hx‰åÿ±„›O`t—�/‰;Jh¡m8<¿)ÅS£)š¶XòÿgïO»ä¸î<ÏówÍÌ—X±I�÷]¢vJ¢”™%euWWWWUW*kÎ™sfökè·2§·ìªÉªêêÜ”’R")Qwàbß÷ bu·åÎù_3‹p€ 	„›û÷“éˆ@„
"ÂÍîýo·%=ÿpKßª¥›�òÂ«(|ùsÆÏ°î  ë]úŸIW—¼&BI[Kß}¢¥­3QÐ× va“/iw7Ò·¶%zfs¢n"-¥å÷µƒl�/WT•%V9Ýqzd:Ös[mïD«-%ÓNOíIôÄý‰vnŽ•ÄÖJYVMpÖ3 €uENY^h%õÚ6›èO·õÃgZÚ4UÆÚÊS¸™ †O¸GÉ­&]-Sû£]m]\)t|©ÐÅår€�
hÎÆý<U?S©eô½´¥íôØl¢ïìhiÏdµ.HEîÜé{O¶ueÁë�C©.ÍÛî_êÖÕ'ü¼ë‚
 `�nrvsËó²
`ó´ÿŸy(Ñ¶Ù(|ÌÚÂ‹ŽW `HÕ·¨zÛc³±¾±­Ž´ßS’�[?öOZHÍ´"}g[/îlkS;RVø³�}–û0ðë'!°y:Òrß>^®« ¬^RÀm²è¶=²ê\ÛÍSNßx¸¥ï<ÞÒ½Û^bm rv?«‡š©$Ò£³‰žÞœhÏt~Ÿ{6máþ·Ñ_0†R�¬·ªÇ�¹/¤§ïíHôÂÖ$T‘Ôý:Ði9=¸3Ös{“°~²ÙIq]ÿOöX7 €u`Ñé,“WŠPîÿý§Ûúæc‰¦º.¦þó/ h�°1³Òì‰HßÛÑÖ×¶$êDÒ•´Y]Ëî À�DU©o|'m�ˆBùÿã³‰fZ.®gê´¤wFzá‘–¿?V»ek«r ”Àú`O¬ƒ:@GN»·Fúîå ›ÉöZ„ÛúÜd hJév=„}k»œÚþƒ�mmnG*2&º·ª›ÉYÜèç'÷^ýÂkK;Òw¶·ô½-íì®m=ê5Q˜=1Ø±)ÒŸ}­­?}¾¥í³‘–z>$SÂ±€Dœ€ÛF  ¸�PTöý¯¤R;)K×ž}¨¥½»ãpàà�Š{  )êý˜Í°ÍÜCS±¾¹-ÑS›bÍvÊàöJîC–—Å$®g?>vbÄrîµ£éG÷´Ãð¿ÉÄ)«&ÿGƒÇFe€Mý· ž¼?Ö·«VÊ˜c'€uÅ5¸ÝÞÿÜk¥ïÃQ?|¶¥>ÓÖ–éµ»Uè_c÷ hh@°òí¶»­ïîh‡¬®mî¬€V Ü(«ßŠœ6…Éÿ‘~°³¥§6%šŒÝ5?Sõò¨~[WMvÛNíJôäý‰Ú‡–J¦Ìì	àö  nçäªéÿEy|Íwžhéé’0)Ù&×†Þ^e €«‡Ú±€?ÜÕÖOïm‡Š€0½½(ïƒ´`pêÿ•Ôk2‘¾»½¥?ÛÝÁ#ËþßL	¿ý\ÙÏÔ¶k©lé…GM´#]]òêeœ
 Ü®ä¶ÿ`ÕçÛ£•8mš’öÞë‰ûmŸu¡O-Íªç’ý 4�»® +´ äE[çs�_±‡¥ÞöäVUÆM0`<Ùz'q–á/B`hït¬¿|°«ÿæþNh¨}^ÅH˜PUWÚÏÑ¦)§<Ó
ÿŽå:rÆk¢+EÝH…+,¸uä&�¯òÂ±~®0˜f¢-=õ@"Ô÷l‰8¯ 027j¶ßêÆN�oŠõÏïoëÏ÷ttÿ¦H>§¼aŒFWöü_éaoåþ?½·£?ÝÝÑ½“ñje€¹Ñ	 µºjÒÊýí}k¯´5Öý;"MO”	–P!pwþÓ€‘D p‹Êiµeï?õÚ³#Ö‹Oµõý§[áFUcZ- `d6x³é8ÒŸìj‡`À™å\g—
õ¼—“•!ƒ»Ñ_4î
û>ÇU¿ÿb^¨—y=²)Ñ_<ÔÑ¿} «=Sƒ3‘nòï¼î‡g×–H_Û›èü\¡rõ³²%…Šà«!  |UÖßïÊãjž{(ÑÃ÷ÄaÓoó ì-½ÿ €‘a¥ý6÷&”y+¼W±f®8¹Ë’&ìwIÖþVµ`<ZD,óß+|þìœ,þý7÷uôüÖr›a™ ÝÊ0ÿºÀÖTÓ]N˜[,tyÞëâ|Ú/;Ýò$& ·† àV{ÿmàQQN¨µ’ÿ½»bíÙ…c M†Dê 0JC m»mäª�ýÙK…>ü8Ó¥é¸-U7IwÝñI¾úV[>õ^K©×¶ŽÓ{_[ÿöÁŽžÜtmæ?üØ¸[;e©>DifÂé…GZzáÑ–6O»P}™ç^‘»¹¡‚ ®E p,«¿ÒW(qÛ4éôôƒ‰¾þp¢­Ó›~ ÀÈ	m§p»«§.åúÍþT¿z«¯ÓGu­"nJŠ&¥¼#‰äìÏQ	0’ê8�•áy™ø˜i;}}KKÿâ¾®^ÜÑÒl+Rf?_±¤žZ"ivÒ…JË{·Eš=Y	hÿ»Ì n À­öþ^+}¯ÍÓvì_[ß}²¥-3Ñj´:Dº‰H F$óo›­ú¶vêb®Wö§ú›ß÷ôû�S]]öš)"Íœwj�vr=©ˆËv� `$ÙZ'÷^+¹×æV¤ïm/Ëþ¿³£¥�Ý¸œæ?8Ùÿ+üo\_M¹³j¹|jO¢™IŽ[¶ŸÏ¯ú÷ãŠ
 à+öþoßé™=¸+½mEõqzÿ £’ùOªJî:óÿê©~ñV_ïLuq¾ÐDÇiÂ6`—Ò	É'Õ£®§`dÔmûñ¨�|`*ÖOïmëÇ÷´ÃÄÿ÷Y§ÀO=PÒ*¦»‘¾õXK—æ]¼Z„Ÿ?f ·Ž  p“7¼PjVõþ[äyï=±öl�Ô©{ÿ-C‘ý ŒFæ?TµUµ¢'/æúí©þëï{zû`ªùe¯©®ËæÊAlÞ)Y”ºçÊ{f›WÑ‘œmëÍ iÚF³o_v\}?'b§mÝHßÜžèOw·Cß»úüjÀíüï]÷wØ1€_¤¥óWýñ“LýÓy™xq‘
çiÅn- ÀÍ¼PlÈM&-®xMt¤glé�´´m¦ìýþ% Wgn-ó_ŸlsüB¹ùÿÇ·úaóoØvRg³çÙþ¿°Óo2©3'u.JÉB¹ùí IµâäFÙHƒ›pËúÏ§^WR¯ÍíH/íjéŸínëñÙ8iÉ’:@°ñžÎØë>›0éV+0™ Ü<* €›êý·G¡^êµe:Ö‹O¶õâSk½ÿ†Þ À8eþ-0nƒp´lm.Å+N­+RÞ-7þé¬—·¿+—¢:XN%@c„Nk©:9ìûmn›þÿÄ¦Hÿæ�Ž^ÚÕCÿŸ»žßâëÛ	vmŠôüÞ–ÎÎ:v>/O¨¾&2À—#  Ü¬jA´cS¤§HôÐÎ8TØbÉ>Nï? `Ôzþ¯ÏüÛæßJ±û™Â¶k†Þ†~9HíKÕ‡ìySRÑ8€J€æ”ü»2ëßYv¯éØé‘éX�ÌÆúç÷¶ÃÄÿm�róßÏ¥v¼–µ_×¯åºY ß|,	3 Â,€«¹ZI¤NWe;
€/D  øa-c%Œ®ìýŸÝéá{Ý»Í­nøÃð¿: À8eþþ’°¯·ãs©5ï¥R¼(õ¶K½åL DyyJ • Ã+”Ü»2«n€~áCÿž©H?ÞÕÿŸßš„‰ÿÆ¾�öÜ;±ºá,€‡«Y §êŸÊ9fäa"À|! À°M~¯/õ²B[¦]8~æ…G’p müÙó 4î™ÿš}¬.÷Ï¤hAŠúUÖßIýÍRÑ-ç„–·‡Rø6Ú÷«�3Ö;Û;‘›�õƒ-ýäÞ–þôž¶’*Õß+ÊÍÿ�Èüá,€{ÊY NE¡2À¾NöþÀ—#  |YïQöþožŠõÝ'ÛúÞ“-m™ŽVoFôþ Æ6ó£¿´*×¶�”:µ/—�€xYZÙåCK@ø+8`(•™§^^¨Ÿ{mîDúþŽ–þù}mýpg[NG«›Ó²õÒ]øº>3`s¤çnéì¯cç²kg¬ãQ„À¨!  ÜäÍÐzÿŸÚ“è��ñêdäÐûO  `œ3ÿ×üÅÕÛjf¿Ä}”­Vúï¶JùTu:@( u»±¿­+¹™sßt¬omké_ÞßÑŸÝÓÖÞ™òÆ6ÚÙ]Èüßèë³ ŠÍÈÖfP]|. Àç›	½ÿ^Ý–ÓÌ¬ÓÞ]qèý¯³$ôþ šèŽdþoô?2ÀÉ©e-™ÔZ’–w{¥›ª @½Y«‚Ø¸²Kx,ç6ÐÏëÁéXÿjO'ôû}[K»ºkyþPýh=ÿwsóïÖæ˜én9àÜåBü(U?µÿ/g_%às  nÀn‚½p”f'œ¿?Ö3”½ÿ”” šêŽeþ¿è³îùOm8`U	`+¤|F*ZåïC%@8kŽ@ÀÝ0ø-µö•0AßËæú=1›èG÷´õ?<ÐÑ÷v´5•”Ï¶Â ûJ6¨ru€U–Äåí¡]qh˜ì”Ñ
J€/F  øœs^ø0ùvÓT"Ì_´Þ¯Avbò?  )îJæÿóþ‡ëÙ ±SÜ“ºg¤hYêíòêo‘ò‰ª=ÀžVHÞ¾>ªî¨ðs6ÌN…÷Ê
†?¹)Ñÿcï„~ro[NÅ«›cïnh|Æþ÷¯«.Ù¹)Ò÷Ç:~!ÖÙËE8
ÐZÂÏ8ƒ�Ï   Ü@T÷·YÀd¤'HB„ÙÎ·¥ÿ6ð†…	  !6"óÿ™¯!.7ùÖ/I�êï·:[Švµù¯X_õqzöã`IŽåÂçyMÄN÷LDzd6ÖŸïn‡žÿGgËëõC4øxpÀÌd¤MtþJ¡W—Ó° VËNœU   nY¶›ŠM¸íNH»·F¡ÿßŽœ	•¹—‹Ê÷ v–ù¿Á6n¶‰Lœ¢\j_vŠWìˆ@¯Þv©·Õ‡ @TT­ƒžûîm	É‹ðÖ¾^Y&¥Õ¸üÍíH?ÜÕÒ¿®Jþï�¨"Ea=4\õƒ³ ì­­Ï¾ùXK®x½$ÓÑ³6¿É‚Q˜å4T_<0  ¢*"nŸnGºok¬Çï‹µ}fíØ?f   šb2ÿ×~AÕ	UæßÚêB¹¶UßMK¾U=/¨`#wË¿�–ÉÏªRÿpÔ_ìtÿd¬ÝNÏmNôg÷¶õÏïíhS»ŒÙ,¤º×Øb/×Ìˆ¤{6Çzdw¬m3Qù³>l_00D  ×÷þç>DÄï�µ’²–¾zÿ×î$eäœ6 ÀpšÌÿ�¾°úMõuÅ+NÝóR¼èÔŸ•Ò-…òMÕJµ®÷®«q îÅ75Ù¿ÞÀ[¹¼=B  lþ#ý`g[/îlé…­‰˜ŠW7ÿÆŽøÚ%OU±im™u­Â®-Qh×<x:ÒÕår–“�èd‡�¼Ö  Øð‹�ÛQ23‘žß›è‰ûuZåMÓ>o  †ÙÐeþ?óVoêÝ›mä–¥È*V¤ØÊÓS)Ÿ”òNYPPpË“ýí4£´°1R7qÚ=kKÇé¾ÉHOoNôƒ�-}k{[÷MD«ß–~•ù·*�&¨ºÂÌ¦§HtüB®ŽæººìC|©—s� ”  7Ìz8Ž-˜¬ŒÌÊÿïÙ©•ØÂÈËyzÿ Ãmh3ÿŸ÷ÅÖoËÖt% ¸©uUÊ»>L·x¥ÓR‘T÷lû…Š€/Èø;¥!
d%ÿå†~ç„Óv´õÝ-=·%Ñ½‘¶vœf-Õ?ðwÔ™ÿaçªìýÍSeåæ™¹B'/:?_„ÿ–	çTÜàô `\  ª‡-–2‹·\(ù¯Ï•µÍ¿áÆ vCŸùÿ<ƒæ¬ßßŽ´“ŠVY`s¬: œPWØ©ÕQo8§ƒß.W—ÃWsŒ,ãï½›ß­�H›g¢�ñjs¬ï[ `{[N¯múÃÜ…jÒÜ°SŽg´…µ›Uüvª¢ÈÃÆÀµ `ìÕ½ÿÖg¥-3‘¾þpK/<’hóÀÒmøê €Éü_ïúÍ{õ5¹Ü©µ(Å}§öe x¥›¥þ/oƒ=êöß>0ô=üwÕD�†:Û½öÖþ¯ü„ø³R÷4}çµ½é[Û[zqGKßÞÖÖž)›2þá�Vÿúïo’:øaýþIìÂ‰ vrÓ½Û"Íž¬~Æc#óƒ Ü @Õûo7	Ë„<°#
›ÿçö&ê¶ËÅ”-¤èý «Æfþoäºcçì¸@« Ð¢T,IQ_rYUÐ­ªZå<;] n%°Ù=UüçN²æýàê×[}íõ1Åö½µ�~î½Šð(ÿûÚ±Ó¦¶ÓžÉH»&"=6ë»;ÛúþŽ–žÙ¼¶ä·¿'œx$ÛænE]¥iÿÛg#=vo¬C§c�¸�‡Ÿuû|+.«$€qG  ¨"Èv-
¯-SNÏ<ØÒÃ÷Ä¡ L‘õ®Q%q €ñQo
Ã&·Jîžº˜ëÕ&dþõå»òpd`½±·Š€ùòÔ€ÎE)›òå©³¾<>°]M}¯6ÿ…9ì¿Õ†Úô¶Û=?üÏé1ñ«½í™~ûÛô—_·WV­[lWë§M-§ç7'úööVèód&Ö–v¤Íík¿Ñö÷%!¢Pþ�ÃúcpÓBÛÂÚ…µqZ%çÙË^óË…N_.Â0ÀvRVKÐÒ‰qG  c/,Š²wlº…²±{·FêV7Ln €¦dþ-«ßØÌÿç±½íàª¯9ª²ÿV°zr@OJ–¥¢[Î°GÜ’ZmNXÊ¼3è—'Z0 È~þ{Ô��/r³Aƒ›úg¾®ü¾îÉ·lµeøÃûÕb¤K]+uïDáítâÂÛ­Ý(Lò~K¢ïìhé[ÛZ×LñÁ_füí¿?$5šô3ð%ê*Íz=g'8�¹\èÝÃ©Ÿ-ÂÇì9Æ Œ­º‡Îzåì¦h}c�Ü“èémžºf¼Î~•  Ü\Ï¿ýþØù<@ûÛ×{zçpÃ2ÿ7sR@�¸®6|QêÂiÉ’- EÛ+M¤þ„4±ÍiÓ§¬ãÕ+|8ÍÇvÕ¹s«YpÛ$[  î%_ýŸ	S¯\w`AùþuŸ´~ën|ÚÐõY÷ª‹ÿšêû¥Jî—úì7Nê¶#Ý?éá™DMÇá­•üß7kSKa¢¿eü¯?ÂÏþ[Ãa€£�ñ¿Nýofx¯ÄŽ;ÜêôäžX;7Eá„ëŸ?ŒUÀÝB  cÍ¢ÁY¯ìýß±)Ò×NBÿÿD»Œ"Ûçéý 4¡ç?üÛŸêß.3ÿs‹…&;ÎüßLE€Íé±™ +åûˆ,û?)µ2).¤éÍ‘6M:ù­‰ŠÄk%—®ö
Í§^Ë™ÇåYlàš{7|mà^½§|N½³¬$mçÔ[ñ~ÝÇ¯|¼Ø¬OTÙý©V¤nä4•Øq}ÒîÉx5 °· LEj_·É­gD*[ë�Ç£.¸ì(ÃDÚ¹9Ò}Û£°¾›_)Âk$¬íÆàßø" 0Ö¬.+
õR¯™	ëýOôìC­�-œ"<7M @3ø*+]7íßzþÿÆ2ÿS-¬ø°ùotæÿ&+BöwµEÀ)±�oÜ?ãuå‚×Ì®X/<ÑÒc÷'jm–Î¥…>º”éÃ¹\G2­¤¶[®6äƒéûêH¼P2>Tm¨ë3èWÏ¢/?¾¤0SÈ‡Í|•È¯‚ Õ&¿ÚèÎ X-#¨# -§]§§í�‰ÃãÑ™D÷N:mëD!80™8MX€ qe?ÿuÂq~#šñÿ"ƒ³ ¦º‘žØ“èØùBO5¿âCP&®þÁhñÄ¸" €±(69·%m™Ž´g{ZT—ÜÑ   ÂÌ¿M4¿~Úÿ/ÞêëÝC#œùÿ¶ù/Ëö×&þ[æ_+RšJË¹W>+mÚéÁm‘žÙìôÔ¦DO^ÎtàJ¬+…íßÉ¦ãÛÆÜû0%ßŽÕ³µ€eÓË·k¿¯«¬­ ¿Weûãºµ ²·N«FpNIT–åÛÇ?oåéöùV•lhG.”ð?0é¡i+ó�ôÈl SŸ³j¯³ýå?A™ñ¯³þã¦Îî[€¥ÓRHìœºXèØ¹\gæòr†BuÂ0® `|§þÛM\>Lúß¹Éé��±¶mZ«¡ey£”1 Œ\æÿFÓþëÌ}üÙÈßÇª²ïÁÊ ÛßY/¸µH\éyýá@ª¹¯—Ò¶¾õtK?¾§­ïmk…Ï-¦…–si1WhXÈÊö€Åúmê5Ÿ)üþjßk)÷ºÞZHË?“†Æ}kA(‡òMÛ`áV¤™¶Ód\¿-�é³·öû©êítiºåÂc&”ýÛs¬ Òd¢�å·@Âç	Ùþ0Äà³ÇÉ5?ç^áuðô‰ŽŸ+ôÊ¾¾ú}¯¸cÖÀ¸" €±Ú- PX‰˜´ww¢GwÇš¶éÁã°X 4:ó3ÓþóÏüžPzoãv9ÇgqÅëÈ\¡K=¯Ì*ìcë¥ïhÏ®X{&þœ—l£ŸW}Ûð§öÖ‡·vŠÀ|ßk1÷áóö<ÔŸ³L|Ý»?c€v¹±ŸJê·eÿÔ@@`6"Í´¾x“ok“úÀræ@9¸ppVÁXîú?G EÒì„ÓýÛ£PåiÕžãøz ®G  c§îéÏ«	»3±ž¼?	Óbg'£Õò±Q;" 0:™ÿ£Õ´ÿ¿»Á´ÿ±Éü�ÐP}kEN3©Ÿz½w8-ûÀåô'ÏµôÐ}k»nû÷šiÙ#ÒöŽý›G¡-À’¡Ì¿jXk°òÿµö€² .õ·hUî¿Zê_nJß²ù7ñ}*Kú¯Íò×ÿ�ø÷¨Nìïß¾)ÒC;c}º-Ò•¥²m£ôÌ Œ# ßéÿ…ÔëKéñû=|OúÅêESb Ã˜ù?ñ%ÓþÇ5ó½z²¾µt[NK}¯¹¥BoNC%€eòÿÔ·õàÎH“mW¿WÍøkÎÒ»sÿ õÀÕá�Õ:¤Îò×ÃÉòßº2Ñ#=v_¬Ãg}t"ÓÂrùoiA˜ü|?�aG  ãÛP½³i*Òc»cÝ³%‹„4÷!jÏâ	 0¬™ÿ¿ùcOïñiÿëU	†õÙ¿¡Ód[Zîy½8•ó6È6û-=zo2òõäþköþwák¬O¨ƒ×oöù–ÞÚ?è`5çÌD¤'ˆuì|¢“]žÏË×“+�u¤
 ã†  ÆN}OÛúóº‘vo)Ïˆµ3cëÏ 0¬™ÿ_¼Ý›ÿ+‹…&Úã3íÿv+lÓg• 6åqÙëƒc™ºÃ–í·^ñvR& ê©þõ¿g}dßà¡,ú8Î¯2ø=(·˜kúÏ«)¨ÿLÀí© ö½· ÏC»âPíùÚG}­¤åÇ¬´  cˆ  ÆF]>—†³~}ˆï½'Ö“{ÍTGÿ…çg {æÙkÂ2ÿŽžÿ›QgzÓª`¢ãÃ¿á›Ÿ¤JS¯ÂI/=ÝÒ£÷%¡ä>¯ž_©·zÌà5ß¨2c¿ú?pÝÿÞ�>~£¯ë«¶Ø÷Ïæ=Ypg×æXï.´u:RYÈàºïÚÀ0ê `üzÿ{
Çõl›‘žÛ›èk{M´Ëª€p£_;	 €¡ËüÏ-T=ÿ]zþoõßÖ†¿Å6 .+®,Ù`ÀL­Ä)òk• öûøËŽ¾.£�áSWuÚëiÇl¤{¶DÚ6i¹_Ã ù&bÌ ÀX±þº¬(ÔOJ&Ÿy0Ñ³%šž°Q°ÕÍ¼z  0Œ™ÿI›öOæÿ¶¦Ä×• “V	°âõæ�´œ¡PU<r_²:/È60ŽµA­-èìHÀ'îOtü|¡OOçZZ)ä½SL(Æ Œ»�Û°¿ÍS‘ØiëL¹Ê²©Éáóûå Æ™ÿa¨HÃ< gC o¥ C«®ê´ ŽU{ZâçÔÅB§.åºx¥lè´Ë™À¸  €±`7l»øg…W'q¡lÏŽH;7­Õû‡ nî €ÊüÛäyGæ(+êÂV™A V�N4^ššˆôÌC‰N\,ôû�ûê…Q ^‘‹”3 c„  ÆB(ã³‰¾…4Ñ‘Ükï®$œ`7tnæ €aÈü§™”W÷§ú%=ÿCU	`±*š¥ Ø÷Í¾ÏÛgÊêO«Áœþú€�@  #¯îé/
6û;&b=vŸ‡9 õð—àN  ¸KÂùô=ÿöû#gs½úAª¿{½¯÷ŽÐó?• ?´J€{“ð}²uDØLR	Ð¨ïo¨Þ¨>fÕŸ÷o‹µc6ÖRÏ+ËËõa8í�ã 0 `|¦ÿçR/•ºméñû=²;	çÀÖ=}Lÿ lÄtrc÷¨ãò�ùÿÅ;ý�…ž[dÚÿ0TXu¸U Ü¿=3„ê?ÃL€fñu+@7Òží‘îÛéÄù\½|­B€ý?Æ Œ'Î‚µÒÊ©®Óc÷Æ¡¬�ØÇËH>ÇÀ  îú´·6íß6ÿ÷FyÔßâ
Óþ‡© ;ýðYé¡]e`µ ¦x°Qó œ œöîŽõÈÙX—¼¯äás.±Õ"U } 0òê(½-´¬ÿËtÎ‚í´ÊU×`Y  w³çß2ÿ'.–GýYÏÿûGR]]òabùt×©Ÿ•§Ô0«fã*ì{2Ù)w�¶–¸wÛ@%@õçøþ·ºÊÓ¾WV	úØ}‰Žœ+ôþ‘LË}©�”Ï)ª¡€QF  #ÍnÈ–á·éÿm§­3NìŒ439ÐìOß? àngþ¿hÚÇžSnþÙ\n|%Àü²×>îk%-ÄøÌ@%€¦`¨g,éc	 GvÇ:|6Õ ýÌ‡ïu•ÿßÈ/¸+ `,¦ÿÛcfÂnØ‰Ú™„èïjïÿF‘ €±Îüÿâºiÿö°(™ÿá©¸¼Pè�ƒ©ºUõ • ÍdßW›ë`¯±{6Gš�ŒÂk2~6ú‹î ýéÿ¾œî:Õ�õðîDïŽÃñuD˜éÿ €¡Èüw�bWnþÉü[%€ÂL€Ï«PX8|nÔÛ¿y:Ò}[#íÜTž�s Æ ŒþôÿÂ¦ÿ{uÚÒÞÝV_;ý£¿H ÀÈº•Ì?=ÿÃepS?Ñq!Hs£J€û¶Åá9ÑÀ	Ìn–šl+œ°gG¤cçrõª–NÀ¨# €‘fý\EaQÝr˜Ò#»#Ý¿#å_õôG  p3ÿƒgÆ×Óþÿö™zþ‡·À¾77ª°oëKÏ–ó…jõ™òTŸúuhßŸ©‰H{ï±êÐX¯r Æ Œ¬z2¯±d™•µéÿåç™þ ¸[™;†öÄÅ"lþmÚ?™ÿæW¼{¨¬°„Â÷žjéÞ­QXo¬nü«Ÿ�Á#ŸëÓ �-ôÞ!NÀø  €Ñžþ/¯nÇiûŒÓƒ;cÍL0ý pç7Œƒ=ÿ¾�Ÿ-3ÿ÷F_ûŽ�ùo|%@WZ\ñzã“T+i¡~îõý§Zaºüà1Ã«çÏc(O°ì¿}Ï¬
Ç‚tœ€q@ñ3Fzúš•=^6ùpú¿á‡ °Þê{Œeþmóo=ÿGÎ•›ëù¯êù·sÇ­5Í²ÊÖ¦vý€2ûYr!‰¥™®� ;ŸëÓS¹æø6IQèÂi ["mâ4 Œö@Ýéÿ…WVxMuË¯½6ý‚éÿ €;ÛóoÙÅšõü¿¼/Õß¿Ñ×›Ÿ¦!kzþ#zþ›\B^úë¶më‰û=`3†b›=T>‡ìÿðVrÜ¶ÎDºo{¤�›cu·z ƒ1ª `¤§ÿ¯ô­ÄKÚ{�U ”ýÿT   îVæß¦ýÿò�¾Þ?’êê’™ÿ  óßH¶)´µ…}/g&#ýð™–þÛouôüÞDÓ.¬?V÷–Ôþ7ã4€®ôÀöH÷o�4Ñ®‚xß>Œ.f `t§ÿ{¯,÷á†üðî2ºÛ
‘]¦ÿ îî´ÿE›öß±²õsT\ÓÔÙü0Ó¡Ê ?zO¬ŸýhB/=ÛÒŽMk9µúg€ýCNèp Æ 9õ�¹œþ¯rúÿ&Ëþ—“yK3 ¸Ý{N�ù·ÍD?ó«ÿ~9ÐóoÇÏZ¿1™ÿæn{©´Tµp|íá–~ú�¶~ü\K÷m‹Be‡U}\?iCÞÊQ�ðÈîD�ÜSÎŠ²
�0Ä“]F Ééÿiá5ÑvÚ:•Óÿ'×îÆôt îÄ´+>t¦ÜüÿÃ›Ÿ�öŸVÃþ¸53ó_ÿþñûcýì¥®þä¹¶vmYÛ%²al†Á×Ÿ½-AôÈ½±�‰C5@šeŠ"KÙÉaô ÀHNÿ·,ÿtGÚ³=¥ÿÝª÷ŸE `½3ÿÆ²¿6þÕÖ¦ý_],BÖª[ü³4îCÍ[WXæ¿èû°9||O¢?ÿF[ú|[»·–›û¼Ux�ùož¢:ÕÁ^§»6Gšªæ8PÄ�QF  £7ýßûpæòD'Öž±ölO4Ñaú? `}{þCæ°ç_ªx£Üü×Óþ­çß6ÿ¡›™ù·ÍáJZ~Ó½7Ö_þ¨ÌüÛÑqµ„ÍƒO°Wsù"ÞZF�6OE¡ZÇN“ª_·Ó‰QBwFŠEm­À¢ñ–õ·#yÚ‡éÿu?ô €;5íßÊþ™ö?:™ÿÈé”=ÿ–ù·Í¿eþë™ VqX�Ð\ö}´þké°‡­ëÓ €QC Foúá•f–y‰ôðîX{ï) ÚÅÝ²5ŽÒ. Àífþ£µÌ¿mþÿ†iÿ£Õóo­–ù¯zþ-óÿãg¯íù'óß|®êÉ±76;ÊGîˆÃìŽ+KEXW&õÀ@Æ`D�ÅÈñ«Çº8íÜ…È½ýž(. àNdþ­çßŽúcÚÿèeþ¿^eþ­çÿÞmQXO�ù!G6ZÀÛcÝo³£ÚR–•kG6K5T `$„þ¬0ÌÅ«;M¶�¶Í:mšZ»l²^.Ç & Àºgþ™ö?Z™ÿzÚÿ¿ÿQW?²iÿ›×Öü­ïyÍ*G÷ìŒuÿŽX“�HyQÈ¹zÀ~¡À:# €‘aQÚÌI�DÚ¾)
7k‹àÖ¥ÿ  ÜªzFØà´ÿ?›ù·lñ4ÓþŸù÷i5íÿþD?ýF[?~~màÓþGO4ð:·×øŽMQ¨ôh'
Ã;mïokÈ|ƒ¿N`= ÀèLÿ·a-Îk¦….;Àú¹ê#—ê>/  îDæŸiÿÍCæ¼Õþ³ª‚tÓ”ÓýÛcMuí³eåh¢ £ƒ  F‚­ËB  šâzÿŽHìŒÃûõ¶Ÿ. ÀÍ"ó?ÈücpÆ‡ú6O9m�‰43áÊ“ ì¸@þ™0B `4X€÷¡4Óú¶,ûoU öþêSlú?E  €/Aæô‘ùÇ5?Ó Âi ;­’4Ò™9¯4·J€ª
ˆ` F IQŒ„ÐŸUH½Lj·¤û¶Gá ëçª£ºìý ë5íßz„­çß†Æå9G„�Â´ÿºç÷Ö(êiÿÌ}u‚È^þ¶Ž´6€=;MÚi yYeÊ:£‚  F„«m>ômíÙkótÙÿo}]ö9²ÿ €›Éük=ÿ/¿_öüÿñ“þZÏDÏÕCÝÂ´];íÿß¼ØeÚÿ8ªfIUï†€�U’î©OÈ}¨2Ï!
€@ /ÿg¥Y±4Ó²ãÿ¢Ð¿Ul²Ï ð…÷¦ý�¦ýã‹tZNìˆB5©UúØÏ‹UD‘Tp F  4VÂV¥ÿ™÷šè8íÚlíX“mwÃ¾.  >/óo�ã:h™ÿW÷§ú[¦ý�TÏ¿mâBU`´–ùÿÑsm2ÿc,ü\¸µ¤Q;)×’î°aÒ‘²<SÛj’Ó 0  Ñ,ÉŸZ¹¦¤™I…~­û¶Åj%Õ¾*õ àf2ÿýÌëäÅ"lþùv_ïU=ÿVl=ÿvÔŸõüÓVÖÌž÷LODzì¾dµçÿž-eÉ }ÞÖ¬Æ—µÿ$±�(å´cS¤©‰²¢”¥$F	 4—Eó­ËûpÁžhÇºok¬{·ÆêvÊþÿð4z¶  7Pžÿ]õ„Ûý¤��.3ÿÿðf_ûŽ¥k=ÿŽžÿQ˜öo OÜëg–ù–Ì?Ö~Nìz`kÊz»¿y:ÒŽY§M“‘ú¹Uœ®Í”ª‡…MÄ@4ž-Ølg}Z6ùß¦÷Zä¶FÔ p³Óþ_ý Õ/ÞYËü3í„¦ýw™ö�›c­ Ý¶B€Í–²ë€µœ2W
£€
 4šs6ýß‡¨¬múmó¿{›]¨Ýg¢ÿ  öü‡Ìÿ`Ïÿ¾2óÿÞ¡tõx¸ˆÌÿHdþÃ´ÿû2ÿ›Ör`”ýcíç¦¼ ØµÁ†îÞR&–ìz°Ô÷«Ÿ³@ E h** ÐxvÎ²²`û¦H›&mÁví1N  |Qæÿ·ÖóÿN_ûŽ¤ººìÃÔo ØÒzþ)ùmpæ¿Seþ_hëÇÏµÃ†Îöyöy[CÐó�mŒl]i V]ÚiöˆP ©¨ @£¹*þj»ÁoŸ�BÄÖXU€ErÔ øLæ?ZËüÛæÿoªiÿ‹Öóß)ï+iµñç>ÒðÌ?ÓþqS?<×¾Ö»-§][âðè´2å¶û'…T?d”  ¡  ±Êa-åM~&‘6OEšî|~#¿8 ÀPOû·Ìÿ‰‹åæÿo÷Ãæ¿žöoÛü3í¿¹™ŸzMu"=~?ÓþñÕXÀ®-e€½oÕ¦.¡­ÍG  �dÙËâØ®“ØQ-N÷l�410ü�” àf3ÿƒÓþÉü7™ÜöÏÐê/eÀ°•”³¥îÙâÔi»PYšx«,%ý�f# €Æ²J¬ÂISm…3|-J›üD3à p+™ÿényÔ™ÿæ!ó�õ^c†
Ó	Uí¥k•§@Ó @3£üáV.Ð�¶EgcÝ³9R·µ¶í§g Æ[�ù·Iÿ®º=;Ÿë•ý©þö™ÛüÓóß,dþ±Þ?OåFß+V™íß:í4=áÂiáóö6„vS4 4–Ea- ¦ÿÏ®Mi àúÌ?ó:y±›ÿ_¾Ý×{dþG™Ü	~à:2ÑqÚ2iv2ÒJZ&ŸªËÐH Ðèm^Hí²üß¦´ÚÄÖÁçP  ãÇîƒ™ûý¡3¹^ÝŸêÞ,�ú#óßldþqÇÀª7vºÔî­qh7=s¹(�ÕÚµhÚ¤ÑØ\‹ÀÚ¤ß$VÈþo›�B¿c _õ=À2ÿQTfþëÍÿ/2ÿV=f=ÿvßzò�Ìü/®Ø±�N_¸¥Ÿ~£­?ßƒÛlãfŸ·jAþ|Õ’Í—²u¦ º­2¸hkP ©  ™œ7õ¬ða2«Ef7Mº° °�ÙBŽ> Œgæ¿ÔUgþõ^_÷F_ïLµdÆ®SÑóßD¶±§9Äk¿üþXÿþG]ý›»Úµymik=Û¬ðUÎj6_Ê~®lÞT§…Ó l•©4EÑ€FòeY–Á™�ŠB%@øY ëÌ¿±ÌÿñóEÈüÿê�¾öIuuÉk¢­ H™ößX–Ù÷©×T'Òã÷'«™ËÐÖŸgó�õÒm— 6oÊ*‡¬ý”*šŒ  š9�Õ2ÿ-§ÍÓN;7Eš¼føµ~ 0¶=ÿn-óoÿþþ�róo¥âË—›¦ý7K�i�«¾kë¿®3ÿ?z®Mæëú³6¸’´ùR»«ã¦»m* ìt ²ÿh* hœzúªEa­$Ë¢²é¯slÿ`Œ3ÿ©×±ÁÌÿÑ�ÌÇ)ÍËžïÍìù—óš™ˆôØý‰~ò™ÜYa†D$m™) 6À~­µ„õ&šŠ  Ã.´vÁMm±—K“N»6;íÚâB5@½˜cQ ã›ùÿôôÚ´ÿýÇÊÌ¿•ðZÏ¿mþÉü7wÚ¿KË
€'÷ÄúÙ�ºúá3dþqgØz3ÌšÊ½ÚIÙnjU ¶Þ´ ¢}.TÈ¯4 4Žµ^ù¢¬ °Éÿö°÷ ããs{þ?HõËwÊ£þæ­ì¿]žã�‘ùotæßzþ§»‘žÜ“èÏ¿ÑÖŸ<ßÖŽMôüãî\g¬
`fÂiªãB@ 8MÄ¶	ÍQgx
°´[åæß­d­+T P— cÙóo™ÿ}‡S-õÊÍ¿eþ3ëù§B¬±™¥åï»/ÖÏ^*{þëÍ¿aàîÈÏàuËÉ$qÚ:S>zY9�ª¬ €fá@4Ž¯æ Øót¤-ÓT  À8fþ-+g™ÛüöüÏ/[ÙnÙóo%ã¹g�ÞD–ù·û>~ýá–~úB;lþ§ý‡m‚þ¸CêŸ-_½okÎºò49je©@ÃP€fžàËž,‹Ân›u×T 0˜ FÓ-Oû¯{þ7úÇ-gþ-¸Ã´l¸j°”ýjýÿ¶æÜ2ãteÑiÅ†RU ö–Ž 4 4ŽE[í§$’¶ÎDap=¬…,  ŒYÏ�ù?Â´ÿQQOûŸ¶iÿ÷%úé7>;íß2°Üóq7Õ•§öh%…–zžF3 @³z±œÙædYÿí³Q(4á\ÖˆsY`Ô|åÌ?©ÿFfþ�}¯ŸÚë/^êê¥g?;íŸï-îÖÏåêÏ]ì´m&
«BÍ}!‹G†³ ª*  	  Qê!N¶ù·©Î6¸Î X  `´�ùÏÌÿS{ýä…rÚÿÎjóoŸgà6ŠU�lšŠ´y*R’”©®ªHš„  Á6ýaÒjá•Ä.LvÞ<eG±<g#¿@ Àº#ó?¾™ÿÿã®¾ÿ4Óþ±ñ?›5Ëú[ÿÿÖ©»p"•ýÜÖ3 €¦  €Æ°A«ÎŽÿK¤-��ŽÂ€P@   F
™ÿñÍü‡iÿÏ¶µ½:êo¥oGÿÒó��•Ä
åÿaýYU „* ¾1h hHï¿ä‹ò(' eÑ×m3.,ê¯Í  4™ÿÑ÷e™ÿzóoø‡�R¯,Ã é¨ Ø£c3 
¯–M   C  �ZÚ£ÝY›ÂjX Àè ó?>n&óß±ÌÿZ, Ø–é�âòçqÓdªê
  iØ>aøUY_ø�m'eô5T $kY
   ÙÈü�¾[ÍüsoÇ0Ì *ìûa•têÒ’‚# €Æ° «EZ-ë_W    ÍEæ|�ùGSÙuÊª ¦'œ&».üÞbÌ D“ @#¬Î C ËìÿÖêÖÁç0‰ š‡Ìÿè#ó�fÏ¢*×›ö¦Ýr¡RÅW}˜à«Ž¤F @cøªÀÎ ¶ì¿µØ)  €æ"ó?>ÈücdN˜�Âc¹—+ËË�oôWÜ h„ÈY™•Wî}ÈúÛæûl.¶a2kÕSHC  4™ÿÑGæ£`p…­C·ÎØZÔéÜe§^ê×~Öi@ @cXöß¢¬–õ·
€‰öµ“Y ÍAæ|�ùÇ(±YT³“Qx$IÖ¡«D“ @3Ø€êVkØ4Y¥üC À«ˆ\¨  ?2ÿ£�Ì?FÉà¿;m™rÚ<íÂû¹/×sÂ±Uù•_Ž  Á×ƒW’òè›À>Æu …Ìÿø ó�Qd•¨ÓÝHÓ]Þ T¢¢A `ø§ÿWç¯Z”u²S–]%±[ë÷_+  12ÿ£�Ì?FÎuëL[ƒÎL:ÍNDŠ“ò(@{°ES @#XtÕ¦®ÎN:ÍLDŠ¦ÿsÁ€áGæ|�ùÇ(«+ &ë
 ;`£¿(à ÀPsÕæ_Q °r+‹ºÚ –Õç0y †™ÿÑGæ£êúD“%¡l-:3áÂÚ´% V&@c*š�  †žõúû¢ìûŸî–‹¸ †™ÿñAæ£.œ<i­%5’ò¢¬ š‚  †–ÅQ-˜Z_T“Äiv*ÒÌ”E\×â±´  Àp"ó?úÈüc¬fRy¯HN�¶�…ùT°µ*‡  )  ìÂº6uµŒ¸ †™ÿñAæã¢NJÙÑÓV`-©$¢Ð4 0¼ª+ªE[-ºÇQÙsf T på6tƒÇk7úÙÈìº]µÅÚï�ÉõÊþTÿF_û�¤Z\ñšèØBÚ)Í«)Ú\ÏƒÌ?ÆÍõUþíDê¶�Ú-®uv«ï‹À0# €F  >õf-¬wØ¼¡Bæ|�ùÇ8‹#i¢ãÂ£È=s Ð 0ÔÂ€ª·Ê&­Ö ñÀy+aBÖØ�Ì¿½o�ì}ëÌ!ƒ;ÞÈü�>2ÿëÙTN›GeÇSÏN8Í¯”kU{Ø�@*0Ì  ,PÎ à `#ùë2ÿö¾çV?O%ÀØ"ó?>Èü³©&œ–ûe»*Ð 0Ôê£÷^qâ4]Ï <ÀzL7ô«Æƒ-nêM¿eýçŠÐû¸i²|ÖÕ VI%Àxfþm0–]žéù=dþ�kïmq"ÍL”ëÒËR?+¯}å<€ÏÎ † ½âš
€ò€:0À&¸óÂ¦ß¦œ¾qöj¡7>Iµ°âõø½±öÞkëL´Z0x$Æ-ó/?ŸëÕý©~õN9ðïê’×DÛ¦f—ÿòœëwc3ÿòšžˆôÔžD?}¡­=ÛÖöMåÅa¥/uZ×^+€QµV™êÂû+U;0ì `¨Y¯•/|XÖß"­¶€¬7!ÊÊÅ¸£, WÏÚ°o/“öÉôŸ_ëé““™ž¸/Ñ¿øN[ÿü›MÙ0$/¥Y¹!tlÆ«ç_Ò¡³¹^Ù×gÚÿfþíûk�§öÄú÷?îêûO¯mþë©èl€0.Âºt2
kS«Rõ¾�÷å” _U Ãˆ  a­À…òâúcõû îlæ¿Ž³Y&÷½Ã™~ùN_¯’êàé\§/ê¶¥MS‘¾¾7Ñ¶Ù(dÃë”J€±Éü÷R¯cç‹°ù™ÿ£dþG«ç_aØÙ“dþ�ë* ¢ð~–³.E ÀÐ³5¦e[IY>ºúqoG®¸ð9 w6óoY½¥žôöÁTÿñÕ•PÞ=·X„þÿ~îC0 Í¼.Ïwô/¿ÛQ·eÙ�²¼M%ÀÈgþígåÓS¹^Þ××?¾Õ×‡Ç3-®øŠ¢²ìŸ¶­ffþë�zž~ Ñ_þ¸£Ÿ"ó�ñ4XáRV¦–C “¨¬~‹¼—«Ë¡€!E  Ã¿ù�ÊÍ¿emRg%ÜÝÌÿÛ3ýý›=½²/ÕÉ‹y|´e*
€ss…~ÿQ6{VðìC‰vÌFêR	0Óþ��+ôÊþ~¨Ùw$ÕbOaóoçcgôü7:óïåÃ&ç™ýôeÏ¿½Æëžÿ6=ÿSv�´Ù&ö°÷­]• 4 ÷ôÿÂ‡2ÿNâ4Y•ÿ¯nþ0Ü•Ì¿-òß9”ê?¾²¢W>HuñjQ¶ã8²þåINóËÒ›ÊJ€?{¡£ùíN8#Ù>ÏL€íù÷Ò¡3ÖóŸêçoÙæ?•"uæ?³©Ø×eÍÐ¬iÿuÏÿ_þÈzþ[«›CÏ?ÆŠ½62û¶&�h;M´£ð¾·“r¸Ö¡ `¨õ¶©ÛŽè­6 óÿÎ¡LÿðfO¿Ý_fþ§ºå±G¶©¯7ƒuÏÿù+…^û0U!§­Ó‘¾õX¢íÌÙÌÿñóE9íÿÝ¾>8–iq¹,û_�ö_“ÐÀžÿk§ý¿ôl‹iÿÀ »W¶Û‘ÚU Uÿh
 ZeVÑúÿ�ºmzŠã�†ÿrÎ*€;�ùÿ/¯èÕR]¸Z„Í¿õ=ÚæßúÃŸ«Î;C�½à÷Yí°×¥*F:ó¿?½fÚ·s]ÏÿFáøÊ™û^3íx�ÔÓý+¶>-+ ÊŠ¸zÝÊuÃŽ  šaMÊgw?óoÞãò0è(ý³ÌÿÀ9îuÖÃþ¼UØÇ/]-ôÇ�Óð«øæcåL N±Ì¿Mû?Â´ÿ‘ÊüëÚÌ¿õü×GýYPÐ^ÃÜ‹�j}ÚZ›ƒaU«@ ÀP*3‰åÃ²6Hl¢uÝÄB¬À]Ëü‡)Çq¹ù¯�öûÌßSUØ/vBÇâ
• ã’ùŸ°Ì¿Í„`Ú£3ÿ~ çÿßÿØzþ™ö\óz©Þ–ªe@Ì* ì};�Ê3 
@  C¿1IªèjÝc`82ÿŸ—)¦`4�ù¯Ì¿½®mhç“÷“ùn–%¨V+T)@C ÀÐ©3‘!Ë¨� U�Õ5Ï°á™ÿý½TŒFæß²Z–ý'ó?zê×r¨¬sR’(õ÷³uôâSdþ�/zý­BµmÇÝÚ) ƒ3 B+ÿ€Z 0ÔÂ™ªQu�¥ ÊÌÿ�þ~C%À¨dþ¥ãçszþG5ó/ivÊééÖ2ÿõQôü_°>µa™ñZ…* h
 JuìÔú©,ªZV D!àö„L¾_ÿÌÿgþw¨hfæ?/³õõöðÙ\/ïëÓó?‚™{¿•™ÿ¿üqWß{²µºù7VÚüU^ûÀ¨ªg¡Ô�R{ytWg \ûqj 0¬ `è…
€Dêp
 p[V3ó¶8‰Ö?óÿ¹ÿ{œÐ¬Ìµ2Xé{;_„Í˜ö”iÿ£–ùß4åÂ´ÿŸ¼ÐÖKÏ´´uf-ó_O6p»{N©BÓ Àð©�ó>dÃ) Õ ;_zõid%€[b™üzÑßÁÌÿgþw©hLæ?¶¶�*“õÉÉ2óÿËwzúèx¦ý—­XLû•ÌÿÓ™ÿzóoÈüŸ¯®P­¬�Ä…Ó3êyõs€aE  Í8g5!Â
¬wæÿ]Ëü¿±þ™ÿõª¸æØOÜ1õÀÕ:ó¿Ôó:r¶ÐoÞïëŸÞëkßÑ\KÕæ¢ãÂÏF¾Ž?ØàÌÿ³­ð´×i�Ì?pËâj�jsS¸.¢	 `è{¬ÊS ¢Ï `
ÜræßÎjßw$ÕxeE¯ì»s™ÿõ¨ ùîdþ-{eßó<÷Úw$›Ëþ[ÀJÏ‡ÀŒeþ³¬"Éµ·1Boòeþ§Ë¨ }KÉü_®>=gð5f'tZHó¡: <€J ' hÈ) åƒÍ p{™+ã~ïH¦x«ÊþCæ¿{g2ÿŸûõ0`¨2ÿ¶é«3ÿ‡NçúÍ¾2óÀ6ÿ}Ûü[¶<0¯�ŽDc„Ì>™àŽ\§ö,ˆÎ¿5† ­Ppý€�•'‹Pà&§ýW[Ëª¿w$Õÿùòu™ÿèÎfþ¿j%@1P	P0pg2ÿÙ@æmó¿6Îž»ÖñŠÆõüW-dþ�uz}¼o•ª�vù°
;[»†
 »o1 Cˆ  †Z([d pË¯›ë3ÿË^ïÉô÷oöÂæÿè¹\Sw)ó«• Ûf"}ëÑ$G68ÀžÇtþý«o@�ù_î{¬2ÿ¿~¯¯OOåê¥uæß‘ùo°�ùwôüwëT4 ¥ºoªž`™‹Vb ×– ° ¾¼ç¿Ÿ–™ÿºçÿü•"lþïvæÿ¦*§rÎëÊBGÿê{�°µë€}�m*Ö}Ú^x}p,{|b›ËüWÇ®’ùoþ´;B÷™ýì¥®¾÷=ÿÀ:½ÒVß³×Z;Ì °uª÷ÔºbŠ # ~®¼¸2ø
™ëù·iÿoöôò¾TÇÎ•=ÿ3“Nizw3ÿ·R	�8§›"=»·< K%À™öèL®—ßï‡Òÿ�ùï{µ2ÿM7Øóo›ÿŸÖÓþg˜ö¬· 8­Êf¥ ÃŒ   Œê´ÿLz¿Îüï_ËüÇvŽ{5¨h¦¹_S	P8-.Ko}š†ìôŸÍÝøt f¬ß´ÿ_¿?ÐóOæä¦ýÿìG]½hÓþg˜ö¬›Á‚T Ä.<O±† 4ÂÀ¾À^7œö¸ÌüÛæß2ÿ“]6Ò¶‰ÞÈÌÿ—UPøÚ‡©
¹pLÙ·K´�™ ë>í?”ýÛæßzþÉü�ä´ÿ>Ó
s5Âç;XözJ’òÁKM@  C¯Ž¤Mn>ó¦ýW=ÿç®aó¿šùß žÿ›­}“Þi©wãÓ¨XŸÌÿà´¼Ðó?šÓþmóžW�†ñµ4ÍàËÈÌªr‘Ý£êãwÊ“xH`aØ  €Ìüÿý@ÏÿÔ�fþoõt «øæcåL N¸ýÌ?ÓþGÇ�2ÿ¡çº¼0é`}YðÍ‚¬!ÐÊ?.€  š� à–3ÿŸéùÒÌÿM�@%Àúfþ™ö?zÓþcé™ªçpÚ¿!óÜÙ×b»ð°`<«v   aF-ó=*îBæŸiÿ£7íÿ�D?ýÓþ�© ` „  µ! �
¨²U_á(eþ¯G%À­#ó?~™ÿÕiÿ?fÚ?°Q¯I;>ÕÖff 8WÎ³	¿ð}Áp! €FàÚ	\û:ˆF0ó=*n™ÿñÁ´`xØý¸5p
€±Ë¸3 juàÔe6ðúH@=1×œ†1Â™ÿëQ	ðåÈü�oæŸiÿÀÆ½×N(+ ê ž*†  h€zßWi…¥¯wG4ó=*¾™ÿñÁ´`øØm™S Ð$ Ð˜’Ú 0î™ÿðpå†oßÑLÿá•å0ØíüœÉÌÿõ¨ø,2ÿ£ïË2ÿLû6–eý­ÀQäÊJ½¼ct  €†d¿ÍrÏ‡Íÿ?¼ÙÓ+û«Ì'ÉÌÿºTåâlÿIÈü��/ÊüÛë¢×—Ú­µë€»‡
 4 -70 ¨»×TaÅeþmÚ¿mf÷Ëô¾¼Îs?2ÿ‘b7Ú™ÿÛ©ègÕè#¶1"ó?ún6ó_ù8¯}`(\7Ù?¼>«
 {¿¾w‡×$å«B   	™ÿ¾×¾#eæÿ7ï§:rÖzþ-ó©Ÿù‘Îü•J€o=šhû¦HÝöèU�ùdþ�áWß‹¨ÂAS @3AÅ©³Vù’T;Ö-óÿÊ²~ý^_gç¼&-ó¹°ù—Ìÿ—U,Y%Àá4|àÒ|U	05P	PšŒÌÿè#ó¿Á[‰UétZNÝ–ïÛ½ÉÞÃŠ  au 0FÙmKþ¯ô½>:^fþ_¶Ìÿ™\“eæ?³Ìÿ—Uh°À;mžŒô­ÇíÜ<• dþÇ™ 9ìœÄR�ïýÍB  CÍ®£…÷Ê-ÃWxyF«bŒzþÍ‡Ç3ýÕË+Uæ¿ÐÔD¦§cœùÿÒJ€žôî¡Tiîuáj[ÿê{]mžvá9M­ ó?úÈüf72Uh hÌßÀ¸ôüfþý^ªC–ùï8mšŒÔóÌÿMÍ˜/ôú'V	 m��õ�W�ùdþ�fb�Š&! €áVMSµknA ¢«ÃÌÿ™ËEØü×=ÿ«Ó…qí¿cU	Pþ[º°™²Á‰Ò².5´À®yYV–—Ú×šçå0H;âŸÞëëÀ©¼<.) â€”f!ó4ÿÞckT«V]-Tò{Æ 4‚-‚Ùücœ3ÿv¬�mZÉüßÄ¿eÈT¾�[ôzý@yˆú¶ÙXß¾A%À°ž�¾šù·ù’–z^Oçaóo�¡OÃæß«�8uÛNYµeÝÙ<dþ�æ²Õ�¤¢RA  C�	G¨z‹ªZ¿s™ù¬‘åÂxeþÎÆªƒ…¶³wëJ€¿òËºxµ­ÿþ{m™ŽV+ê¶�¡ÎüÒ¾£™~ó™ÿQAæh®Á‚Ôz�š‡YU `ø @#Ð[…qÏüçôüß2ÛÓ__	`ÿî›§#}÷É–véL€ë3ÿ‹+–ù/7ÿ¿~?%ó?BÈü£µN¥ M@  CŸ!±Å°m~¬ô™6 Œ[æ?%ó¿>• ~­ ËWtáj¡ýýŽ¶N—˜a™	p}æß®{ïJÃÏÅ+û,0Th%­zþ«ÏSÕ,dþ�Ñ* 
¯¬® †H2ð  ¨ À¨ çc+./z½y ´m³‘¾7D• 7Êü8•…ÍÿoÞOuèt®4/7ÿÝ–›:ÅZ³yÈü£…u*š„  †^8@Ÿ�P~’I«h`æßKq\~ŒÌÿÝ­0¶‰þàX¦ÿã×+º8P	°‘§|Qæÿå÷S>“«WÍ+°š…�ùgóß(dþ�qÝZÔ®ÅY˜°v]&0‹aF  ÍŠ¬r F$óßK½><Æ´ÿ�ª¸²4<• _–ù·Í?/¿v{XK™ÿf"óŒ[žR€&! €¡T÷PÕ3 B©«  �ê¬¿ýüZ†×||"=ÿ¿z¯¯³ôüoÈL€ÏT¼ØÑÖ™»;à¦2ÿÖó_eþmóOæ¿YÈüc0 ÷áQ¾|Í»òãÀ0" €F ²ŠQÈüGUæÿ““¹~þV/Lt·iÿSÕ´øg@Ýy·R	PWmlHæ¿
D�ùo62ÿÀhc�Š&! €¡f‹cïËþ;c•`*F!óÿ^YÑ¯ÞíéÌ¥B“íµiÿaCHãà]ù¾\_	°ß*~SVüßë„`€±¸m¾×ûûzFÉü�40ùê­ýü´"ééýå�»!ÐTŸ@‚@	¯} ©ê ö÷îãr ÐDV1J™Ûüz*›ÿM“.ôw“ùßØJ€«V	ði¾q[¦�^|ª­{¶Ü™J€ë3ÿ+^Ÿ’ùÉk ™`<°NE“ ÀP«g ØÀ+{K?F!óúb¡‰¶S•›ÎÞ¸ïÓêé UFÞ*þ÷_{]¸Rèß|¿«í›Ö·àúžÿ4÷z—žÿÑÍüKjÅdþ�Q3¸UªEù¨¼Ž2 1 h"«hšÁÌÿ�ë2ÿ¶ùŸ™ŒÂæÏ†[R-8$• QY	ð–UÈfÄúþÓ-í¬ðåÆn½zþíçá7ï[Ï_‡Ïôü� 2ÿÀøa�Š&! €¡UFOËhªMVÍr/Æx—«oú¬0”™ÿj!Pgþ?¹Aæ¿ìù/gZ°ùžï›¯‚1”ùðx®¿úÍŠ.ÍúWßëhçæ²Àf5|•~íë3ÿö¿ñÞ‘LÿtÍ´WNû·Ï3í¿Ñ™ÓI¤gHô3zþ�‘f÷üµS ì_•ÿ†Wa @3†«T=Ò¡Tb¶ø�âgþ»dþR	à´°ìõÖÁ4,â6O;ýð™r&€}þVgÜ0ó:ÓoªÍÿ¡ë§ýÛb’Ê�Æfþí°eÊ…�?ýF[/=»6ðo¥_éx‡N– °1¯ý¬(ì÷Ñ 0|ª´hyŽª€^æÕÏÊj `ØÜ¨‡ÿÀ©\õòZæß6ÿdþ›S	`l1÷á±Lõ¯ËóŸ�	Pgëo%óo�ÌwªžÿWö¥:x¦›ÆvâBËHÈüSÒèiÿÄyö¡DñÒµÓþÓþ�Ñ¼wØÕ¡’¬* `ÉŠaE  CÍU™¶^V.¸í}`˜]Yô:x:×/Þ)3ÿöþ`æŸŸáfÍ˜_öz»ªØ6éûO·oz&À�2ÿ¦ý:�‡#mS2ÿy9ð”¶�†öü[µÈ”Ós&úÉmýð™–¶ÎDåçûk?S F‹Ý×ûiµNåŽ  €¡Ï¨æÞk¥_h¥o›§µx*‘Ul´:S[ÿ¼ÚãÀéLÿáåž^Ù×ÓÙ¹BSÝrpÝó�æUØ¦ü£ã¹þ·ß¬èüÕBÿúû]í˜	ÐJ>øLæ¿P˜öMÏu²ÀjæŸ…c£§ý×™ÿ¿üÑ„¾ýx6ÿ&�¾ÂÜ Ãkð~nÓÿ­½g¥çÃšÕ}aNUu/† µ¨Ž¬fe ÙS#Û'Ö‰=T9›éÈÙ<²Œ mþÇX6w&€U„Ó¼´e:ÒKÏ^7` àúÌ¿ýÙ'ËÌÿjÏ^þÝdþG'óo›ÿŸ~½­<Ý
s#êÌ?=ÿÀh³µi ôY§¢(FÃÐ©£¥!£•‹é^ß¢«Y½Á�RgÿïÙë™=¼;Q§å´Ü/ŸGkC4ƒ}ßÂ)$Õ@>{ÿ£¹þ÷ß¬è?½¶*<jV	*ªÌì±ÿ7¤ú/¯õôOï¥:|Ö¦ý—gÃ“ùo¦º×ÿ3™ÿOè¿ùV'lþ™`„ÜÌíÞ`kÔ²Ru­"�û=† zu 3 0¬êÒ^ÛôíÞéO¿ÖV»p¶»õy[VÀ·Ê�ês4‡mòâ¸<À†ø™mÓ‘~ôÜµ• ö½Ìür¢ÊüïKuì|‚	ö\{=ÿ#”ù·ž2ÿÀX*×©…VªJUkÈ7ú‹¾  uoµeX¬|Ú¢ªËY½f×Ä¬ll¼�	¬6~¶¹›è8}moKÓQè´MÞÑsy˜þnýàq\nüÔÀ™ y•ÕñÒ''rý/¯èÒB¡k3¶D«?ö}¶Š€·¤úÕ»}ýöƒTÇ/äác¶ù·k=ÿ#Ôóÿã	}çñ„Ì?0FÊ©>n`V•W/-”Ë‡"†Vcˆ @3z«lºjZ0 C©ÞªÚÌN:=û`¢ù¥vøø+ûfXÖ0<ŸJ€ÆW,­¬UØL€?y¾¬°Í¿Mû·ãÿéÝ2óo›ÿÕÌR	˜öß<dþ|Ñ:Õ¡ š+ NSÕËéªõ NÀp²ŸU+ï¯Y�÷7±J€2]h?ºG¨h´ÕÖ�|í÷ŸÈõ¿ýzYË…þâ¥	mšrzïp¦ÿû=ýþ£T'Îç¡}i5ó_0í¿iÈüt}_=ÀæU…ê¾z ½~R 0ÔBU!e}…ajœ€af7üÁãßlóÿÜC­Ð7‚Zû¥#ÕñoáùT4’8`©çõöÁTS§�›bm��ôëªìÿäÅ\)™ÿÆ#óà¯6¬:+O¨�~† ¥ºÏ2rN…U ¤^Ëv¾jñÙl×Yû¹MìÌïë*f&\¹(°J€³åL ›`Ÿg&@CgT§Ø¯V	ðÿýå²Z‰Ó©‹¹NÏá{\Hæ¿yÈüø\Ù}»‡÷S¯~æC`ØŽ ¶ƒ@) À°" €¡ç«‹«§5  †yã`• iz]%ÀÊÚ‚À‚ 61Øö‡T47`• çÂÄÿ7¤áU�\˜ô_—�Òóß<dþÜŒz}JÉ?š‚  †Z}1‹h;f%]‹§–V • xÁftË�0`4„“I|ù6\�ªÞÏÁë—½åZÕdþ|žÕ“@êüí”* „ÞÿÁy1À�" €¡Ž´³Óeç¬|œ5šV	Ðµ3Ã[![fp:ÀH°K‘µrtZUp§jAV��Què�ùð¥l]jìo½ÿaúÿÀ ``˜ ÀÐª×Ík§”QÖ�M«>V—×@Ófp:Àè›F«È®Elü§þÞ•Y<:Ï>”è/<¡ï<žhót=ñ¡<Î‘û0†êáSÕõÂúþëSªÂ‡m]ºÑ_#ð%  ì¢jÑU« °ÁZ­¤<ghôL N9dü››ù·3ý´|½n™ŽôÌC‰~úõ¶~øt+lþÃ¤ïTa¶™>`¼ÕkP[—ö³"¬Q)LES ÀP³‘i« ¾<	Àª lÒ¶#€át  ™'Mt¤ç÷¶ô³uõ­Ç2ÿŽÌ?0îV ªL¿­Kí8Ør€«N~¡ Ã�  š“A­Z –V
ÍLÄ”_¢q8 N–Ù·Uý–)§ç÷&úÉmýð™–f'­@êõËÍ?™ 5[—.õ,À 4 µµ~§,÷ZX.4¿âµ-/« êç„ÉÛýÅ7�Ó€ášö_Oî¶#­çÿg/Mè;O$aóMÏ?UgÀXóƒ% Rµ.-öþàl*`˜ @cNÈ
ia¥|Øû­�þÂ€;}:@¶öˆí$ŽÖMÈì§å‚}óT9ðÏzþ@Ï?€›P®K-¬øð>Bh
 hÄfÉy&-,ùðÈóµÏ‡`ì@D•ÓŽžËÃÐKÄ±ÂÏ½øQnïµ·z–÷@æÿ3Óþéù0èº ¼­Kç—|Þ[@¸¦TÁz`˜ @3* Ü`¤µï£~:À+T w'óo=ÿuæ¿: œ6CÙ?€Ïqýº´*ÃŽ  †—í�,Û9EEÙkuu©|Øûõe¶ž 4• À�eþ­"Çªs¸¯ ¸Î`vßÖ¢ó6›Ê*S3»¶¸ÕÓ8 ÃŒ  am  =T Ã‘ùÓþ[åk ¾ÈÚlªª€ò4 -?p
€É3ëÿ/Ê ÙZ–V+Œ*€�Ïü‡iÿlþÜL@æË Uej¸ÖØõƒ�½r Ðk3 ÖN F• Àgþéùp“Êu©_]—†�Õd¥Ð  0ÔB{$ÙšÌ¦¡¯EZžÃ Œ*€õ{-‘ù°ž|¹2ï_3›*óê´\ø1 ; z¶ù·¬Œ�‰>"­…r* 0Â¨ n™ wRa K6°×›	›0� † µz€MVÍòBýpæj¢®ÿÇ(£ øê¯2ÿ î´4+[ Wªìää
Ž÷† 4‚ì‚ÚK½–ûU?çFQÀF% pëÈü¸S×žËi¹µ¶T›!ÂºMA  �bA «Xì­…W­ãª>w•‹/F• ÀÍ¿VÈü¸Ó©¦(¬÷ßŽÿóŠ£êô¦ÿ£!  QÂ0ÀBZªæ ØE—©ÍuT _ŽÌ?€;­^sZæßfRÙ€8.×§@S @#XÇy•òÜk~¹ì¹š�tácÕ“(ÀÈ¢ øü×™ wR½Ä¬[R¯.W§Reö±ª5œJ? hWE^Ã¹«Ë
A€™‰ò¢Œ*€Ï"óàn²
Ô«KåZÔÖ¤T¢¢i  Y½W‘Sšy]^ôš[ôÚ±É«�”€xu`´Q	 ¬½Èü¸ÓüÀÓØIT—‹°Ms¯ØÖžÕõh hë¯²(«»re¡ÐÜB¡4‹Ôæ§c†J €Ì?€�Ñ¿fZ®MWÛQ�`ë„U 8%*£­—æ‹ðèg^SUHÖz²bæ `LP	€qEæÀ]eÓýÒû¶ö¼tµÐÅ« °S ê Udr Ð¬EŸ++ æ"¯À¸¢ ã¤:ekõ8X[požrzö¡D?}¡­>ÝÒæiWÎè—çrÓ›`½]¿×6þh zQ‰}+±R9 ¬ ð!
»ú¼ý*��A% Æ…ÝìBoÛæwZåæÿ/<¡ï<ž„ÍxžZÃ`½V ¤©­CËG¨ °“ªà$kQ4 4j£c:Ëü\Z(ty¡P–oôWl<*0™ÿ¢¼þ[¶mëL¤§LôÓ¯“ùpwÙä[‡–­¨Rb»)vþh hÔ) q$-÷½.^Uè½²
€úsåù«LaÁx¢ £Ê6ü¶ù·Ë{ä¼&;N_{¸¥÷ƒ®¾EæÀ]9 \cÚ¯–õ¿8_„‡é´#ù¢\�M@  �[ZÖ>óººd¥W”y«¯+CôVž(%±4=áôÜC--,—u‰¯ì“ŽœÍÕ«fgX¸Ì‚ju›0¬™ÿ^Zþ|oÝéù½‰~b™ÿgZš�ráç×>OÏ?€»q]Zî+ÜW-!eGQ‡
UŠ Ð  Ð!î.°NEáÕK½WÊGÍ>G Æ• µÌ¿«3ÿ]§ç÷¶ô³—ºúÖ£IØüû<=ÿ î0Ú}5ªÎù³ßÏ-z­¤eÀh" h¤�ñÉ¤«Ë>TX¶“iÏ@‰J ŒRæß6øÛf«Ìÿm}ÿ©–f'2ÿ	× wV½Æ\î•' „µg´öq I  Q¬Ë67væªõÿÛ ‹Än›]+Á²ˆl¨Æ• ©ÌÿÃeæÿ›�%aóMæŸ8€;Õû_%ížšç
}ÿ6ü¯—Ùz´®
  ÍB  �\ZÆ?Ë¤Ëóå9¬›§ã‰0ðZa& F4óo“·[T~¸ËÓÿ- * ªIìÁöMC  �œ`\« ¸tÕ‡ À}Û"%�µþ¬úyÀ¸£ £˜ùoYæŸk<€;ÉÖ“L…ug˜þïÕÏŠ0D·<…Šoš…  '”bEv‹4·TFb-4ÑÙè¯hx%@Z>ŸÓp7‘ùÐ¶Ö´5ç5 ýE_ 4.ë"§ØJ@s;‡Õëâ‚Eb×B´ƒÑZ 7_	pä\¾:T3ŽË~GðrÂÝÈü‡ƒ\,óßYËü‹Ì?€4˜Ý·¬ÿÅ«e€­;mU¸†'nà	Ü" h‹¶ú¨œ°‰Í7ú«š_	àöKGÎäá„C% îfæßÛg#}íáDFÏ?€!0¸¯³§
]ª*O9 ME  �Š¾î­{±Ê* ›ÆªèÅ¾R%ÀÌ„+{ª­àlY	`U öy*p7zþ§ºN/<ÚÒ¿ÿqWÏí¥çÀÆ+'ü×ÃGmÍYèÂU¯4óJb§¼ªN¥  MB  �\4ÆN!KiÇ ÚÃ¢²„n³`Å¯.b,°b¯+*p—zþ-óÿ“¯·õâS-M´Ë·]çÛLû°Áì:eYËþ[@‘Kí–Â[ i  Qê,¹Ð‹eQØsW
-õž³zj+€›­°@À6 »6Kƒ™ ¸ÛÓþ­çß6ÿÆ>ßfÚ?€PŸ&åÖ“ËÖzê5¿ìÕ‰�"g•se*Ð$ ÐHvQ¶²«^ß‡þå«K…ò"G²ØÆÀW¨è:=ûP+,nÂL€út fàfþŸß›è'/”™;ê/üLfeû	=¶ 6R}²ì¿;m	'»†ù˜ïš‹  Ê‡a€V	°’z�›Ëuu)Ñ–i¦²ÚÂÒ‘€Û?à(§àgþ¿90íß~&[dþl?Xqj	§B:7Wèô¥<¬9“È…ëY9 h h$;1Ê.¾¶H´L‘]˜-2;;‡Áe Öït€W¨ÀÌü¿Êü—C¶Èüv½²{£­3ÏÎ•3§lí ýÅ_ 4’/ÊM‹•ü¯ô½Î\¶G¡]["MÙ„À*z[÷pøbT`£3ÿöù°°æš`#ùòšU	¥^ZèÌ\Ö™+ý¢j7-ƒ–@ ÀHôe]¸Zèü\²KSÝ�þÊ€f¢ ë‰Ì?€Q°ÒWXcž¿R„5§ H.¡É  qV3ûr¡Üß"³ç.ç:3Wh%µæ€2d[Ý
àP	€�Êü³ 0,êì¾½µ¾ÿ³—‹PÐK½â¸Ìþ[ëU h" hôâÒ6+™=}¹gëÍª­… ÜÒk‹™ ¸dþ4]]Ýo�É,_›`kN;žÔN¢šŠ  ©žðoËV¼N^,tÒ¦³ö®ÈÞË_s‚+€›E% ¾*2ÿ šo­ŒÔ6ý¶ù·6 +ÿŸhGò…'û�Æ" €ÆZ=ž%—–V
Í-Zì|~#¿8`P	€[AæÀ¨¨[’ìÀ«K…æ—}H2u;åQÓ@“ @ÃY–K=¯Kó…²¢>£Õ…L}–+€[G% núg…ž £RaZGbÿ3—ó0 ŠËu% ¢é `$�I´vÀü’×æ) lôWŒY%@Z>ßÖGV&YìÄh#ó`ÔXâÈ²ÿ–X²þ›1e½ÿ!Ð¹Ñ_p›  Ñ,ûo››ÈÚë[”¶œÒ:Ùqê´Ü5Ñ\Š €;[	pä\†%Y�ÀNè°ö{ýñÚ�Ì¿}£�óšbÚ?€
Aë�¤lâ¹®ôZîûÕáÓž Ž  ­¨+ |Y`g´Úi ÷o�ÕimôWŒW%€Û/9“«W�ÆA%ÀxeþíZ¼m6Òó{ýä…¶¾ÿT+õç«ë³�¨ÌÐÖóoÙ«.µk˜U›V�@£ @sU‘Z›óoÙÆ2R›—½ZýD3–™¬ÏrˆèXÿJ {½…YV	p¶¬°×¥}žJ€1èù�ÊÌÿ×néß½ÔÕ7KÂæßØç[ö3Ã5À�kÆê­ Î^*tæ’µ¸¡Ú´^{ÖÏšˆ  FbêªcZN_,túr¡´Ê@®ÑÀ]ªX±£7KXÉÊ×&• cÐó¿)Ò×Èüh8»·»®ÙZòôå\§.Zb©¬ ¨?4 4V¸Wýý6pl¹_èøéÄ…BË©¿fN éàÎVX à›	Ð]«¼a&ÀMûßÛÒÏÈüh¸2Œ]ÞÇ¬ïÿÄÅ\'.áš73)ËË“§€&# €‘ØˆØ‚Ô"µ—Š0`aÙ¦ÄáóT�w© ëôìC­plR˜	PŸÀL€±˜öÿ"=ÿ ®îñ· ®,ù°®´97�¤<Ð®{”ÿ£é  ÑÂ€pAv*¼W?õš[°#[|Xßi•½ÉõsÜÝÓŽr:Àèfþ&ó ùê5b•ƒKç¼Ž_Èµ¸\Îš*×�¤þ1 `d”� i¹'�¹TèòB¡í›"¦N|:À+TŒtæŸiÿ š®.ü·ë›Mü·éÿ'/ê§R;$“èÿÇè  €‘`}þvqNb§¥ž×±óyÈ:ÚFd²3p@uq°¾¨]dþŒ²0Õ­sTK½"¬#�ŸÏÃûØŽB)éF¥Àú  €‘¹xÛ"µíú�màÑó…ÙíW ×v w • £¥n�"ó`ÔÕkDÛãÛÄÿcçr�8_”Óÿm·d×Â�þ"�uB  £¹›'g§ôì4€L'ÎÇZê%Ú2]-d‰  w• £Ð¡çÀ¨«OŒ²76ýß²ÿV°Üóa.€]Ãz“* Œ  V»2rk}[§.«ýª îâk‘™ �FæÀ8ß¿lyvÎJJsiª#elü1B `$XdÖ.ÚqìÂ€gV
�¼XNo½>ºàÎ£ ùãœ×ÓþŒ¨°2´“MÖ‡W]¼êÃÛVË)Š"¹Ü“ýÇÈ  €‘b—o[¸®¤ÒÕÅòüÖ~‡	®V! àî¡ Ù™»fn¯¦ýÿ3¦ýaaØ©­û>dþW|ÙµÑ_p ÀH±,¿]Ämb«õpÙ—Gï�µ{k¤8rk³ ".êÀÝ@%@3ÿ–‹¼f&œ¾ñhKÿã»záÑD³“åRØ®£­„ö* Íf—;[Úü¨PúŸy>“ëÐérú+±ì¿=�úŒ )aÎ_$uZ.œãzüB®S—
m�‰4Ù)ŸC# 0¤• iù|W½ŽëŸØ€Ìÿ¦H/<œèŸ}½­ï?Õ
ß3{Ž]W[v$U F@•
7Ëþ9kG ZÉl-Y^íÚŒ ÕtÖp@lç¸VS\Ïåzøžxõ8@{Ž#
 ]%À‘s¹²¼Ä±”çÕz¾Wwµçß2ÿ/<ÒÒ_¼ÔA€ð="ó`ÔLõ··¶n<q!É#;QÊæJÕÏaú?F	 ŒËLYÄv©_èøù"\ÌûéÚŽ5Ú`¨*Ü~éÈ™\½¬|>• w'óŸR?-«.vnŽôÂ#‰þìëm}ïÉ–¦»dþŒÇõÐ®ƒ6@úÄ…,œ`÷)ËþS‰†QC  ##\ ‹*Óh3 z^GÏ• VÖU?‡Ó €á«°¬s8²Ó*Î–• V`Ÿ§àÎ}/òjezþ'�¾ùXKùRWÏ>”„Í¿¡çÀ¨\.­(TŽž<_È;iv"Rê™þ�ÑC  #'ç)œÝzy¡Ðù+…®.ò>Ÿ› ÃW	°²6jÉ‚ Öƒi/W*î|Ïÿëù¤ìù·Ì§]fþ­£MÏ?€¾™4“..aÝ¸Øóa–T½f¤ü£†  Fò<×ð~XåuyÁëÄÅB�ÞçCF+©O°’c‚ÀPTX ÀúÎë¬33îNÏ\Mû·ûŸYÏÿ#IØü»>Úª\'ŒbÅ¨Mÿ·¢¬êì•"ž–Ë (Óÿ1Ê `¤¹ÖÓZu)t~®ÐÄÎ8|Ì0²J€®Ó³µ4_Ïàt€uUuX|î´ÿïV=ÿöy« bÚ?€QN�ª�½¾tòBÑÚµÑ²ÿI´(F Œ¤ú4 ;«zi¥Ð¡3¹žÎÃq€›¦Ö2Œƒ î>N¸‹ÿÖÑÚqV¡çÿúiÿUõ…=¯E»€QBUïziÑÖ‰§3>�‡òÿV¼V)Ê@Œ" I¶Èµè­¥¼¬ààéLŸîŠÂ`«: `Ï‰,ü`Cq:ÀÆfþ™ö`œ+ –ûÒ¡3 ÈBÒÈ’G–ý§  £Š  FN=¬Å¹v†«EsžÊõð®<ÂsÂƒ& `Xp:À]Èü»µiÿ7Êü×Óþë¡X 0²¦ÿÏ/ùP)zøl6þÓ‘²ÂËWSÀ¨! €‘Uq±s]/ô�¹Ìi À0ãt€;Ÿùß6{í´Ûü—Séù0>Üàôÿ«….^õaþÌêôªÿ1Â `$Õq]{«§aà£÷r 0¬8àÎdþ]ä5ÕuúúÃeæÿ�|6óÏ< c5ý?—ÎÎ•Óÿmó_'Ž(þÇ¨# €‘W¶HË=q 0J§dåómk§{Ôƒ=ÇÝçeþ¿¶w-óo Éüëéÿ©×ñó6ý?×ÊnÛ)8&U 0ú§DN-US^9 ™ÓŽžË•åe�À‚|–Í±…Û¸·°ß0ó¿·Ìüó±$lþ™ ã=ýßzÿ³°6\ìJ¢²üðyÀ(" €ñ8 *O8p2Ó^N Fât€W¨øüÌVþûÕ™ÿŸ¼ÐÖ‹Oµ4;IæÀøºvú 8|Æ¦ÿûÕéÿÌþÃ¨# €ñ8 rZXñúôT¦‡wEœ 4• ·öo* lÚ¿“¦ºº&óo›CæÀØœþ¿ìC;ÙÑ³…r/Í0ýc‚  F^TõÛi ËÕi Wy—“^Ç½^•J€t<g¬fþUöüÛ5më¬•ý“ù€k®—ÖB¦ÿû0ùßN `ú?Æ Œ´ç­6øå_š[ô«§X/lÝóe›‚@s+ŽŒéL€ ©ÞZÏÿDË$‰þâ¥	}ëq2ÿ Æ[Wk¼rú¿É ÃgóHfú?Æ ŒÍÅß.ð¶�XîW§\)4Ù‰C¦p°/@3+Ü~éÈ™ñ9àúÌ¿ýûl™ŽÂæß¦ý¿ødK›¦éù »wØ„XE¨Mÿ?|6ÓJ_ê´�»¿Ðü�1A  ãað4€ž×¡³¹žÎµmÆiv2Z�ú:X1  9• VÍS¿Ž­À*¬
 5Â• uæ¿nešèHÏ?ÔÒ_ü¨«ï<ž„Í¿¡çÀX³õ]¶{ÁÂJÖ€‡Nçá}«µë)Óÿ1. `üNX)Âi í,3e›¦ÖžQ 4·`Å¯fú-°’•›þQ«¸QÏÿ–é²ìß¦ýÿàé–6O¹ðËtÙdë°¸€1g×Â¥éàé,<–zR›éÿ3 0>§Xæ0.O¨ 6øåž-«Ï\� Y• xÁftË�ŒòL€ÏdþÛÒs&úÙ�&Bæß6ÿÆ~µÍ?UM ÆU]Ù9ü½¼èCöÿè¹"|nv"RZøÕõ"0ê `lØ¢Ùæ Ø À‹½B§/ºpµÐC»âP&Ì"hx%@×éÙ‡Z!°fÔ§ŒÈL€ÏÍü?Hæ næ~ÑK½Î\*ÂôÿÅ¯‰NÙ>V__�q@  cáúÞþ¢pº´Pö€íÙéžÍQ˜[Ÿ`w‚¦g	�qp3§‘J€úfoí¿»[gþLæ ®W{ëj©^ßëà™\ŸÌ4¿âCé¿\kÆ Œå, ×*{À>9‘é¡]‘¶LEšêVÏ±��MÛ cìËNxe„*,óoèù€/WÏw²û„MüÿàX¦ýG3-÷¼¦ºå¬¦ÿcÜ ÀØ¨{»,Óo­ óË…>:žé�±Ýk¢¯n$"Æ �2Ê• öß¶šÅ’ÔI¤gªžÿï>AÏ? |žÂ[~ß…k§­ûló¿ïXª«K^­Ä…Í7-Ü +Ö;k›ËþÙäW› {àd¢ùeÐD£Z	àëžI›¦œžy ÑO¾^Nû·J ¦ýÀ�­ö÷{…ÖÏcçr�ºX„ßÏt�ìv0Ì×àN  €±b| ”§ac`“Â/\)ôØ½å€u¯˜=—Á€@³ŒR%@�ù�3ÿXÏW/>YnþÓþàZõ.©z:m8ìñó¹Î_)´¼"µZk?‘ýÇ¸! €±e|;#ûòB¡
]]öšê8Eý…¸-£R	p£ÌÿO¿ÑÖŸiiÛLDæ >‡ÝlÀŸÒ\:u)×á3¹VÊë}`Æ ŒmO˜Ý Úm6�ÈôÀÎHO?�„¡0ƒaª €æir%À—eþmóoÈüÀg…õ›_{~ÉëÃã™>:‘‡J ëý·jÐÁçã„  Æ÷4€¸,[î•Cavo�ôð=‰f&®�h¦¦V|YæßØ4ëv‹K àóf>ÅUgq¥Ð‡Ç, �ii¥G¨Ú:�éÿW 0Ö§XÖÏJÿ?:–éþí‘þìk…vlŠ×ª6<`\*êj£/Ëü;¿šê$ ørs^Nå:x:—/¤™‰H©<½ÿ[ 0¶êÓ Sé|¯Sa/^-ôàŽ8lX\cV	�n|%ÀMgþV ŸËU×ý~êuv®Ãÿ¬ Ûr×{Æ Œ¥p¦võGhåÒ¥yÄ<¸3ÖöÙ(Tp 0>• G6¨àšÌ¿“:1™ ¸U¾>íÉ)tî¥^GÎeïÿ’/¯íÜ¥ñcŽ  Æšõ…a€‰Â±€Nezxw²o�V¹*g 0• n¿täÌÆÌ ó ë³®‹âòzßÏ¤�Žga^Ýèd  ™�IDATÎÓROá¤§ú9À8# €±U/ê£ÈÉöú6ö£ã¹öìÈôàÎHÛfœ\Tn¢ê<Y £Y	03QVüØEÁÚ¬Àª Zw°àúÌ;V8‰äg?žÐ‹O&ôüÀ­ðåü¦újmYÿýÇÊ ÀÕ¥"Lÿ·ÍXÿQþ�1F  cÍ‚ÀIuìÒŠ×'§ì8ÀX?xº¥›6ú«pW+VÖ
C-°’­µ
Ý©J€zîÀ¦I§§Hô“êžÿrKÏ? Üz`Õ®ñ—æ‹PÕuòbÔ�êHVàÅÞãŽ  ÆZè‹,àte©Ð±óE˜{îJ¡Gv—§„@=,€* `$+,ð‚Íè–¹“3Â ªêk0VeðäžD?{©«lþÓþàËÙ5Û®­6¿ÉÞ¿²XÎu:s¹m^v�unm¶0Î  Õ‚Ün½¾t~®Ð¡3¹ž¸¯œ0M®ì F° ëôìC­ÐfÔ§Ü�™ uævb-óÿÒ³Vy´6í¿Ã´ ¸)õ¼&»®ÛõÕ®ÝÏte±Ürø C  ¨zÆ’Ø©Û’®.y½s0Õ®M‘¾õX¢™ÉrA^÷Œ1 ¯ÓŽ®S%Àõ™ûûlóÿ—?êêûO·´½Úü2ÿ psì:’4á7–ý/ôö§©Þ9”êÊ’W'qå©Oôþ  šÛJ,ãi±WèÝƒ™vÌFzjO¢ÍÓkó8z¿Ó^Y§J 7�ù·¡ƒO>�è§dþà¶ÕóZì—¹…BËôÉ‰rú§½¸@  X;76ÌPXô|2Ó}Û£0@ÆÞ®¢ Iw²`5óÝ8ó_—ý2ÿ pªÊÌº²Ê®Õ§/a†‹õÿÛL€MS‘¼÷ôþ* €J=ì/+¤•ž×Ù¹BÇ/zx·×D»,0ºîd%€eþm:3…Í?™ ¸}õ|&[¿å…túR®§r]œ/Êã\Y¼ŸA  `t[Ð[;€õ�½w8ÕŽÍNOÝŸh¢SÞEêŒ³ €Ñ³ž• «™;P¤_V <~2ÿ6íŸÌ? |uuO¿`‹jòÿ›Ÿ¦zë`Þï´\¨ °9OL Ö  ®›`%¸í$ÒâŠ×[3mÛé¡�‰¦'ÊçX„Ù‚ FÓzV„žÿÔkr"
'‹Ô™ÿ�›™ö ·Ë\ƒç—
½s(Óû‡3-­xMu#å…k; k  •zñ;2v69vß‘T÷lqúñ³míØ¯V	0 m_µ >)d5óŸ–×UæÿGáZBÏ? ÜŽ°»®ìêüÕBNæ:|&Ÿ³a«õœ' k  ×±2]‹$÷3iq¥Ð‰ó…N_*ôàÎHíê( £ï¦+ªÉþ«ƒ¨ìê~•ùïFzò¾D?y¡­?ßÖ=UæßþŒUÕƒ 7o0Øj•™–ñ· ìù¹BË}¯nË­~žý?p- Àuê…­ËíÆqiÁëÃã™îÙ… @Ë‚ ÕÆ ¾¹ ßJ€#U%€Í±@�Y	ÕDeæÿgUæ×@æßžË øê½ÿõÙ+…Þ?”éÝÃY¨Þ´àªõþ—› ®G  ¸ë³E;-.zç`¦]›#íÞÚV·½ö+û0Þ• n¿täL9 —ú°&�žŒôÄ½_�ù'r _™]“m	f›Ë=éÍƒ™Þú4•›ÓQX£ÑûÜ àsf$‘‹t›$ûî¡T»¶8}ó±D³“³ <% À8WX�©³€…tô|®«aò´ôÔžXñÃ®^"ó wÔåùBû�¦úàhf±LMDÊäC� Àg  nÀÆZonbSe—½N^Ìuèt®³s…vo�ÃâŸ0^>·`Å+Ë¤è#éâU§=Û£ÕÌ¿UÕ™+û'ó _ÝàžÞ®ÇË=¯cç�ºXhn¡P·…ë¬µXÑ Ü àFzËìÒÏ6ÿÏuÏæ8œ…;ÌZ`ü*,ðÂÃ-u©Õ’––½¾õXK/>ÕÖÎ�žû3lþàö+4ÃòÌ•ƒÿ><‘é�Ã©./aF“µfìü�/D  øuŸ'Rˆ,¿y ÕŽÙH[gZšê–Ï±é³á¸/ cU	`Yÿ¸®ØÛ
�B+?}~o¢-Óåæ?­žc ë0£)– ô¤·fzã“4Ìd™™ˆä­ôßÊ8|. Àç¨[üm Eš-ºüú'©¶Î8=ýP¬©n¹ë·HsÄ, `¬„ kª6öm§¯ïm…ì”Í¨ÙB•iÿ pû®¿–ž¿šëíOÓ0§ÉŽnžèD!Kï?ðÅ8�ø²)³Q9µ»ŸJÇÎçúøD¦“
õ3‹3W¡Ç´ª²€¡UØæß>fÇÖçT nÏ`U¿eøm>Ó¡3¹Ž�Ëui¾(«­"Z­€›A  ø"ƒ7œj�×™Ë^û�e:~¾P?õå,€*X@@ /®:¸Ñ·wm!Êæ Ögó?¸ÆZX)ôþáToš…Í¿UjÆ‘SQ�˜n- À-ôœÙ^n±Ð2mŸ�´cS;ùe¬ìÌz}Œ7°@5õj À:VdVmU‹+Ò›ŸZï_‹½ª÷ß®Áôþ7…
 à&§ÎZt¹Ór«Ã mèŒ�=»ö<J €qe~«`ó ë}tþJ¡w§Ú4Ó•E¦ÿÛõ7T	PŠ	|) À-Ì°s¼mÐÌ©‹¹œÌuüB¡•¾ç†`õh* Àú¨+«\5oåÊ’×§§óÐ†i›ÿp½ÿÀ-!  ÜŒ�ˆ²E—mÀ×Ù¹BïIuäl®•ëg�  øÊBaå@q¥þ[­À\(Ônôþ³în3 €[��”=hWýñãT[§#íÚk¢=0€Ð  Àm	§©T½ÿ+^oX à@_‹+eïî=½ÿÀ-b›Ü¤zÈW¹u¶a€‰~ý“4L¡]{ah  €¯ìÇ¨ž»\hß‘LË5¿äËáÌuï?ÿÔÀM#  ÜÛÛÛÍ¦—³ Î^.tðt®cçs-÷®-Aãf  pëVOU±~¡PòÿÉÉL'/!ûo½ÿ `ì
pë  _ñÆ"ÓNº8_è�C™>9•i©çW#Öuï   n­â²^G]]òúÃG©þðqª¹¯nÛ)‰�
N_¾f  _�E£Û‰�
à4¿\èõ�ûÚ:ítß¶DSÝ2À,   €¯Æ*±Sh¹üÃ'©Þú4ÕR¯Ðìd¤¬(«  Ü:* €¯™Ž�S;±Y ^oÊôÆ§™Î_É×žÇ‘`   ·$”öÔöÛ‘ËÍôééL‹Ë^q\[¦  øj  _õÅc‘éHJ3éâ•B‡NçálZLcõ½‹6   €/gë'cë+Ëð:“ëÝC©N]*ÔO™¯¬ Àmt!}ñj¡×?ÉÂ< ;ªæú>6   |þšÊ6ýõ’ÉNXúÍû©^ÝßïOvœ’Ä©(®ºàÖ0 øŠüÀ,€n+Z�°yRzøžH³“qù<‹f3¦  àKÙ’É6øvÒÒ›Ÿ¦áè¿•¾4ÝuJ‹µ* _ Àí ªcm­M©Ý¬¬ °RµA×Ÿe  €µ5Õà±—æ½>=•éÈ™\®zõ³ò”¥à¸- €Ûäªy vÃ²á4ÇÎçzÿh¦3—òPÊf}l†ˆ5  Àg…ÙIõl¥\úðx¦7¤ºpµë,vþÀº   Ü®Ð³æÃ‘€múÔ~·¿¯W>HÃÑ5á)öf   \»Œ²yI»û‹Ws½²¿§W?Huq¾P·íÔŠ3•€uB  X§Y ­Dš�t¡OíÝÃYhƒ¯?Î   ×–ó[  —z=—‡¾; ŸzuÛÖjI%%°^  ët³ò4IË}¯“
8™éð™\KÕ‰ öyë ‚  Œ;Ûð×Óü-Qb›ëùïP¦Ó—|8ö�²`ý  ÖQ½¹/ªéµo|’ê£¹²¼ìk³ ³    Özÿm˜òrOa�ò>N5·PhÂ2ÿÕP@’'Àúá@`]{ØúÔZ±Âà;¿v¢éÞ­‘îÙZÆÛ¬Ï-rŽ¶   0¶lã?¸±?w%›ÿ×¤ZXöj·\XW• n À:* ÒdG¡tí““¹Þ9”êø…BýŒ6  ÀjéU59¿ìuàT®ONå:;W„ÊI[OYõ$›`}  Ö[ÑÎ½ó N_*´ïh¦“Ëa6õ@ÀÑæ_  ŒaÅd½±_Xñ¡ôß†'_¸Rûç¢rê?€õG pØ�Í&ÖÆNº¼Pè�ŸôµuÆiûl[3e ·¹ 1ÿü  `¼Ø!É¶F²µÒüR¹NúÃ'}Í/š™ˆÂÑÉôþw àNLµµ[äÅe à¥Ú<åôüÞD3å®¿ð^±·£ø  €ñtâB¡·?Í´ÿH~?;a“ÿ< ÀB pXÙš•°µ)Í¤3—r}x,ÓGÇs]Yò!HU¯>zÛ  À8Mý·þ~{ÿÈÙ\oHÃñ‹+^¾ú<¹àÎ!  Ü)ÕÔZgÿåtæ²×«ûûáFgÃnìc&èƒ  E¶Ö±5OíÒ|¡_¾Ý×/ßéëâ|¡é®S+qÊ’ÜQ´  w�ÝèZ‰Ôi9]]*ôû�úšžpzäžX³“    £ïú<‡UG?_„cÿöÉÂÔÿ™I§4¿6H `ýQ ÜÁ›]Q•ú‡!7Ë>øîÁT‡ÎæJ³òvXŸ
   0jlµ³Zéè¤^êuüB®wg:r.×Õ%¯Ô¦þUÇ¸³  w˜ØäÛMïè9«Hõáñ<D¹Ãq7®ì…  åÞÿå¾ôöÁT¿ý ¯Wµ[.œŠÄ:¸;h îÒy·Ö×f78»Ùýê�¾:‰ÓÎÍ‘îÙRÆá¬ç-Ì ü  F„-kg�¾Tèå}}ýîÃ¾—½º­(Zÿ™‰ÜqT  wk@¬0àÆúÛ>9™é�©>=•k©ç¯é�ãÞ  F�mêMÈð{…aïNõÁÑLg/a}Ôn•Õ�õsÜY €»ÈŽ·)¼W?•N^ÌõúÇ©>>‘i¹Wfÿëç  £PND’te±Ð+ûRýæý¾Î_)Â€ä8^›úO$pwÐ ÜEé¶�€­Èin¡ÐïìT€IéÞm±vm®Žôç  €QP·6ž›+ôûÓp²Í˜�Œ”¾œúOö¸k¨  î‹€Û#‰œÚ‰ÓåE¯w¦á›†»öD¾%   ¹—2VpyÁë“™>:‘éÄ…"´?FÎÕúh¿V`Ü  î"»ÁÙÍ®žv;·XøÆ'©ŽžËÃÇ¬B€S  @Ó§þÛš¦Ÿ)ôýÿöƒT§.aÃok! ƒ  °A ëw³S&ÚN®úÅÛ}ýòí¾.ÍÏa   hÛà‡²þÊ™¹\¿|§¯zÏŽýË5ÙuJBï?ë`#  6èÆØJ¤™I§^*í;’•­ ç‹pJÀ``œ²8  Ðõc›êoï_]òÚ,ÓÛS9›+Ë¥‰vy2Sÿ��A  Ø õ&?Í¼®,z>›ëÝÃ™ŽŸÏÕK×¶ýáT ¾K   	[³XùÿÂ²Gÿv? Œ"N<²ö 6ÀÆá `ÙMÐæØñÂÕB¿ý ¯™	iëtG›§ËçØÍ”S  @Ôýý¶®ùÃG©þøQ‚³.œtT	 l ÀFž�k/ÂØÉÅ.ôÿÿîƒ~(�{âþD›§“kÊé   †‘xk�¥é“S¹Þ>˜…aÇöÑé®+×>¬k€E °�ì&h}rí¤ŒˆŸ»Rè½Ã™^ûÐŽ,ÂçmV€ÓCÉ  À�Ný·Þþ~*½{8ÕËûú:|&W/+wüöy†ÿ�  °�ÜjÏœW+všè8�™+ô·oôõw¯÷téêÚ®Ÿi¹  `Ný?u)k˜|«§ó¹¦»–Ì({ÿ©j6- À€*Ó?™DZ\ñá¼ÜÙ	é¹‡’p\ÎdÇçTÏ   °Q¬R1ª2ÿ¶ž±¾ÿ?~œ†ÇÑ³¹ºmN<êgU�€°á¨  †HQøP°Üóá¸œß}”êÃ™–zk›"è  `Ø¦þÏ-úåÛ}ýÝ=�¾”«�8EÎ)«‡þ±ù† À±Í½EÑ[‘ti¡Ð«ûûšìH÷n‰µ{k¯³)7Q  °QçøÙ¾>Í¥cçm˜qª7¤Zé+dþ³\Ês¦þÃ„  0$ê¾¸8rŠ"inÑë�ƒÖ
àôµ½-íÞ…»,ýs  `£„IÿÕÐ?ÓK½N^,ôŽMü?•éâU¯$¶Çeû"ë`¸Ð ÙMÕzéìÆiæ—¼>>‘é·ûûúàXJíÂ© ŽS  ÀÆ°Þÿzê¿µ)ZÖß¦þŸ½\(Iœb›	À7JT  CÆn˜V.g‘s;"ðÂ•Bÿf/”ØmšŽtß¶2ng³œ[  p· µrýú½¾~ûA_K=¯‰N>ÏéEÀp"  ë© ±Âô«øäD®MS©žy°¥énK›¦Êèzý|‚   àN³M½%'ÚI¹þ8q©Ðk¦zïHvœq»%¥ÕÔrÀð¡ úsu]y“½Pè×ï÷õÇOR-,û0Y7Tp®.  ¸[Sÿ«ìÿÅy¯¿}½§¿}½¯ssE8¶ØÊÿ³Ü—É	¾#ÀP¢ òm’H�¶U”gëNu¥‡vÆzôÞ8Ì1  €;¸&1V}hU‡+>Ì&ze__ûŽ¦á£Ù©HiæC#€áE  Rá^ëN°�þâŠ×¡Ó™6O;=ý@¦Ù)§›,¾îÖ&ò–   ¬kB¢^�XŸÿ{‡²0ôïÈ™\+}N0òƒƒ -Z €!¶ø®¼éÚyº‡Ïæ¡à�i˜`'Øç8f  Ü)¶Ö°ŒÃ™ËÖ÷_ý»<_¨Û.O/*Û;* €aWEÞ[‰ƒ/Íú§w{á»·ÄúÆ£eÏï‘ß)   ·¿üÕ…õºÂÖ®zçP¦ß”ê£cy8‘Èzÿ­ÀÔ  Ã�  Ð„°/ûîÚ±SoÉëÌå\o|’jïÎ~8)à±ûbµ’k'ô  ÜÖÄÖVúKW‹°öøÕ»}8•«—úp€}>lþÙý�À6h€Puç¥´ðjÅNÓÝHçç
ýß\ÑùýŠN_Z›¸cmÜƒ ÀmñeÖ¿þÍ�“¹þæõž~ýn/T#NvlP±cèÐ0 €&áÉÚ 6MEá¦üÉÉ<áùÝ©Î])›ï:­2`À,  ðUX5¡Í²êB{ßÑ<dþ­Àªm¡aˆuï?Ù 9  cÁx;c×îÌ6‘÷è¹\ÿõ=ýü­¾æËP½ÝˆC% ¥   àVÖÕ¢vòB®ÿòZ/¬5ÎÍ¡
Ñªëu†
 43 €¦V$ÒDÛi¹'½u0U·íôÐÎX_{8ÑÌD•¯ŸÏÍ  |Ë/Ä®¬&´Â¹Ë…^ÝŸêå}©>=�«“H³S‘ú©/ƒlþ�Æ¡ h 0ìß¯æ—¤�ŽgúÇ·{zóÓT‹=_X•ñQ	   ¾pmq]õàåy¯¿}½§ÿüûžNœÏC¢‹œÒÜ—³†Øü�D Ðp‰½Š½tþj¡ßîOCÔþÞm±½'-¾ºAS	   n¤Þô‡M¾“®,•Çýýú½¾Þ=”†ÀÀÌ¤mþËÄ€æ"  4”¯ýY¦ß6ú‹+^ŸžÎ4=éôð=©&ÛÒî­eÀj€#`  ®ËüWGÛšÂÖü8Õ/ßé‡aÃÖjh·5G¨>äh4Z €«³úq\>ÒL:t:7í?|œjn¡(oèV	°Ñ_,  *u‚Àúþm“Ÿf^GÎæzu_¿û0Õ¥…BÝv9wˆvB`4P 4]=0rjuÎæýÍûý©ßµ9Ö÷žŒÂ@@»q‡‡EþèÛ `¬Ùš dõí7¶ùÏ6ÿ¿ÿ(Õ›2=›‡çLv�ŠjžÉ ù  £Ð
`¥{±ÔN¤^_ºpµÐ[Ÿ¦Ú³#‘û¯ím…è½ª¡€î  ÆªÍ™+EØü[ßÿ‘³EXÁªlž Àh   Œ WÝ˜­ •8ÍNJçýíW”e^³“‘¿¯œ`ÕVÀÑ€  Œ'ÛÜ[¡ÞÔ_]özÿHª¬Z—û^-6þ6€Ô?0:  #6ÄÇ&øNODš[,B)ß+ûRÝ¿#V§ÕÑží‘Ú­µJ ›   ÆoÍfIZXñzó@ª_¼ÝÓ»‡3Í-zMt¤N»l°õ�ƒÀè`ùŒZ%€Ê!>qä4Ñv:u)×þÝŠþÓïVtæ²…ñKƒgý €1PeýC;`åÀÉ\ÿ×ïWôó7ûºtµÐT×©—Gþ…aÃùõXwT  £X	`Cciªã´°,}x<W;éë¾­±~ô|K»6GêT• õQ‚  `´åUæßfÙZá“™~ñNO¯}˜êäÅ\SÝH3.$ìó´£‡
 `„ÙÍ»Ý{:“ë¯_[Ñß¿ÑÓåM°€J   F[}Ï¯?Ÿë¯·²ÿV!h›ÿ$vavP8€ä 0’¨  FT(ñSå·v€¥ž×ÛŸ¦á÷v:À7M´y*
¿¯�äf Àè©çþXõŸÝïO],ôOïõõOï¥úô”U	:mšŠÔOËÌ?uÿÀè¢ eÕ”_‹äÛÍ©'}t<×ß¼^–ûYP ~•   Œk÷Ïr¿:ÈÿÜ¯ÿüÚŠþúÕ�¸Pnþ-Q�ÖÏ!óŒ4* €1a™~sy¡›ËÜ»5Ö÷Çê¶�TžH%   #¢žóÓi•»úWýá£L¿z§¯÷�æŠ"iv"R?÷á˜` £�  0âB4¿*ï·‡�í{êB®·8íÞÜ·Ð€žz QËZŠ2S`± Ú  h~Ï—A€+K^¿|»¯Ÿ¿ÕÓÁ3¹|èÿsÊ,JÀ©@ÀØ   Œ�º¿ßúÿìt [;Ÿë×ï÷•$ÒæéHìˆB& ^0  €f
Cüªÿæ—½Þ?’…ûþR-öŽû+,ðÏþ+ €qQÍˆ"§N$Í/y½{(™��›­ ¥�›£kö­€  4lp.Åqyï¥^oHõËwúÚw$ÓÜbùqKÔÏ0>  ã4°:ÿ7‰¤~&-¬x}p,‹[|ÿé–¶ÏFae`í õŸ#  Àð«7óÜ¯Ûþ>=™ë•}}ýîƒTç®á~O›0¾  cÄ]Óè4Õõš[ôúÍ{}¥™×Ô„Ó‹O´5Ù-gØ/õì   0ä™«ôsVí'¥¹ôáñ\/¿ßÃŸËÂý¢åBpŸÒ`<  Æp�`7}Ë´§|ÉëÜ\®×?‘¶Í8%Îé�%š™(wýƒâ   oæ¿.û·�þÑ³¹~»¿¯_¿××¡3yø˜eÿí9uï?€ñC  C–Ñ·ÅBš•• ÓÒÅùBÿFOK=¯vkBß~¼‚aQQõP	  Àp±[ôjæß•û£çr½úA6ÿûŽfa@8ò·z.Sÿ�ñE  çJ€¢ÌLvœ®.z�¼˜‡Ám3Q˜ðÜC‰&:J   !H_�òãªÍÿ©‹…~÷aª_½Ó×‡Ç³Øï¶¤N«¬°û9·s`|  ÆX½X¨+¦&"�¿RèÿþcU	�Lèë�”—‰¢žPý9  °qBœ·Ì¿9{¹Ðï?Jõw¯÷ôæ§©–V¼&Úöy§,c°/  ÀØCëJ€n¤«‹E(|ùýTÛf£0HèÉ=±Ú‰»&   6FÝ¾o÷èúž|n®Ðk¥úÅÛ}½{(ÕÜB*üìaíh@îß ÊC¿ŒµP	 «ðŠc§‰®Óé¹\ÿå÷+ú�¯®èà™|õ¹,ƒ À]WOðÙÿÊÜ‚×Ÿ¦ú¯¿ï…©ÿW–¼¦º.ÜÓmóo÷l6ÿ -  ®­H¤©Äéê’×§§rÅ®§›"ÅNÚ»+Q»ºjX¡}  ÜåÌ¿ï«4ÞÅy¯×?Nõó·úzã@ªóWsMwmÀ¯-~Ö÷Ïæ@�
  7< Šœ&ÚN'/úëß®è?¾ÒÓ‘³ké[PP	  ÀÝŽï+Öªð®.{½u°¯¿þÝŠ~ùv_—Š°ù™ÿ¬¼O³ù0ˆ
  ×°E…e÷-ÓßîDš_.ôñ‰\‘ëiëL¤$jë�]q˜&¬�D  pg§ý‡žÿêcWË²ÿŸ¿ÙƒÿÎ\ÎCÙÿÌ$™ Ÿ�
  ŸUWä>T´[Òñóy¨øÿýn%TÔBo¡e#øw àŽ¨{þëÌ?“öNõŸ~»Jÿ/Ï—™;Ñ‡Ì?€/B €Ï¯P9`"vZ\öúðD¦(öát€öõ¶îÝ:P	Pý9*  Xõð¾x eg3zÞ;œéçoõôÚ‡©N]$óàæ  ðùlÚÕïo• ±¼ŸÉõüfEç¯ú0¡Gv—«;^ÈÎ!¶ý†  ¬OæßnÄu `©'½õiªÿøÛýnªUæŸž 7‹  €/T—Ö• Ë^û�fÊr¯ÙÉH…oë�‘:-·úüºW‘j   n?óo·ÕKó^ïÌôó·{ze_ª“ò0éŸž ·‚  €›dv:€³C¯£çrýÕo–uv.×¿ýAWÏ=X^Nl€ -Zœ-^˜2 À-ñ÷Ò: `Uw6èï¿þ¾§×?IuÉ2ÿôü¸u  ÜRÀ¶bz?<ž…A�“]Z ¿/Ödg-ï_¤  €/WÛ—Äåï-pf.×?Îô�o÷õ»ú:w¥ÜüÏN¸0ÐÚôh½p³  ¸iaCo§dR9Eméä…BýêŠ.Ìyý»—:úæ£­0Àa!c *  øBvÏ´Í¼eýëÌÿ©K¹^ÝŸêoþØÓÛ3]Yòá¨¿8*7ÿuÀ  n  ·$ôø×• I¤«‹…žÊ•=MO”Ç=µ'Ñì¤Sì>ÛÏ  ®UoäÛÕÊ|%õ:u±,ûÿÅ;}½ñIª‹ó…f¬çŸÌ?€Û@  ÀW^¬ô3²“]éìåBÿ×ï{¡Oñ_¿ØÑ·o‡EJ]ÂhAƒ„    7Ìü'ÑZÅÜÇ'r½²¯¯_¿ÛGð.¬”™;‘‡Ì?€ÛA  ÀWR—ø[%@;‰te©Ð‘3yhè¶œòÂé�´´mÖJ¯ýsT  Æ]8á¯j•«3ÿóËåq»¿~¯ïNµØóa¾Ž=,P@Ï?€ÛA  ÀWæ*l&ÀÔ„B‰â?¼Õ×å…BýÔë{OZ Z«(¤8a0  `¼Ùý0µÌ¬Ð2gû7¤aãÿ‡�S9[¨—JmNà±çDp»  ¸-¶É
› M%NW—­o1×kyM´£°éÿæ£‰vm‰Ë©ÆQ™õ°À� `ìféØ=0’:U…ÜÜ¢×ÇÇ3ýêÝ¾^Ù—†£víÞÚm;uÛåð];m‡
: ·‹  €Ûf’²À&;Mu¥+^ÿô^?œU|e±£>#í½§<×ÈZ`À  ãÄî—¶¡ï´Êû§eþ_û ¯_Ú°¿O³D·�Y`Ýâäö\2ÿ Ö  ë[	+ô).,{��Ëõú'å À°àÉ¥=;¢PÎXÏ¨'S  ‡žÿpÌ_»ü˜ÎýðX&ýÿîƒTgçŠpO´¬¿ ,ëŸWs `=  °î• –­°IÅ“i©'½q †^šÏõ£çÚúæ#–öX{®êÉÇ  ŒjÏ?·A¹åïç
ýü­žþé½Tû�¤ºpÕ‡Í~»ºZ€EØüXOI‹4tXßJ Ëô/÷¬·±ÐûGR…¥ÿ¶ yäÞD›§\(�¬ÛB% + À	íªç¿•Áï3—s½þqªŸ¿Ý×ëŸdZ\.Ôi¹°�€ahnµB€õQ^Uï•y'ç¼��³n\®6 Ö© XÔn¹�é?p*×R¿§3s¹þô¹Žþì…¶&Z.\Žl~€•;ÚÂ €QbÞÕÜ›ú¨¿Ó—
ýç×zúÕ;}}z:×Jß‡,(¨ÿ °Nl­]xï”;/Ÿx©ç¤X.\{Ê	] p›lS_T½Žu `¥/}z*çç¹S·ëôüƒ‰vlŠB¿£a&  `$òlÕ|ËüÛ½ÐÝ§/åúÍû}ýüÍžÞ=œÉVä“]É[ôÛ‚çdþÜ	N…“R‹1&ÎiIòmy—¸(Š½Å}7BÀm^kÊE�1²µPX åÒÅ«^¯}Ø×Õ%¯3_ké¿ûvG›§Ë¦G[ µ™	  �£þL=ôÖ²ýÿåµýúý¾Ž�ÍWàÖ›~Þ Ö—÷r±³<¿/ŠBÎ÷œs}›Ð³ 9gUJ °¾—žj!dF±õ6ÆeÉÿ™K…æ—Se…×t×éÛO´tÏ–xu8ÓI  MÍü[Ö¿¶¸âuðLŽùû‡7{úäT®Vä43áV{ýë{% Ü	®Üë§^¾—x¹Tr­Ðüo¡H®> î€P	0°Ð1Ö÷øÎÁLK^'.ú×/vuß¶µJ€$®Ê'I‹  rŸ3vÿ2iêõÞ¡Lÿéµž~»¿¯Ó—ó0Àît6'§þs pÇ„=~(°2ÿ4q…Í'ñ+l wÚ`9dÜváè¿¹¯7?M•å>dCþä¹¶îÙ¯ž0øçhL s¥[½ñ7Öî¶ïhª_¼Ý×¯ÞééØ¹\]§Ù)§,[ À]Qx›PØÀÔ9—y/;àîü�kuo¤#…ì¾“>9™ëû§�ª*žÜS®¢¬7ÒÖ�‚  €¡;þ6³·µ~ÿW
ýöƒTÿõ+zã@¦Kó…&».´Á¥)SþÜM¡ýÖªý3ï}jC ûN®í�R wÞjF_
ÓÿãÈiaYzÿp¦~ê5Ñvêgm=´+Öì¤¥’5Ð  ¦Ì»ªZ[êù0ãæ�ƒ©~ùnªW?Huîrîe›¦#¥™WV•þÀ]=À»TÎ÷çµ$ç[V`p—S-B@9 €;+ùgoó*kÒ’ŽžËõ¾²Þþ·ßnë»O´ÃÂÉX¹¤=Z6€‚% À²
5ÛÌ×-kØw4Ó+ï÷õÚG©œÌµ¸,MO”™ÿž�ß¢ßÀÝbþQöÊÿåÔsÞ/%^~IrÎÙ, [�S àî©C¶€²Òü’×Ç'3-.û0Ey¥/=ó`¢]["MuÜjyeTG( pWîYÕ/vÿ	ólª{Ò¹¹BŸœÈõòþ¾~ûA_ËÂ Û©NJÿmàŸµ	¼pw•½¶¶×÷R_Òrâ¤%/?í¥ÂÞ¯.§«ƒL àÎ³±¤Eè¡tšêH—¼~õN_GÏæúî“mýðÙ–¾ûxkuñd§X%@½ø àN³´5ÍZðº•”;{¹Ðß½ÑÓ+ûúáˆ¿‹óE¨VëØ[NJ³µ 5 Ü%«·ÎE–â/ä}ß9-%…|ßy—)| 6F}< õQZÆd±çuêR'-ô¼VR¯,•¿?ÖÎÍ‘ºuÉeýÕ  €;x�
YÛÄW“þ—Ã}ªÐköõoöôÎ¡LóË>lü'ÛVö_¶ØƒÍ?€�Ée€wË‰äRï\æ|¸´<‘  ÓSÙ·“JC[€•V°°ÜÓáÓ™^z®­ÿîÛ]íØT^¯ê’J;R0,Ì  Xï)ÿE¹J®�ù³{•õûÿ×?ôB ÀN°±á´šªR@6ì�Ì?€.>e€�ð®ð¾èÉEKI˜h' 0”À�,´lád‹¬NÛ…2Ê^*>“‡c•–ûR'qzñé–vmŠ4Ñq7ÌÒ  p»÷#[Û”k93VÎo%þNäúõû=ýü­ž�ÎCÀzvÊ©]µØ}¬>Â †@ád§ ¨_V xå‘]ãêUsˆ¬ €»ÉU¯<_;)À²*ýÌë½Ã©.Íç:pª­ñíŽ^x¤µ: «žÏ) €ÛeYþÔzùmµ\­Š�œËõê¾¾^~¿¯}Ç2�¿R„@´­µŠ´ò¶Ú| ¨ÎŠ9ÛÙ{'—òiâœë«ð™œc €¡;_Ù.[¶¡oWÃ”®.y½{(ÓU;%À¦˜®H�Ýkûl´š¡1uà€j  À­Ü{ê.Xëá·‡±y4ÇÎúÃG}ýæýT¯œêòb¡™I§ÙÉHYîCš�?€¡å|á¼ŠÄ©Xò‘[ñÞ† Ú»
]À°«Q(£¬¦.[k@9�¾Xè¿¼ÖÓ�S¹þä9;% ­Çî]‹ Ø)‰Íˆ9Î ps÷›º|pÊ¿ö³ŒÿËûÒ�õ·ûÏJæ5i™çÔO=+g Cª¬ �—w¡³Ö¥‰÷Ñ’\Ñ·Y «O €aÌÈHê¶�’Øi~±Ð¡3¹.-øÐ“ÙË¼æ—Úz`G¤í›ÖN	´>…Ë àlÓUeëÓemÊÿ¹+…Þ>˜éÞìëõ©ÎÎaÓoeÿÖ�Zë5´ †�óv©Ê¹^"ï—å]/hW=ë°9�Ä2!
Xxª ¦º6�É‡IÌ®zÿp®>“èÏ¿ÑÕ¶Ùr·osÂþßÊ9	  n°ù·ò}›'SÏ”±{ÍGsýÝ›=ýáã¾Nœ/´¸R¶žÙs,°lÁgjf«rO_Wø[²_+./–¯xI.ë»Âf �Ð€©ÌVšÙ’&».”úÛ\€Kó™Î\*´Ø+äœÓ·kiç–H3×^×Âl€rœ  `ŒNùoWåþ+}¯W½žÎôê¾Tÿðf/¼oYë÷ŸJB)m8¢ÖÜK ?gÛÿÂ;ß—�–'·ä­ÀŽpa<àÚä- R«Ù—jCo˜—û^o~šêôÅ\ïnëÏ¿ÙÑ·K4Õ-/h¡ö©(g„‚' ÀX²{‡ÝŠÂ‡#üj�Èõêþ¾þðQªONfáøÙ–­–åÂó-XPÿy–Ê †Zu¡rå¢·��{.Š–©èGáL@{ Í¹¦ÙEËcÖïoL[Œ]ž÷:w9Ó¥…Pú¤Å•BOìI´kS¤é	§vtí\€paÜÈÿ À]®ýUEl89&S±tn®ÐÁÓ¹~ÿQªßîïëÝÃiþ7Ý-§üç…Ï[½w @c8»æN¾Ÿ{·œXMÎgÎŽ¬Î	€&¨–Bô²n°c›"Îfþù[=}r2Õ7mé‡Ï´ôâ“íÕ©Î}ë÷tkCŸ  £Íî¶‰7v¢LíÄ…B÷FO¿û Õ‘sY$ÛL :kóflÖL}4- 4‡Í °²×0ã/÷r+ÎK‰œ·$—4 �µ:å_ÒDuJÀBÏëø…\çærÍ-ašs¯/=õ@¬�›ã0½ùú¿ƒS `´{ýë�¿æ
�ºXèµ�Ë^ÿ÷gá^aþ­uÌ‚ÉYá™ò ùœ+œ\æäÓ$’O‹By({œ,ZÀ\S Mc<ÊTd×,[lèŸ-ðþñ­¾>:žë{Oµô/¾Õ	�€šezl�Çký� €Éú[¿Vöú×�^ûÚG}ýæý~Øø[€÷þš �ýž€Æ³Ÿ7.W¥I¡dI.ïIÌ  0:™k°òÍ0ø/—ŽŸÏuòb®+Kv†³�ÐÒƒ»bm�qjÛTç�?0  š_fY{´Ëëü¥ù2ëÿÎ¡T/ïKõÛú:w¹YÿÙI‚Æö°U±½€Qfý;—Và½.¹HW%—–§ „Uoò$ ÉYŸ¼\ÀÕ±�æÐ™\õòŠÞ=”êûÏ´ô£gÚzrÏZ?€+XŸóÚ¦6î? ðØ5ß2øvý¶ky�õŸ[ð!ão½þËtêR¡…å²äßž—æÕ_@,€¦+÷òÞ.€¡ @²Uñ’"w5I[ÑéNQÌ9ï3[ì²Ü0
6Ù±VúYfþ½>>™éì\®¥¾W?-?vÿŽH;7Åê´>gbô†üW  ¾J¯4PÊuÁëÂ|¡weúåÛ}½q ÕéËåìk›c÷‡,/§üÀh)³Y.œ|ZÌ÷Šö¹¤¿´|¦Õi]Ž¤~9ÀÙ€°v& `„rÎ|-4Õq¡:ÀfœŸ[ÑŸ¤úÎ-ýù7;zt÷Úl [ÚÃœ  ÃŸõ/Š²×¿f½ýü8Õ+ûûÚ4½ÿ‹=_	"‚õ” !>ìéC€· i¡èrÚßt:9û¿ì^Üûÿ¼pÕ9ååô++à2`43C¶0œìZ À‡ÒO;.ðØù\—ÊÔÏåÇ[ºo{¬-Ó.d†B+ ³ `(ÕUZ«Yÿ¸<Úêü\¡Ó—
í;šéµË À™K¹Z±ÓÌ”ÓôD¹ù¯ÛÄ `tYÀõ�÷sgÿ·X6¾FÉUù4-×Ç«a‚�þJàÎTd~uÁgÃír÷ñI¬èõ©¾ýXKßª­¯?²6ÀzC]½È´R*z `ã³þÕµ¹žÞoÎ^¶“_zúÃG™žÉB ÷êbY9+÷_;ñ…å.€‘TíWÎ4)ûb—“"»jJ¬: ).÷¼ü²ÏsgcO½÷Qýg `+lÁØn•ýŸöþÕe¯�g:q!×•¯ÅéÊ’×Ã»#íØ©;PRZ/<Ã¡©\*àî]ÃW©²Uœ¶ŸKWŠPòÿÖÁT?«¯·fº8_fýí>=)/Ê^6þ F�·Ò~Ÿ«HS{!�:Ëaï/ëø�.ô}î.½E«�²E­ý•—G–· FO•²jo¥þvl e†>=�ëü••0(ê[�·ôÏ¿ÙÖó%×ÎÈ¥8.›¦¸JÀÝ¹n×%ûvÄëàÐÖçýþ£¾^û ‚¹gç
­ô­2À)²­ÖzýÙüiÞ{râ|{ŸÊ÷W2çüeßÏû¶÷+Ú$/²¾‹.ût¹çâv§ÜüÛ²¶> F;“dÙ¡¸š°Ôó:w¥Ð‘sy83Úž4·Pè¡�±¶ÍFšê®ÍEÝ1Åi °þ×êêkÁÖ8d©B¾*c­¼ÿä…<dûûaª?|Øëvœf'Ê	ÿ«Aº[Œ©Èäóþ²‹“«QÛB§¡@ZŽ’~ìòKEáÎ»"»×Eqh°n + ¿`œfØb³cõQN:r6×_¿º¢·?Íô�G[úþÓ­pb€�þœM�(Gå´  Xu¶>\g¿šÍ¯?Ÿëßîéõ�3>›ëÂÕrÂ¿UsÙ5ºžÝþ.6ÿ Æ¨ÆÕÙP?çTy¡(º\¸èj^Äéj  •YÑŠæœÓEÉï”¢öFé °Q³l0 - mC?¿$}z*×É‹E¨XX±ù ^�ì¶“"ÍLºk†OÕ—¡5  ¾Úõ¸¾†º�éþÆNo¹²XèÌåBo~šêßîë½Ã™®.yµ“òÚÝJÊj.°ñ0ž¢êmžIÑœŠb¾•¹l5 àãv¿È/Ç.¾(§¾‹âvHÿ;W8ùë–¶ 0ú� o™#»|V³ÌqøfOïÎôäžXß{²¥o=ÖÒî­k)©4a×pÙµ?[Oš ÜÜ5¸îñ¿~º?õzÿH¦?|œêÝCiÈúŸŸóJs·6áßþ\V÷úó`yÛÃ;YW¿WÚ—/.Þ]rq§¿ ˜èÙb;š“Š9§¸¿1 €ñØ�©ÉN¤Â{õ3éèÙ\ÇÎæ:~>.3QK^Oï‰µkK¤í³Qè7½þï	˜  7¾Þ®þ2Ðç_-EíºkÿKó^Ogzã@¦×?ékßÑ,\ƒ'Úe%–o];$ Æ[úR�œmú/9ù9Ûó¯ Îlî¥³½è’¼.x§~Eò¡nÊf lô 'ÌÈ}(Ö²Qç½öa_�Ètß¶H/<ÜÒ�Ÿoë¹‡’kJÿíT»Ž†ãªªrV À»¶†km5KepÈê±syØðÿñ“LŸžÊtáª×Âr ZÀÕžk•Wôú@¥ÚÃ»(Rád“ÿ/ºÈ]²=ÿj `S|%unÇœ”^–\Z¯Ö hÜ+ŒmþÛ­r6@/“ÎÌ:v>×§§œÎÏ!SeC¨Øaóœ¶ÌDj%Ÿýû�  ãl°:*´K­~B¡ŸÿòB¡½(ÕëŸ¤! pv.—�©žî–Jþ}Ðë ƒÊý¼“R9Ù¹ÖÜ¦ø|z¾ |ºõM>ý?]rÞ]ˆ
õ�‹%`Ë&*2V Pf¨Šò€T[lZ  —=§ŸžÎuyaE¿û(Öã÷Åúæ£‰^|ªªÿ¼õ¦FÖ•UU 0nê{[^­]^*ôÖ§™~÷A_Ëuúr¡«E(÷ØêúkÕU.œT XUîÝ½H]y4U¿ˆÜïü¥C[ÿ×ªÀ‡S
ý¿ÿ§+.÷—ä”…P¬—Øµ¿ °še²#¦lóo½ªö¡¥žtàT®ƒgÊù ¯š_özú�$6OG!ceØAT »Œ=Ù¿’f^ç½Î_ÉõÉÉ<ôùÿv?ÃjÕV“m»vJSI2þõt²þ p#6EÕJ«,×ï3—ë’OtEÿóÿ\ØÞ?ùæÿGÉ›Rzèò–…Gg/Ÿ—ÏúÎEÞÂnmˆ*5  0xiµÌUõVUËŽ ²ßÎ-úãÇièWÝ³#Ö×né;�·ôÍÇM ¬lÕ³¥µ¸«}†Š  #Y=UçóúLkÔ¡3¹^Þ××;39—ëâU‚¨õuÕÞ^3ÝŸü |ï¼³Å¥­/½¼ë{é‚íõí“¶÷O.ì>b1ØTÿÁåþÿu~^å¤@6ü ð%¡vZÀDu\ -rmÀ‰^‡Ïä:¥ÐÜ¢×åÅB�ÜkëL¤M“N`EE €ÑÏøÛÛ:éo›y”Î-x�¸˜ëÝCY ì?šéÒ|¡$ráøÕ™	wÍd¦ûÀ-ð!ÐsErÅöúö¡½#q’_µÖR!·«X.ŠLÞ]C*ªàð* ø¡ŸµºšÚ"5‰m+å¾œb}i¾§7ôõÐ®X/<œèÛ�·õüÞkOøLE W_ #˜ñ?y±Ðëúzû`¦��ç:s¹Ìú÷RZ«B'ªe§Ârµü;HúÀ—ñ6ý?²•¤÷¹ò|Å>6»|±~F¾»�K²w‰›ë{ŸÏÙJn�ZïUÃ  _tÉ]ý¥ÌvMtìm$ï½ú©tt>×ÁÓvŽµ-t]YT¨Ø³3Öæ)§M“QP  éQŸÉø{éÊ¢×ÜB6ÿŸÈÂdÿ÷Žd:z&W?/+¨¦­2ª}í�@ À­°ª�Td*òÌ†þýÿÛ»³ 9¯+?ðÿs¿/3kÅ A�IQÔ+Ô‹ºÝjºmËa�Ã1aÈãî–­vÐãðè¡ý8S¬‡‰˜�c¢cì1¢[j¶¤¶‡Õ=cYKS;¡…„$‚¢D¢¸� 
[¡°T¡Ö\¾ïÞ3qî—™•U(€ ±ÕòÿIÅBeeíU™yÎ=ËÕ†ø†Åú@195MÆí|ÊX¢à²í	¼ŒÐ˜VÈM!ÎF\[#3DD7A[^m‘JóÌ¦\;ÔŠ7Ïxœ»RÃ÷�¹vEÀþ”±ow²DE@Q	×d±9‹ˆ–¡v™~(^^|âo“ü�¾�ÅéþožÉã
UKT3Eâ€Š³ä§õøwÌAaðODtklLŠ³:RMÔg
AÝå`1~¼UMz¼.¸‰Nó�û²ŒCý$T×ÃY{€ÅýÍ[t""º¹ÛàVj5fZ§ÿ·vVÛv€okŽã£ÅÆ€‰YÅØD	»·:¬·Š€^ç
ØƒâÅï3¾_&ˆè>Z|{d�;o¯âÜ“é€óãoŸ÷8úvŽŸ�ÌpbÔ£–Ý%Äÿu=¶¯ª™4mN÷'"¢ÛáêmYê¤=¥Þç­×”Ö=¢iïÜ#íè^�oh(]�àŠB·'’Tâå»¯šs®‰ˆèfµ&VÛX•˜šmÞšÆ2ÌÕ¯�ä¹â¬GHðË�¥øµÇËøàîŽ=Y òøà8&w¹5€ˆîïmÚNü/^xù�GßÉðFìñ/Nüçvû…ØîdƒþìáiÜ:Ýñ¾‰ˆè}÷ÿÛ"¿²‡à3@'ÈdV¶Ê°° I£!pWUÜ¸Äm ®ÂÓ"¢;X`k­šìF:{cGÇs¼Å»ç“¸A`rF16YÂ®-EEÀº×a-^ÒÒ9i›Z"ºÛ3Nš�-‹ÿE'þ“³£ãïœó8z<Ã«'2¼{Þ£Z*e ¿yâook·]ÖæÄ"¢;Én˜íFZ³¢ÀOVPj' Lºuï|}¿dI]Òtð¨‹$ýÍL¯òìŸˆèöÅ»
ä1Z×ö�«VEÀTUñšÆ³Š€�nOð«Vðd{¶/ÅÒ¹5 Î	h=0'"ºCÚ§ýñyq{cmM�l éËÇ‹ÿá�ã“sÅ‰¿Ý&Å§	Ú'þñ¡é¢6""º=EÌ.ÁªRÕ1�ŒIO½ÞºN÷ÆE šÔÖçùyMqÁ9©Ã¥Í[gÀ[i"¢»±1 é¨È¼MÊVœ¿’ãísˆ3l/öäœÆµ�›û‹j ;Ië©Èu·&ˆè}ÝF-º‰	Æâ¥ø_ä-ÀŸšÓXîÿŽõø·!Y<ý¯Ö]Awñ´øÄŸ�(‰ˆîQØÜ~±5ÓÚÀE0:1™Ø>À¨o4=<Ü¼`ì±íÕþãWNAÃi…Ì9—(‚·4‚å¬¯€gKDDw³" ³§6®Î
xåÝÇG=¾ùSÁƒ›~éÑ¿ò¸mHôÞÚû²9&V´ÖqÝêDÿæ½%mÉü€3—<~z"ÃÏOú¸ÒoÌ¦úÏ†8Ó¤XƒZT	ØíY{òOü‰ˆîžxfo Î–÷)ÔUpNC8o1~ëjû§x!>Jü_ÕaPBíàé+]åÊ9UÔâ€àÚï‘ˆˆîrE€+¶XE€±€Þ* Î\²È^±m½‹å¶W¦{mÚâ°±O°®×Å“6[7xÍûçœ "ºÑmPçmDk¢ë Õ†bÊzüçç.{¼s.Ç«'s¼~2Ç»||}WYÐßUôøÛû°{ü‰ˆî%»1·½Ñ©kçW\]¥ËãÇ>S«x!Ö@Uöÿ+$G�pvhwuÏ��:`RC>_¦%öFö"‹J‰ˆîúé[3çZT*©ÍÌÖÃ§=F.ÖðÂÏ;7;ìÛ]Â¯>^Â/îI°¾gáœ€ÜÏ÷írN ]¿¿¿Yêo�;Î|fkŠ7ÏzüìDoœö8yÁãò´bj®ãÄ¿\œø{{ÐØãODtÏ5o·cì¬öJ§B"çOìØ8míúhzô�æû·‹G«GüIi
>¿²¹†ˆ+Caµ\ÐBDt*ºÀul°¾Ûóã¹ØØçâÀ­+ÓŠ±«	y ÁÖõ.&Öõ¶†u]N ·­ÍÛ–kûû–°Û+é·y$§Æ|\å÷ê»¼uÎctÜ#÷‚J	è»Î‰?{ü‰ˆîµ8lÅ!dÈ€^v¡4Qœþ“§×µoê‹€=6<8ÿæ®ææ�êiÕ|TŠ¸DDDƒq « ˆˆîCE@±5À.³•€©sÈràä˜ÇÅÉ:Ž¼)x`£Ã‡v¥ø¥=)~é±vm^XÐš`U®£*€‰ ¢Õ­ó¤¿H.ÑßàòdÀÏOÚ@¿<÷³€ßJÿmÍŸ÷³·±õi"EÀßZ8Å"¢û4û°pÐDCÝ«ÊQ=UvOÿM¹¿ÑÎÍ¶+ :×ªóQœƒ÷çE°I%-î-ü=þ‚ˆˆèF[|PÔÀå)�z¦èí’Ø£kC¹Æ&ß‘`ç¦}ÝOëìõÅœ€kçºpƒ Ñ*=íïèíŸ7ßß?SULWãS6Ñ?ÇÏNäqªÿ‰Ósi*(§×ùÅ6#)–¶
÷áë#"¢&±S~—ØÉŽúFÐ3¢2Ò¨åµVïÿÖ½ûÂ5	€ö6 ›>Ý›Î5füiçÂiù€“´Û‚»�o–&"¢û uz§²Ø‚–æ©žm°}Sìànàç'óØðø‡=;|àÁOîJñÀ†EUÍµ^V`QBkƒ@,æO™hEi�ÄÏ÷÷3@¬hñßs#G\Û÷Ú©,Î9{©H¶Êÿ-ÁX.5o¤Yâ+A›‹‘?Ñ²¨—@œ@½ÎAä„ª{]e6flÅúó¤öÎ_819WëMÜˆ;EMœ XsW¬XT,FDD÷Zë�·= ·ýJóAzìÃõÀ…‰€‘±[N�9ìKpúRÀéKØ™ÆÍ½].Vô]gV@çÇi}0&ˆ–ŸÅÕ;1Øþc-þ¡Í�~35�Ãû&f4nyólŽ×›	€>V•K@%ôTŠJ#{ØÙB@DDËˆ X?—KJ²ZUÅ�Å»]Sµ¥býùÇrªv+¯­•€?»³§\ùàäN*×ÐŸÍ6D%…0	@D´œ´Nëc®V�,×˜°Ëm=—=�ïëô”›ûÛ7:|`WŠ}»S<ùP_^ÌÞ>,UÀ, Ñ²Ð*¿oçè8í_ÌÖ‡¾;êcÀÿîy�“£Wf¬ô?ÄÞ~ügmDö~ìí[½þ�ïþ‰ˆ–UÛ½’¹r_EÒ®�Ï]y;þ÷®Êæ¿ÞŠ¹ ƒ�k T ´µ‰ÿAž¾¢e=o °¡�ÿDDËUg®=h/wþìB+Û�ý½3!žî%¢Ø¼ÞÅŠ€óWN_öØ½5ÁlV Ð×íÐ[‘ØV�¼WU€ae Ñ=±øo¯Ý¦cýý­?Æ¦©ªb¶jýýãÓŠü‚ÀÈE;íW”ÒùÙ 6+ÄÞ§=œŒÃGyâOD´rØ èlHdtø?ÈŒ]ôÂ@Üú×îÿ_˜ °Óÿu{Ÿ9–�³C»k{þxlÔ“òŽš�ØyÚÜKDDËM¬è¸©·a]ÆNñmu—%�çêŠã£>& l{Àú^Á®-ÅÁîJbUÀží×#Æ-6/ ÅIc«2Àð^�èîýM/ìí/•¹æ)ýb¯¥ýÇNçxëLKý­äßNú-h- qÅheþíc°ß¬*>(šDDË›•}ÁAíÉÃg3vÿp%	¸ÒºÆ%kßP×Z¸d@c¼<ÓŸ”¦àóË!›kˆ¸r|ç­#%""Z'…ö@?IŠ!�Åƒûb{€%lå—­tN±u}‚ÝÛÎ^NcUÀ;‹��¶çÛZì”ÐÚ	¬2€óˆîâßoû?×žô7/i¿®ž!þ-ÏÖfk6ÿ£æ÷Ö9�áÓ9Þ<“ãòtˆIÁJb¿6Ñ1égÿ³d‚µu$"¢B¬W.„††¬^IÆ2W™ÅÀ€Ãà`hŒ¿#ØôÄ‚7Y˜ xZþäí›~WssHõ´j>ªŠÅŠˆŠž÷-wñ½U´c†b —¶¶Ä@Ál]12æ1>ðÊ»ë{Ø¶AðøŽ�ïLðØŽ4VXà°Xkø š•­Y­¹Dtëü‹`\¯{ÒoÕ8VÚo«ûNŒeýg.ù8ÁßþÅÄ@]‘:Aj‰ÀfO¿ý½ÚÛJ¬å)>0ã~"¢•$NgU±;…ÓàâÜI¨ŽHžW-ø·k•/4ºð&þš
€­{ç{Ôù†(ÎÁûó"Ø†¤bë l4Ô=úÂˆˆèn�(¶¶tVØiâÌx@µâÉàúÁ©§ÆÒ¸üÑ¬MÀ¡¿YÐSqèï¶D‚ÀÝLe@ó*Ì	ÐZ·øoré	þñÒø_Ø- ·)þVÊ?9«›1ø·Þþã£9Î\
¸xÕ#ó‚JŠø7jãö¼3ñ×êígÐOD´‚Y¿ÍæwNBžÕÅ%#¢z¶'/×[WÙºwß‚þÿk >8PêMç3þ´sá´Š|ÀIÚmÁs5¿­ôžâù”o4ƒ‚
2œ½0>“Å~âîŠÄ‚ÛÖ;<º=Å;“XðÐ¶$nXÌÊŽ-±`Ú-Í)2í²f¢5¤}â¾¸¯ßŽp®3ÁßXpÿîhýScg.}ývÒ_ËB31`ü‹j{?ñÈÆf?wfáø­š ëÐ·‘Íng z¦»Ò¨¶®sxøÚ\ïµ[ :vNLÎÕzwâÎÚ6 qV `už±J€kˆˆVÓ¬ ›$ž e;ÍoÖîÛm¾Í°bç¯ ™×\lêwØ³Ãcd,Å©±"ðÐf«pqV@ëÉ®këÄnæãGL
Ð8å�¿ç×üYX¾,–îWÕF±žïâdˆ%þöÔJ Ø ÏÖÿîrø[owÅµOûÛ'ý<ê'"Z}DBœ�”€vê.•dd²²±¶Tl�€(žQ`°¸{l{õÁãgGz\å4œÌ‰KÁÇ™1P±©ƒ<¼!"Z%Z'’vÃ^ÚÏ—'“E/²½ÊJ�-¹8ðêÉ¢ÄxsŸÃöM�íLâ ÁÇw¦xp“ I–¾«ˆÛZ‘‰Ut”@sv ­d�§û­—Có…Dìoâúo{a<àÄ…¢¬ßþÆNŽy\™*Jÿ-à·Ä€%âÿr‘d‹«ûì´?NòŸ¬ÇÀŸˆh•ÒX‘¯ñôß•¬o³ªNFÆ×o:5öïÐP7h“ÿcÝå�g ´µz‚ O_Ñ²ž·
 ¸DxðOD´šuˆ[)±,†û5O)ƒ#ÀäLˆ�|]%Á–õ'ÇŒ\1pÙµÙaûÆ=]‚ž²,Ý•"p)J�o¡: yufži9Ÿð/=µÿšâé¾ýUë!ÎÞ°Rþ+ÓŠ“cÅ	ÿ»ç‹àÿôE_g‰´.;éwÅ&Žõåù)þ�=ýú‰ˆÖUKÏzÈØØ¿“Y»è¨=Êº¦ÿé€p{Ÿ9–�³C»k{þxlÔ©\UŸÍßÏ‰vtrÑjÔ
(dQ´Óªˆ'™Ö:ïË•ß>k“È~ü¦Ä`c¯‹‰�‡HðÐ–»¶&ØµÅaç¦ë'”CœPôEÇ0§UÐ1„†÷>´¬úøãsû}Åu§ö·ØúÍÓ—Î�{œ»lOg.{LL'ýõL1Ó<é·÷[)m9­nûûÈãŸ§ø­=jw6ÎFÇ@=|6c÷?W„Ë­k\²výu°*€E®[ÐoOsR$¥)Éóñà«™À•âkMr""¢Uoñ©bk‹€Í(‚óæId@\®LdÍ€]©Ä™?àðÐ–4& vn–˜°Ëû»•2Ð]¶Nëg.‚§ÖzÂ›ýœŠOŒtïÛÿ¹µ>þÖï§�òÛ`¾Z#`.žö+.O…8½ÿL;�ãÜeÅÙ+sµ¢Í¦ó¤ßþ>¬§}Ò¿`p ­Ib‡þp!44dõªH2–¹Ê¬äÛ
ÀÆø;‚MO,ù¦K' žyFËŸœ¿_qpsªá|6
Áƒ"’ˆ8ÑàCÑRÀs"¢µ:/ s‘xsà¬ˆûÆ]‘ °SMÛW>:ðÚˆ œXu€`]�`çf‡›,9à°ss‘ Ø±ÉÖ˜]?øïÜ.ÐY!ÐÞ0À{&º¿ßXbR|Ä%EkÌ�ØïºmÐ8{ÙÇÓý‘1Oþ'çŠ^~;ÝodŠª=56ÙÊ>K|Ùû�?6wÙ¾³}“�?ÑŸý¯*ÅP&§Á7DÜI@G$Ï«üÛµÊŠ?]:O|Ý
€­{;zfóº”qJUÏ¨b‹$åž¢&4æ¢Ù@D´F->…·àÅ‚ÿJ{¨_Q¤lAŒõ;ÏTCÞë¨±´yûFK vmIðàæ€][‹„€]n›¬"À#«°õ„­Ág7Ú.°ÔçÖÖ|3Þy­]í_�ëüŽ,ÝÃíÖ»oåúödA½½lm0ãÓEàþŠ6 9FÆÆ§ª¹¶Ë‰ý½ó0Ú'ýÃ7[“üyÔODDZöm!Ÿs¢YÖ€$g€ü\�/×çcù}Köÿ_? Àáó/ö¦ÉLÍéÛAñ6 OˆK»m€›<x½wMDDkMºíÔRFX­Ê€³;ëiJ¡8I�®*¯*†Oûà[	t_—`c¿U$Ø¹É	Øà°sKñüF÷?KÍ0í*{ÆJ¬õ“ýÖeó¯»¹~c¥ü£Šã—®œ/*\Î]	˜ž+VøÙÚL+ûoµXÅ¦Ë´ßÃØÓßü<é'"¢›¥**b�ƒ’ çf¡8+R:Ý]iT[×9üÂ žZòí¯¿à)ŽBf×½S•¹MÇUäM@$®²- „†eÞ£ŽˆˆÖzß´;±- =3 (ÝoU4òb÷yî›[¼Æ·Y×ÛjpØ¾!Áíß	¶mpØºn~£@¹TT
”KE€u33–lgX
ç
¬ŠSýVÏþÒ'ûWÂ|P^·Iý§üvÂ?W¸:«�¸`Oã¡™ È1:®ñ2»nÚœÚo¿‹öïrŠØöÒú½ïìãoý›'ýDDôž¶þ/);ds5ˆ¾[JË§&Ëýµæñ†â©§š±üM' D1ï‰dÿÓGÓ£º¿ñð§p²”^~C&Š�Ë;9†ˆˆÞSû”µýŸù	ævZ»Ê,IgÚÌ—÷g¹ÆSÕ‰Åñó¾Ý
`oØÐWTlß(Ø±©Hì°J��ï¥˜%0¿ê Þ³-ªèÜ<_fåÛ²ý½ºÞ©>ší(1uÛŒííì÷.>Mx\lû¯O6Ó¢–)²ÜZ[Š^~{ÙÚ\¬œß~c;L³Ÿßxû\|û³íø`|0EDD7Ïbðf£¥=&Ï�cS=ý'Ïþ{4bì~HsÆzÇ[›ÐzÈ3yz�=Ó‘gQ{ì_^:à‚ÏkNkÍÅ¿ñá	ÑâÊ€Ö?c Ôê»î˜`lÐŸUØà4ï¹­?³çHèï±@13Àÿ˜ ØäðÀz‡­ëú{š	ƒ´°Ö:‰m=/z±›w§·9þº8sàæ¾§K¾°ôu[§øí$MÇ÷ùº?€VqÒÈ‹ ÞžÛïT¼¬¡˜ªã3£W<.\µ”�A¿•ú�]-¦øÛÛ¤Í-­ß¡žòwœô½?Å= Åàª¹ªuh8 gÏþ{‰åÿ“§¿ÖLs/ü¿G Pî¢ýÆâÂU	î�à!‘¢˜SCà6 ""ºCæÿÑ
žŠ¾lÀØ ´Öö<Øì€€©YÅÈ+bÀŸ�ØúÞbv€%¶¬lèuqõ µlîl]_$nöóŒ£oÛÛæï[‹ ´x?‹+ZwÁ�U­+®ÕÌyg Üù#×ë½¾ùŸö¿›¿­^ú›­Ê°$Ò•iÒWòWg&¦®ÎØå!^fåüÓµ¢ìßzøkuE=/Ú¬ÀÖ_ÚŠ¾Ö´~{^¬ÁlÍ�˜¯néü"ûÑíMÿ‡Mÿ· ?Ußh¨MÿW}£’„«­k•ûw¿çÝÍ{& ÚÛ T%û7³³¥¼ú–ªÀ6—t•`¯V+àä, ""zÿ–:µÀÎ‚ý"À[8?À-ªfªû²ãÊ´P´Û"°=¶¶¬s	 Áæ~Á–~K¸8?Àv®·NqKéÂçvy<é]ÁßÁöÛzorûW¹© õ}F±­7[|r¿àózÏ¯áúW°G!¬gÍyöóï<áÏ²bØäÔ\ˆ	€‰™€Ë“Š«sÍDÀå)Å•©'ø7¼úÅL	û™·~þÖÓßÓuí	ü;ûùßß·‰ˆˆèÆ½ÿ.¦ Åç³u;˜‘á<í�µXÝÎå·î½tÝéÿ7� 8<ÜnžÓ-OëÔÃpþCPÝ'®Ô£š;Õ¬Ø¸V�2ˆˆèîV´"ä%*:7HÒl)°õ¸Í·µ€n¶œ»âé­õó�}ñrOqãÀÆ^‡}‚õV°ÎaSŸÃæuEÅÀºn[Õæâ0ÃÛÑª"˜jEh>[Ø3Ðy×zÝ“îŽˆsÉ«ÜìÐžkÛÓß÷i~ñlþ•­9­“ûÖéýíh%ŠPÀÄ¬ðŠ«3ÅsèíTªP­I;ÍÏ[‰K´Åeöû`¿­þÖ÷¼uÂo??žðÑ=›ó%8{ #ippS¼™Ke8<Ð7U¬´Øý©fÝäm$ ðœMŒUöL þJo×I‘Ù7!n.ÝYLO²'FÿDDtw\¯ïÞîyR+†³ûÃV…@Ç«°»)Î6W³k±"°™8°ÀÏ‚ÈJÚL ôY• °¾¯Ø2`—mnV¬ïôu9ôuºlû€Í° ±y:œvô‚[’ uj\…+’í¡pw¸’àŽ¹ãŸÊÍbÍYöo›óÐš÷Ðša•­Ëí”?þ5�?S;ÙŸ®eü–¸ÒL Xiÿ•)Å¥)Úb€­á‹­$?‹Î�}V	bU#E®iá¤þV?Oø‰ˆèþ±;¯Ô©¸Þåôôl=_sú;vß	 )âªÊþ…tè�dûŸÖWóÙ7á’†üÉæõšG­ü>ÑÝ×
ÈZ“ú—8‚nWÄ¾ñæ‰®kvüYBÀ.·IîV-0=‡¸ßýDêã�·V@ä›Ï­’ÀfXå@_·CO¥h7èé**z»ú»½‡ÞøÜ^o­@w— »T�k•ýLªqÅžb®j+ C<ÅŸ«'ú³Í—gëŠ™¹æëc°_Ì{°^ü8U¿•Ä±ÄA<ÑŸî×:Õ·1à/·MÎÏh=µ>';Ï°¤Ñ‚_%Ã²~""ºoâSsT’=°É­ÿŠBÞÙÚ{ƒö?­¥£ÿIóV%ÀíU 4U'Šzô�d�ÿ‹Ëc�p&äs³I7Ärêöê÷l9 ""ºãn4™¿sË@kŽ@ñ¯æÖ�fú:V(bÿ·¦örq:Ý¬°—-ÅÛÚÀAèû›	 ë·§õð7 =•¢b ·è©×·$�% ,P)ÍO’ï¬&h­«k¯’ë8±n}ÎñßÍ/d¾ò¡ãyëëloVèxêHž´§Ó·ÿ­×¹|áÎú/·¾/ÍSüß/;¹×ùËbÅ…·JŒýV`¶¦¨Ö4øÖª1ÛL ØÉ¾þ–�™«×³Rþé9[»×<ÉO›"¥ùýi¯Þ›ŸÎOô›ßƒâ×¤øúÏ`XÜËODD´|ÄS§>ŠZ"g�¹K”¼3V¿7—  ûéŽs­M«”‡ÂTñA‘¤'†ÿ!h‘t` -‚½EG»q™Ng0Ü1ÔÍ5Kb0n—'Rœ·Zö¥(Y·ÀµÚ@Bh¥ÿ6<.I|³%@®i°ë$ Æ¶…¢,Ý*
bÂ V	‰�{n–8°„A¥¹ºÐzÔcðÛlA°€¾õ±:’qxbÜœÐœXß¼¬ä:’ÍÄ‡}Vfo_Ÿ•Ù[Àž·ùæë›íEi~q²n}ÍùF@µn‰ jSó›Ï«™]n�~1Ußzï[}ôí�Û|ßóeþ¥ÿ�­Íç–0i†lŸäw$8Z—µêã£ü‚,xFDD´ŒhÌË;»s·óõs�ðf=&S­kuoDQ¾vnº`Ïï#=?	©'“³•�½Áªþ‘¤Ô×«±Áîº¹€ˆˆ–—Å�K½Ø
 ãŒ¿E³Ú'í÷®­“dŠ[â,H�³{êf5AëiÁ
Á0¿Î®Û‚~kèL TŸ	 +l½a+ðo=o­¢›O0HL
X‚¡èwo~]K$ lYBì¿·Ï£™ °¯!žâ7 ó	�âkêìÇo,H �¾�ì×– @L Ø½j3`c~uÞ|EC|ÞúZZ�|œs<ÿ²%?ºâeóŸûg·#5_^|’ß‘Ô!""Z©Óÿ�KÅ7fj€•×ëI2ÛêýŸ�ÕïX@tèX{L±ž=®S�>qi8U÷!~W¤¼?x€j²œæÝòJ¾kf
´¯µ ˆ`q�Ù^çƒZ�ïÇæt^×6õ´>N«âÀ‚\®-X¶Y¬_]Ü‡Ž€ÖSçÐÃâc´.(ùo^Ðº¬sòþ5«ëš[	®WòßùuÚõŠ€ùSüâdþ²V[@\¡W²}z‹Û®×ÆÐQ²ßñyÄ	üÍñD­ïáÒ?LžèÑ* ñŽ1ˆ$*R²{Ái�¼é]>ûÎú©æž$³k¾wÿÿ-U à(›�\Dòòc—FóNˆ[AàŠ{s¦Ø‰ˆhuÏXP5Ð
¾[�ì‚&¸ùy­ë¶þÓq•æ¬Ýbø\g¥€�Ä·_ŽÕ‹öÎ7ÿÓYÝÐNLÜèu‹¾€öç½èå¥¿¦Žà}Q’!žàw\Wé¥ó+ÿZ[|þÍOLo´Vpñ×ÁàžˆˆÖµ2¹b t:xw¢ìd‡%ÇÀ€Ãà`hÇêw4`)÷�·ÿ’£@öÖg·Ì<ñ/®œR	£>›ùEçˆjó|‚Û ˆˆhm%
Ú#Úe ×K"Ì_Øyµ%K×\¯@·ü­*…|N×|ÄEŸë‚Ob©¥}�	�Îët$ì“jŽ&nWM,¨¢h'nâä~‰OšGDD´6iqþo1¶z„¬a÷§£"zÊbq»Æ^L‡`ÓÿozÿÍ' šªçãº¿Økàõâ¸œ
¾vZÞ q.¨u²€ˆˆÖ–ëÍxÏëwžÀw×­Ë¼Õün¶ãn©ÀþFóÞËR=õ‹“!�¯XxêODDD7Aã@U|æÕ×§ r:hi¼•foŒ¿#Ø„[rk[ˆŸÑîÑùþMº§‚bX ¯!øY¸’ØFÀfAïç‰ˆˆnÒâMí‚kô<µ{ïßû)_üÔä×ùt³ïË_çs‰ŸgGÃ‚ÙDDDtËÓÿEˆõÓ…|V�× y]×œþ/º¾þD°ýî% lÀ!4ËT’Z½**¯AÝkª¨º´[àR ´®CDDD·£µypAP½ÜžxºODDt§Ùô íU­:Wú)¼j1x«Én>6¿k	 Ñ¡Ž¹=¿ÒØ<«�®cxC€iqeËRX“Ÿå+˜ô'""""""º**qúªâÊ†OõÇºÓòÏ-Ç@ÑÝWÄæ·wßò€v’ÿ“pCCb3Š/íùtõ4 “P_t$›ÞÇ»&""""""ZÛÔNù-®™ùã’»‘×>»aâ5{åµ8ÞNÿoùÐý–[ b†a`ÀíÅ±¤õ²ÎCôLhL×5Äé„I\h�DDDDDDDôÞ,†q¢šj¨#äs3€Ž¸’»ÐºÊÞm1ÖŽƒùq÷ -ûì?1+!&5è‰�×/_÷pI±˜³ˆˆˆˆˆˆˆnŽ­ôsp%|ÃÃ×.(ä¤>�;{¿½m{ï/0øŒ_l–ˆ¨”üT�ä5^Å¤HœÀm DDDDDDD7=ýßFê9ˆ”‚ Sªú†}ÓUz¦0(1�±øûL¼ÿ
€§æ·LÎ¹ªx}-8ù©B«.íqâJöJn """"""º…éÿ.í²,ÀŒHú38wlbr®Öšþ?‹ß³€(­ß@åÀ ’±Ç¶Wg|þ¦ ù±d¡ÝÀ1 DDDDDDD7ÖÜ¯+¶V/–Û_B�Wgùs[ì“ ±àýmÝ{?[ ˜…à�„1`¶÷Ó—FDÜé�×ø.ˆ³• ·û!ˆˆˆˆˆˆˆV3�çó¢>Š¼ªª§àÓ“c_Ø2kW˜yZ›ƒøß¿ÛxmdjÙ%^	¡öVÈ³ª¸ÄÅY ª¡HeÑ¼¸>/Xì,.Ùœúü¯ˆ”/âº�@´ç÷‹þƒƒ5	è™Â²ŸhÈç\Ò�À•¬O�³ ˆˆˆˆˆˆˆ–¢Öû_—ô$P?d?Q•—|W}ÆbíÎØû>& D‡>Ù¬8œÎÖOåyùHP¼¨ÐKâR@[TÀ ÑRÄÆÿ;« °ÞÿËAÂO0;uôÄŽ�Ók›"ö~½ÿwl@«àÄ·à0$Ùpõ±O_xK$	¾þ(ÔW "··­�ˆˆˆˆˆˆh5’8ñškðZà’ÊÛïíœ´×žxZmÅž_ªÿž· ˆæ:‚¦ÄéQù™†ú»êõæ, g!ÎÉSµÞ±˜Ùbg‹¡EÝ«Ip~‹,æ¾½Óÿ;” (ôíx¡HÔÄÕý”Hr$„ú«ªyÍ¥q€]�­ DDDDDDD…`±²ÅÌ;‡¼þªˆqõÙ)‹­-Æ.bí;ã% D>Uì"Üý…ÚƒW]ZúÔýHWàÊˆÛ Äö‘
‚¸HÊM_�àGiW÷‹©�¡…±öp'f 45ƒûaÈÐ�XÂèž§'†5ËÏiÈv‹†Rìk """""¢µN¬@ ²L]rNÃÃÿ¡ïÂ°½úÀw›ñú�;H¿c- •ýçßgpî¬ˆyí\ðõLœ8'qÅ�õ;­¹Þ‹�Å9òz²êyQ=€³­kíò)ËÜÑô;œ 0G‹êÒºŒúcõÕaU_oÏàZ@""""""Z«¤Õûß“X¬¬¾þ:Äý(í­Œ[,]þ[ßYw8 ztâDÑŸ0(áø‰£]/i�# &à*€Ø^C„Û_`@DDDDDD´Â¨ý_ƒÅÆ1F†N x)MK/ßÔ?�A»FGl½¬+ žûdÑŸpð¹‡?–×üº‘äç
\ÐàC¬ü·>""""""¢µH›½ÿšyr^\òs_7‚AÉ1`Ã:bëe� °µY ãûyVj)’ªîÍ�ÍŽ«¯Ù‘ Îˆs X@DDDDDDk ÷_5ÎÅƒ$êyÈ«cNôX)s'†‡¤a×Ú?Š$&,¶¾ÃîÂ€BuâXs`�JMË—€ð2Bí-Õ¼áÒ.'.å, """"""Z‹½ÿNCÞÐ¼öà~T�K­øùn~ø»“ ÑaìóE¿‚hï\ï8D^ð"DÆ]R�¸Tâ¹€ˆˆˆˆˆˆÖFï?¼$©ºÔzÿ1Á‹^ò:óæx+~>:�`1õÝøîZ ž³U€M0´RïgŽ‹¤¯ r)î;„X gÑÚ 1Õ €sRzµšn?qøðÇòbúG,½¢ –±°Y Ö¿g<2™8yÐ!›�S_·¯ÞAb"€s ˆˆˆˆˆˆhuR+€·Ø‰æuÙÜT ÞAžœ=$sv•ý£G›½ÿwçôÿî& šªVÔûDsÈ€W54NÍ¼K*	8€ˆˆˆˆˆˆV}ï
—v»àó\}ý8Ä½RÕéKÅTª]w½Bþî& š³ €õnó¸îE÷¢À�‹Í�Ôr!¶ÿ€U DDDDDD´ºh<þ÷NJ*IÙšáÇ÷"’Ò‹‰<t¥¸RsŽžÜÝÀ]¯ èœÐ÷¹tÃ¥G‹_œ•Ap ­ZZÄ¾ÖàÜ˜ŠüÄexkä4îEïÿ=J ˆvÎ8|Xò3Ó=cªò3 o„¬:	_Óæ,€¢/‚ˆˆˆˆˆˆhõôþªN}>››Ö oÃaøøîþ+”°¨÷_Wv@SuâXQË0$^Óêá°úÆÏBð™Kûq%û®VÑÊ§ö,ÖuioBÞ@^ÿ‚êÏZðo§æ÷¢÷ÿÞ& Äú†}ëÅW¶_Éêú·ªáy	¸(iÄ•lT ]‡U DDDDDD´Ò©Å¸ëÆ˜WÅÚà¿šIþµ“S\n]'ÆÊwqòÿ}© ÀÐ'‹À€¦Vpú¯¶ŸÈ5}IEÞÖ�Õ`Õÿb-ùÁV """"""Z©ÔÜ"ÆU…Å¼
÷vyéôç¶Ÿ°˜8ÆÆ�±òªJ D*¼œž
Ð#ÁWß¾Q—Šˆµ?X “ DDDDDD´"Çþ«Å¶ãZ¬c^Ñ#üHëZEl¬÷¬üÿ>$ €mûbp/ŠlÇUIð=Í«/ªæÓÎu•àRÎ """""¢Ýû—ŠÅ¸ëZÌ+.|èºZÄÂ*El|oÝã€èÐ'çWŒ<²aJ]éˆ@¿­Àˆj»òÁj îi&„ˆˆˆˆˆˆè¶ÅX¶ˆí-ÆµX7Æ¼®tÄbà™Ñ"Ö-bã{Óûß* Z_à¥ácÎ¦ž8´iRÝÆW¼ì³™K|p.Má¬@À¶­j'ÿp®”Xlk1®ÅºóZìk1p{CÞ=þïS 0|ñR;¸¯Tº.¨†oBñmU?!i—mPUñœ@DDDDDD+£÷_lê¿ZLk±-à¾e±®Å¼KÅÂk&€§^¶aÿÓ/—ºsÔ‘û£�ô;Ðpâ$>q# ­Š"žMD5Œî»ëZÌk±o\h±ðÚJ ˆbp0~ÑÕ‰.9zH²§ß>¯?U„7BV›„¯Y9„íMˆ‰”ûóy½‡³ÆÊ~�¯ÃgÕi(Þ¡þªÅºóZì¯cá{_þ+ þXîz+#pò‚úÆÏ4ø†+õ¤p%n """""¢e>õ¿$Ã†�7�×ç^�.±X·8Ü¾ÿîo@D‡1l£ÿcöãø¦þ+™¯ü-Ô}M$‰³ l�"gÑ2¤j1«Å®ÃB0
Õ¯f!ýÚ‰+ß¿ÒºRŒ}åþœü·,‹,„í@Ä ŠeFðÈ�ÿnšæÿ‹”û~G‚ï¡‘‰†R‘'�eò9ÑÚ¦±ô_ÅeÎ•Kê’ª6f¾ïCú¿�ü‹Mß�WÐƒð÷«ì9¶ à@Ç¿×u2(~¨YýXð�9q%Il�bàV """"""Z�ÿ,V—ŠÅ®1†UüÐAO-ëÞoË&°mŸï«ÐT²¹Iñòõõ— Ù´s•Rœ j	€ûý©Ñš§–(zÿ]W	!Ÿ±ÖbYÉtÒb[‹q‹XwyX&	 Ñ¡O¢½
áø6O‹—£
9¬�3ª­1ö^.mDDDDDD´fi\YWüS½ýëŒÅ°ËZL;3ZÄ®E¬{ÿËÿ—QÀß�KÃÇœF8þÅ-S¨t½$/ûlú’œKS8K¢X% Ñ} vòŸÂ¹RªšûÐ˜I~t½cÙÃþ–Gð¿Ì …á‹—ÚÁ})k\PÅ7¡ø¶ªŸ�4n°)Ü
@DDDDDD÷žZï?lê¿JÚm Ç!ò|òµ¾|ÝùÖÕŽNÌW¹/Ë.€§^Ðb@_º¥†¼~’~G5ŒA‰ODDDDDDD÷“8‰»íÕ_‘ïjR>údµØû¯*xŽ	€÷ú*C«àè!ÉNÔvžS„ŸBÃ!«NÁW›å–°ÄÑ½™úÛL/Ík!äsAuX5ùùÉ?ï»84$>¶µÇ�ÕJÿ—Oùÿò¬ XH0$ÞõVFDä;!Ô‚Ï\©·¹ ¶ÜïÏ‘ˆˆˆˆˆˆV=µÿ{¸²XLj±©úÚOEÓï@“³E°¯Ëºb}y& DtÃ­Ñÿ8¾©ÿŠ†ôË¢îKPœW†ˆkŽZ´*€eý=&"""""¢M,:U‹A-)Û%ç÷åZ£ëkÇgúÇ‹à¿Ë.¸|,óÈYO#Å!Éì¥Ç?=ñ+ÐìO\Zþ8ÄmÕàc
!·nÙ9DDDDDD´Â¨ýß¦þ[Ì©b½ÿŠ‹!ÔŸ×Pú?ßý‹�¯Ä«=ýr	‡>c×åjyV tê˜œ˜`ÃqUùUÿuÙUWêq©¥aš• DDDDDDDwzê¿zq©ºRŸX,
ÏCÒ¿–ÌŸ�]÷¶ Ü®89QeÿÓ/—Þú,f5ïz)„ú7‚ú· ¾'/ÆÍ –Ë`€ˆˆˆˆˆˆîÕkÆ�tvòïë‹Í¿á’ô¥ã_Ü<m±jü—áÔÿV 6a1žì÷íØo½þáÄú/æ^à…àkï¨oÔÄ•`Ù…X²€• DDDDDDt›4Æ˜âµ˜ÓbÏà«ï@ä…Ì7Ž¾}hÝe‹Y‹XuyNý_a	€EÔÙ>Å¹Þôl€û¶úúaõÙ„s¥.±×-ëo6­$ªÖûo1§ÅžƒZ,:“”ÏYlcÔdåLÍ³o® ÂÙnÅÇ?sy�›	¿ÿVÄ=K B–‹¸¤X`Ë‰ˆˆˆˆˆˆn=-ÂPÍ�+•T½WßŠÿÃõ¹ÿÓ-Sj24„Ð?WÄaôÊÉV4¿¡Çl  ö/»îWT’çUýO5dÞ•zS¸’MdôÍŸÑ­Ný÷[º´»B–«†"ötÝ¯X,Ú›®˜àe% "Û©hÁ}Ý¿þg}½Ê_ï† 9'i7b@{+ ‹ ˆˆˆˆˆˆè¦cÎ¢õ_Õ‹8HR±èóŒ@žóÚý×'ÿ¬ïbëšElºr‚ÿ˜  0$vº/�üíŠeZN}vÓˆ ô9òÚxL¸´„Ø	àcê†ˆˆˆˆˆˆèÆ,|ô
W’´d‰€�U/«â‡pé·N}¶g$žö[,jSÿclº²¬¼@Óñêíovenê¤ _Ö�ÙPÀ)—v;‘²MlÌ[ÕDDDDDDD7cHq%u¥nB>©Á[Ä}I«N´¯U=·âÿ–+ÕSxJÝþQ$Õ‰c3�þ"ÏúUt�ª~8öHâW1Æv öÑš-ä6Š8Õà5ä'ä›IâŽ?‹¹ýOkéè+û&àðSX‰Vh€(Q<á(†‡>ÜØñÎ«gáEQ})äõÓÁ×r‘$þì`ÿ‹?P""""""¢NÖóµØÑbÈ�×òàë§�è)¥?>þàæó8lÕåGQÄ¡ƒ–,X‘ñå
M ˜Îo¸ÊáÃËµ/9	Å7ò¨úI—”J¶³E Ñ4Xìè’JIC>…<ÿD¾à4%`` 3v^‘Á¿Yùeñª¿Šˆý`öþñéMUíù˜ üÛ$)ý–}‰êJ¶Q�cÿ3I*e{Ñçõ—T’×-sßþó‡& ƒvò¯+kåß*« hjþ §dÏ‡ÿ|÷xZê>â€o„ÐÖ�—v—m‡#4Ø�ûýÑ}§vðï-V´˜ÑbÇàÃ|ÃbJ‹-­ò|h¸9;o…ÿ«#‰ÿ�'lâôÎöžQh×�-T£’vÛL@ËØäq§ã*(| """""¢÷KâÉ¿Åˆ+J©1v„{N�<cÊ¦aØà¿•ü¯¢ €j;Uö¼^¶V€ãŸ[7œºôNÃ‘�×& N�¤e¸Ä²<�• DDDDDDköä?ÄØÐbDqòú„ÅŽ)äÇ?·e8¶—hÙbLY¬¹:¬ž@33üÂ¾öÀ?©¥o‰$_BhÖ¼1ãÒ)Y	@Î­ DDDDDDk‘Æ˜ÐbC‹-V„ÏÇØ1Kßn]kø…Õ7L¾èeXMžBÀSê nfSÓáê4ä½ R¿ —–EóÄ†<6w=²€ˆˆˆˆˆhMPµspq.±©ÿª¡¡êß‚ú¯‹KÐÛ½nêÀ€¦‡‹Mr‡±ª¬ž
€H´ØËXÔ=$Ù/Mn8ùúm�w4¯g"©ˆKƒÆ^û """""¢5pòï-´˜ÐbÃ#B¿m1£ÅŽCÆ«¶ãÊÕÑû¿J ¦ã¤*CCâg�“!qß¾ñmùyˆ8Hš âŠ�€L­^­aðÍXPÄYlh1¢ÅŠ3Zì{þÛVWðoVoù»ªÄ¯n bžüô¥þÜc¿$á’¿+‰Û„‚ˆ¨o×¶­6qÚ¿Ú´µ8Ñ9§>Œþ›êÝÿ�&8úÖg·Nc@]<õ×Õ±òo�T 45`{ãÎFû�J¾å…ûª†pX}~®Ô¬ """""¢Õ§£Ú[ÒÄb@‹cL÷U‹cðoåbì¸zƒÿÕ� ˆD‡÷ÚÄÿâxü‹2%š=•¿ô'²YU{µ„x�“‰ˆˆˆˆˆh5°ó|qÁb>ÕZ,h1¡Å†#.;®V«<`Ã,¸W÷ð§¾ÛeY�ãŸÛy©’–¾èè5øYI*iQBÞïÏ˜ˆˆˆˆˆˆî±ÒÿRb1ŸZìý¡Å‚Zlh1b3VtEì¸º­¾5€K’0òˆ6ZÙœá?ß0þð§ÆþkÅaF¡4ø_·	 q"dü±½÷ûs&"""""¢÷=ðßæ½A¼¨&±Ø[õ˜¨|¾ä[ÇŸÝ0^\Q´+®úàmT ,ªØuðt·eyFž}à‚TñQùRðÙ«|æÒî²¸²Ô¦?ÞïÏ˜ˆˆˆˆˆˆnYŒå\ê\R.‡�7‚Ï*Aÿ›Å€ZLØŒ×ÄÉÿÚK ô,jW¼õ_¶ŒzŸ}A�g¡8)R*#²bE$­(Åÿ×þ!¼‘ÏeIùW’fl¸¶N~×X@ÍÝŽÿŒVìåŸð´&øšB¿æëÓ§UC�¤Ò%®dM¬ """""Z,–Þb9I»*Ðà}V{À—!þoO}vÓˆÅ€E,¨RÄ†«{èßO ´ˆ>ÿ;6á±pÒ�>)Ð¿‚ÏCý9Iº —Ø¯+ˆˆˆˆˆˆV5Èà,¦ÓàÏø|Þ¨<ûî®m§ZW{þÂêŸö¿Æ‡ .áŸŠÇÀ€Û;üL:|HÇ�Ÿîùô¥DÕ?à³ÿÀ¹äAIººr@3Ë%±|„ˆˆˆˆˆˆ–‹åÕÃ¦ýÇÈð�ÙsÐðõàK_>õÅõV€Ç?£•ã›žÉ0h'ÿk“[Ó¿#ƒƒahÿð½ßòº&ø\P}Î‡ì’K{!’Y¤86’	 """""¢åÃ:·5¨jf±›+õÂb¹ á9x6¹x9ÿæ¸U�®™�KY» -{¡Pw p‡¥†=òðÉ•ÔÉnÍk¿q[%)[ý4äADDDDDDD÷›ZìÄ¥.žüKõõKðù÷|Ð/�<ºýþâ�°ÿé—KGwì÷8¶¶þ-eíV ´ØÊ‡Aèa[Ñ|YóÆ«*þ‹Á×ž÷¾>íJýW
ó3X	@DDDDDtŸOþcµvqòß‡ªÓÁ7žWÁ5ï~µµÞïèÄ‰óa­û»V t:¨	.¾ §ÿêá‰þ›³ßËfe…ìRŸí‡K×9—Ú´HEbÉ&ˆˆˆˆˆˆî-4¸D’Š�ü‡¼>��ÿØ‡ðåJo÷÷N|ný|7Å¶KŠ½×üÉ#Ø6àÁÁgšë €=xn·KÒO éúG"ùWêé
¾áCVË�H	âÜ[IDDDDDtŸOþCPhCÒîÔ%•4d3³
ùºúìK�ªûÖ™ÿ²õ|û€w¨Yé½F§þ/Æ€6û…x¦ø¥PìÝC§wžwê¾ƒ¼ú¼úüu_s®’¸´\�sõ!VÑ]¦c0çœ$¥.—”S¨¯!ø×4oü­4ú¾Sÿ®ˆé:c=Šß	~®ù¥Šß“@!aÿÓZšœ}"”Ý?I’Ê' ý5›,©¾ê}VÏ� IX	@DDDDDtWOþ}ªYRêJ%éNB6gñÛË>ä_*gxîÍ=[�[Ÿÿ Ô¶KµüwbÀ5Š_�¯ìGbY££‡$[ß»ã�PJ¿®yý«ê³ŸhhLBJ‰K»*p©c% ÑÝ>ùO�K»+‹©oLªoüXóÚW¼sßrµ­§â�¿ƒÏ%1–ëˆíh+ Þ£ õK³ãés=}^VM>Wú‡áï&]JšÍ†àëu�Úð	VÝá“…Ô]R©H©×ùúÕL _²¯HîOWpzôÐƒsExÄq´· \—ýÂ¨ài-aüè X}Éø—µ¼1«’–zC^ÿqé&ºE=4ä¶@ ab…ˆˆˆˆˆè¶OþUÅ•$é†KmÚÿÿóü—Ë	¾þÆ³ŽÄ«=ÿƒðþ¯��ê-VØ$É‡Ý©‡Òžžß•¤ô	hø‡Ie}�æsªy½A¶‡‚ˆˆˆˆˆˆnCðPiHZî’´O|ýê,Ä}ZûJhè÷NìÙy6–ý/·Ñ’XpÓ• /—0±?ØŠÀàÔî§/ÖÓF#‡.ŸÍýšÙ.I¥¬ """""ºÍ“¨$¥HºíÜÚgs²Ÿ}IKÙwN~þ±±xÕßMñd¿àrÿï� 7KU �Ù$•=pak’êG‚ëú„ÀL*ë·h^…††ý§q²HDDDDDt+4ˆ«Û«¤ÝðµÉË*x.É_ÎýÅWN|á—/Þ8V£ëaàVhŠa¨UØ‹»žîîê-ÿ� ü�KË¸Å9PŸˆ•¢p& Ñ{Ÿü‹�ü;ˆ³öÿ Î†¼þB"ùçµïÁïÿS©Ç«Ô{_~,çwõæ1pËb@¿ »ôø?{{].ýr]åÿÞiø#W^÷|šWë�Øfá˜ """""ºnœe1V $“¤«I¡1uF�<²ðßÊîò›o}öCÓï›Ñ�1ð~©ºO½ào{ª]°çÓ—>‚�Z\úqçÒ]â¤› Úñ­æ÷œˆˆˆˆˆ¨Xµ%WŽ;Õ4 !?«þVJ¥?÷ÐÆWâjrÀÐ^èüð?ºFß·Ö”Ig!~ü×ÃŸ:Ù%.}2I*ÿ*ÿ,IÊ{í[¬y-ƒˆkf¨8€ˆˆˆˆˆ¨ˆ«‚Zß´j�´«d—ø¼þD>²ü«Aªo�<ûhmaCYžü¿Üð¾µ~áÔá d/�?+ö‹ù³'þõå†¯e½šAÒÇ�K{m3 †F|ƒ"aÀ¹ DDDDD´–Oþ-ž·	jeË$ÁgsP\5|5M{þ¿wÿ|Ë›vÍ½µ<xY Å“ÿÛÁÀm“€!•áV €u~óñKÙ…?K9ãJá‚êo:—$P�Ä¦
D`ÑÚÏDœ´&ø»àm‹~‚<›çú��¥þ³­kÙŠ¿üóÔÿ61pGØ/¢ŸKß~0=ZL¦<ùø?»üIµ7(rÍë¿,®´.qêc»ŠI/VÑZÃ&�ÅÐ"‰¸24dP_»ª*?w_IBò•_Øqî´[ÿŒVŽ_Ê1‡2ø¿8àŽRiV÷·Úä‰?º²Ó‹üN’„èI»º4ÔUU¼µ»ˆ%a˜ """"¢ÕÎÖúY)¿$"ÐD\*êëSP9�|As/ÿâ®sí``ÀaðžüßAL Ü5ùÍ]gÊGþýîª½¸ëàÕM]ýÙ'Â?‚“ýâÜ6IºWZ2+„€8ï’Õ DDDDD´Ú¨�û+œ�|&b+þÔ× ê/ è¨|9”Ó¿9qhÓ¤]û7ÿD»�œE£µm�îN¤¿†Ž¬{ÈÚ ¢³CÆ3þ+÷EñM:f»-Ä•læ…õ³dÅÎK"""""¢UÇb�H¼H÷üøK¢øŽºô?…Ü¥ü›#ëP/ÊþéNcÀÝtP“{Q:<ˆº•±ìxZ{z²KŸà ø¨$én—Tºí@Õz_rVÑª:ù—$u"ñðš×«ªÙY=¢p_ÍwmýÒÈ mSp¿ù'\9rö!žüßE¬ ¸›†�VËè!™«¸ò·²þS þ*„üg!¯AÒn ¶ÀÕcOLœHDDDDD´R©5Þb‹u,æ	yAýÏƒº¿R/ÿw©ÑøVü›Ápäì‘Oþï.V Üêœ:U>üÈ#{+wÿó‹¿ZVÿ÷ îïI©ûI¨ß!.îÁ°J «’i&8€ˆˆˆˆˆVŠÖa¦ˆ$¥xæ¬ÁÛ ¿Qõ�7Uõ[HÝ7Þý³­GãÕÔ=üÂ©òÈSó±Ý=L Ü*€tþB?ü©“]]èÚî¿ Wþ} ücWêÙ ùœWm.°Ò þœˆˆˆˆˆh%ÿE,)õ¤– Ùìi�û�Æ·½¯¹0òlëä¿H`Ðö©qÕßÝÆÀòžRÙ{ðXiëÅKáðá�å­D@ª]E*ÿH~×‰<
`}Ü`s‚upK -ó)ÿVÒììü²õ6]&ƒúS€?ìòð7ëºÎ¿tôÐGl :pà»éÞm[ÝðÐ¾Œ�ÿ½ÃÀ½¦*hí·l=8Ö·n¶«&Ç©þ ü®+÷õCshÈsy°Àžˆˆˆˆˆˆ–õPäpI*®”À•êÓs÷B †Düfêatì;fß+6¢»+½ËïŸ‹¿à*8w`/dfrô�Ì\Žð''òt.’¹�Íý
ÄítI¥Ç¹2·Ñ2�ò_JÄ¥‰5 ß˜AÞ8¯Àk@øz9«|ùÍÏo¹b×Þ{ðõr÷Æš�80t00ø¿÷Xpßhó{¿0ãµçF·¡> )ýž(>îœûÍ¤²Áúf !«*BI8€ˆˆˆˆˆîû”õ—‰+w»r|u<¨“ÃðúÕð½�è»'ÿ|ûØÍÄAto0pß©à ’ßÜv¦tdè¡ZëááO_ü•’÷Îý=I¹%€ˆˆˆˆˆ–í”ÿ âÎ…P{] Ïkpß:þ¹-ÃÍëËÃŸBeäroÜ×O�cÀ}'ŠÃê�<¢Àîù??ûF‚®	ïÜ1õYÜ I±% htl	Pn	 """"¢{>åRJ!ê§ý/AÜ7Koö•6_šÑ‘G´�gc Ãàÿ>c`YÅ<Ü^<“nÂáÁ¸ãÔÃŸ:y!Õ®¤ŸÍ5·¸õ.å– """""ºçSþS‘Ô‚~hÞ˜šYðÿ-	Ù=ñ¹?j½Å�M/á˜ÆPÞ¹�î/¶ ,7ƒƒþ@¸%€ˆˆˆˆˆ–Ï”ÿ¡>SLùWÿ×®„ïÕ&êçÏí®v¼‘``@Ç6t1°,]³% îÊüàNnÎÓ¹$"í-bé8Í >/þ¸Ä~®ÂŸ-ÝÞ©¿…IÉ‰KÑžò¯z^5¼Á×KYåÿ}óóë›SþµÜ½ñhsÊÿ'­ßŸ–‰«jK@£ªÐD 	 ŽI """""z±ˆšSþsq¥ž››òßŠa®�chyà€e«õ³pKÀ‰/ÈE þôÅÙRðu…V}6÷$4ì�¤«[ìà?d6‰ÐX@DDDDD·Öë/vâŸÄr ¬>¡1sN%¼.*Ï+Ü·Þý‹MùÁ¦üçüN/oL ¬¢-.íÙ§p}:‚\‰Ø¦€˜ """""Z‚ªû{ØI¢Õû'’Øàñ€�×F ýn<åÿ)žø¯ L ¬¢-ycò7Ä%Û¡~“s]ý’$‰UhhØnÑÁÓ L‘ÎÇ6àß•S›ò¯>Gðõ4¦¯hÈ.úNù_x*¼Š¶ˆ&{Tä· ù'Ào§Ý[œU„lÆ«j|›¢À¹ûöùÑò !($ëçJ}‰¸2òÚ• ‚!Éw�å/!­¯Oá§ü¯|L ¬Ø-CnÿÆƒ1�om	0O|jì—ƒÓßÈïÂ%ç¶ÀûRêvöÃÖ8 ³¡Zé`5 ÑÚ:õ…¨ˆ+ÙS,Ð¬�$WÕ‡ËÐð¦Š~!ÿÎ»ñà+­·,¦üC�î€Ç p½ß
Ä€Û á(O×l`îÍr¹ÿRÖÈ~�ªûý=¨þ$y@\µÑ *�`ð ·­Öæ/*ê%&\E’rs€¸^BÐïúíî§©«žËü®Ë�o><„öÁ#­L¬ XÕ p�O¿“®ß=ŽúHû�òáƒcÛK}úû€ ä—%MwBu›HšÚ°@„œÛˆˆˆˆˆÖÊtçœH
¸°Yašç¹¨y~�W8ò­‘g¸ÐzËýO¿\š<½Îï"ÇPÑ.@+ «‚
 K•á|àé©-.ŸÝžkéƒâäïèÇ�Kžti4¯B5óš+l[ ¸-€ˆˆˆˆhõ�÷÷b½þ©¸r"I7B>‹ü[ò¼ýA*Ù›!í½ðö¡uNý£u´N�…ÕÇ´ò0°
ûG�&“•ýîøŸJ½õšŸ8×Ó³Ùýzpòq�üºs²�-.©ôŠ­Ü@DDDD´Ê¦ûÃ‰•ùÇî_ÄéþÓP¹¬Ð“AÃO\Ðçç®„�~åÁ¹Ö[?þ­¬¯Gwì÷üW& VìgÏâ(O]¼- »O·¥’<*Šß�Ø°@ý-n """"Z¥Óý­Ò·ÔïlØ_^Ÿ¨ôû÷Ýô%U?R�‘‹—†˜Yøö*ó‘"OýW\uš ö; î à.ÃÅi�‡Äþ°íéÄŸš¸\}�ñ¼6QlPlp¥žÒ‚mö¿öŸ?7-?ZÄ ÍÇî’”�s¥¸1,ds|u\³é‹x]E_P//Œüå–cí7ZK{'ŽÉÖ½ûÂa4.œð¿Z±`­T,ÊÜ=ü)í*w]Ùœ5²]©¤¿"â~ÁÿŽTúp.A°ù y£n¿!ªjó\‘`€ˆˆˆˆh¹øS ˆˆ��úi¹âÒî8ð;4fÆÜ÷ü×‘á•-oÚ:ÞÙ.|£¸�V& ÖØ¶€½@²u/ÂáAÉ¯Ý� t~[€KÓb>@€†Ð¸Ä²ŠMLÝÇ{H.�¶ò{~¶W1Ýy~^E^õÞ¿Pªô|½sÀŸM÷¯Nì—aÀcèÚõâ´:1°¦ÜÄ¶€�|H’ä·‹mé“I©êë¡õ>‹sT�ÝÌØD&ˆˆˆˆˆîyðT%@âÙ¿H’”œ«@’
|fÓýóbº¿÷?L]òF¨Ö.¼ýŸätb`mºþ¶€]µ»Òsá7l[€sî#²ÀlrRNâÎP€æEUÀ‚	£¬ """"ºëSýí1yóÔ_}† [í=!"z:„ð²M÷¯ÏmÿÑÙ!©¶b€Ç?ƒòƒ›àcŸ?×ú­I¬ X³Þ{[€·«ý¥ ùu uÎ=æÊë€àcU€ú,WAˆYGQK�ˆˆˆˆˆèN=nW;�+NüEÅæs¥•D\°Ù]�I„ÞÜKNÃO2Á«AÃÙ%§û¨cà¿¶qÀšuí¶€™QÈÑÐKƒóÛöüá¹SZªœø1þC¾võaÀm‡�âÒ.—VâX «Èb5R¼�Šy &ˆˆˆˆˆnûÄ?)%NÒÄ.Ð¼†àó9ä�	ˆN 2¢Ð7UqDóôÇ§>¿étûÝhºÒ·zÏ„¥Z�imái-ÝxêçAMv­;³¾+«l”$l�”>¤ô£
Ù—vm¬Ä·¶Š€l.¨ØpAKRÂqs Ñû›è«´µ5\ª©”zœKºã€?_ŸœäçQÕW�È[šù+µReâìÔúI‰_ô>9ÝŸÚ˜  %·ìßW�€?‡bð_ÓÞ?ÖMYcìW5ÅGUÜ/:q{T°YÔm€æë¤Ô+Ö ­Š µŠ€˜°�¤ü�#""""Z2ðÛ¶%ëñ/!öù«"d³
I§ ×�_ÈÛ�äU89â'ñóC›&;Þ�ìýä±R÷Æ}zt�Óýi1& h	*ƒý®Yòä§/õgi²1	²IÅ?•ß@Ð_u•¾Ä²“¾†�M«j¬(& I¼Qck Qç‰¿�ÚÇ>Z;ñï—tÛ¸3xY¡?T‘×‚ON¹4LôÔ²‰ŸaÇì­>–§µ�	 º±�wà…§Ü¥m[�½8Œ}¾³¬hïÀëåìôú!)ý††d?à÷AJÛ l„ú®Ô“Ú>RØ>RßˆeKÅÐ n """¢5Üßo,Þ·ÇÊ®\Lô·ÇÌÙ\®’^„	…ŽAÃ›ý±jí‡Ç?÷Èð¢wåö~òXœë¶õâ¥pø©ÙçO×Å Ý„gÿÌÛ•lª´±‚¾HüƒÞ%D�ßüG“´çQWî|!›±53œ÷XRÁ±"€ˆˆˆˆÖ†x¬²ßæùY…¬H’H©’”í´!¯žÜçô‡9Ò7Ò,?Ÿ¥~bSrvüè¡�dK¼OžøÓMc€ncFÀ1¾¸/à°•ùÏÛõG§L“Òo‹à£	Ü/Â¹‚d=‚ß I¹G’T2h°b‚Öœ€¢A ù«ÉßM""""ZÁšU¯­ÿÆGºÖßo'þ%ˆ8[«mU²s*n®"„Q~•—œw?|ç/·œë|�û÷¿\ªîÙ/Ý�êÑ‰ýìñ§[Æ ‹Þ‡Ö$ÑëöÉÎ?œÜÔ]®mT¤Àç�»$Ý��Ûæ€_M»7»XÐ˜µA�A¹Xï“Ý(jì{rÍ›HÎ """¢Ù×o�lU%ØÿÖc]Q¤âJNÊ½°ñXyõJÑŸç^‚†—ð®8\Hæò«oÿç�W–|¬]<jnb�?Ý& è6©` r p—†�s†>Üè¼Æžƒï®Gÿº�$A?~â`³ l€K×Ù€“Ø	€PTXïSœí@�¿²ü�%"""¢åyÒ_´ÌÚ$ÄÞ~Iboë±nð5 äS
wU�+ÐpJ4üÔ§xIdö''=6?Ñßæm|½lÏ·îÝÛ;Œƒ9Ø�Þ7Stç*n0'`ãÓï®ßXÝ¸>qÙ¦�”QmüšüD~-©lèuÎÚlP`7Ø
AUÍãþSËŸ‘¿cU -¯à_‚Ú�k‘«Õù‹�ôC’.H’Æd@|ýê,?	*/òrüI_)�“‹ƒÿkûûƒº=L Ð�7 îÀ/ÌoØ»/Ç Ý Î¿þÑ‘Ñý‰KKEÀCI¿JèB�u"ÚÈºxƒ§¡Ú©UäÐš3lOj«�UDDDDt?Nû›=ývÒOü%V´Ú� Sª2§S¢®à§œM~âƒ¾xrö»¯`è“¾ó1òÞáÎ‰þO…�¡‰î & è.¹ñ4ÒŸx¹gÝ¶‡7x•>Õ^§n“ˆ>¨^?ìœ~Xƒ~X\i‡+¯‹·°V€¼ÚÜ"`k-)`åUê,ÀÊ """"ºÛ}ýj§üñ´?–â[{*Iê$é’4>�ihÈG!zL5yMœ?¦HÎ	ãI.³‰èÕ©‹�«£_ypn‰�Ã‰þtW1@wŸ*ùdks dà‡†,ˆ_h×Ÿè¦®«£¿à’äÃ>è>Aò0€!XH¿ ô‰+w‰+ÇßÜ8' Ømp^Ì°u*ÅìŒÍù{NDDDD7õÈµ5¶¿xfYq|Ÿ´Où�=wEN 4ì ª
$Ó€N«†@Ï+ä”Ö ¯ÍõT^?ÿ­¿²ø<¨É1 éÞ=:�€çl5 Küéîb`D÷aNÀõoØžüô¥~Iµ¯Ð_Êe½}Ô9}’ì!|Øf¡¤åõeë¥ŠkSâ*A› ¹@¼õ4¯ãÍtk~@|‰ˆˆˆˆèºWcysz|ÔZœôÛY¿Ø,*—Šköô»â±¨oLÏAÜ1…sjÏó“.øÓYšNV¦5—™·>»uú“ýéžbPD÷�
¹ý÷¸êÄ~il‡¬¯#=„|q»ÀãŸÑŠÌ�îQIö!Xñ€î…Êƒpn³hèƒ¸>EèsIwj7Ä±] VOíÇ¹Í¦V­aÍ>þøÏæã#D×œÞï`ÏÛÿ¶,@ÈòZ&�¦E`Ï/‹êY†Ž¥Òõú®]ëO”|ÑÇ“ýO#�¬À•/@»7Õ£'†õ£{�	 º¿Ïðn´ÒdÿÓ/—¦Ñ·¾‘oëu¨÷M6§‰{\>à€½a¯séž¤¼>Þn«o 6|%ÌíßAEòbÿªõUY5€ÎWÄ|V­…>þùþ8TÚÆsxëç‡Kœ*‰¤E©¿+Ç+ûú„=¦|[ Ã2'o#¸wÅ×'´«2ÝðnæìñŸNáðÇò­Î.÷>Ó|ÌËrº÷˜  eÂnŸï“{Ê¥ácØ‡aùÓQ›vþÝÜ]ÿ ‚ß§ð{]’~ A€s}€VDÑÑ.Ué—–\Ziï_�³âf�Ö¿Ãü+ˆˆˆˆVé	¿,qÂŸ´#†¼n'ý¹æ RSÑ9¨«)‚�ø�ªÇ›:œÃMßyvãÕk>ôAMö	pÝkztbÀÞg´úðÓýÇ -ßY¸ñ¼€OŸë)×ÓuiZïíï÷‰lNBþ$»ÿ�*vÛšÁ¤¼®×’ 1ÝìÆÝ6+¼¾•ý…ªÝÄ{‰âîÂ>'V­˜~¶ã¿['ü±4Nð‹m£vÊOø+qT”ÿ¾>9Èœ†$gTýiHé´wþLÐärÙ×§|¦3�z6}vhwõŸ†,Œ´øÓòÁ -sE¹ÔÁaÈ‰�p“•w\ùBC‡‡öeKÝ˜îþ×W7&³á¡¤ŒÝÐì!b›vAt—ˆl \·hèR �.�öHRq’”æ+,9PÌè¨èÈ$_óWÃä Ñ½Ññ˜,¾ØúO<¯YxÂçöÍŸðÇÒ¾bÁ{UDç®„ªª^…â�œ‰�ÿ™¼ŽÓ¡ãéÓÿQ&–ø4dï'�•¬bµ=Å/ôFm­DË ´4³¨ÆÚÞ£„êñ�¿]ÉØÚ4ºÊ®Ò£È»r ß¹°"»�I"»C�‡DðˆBLËm‡kÑà­BÀVz+‹m_�æŠÁù­–\nmÀüpA&ˆˆˆˆîðcÁ¢Q³U#Ú>áoFÿöˆ¬x… -Íþ¤“öØ.¯OØÖ¨s0âœœQ§ƒè@FBpWŸÍ\­áeNÒRµ4v©züùÔß³…u¾§þs$Z¦˜  •i`Àaø9°q^@c{YÖ×ŸXr“@§­Ÿ:¹}£ô=Òð0¼ìR'� ú ¨ì °NDz¡KTz è†¸.þRd�Ñ±a ØÍ-1•w‹KÀ:ƒ»òý!"""Z¾ìAÓ’—ì±ÜüÅÉ~ó&žô“ùãe’´·=[�o9P­Ú)¿@çÔ%5�ƒÓiUäœ�KÎ
td¢6sæò½Á§Úœà_T¡nÝ»/R<w0Ü¨U•h¹bðA«c^À3ï]Ð²ëàéî¾.×ã¥«+”|·jÚÁzˆÛ&!<*.X4Ù­ªúˆ¸ÒfWî�åd¶Y V>“ ¾cÍ U±ž�Ö§UÜYÅ>°f2 U9€ŽË9c€ˆˆˆÖÌI~3¸�ÁsÑ¤_¬,¼<vðGv¼¯‰´êúÛ%þÖ¿ï ;¨‘$¶m†zœÉwAUGrÆ[/�3RJN)—‘§WEòšË’j¢¥ÚLmrî†½ü‹OúŸyf¾ö“eþ´B1@«H,É·í*qfÀÅ½�™QHuÒØþŽ¬¯O…£‡>’]ÿÍUvzòÑ.­>¢Iå!hþP€<"ÀN•°]�öjsÊ
­@¥hÙJÍàR'®{*2ÔEu@q×:
š•vWŸ·«	æï;+Þ÷_)«ˆˆˆè.œÒ¿Ç[,ÔñØ¦uà'Y_œè·Nö[ÿnogn�òÇÎY|BÈƒ"V{6 ÍDlR¿ý[jaF ç!8'AFpÖ'ÉÈ\V?3ö—;O-°xåôde�+_xB­Ÿ¿otÛ0tÈzúŸi5|ò´ŸV& hêž[Õ1c{7Ü5y²ÿÍž¬¼«!ëJëÞZú}	;$àAvŠ`[Ý ÕÍ€¬ÅF¸t}ÒµÑÒÅ}L(‚ûù¶�fÅ@úÛ+ã5â[™nË´ã÷ÖÙhQb ^T\¶ [°àmÐq§»à�ˆˆˆˆ­Ì[PzßzØÐ¾¬Ù€ßê½ï¼ÒÂ·k½MQY<¾‰¡¿ùÄI\¿×Ô×^Ëgåüö\ —2ÙÃ'øÚ„ÿ“*°a|S\�Ê„¨^"�sçTÃh*8èt–'U‘Rm:›�{l{ƒRÌrº{üÔ~Ì¸øk#Z=ÐšÛ(€á!9pq«Ì<Ù/Õ‰.±ù–ñÝzñ…pøðÇl/àµØý?^Ü‘VòI·y¸­Ð°!�nŠuÙ$"!²É¶¨ õ)TÊ*j+J¢6�FËjÏcå€¤pI³rÀ†Õs:«Úw¦í;ÚŽ8í©·Ï—¼láÜœù÷MDDDk[ç¦ãÅóŒ;žÏ—½/º¬ù6­Ë¼mçé>šÃ•óæI¾
ë«”LD3¨djÏíeë·©«¸\ÔNûCŠqU�Pè¸LùD®Hî&’ CðcAý¹_Øqñz_å�ßM/m{ÊYE¨õñwo¬iß[ÓzxÛSÊÉý´Ö0@kÐâ
ÈÍ®lyøSÚ•T&*põJ2W*I9+çy’JHÊNòÒJIèÒ�¬Ó¬±QÝÅúÄÙót4ßÄ­`S¬ €l”$ísåõ¶•6&¿Äþ×ÄõKµ,J´^×yyÇëãÛ0	@DD´Æµ*ò–à/(Å_¢D¿5“ïÚ×-j@ì¸Š@¯�I¨Ïg �€bRÅ]qê§éH>I®ÀaRsLˆ+MÀÕ§$¸*rßšfê|#M}®I©ág³=•º¯OÖGž}´vÓAí’þö÷�§"´¦0@tM… äÀÅÚöš}Øç‡†lÀßÍÛñ‰s=é¶|ƒó=ëJ%¿ÚÕ¯¡±ŠuÎÉÆX9 ØD×‹êÛ@ HÐX- €5ÄÑ¶V§ª±>.þ[`	ã¿Ñ~Ù^­e·�¯³ÙVgW¼¤cï;¾+Þç­=1*·ã oŒµ5”HÐjI´Åfß¢=9	Ö Ú¯	örómƒˆØ©~€Ærû €W)Nù­«êœŠ\u*“ª¸j'ùÁëU¦Ä•'µé$í™P¹:=5[º:ö…³·ò§ü[í±xÂOt}L ½W…Àm~QÁÓHwà|©w¶’–»Ò´VJÒDë¥,s©y9IòÔ{—–\RÉBºâ×'	ú¡Ú­ª]
)AŠÄ T+	`-• -®¢!”]âÊìz¡UÛ[X6·¢ÍëÛs�”¡¡"=âK04çp. ÑêgA¾ 4xN4qU…6°AÉõø\ÕJðÐP‡ÙSW§Yð¡!Î5€Pwqê>¾�6€RÝvð9h'övUï1ÕÉ’ÃT|=IBî}š—6R7ë½–²J#ÏóÐ•ÍöÖó�Ø™½×Jç›Í~¢ëb€èV«ÚÛŽÅùÀÈ¦N‰ŸK»ÎžÁ:Lù÷S5`¶ëëßXÚä²Ð'}¹Mµ'ÕR9äõÞÄ•ÊÎI·Ï²IÓîà}·$Ò4)Ãå=B·HÒ-E ß­jûq´Wãží–l§a¿¸Ä¶0@DD´6 èO«sÓP©
B*³"ö\«j‰õUu®Š�Î9ñõZuIRÕ<¯&¥Ò\Zõ!kˆû.­:/³©ÔAÊ³¡äf¦'²ñKCÌÜêgyðàsÉ1ìMf{ö9¿	b�­’¯¥u�(ðŠ>þ}qZÿáa°�Ÿ7ïÿˆè7Tî]âk    IEND®B`‚ic11  ‰PNG

   IHDR           szzô  ×IDATxœ½W[lTU]ûÜÇ¼ZJÕ*à¥¢ "Hx¤1Æ *1’¨Ä�"õ~Lü1¢’Hð!á~Œb"~h0ÑmˆQZl�ŠÐ¡-}Ì£sï=Çì3s§ó¸ÓšTÝÉdfÎ=g¯µ×Ùgß}Ú¤ø×Üíý+²v(é®�’³ eaJFHô’0/yÊ9Ò}tÆ÷…˜äÿhl½¢týA�±CËRÞ”tyâÔðA a‚Œ¤t(ïˆ
ÇÛº7�16áe46À¤ÔÀ93\×â¦âŒ(€ÿŠ©¼O3ROnzà¢ŠÔ­ïºWàsò�ˆ¿gFêZœd_&JF%p5Dð§2ÝqŸN2ža,Ædlš÷ê�e q�J•\vA@*£�Îdcâ16©²ÏÂ6±IÿçpõãòT ’€Pr¹	%[…#éŒøKÊŒ£K¤\	4Í2°¬ÙÂüÙ&î©úyß�DÇu?t:èèõ6€ˆAš„2ËH”„ÆÌŒ´òãµÊKë …00¢ðX“…]"hYl#leu¾ûÙÁ[gèHºˆ¸sÐUä0×š
h€ôrpÅà,óhZáµMQ´=ƒ•säqh%Æ²³üµ�„îE.†3	Aˆuª¯Q‰DJzü·Á$"3h£˜ÍHZáí­Ux¥%¢É0°È%\YH 	ìøv=Cu!Ò[–˜«‰ç”("Á©@f€«,Ààh6rw¼ññ ñÙ'�§\…¾´DÌ"ðŒI$MU!»P¾ïœÙœpK›LìÝÓQ›“TÊM³	-³m$”Ô	8˜Q˜iš#&Ò^0	QæŒ ×ö<ËK=Y9òIÞ–ˆ_”¨¸/&°¤ÎÄgë¦ã�gbH¹ãÇ¶ÐÌRðä˜Âü9&Ö>dë}/Ýo+$ÄàFüåw†põ†CØ·(†­ë"zNz‘Bó,=q!‹²u1HAÐEfù|–™ÍìBóŽ?^~`W{\x¬Zlaã#!=/ãa‹ðx³¥}—ª ‚$]ø@V˜B¦>AVHä¶É‰Á¯»på'Ûj0szÖµÈªúLH@ ®:;ËŸìGÜÞíbõë8ÿS¦Ü¾›ï¸áÂSÀŠN´Õ Ê–c¿|³Õ×ý¿4(³,|®ãª|Ï{û%^<pÃ	…Ö�‡ñæ–*|z)�_{\}W€—ª7é) ‚Ž„e-çïúÂÎ§£ù:Òvt¿üéò+«ÚÁýˆÙ§7Ù¨Ü„ŽnDÆ'³CË$]˜ömŽáî¨ÂŒiB—éÕÚ8¾wZÅÈ}œ#4ÙH]Ï�Ë�2®‚eP¾ÊQ.ë÷<ÕÉ·ÿø(Ö/áØà¼–ÇÆ…ËŽö-'" r/”Î¾¹’ÁSKBù£ÆÆßì`÷Æ¨~?ù¨]\”[ûõ•®õz˜£²™(]Ä$ø­wèL2?¹¨päêÀæ'Â¨­E�I©6>®‡¾LjŸ¥ò`ç±0áÇß\ü"¡#à:_J‚É•VÅBp_¹wO'Ðþ»«}ÊB€�×VÞ?“ÄÉ©¢>À÷Ôò3­A×‰cçS8üUµÒûf*(— ÊzŽ¢:LØbÈIŸ8�ß=�Ä‡g“¨Ž×þqãqéÒ¼m}×É°f+é”	ª³Ÿ€Á„Â’F»6DÑò°­5È¸L_hÏà£sI´w¹ZEèK	‹”çÜ`§„]½E:#^¶už )õ€y¹¦táõ\ïU¶)åŠÈMi×MOËÏ{^I)@yÂª6¤“8UÚ–sNÐTÛr~”pAm9ñHã¶[‡­Ø½»�D<CDvÅ¥¹-	:v>‘àý.@W*cÅêm'qûƒ®c­ù«Rç¬ÿéjæ¤ú/":C_Í¨ôrJ;É°Íÿârª<>ò“âËi–aþzÞ¼½…‚µ]Á]©îdhjÄÝ$˜—ÎÑÎ’ëùßt—ð—Mëýñ    IEND®B`‚ic12  ›‰PNG

   IHDR   @   @   ªiqÞ  ZIDATxœÝ[{pTÕÿ�sïÝG6/’@"_u¨ µõ1ŠZG©�>â`ÇVŽS«bÿÐÖbg¬3í¤V­õ�ØQªÕ*öµ*µØ2-Š¢<U($!�lv³�{ïù:ß¹÷ÆM²	»›U>gvï=çû}ç|Ïó�a‰f¾ià­óþ×‰;Žpž%H�OD3@îQ Å aàÿJä"	a|*„XGR¾nPæÕÍMØ£n%+¡ AùÞyÇ¼“$–Åm™·oª°¬ëAô)­F	R¶þ€xÌ¼ãB€ÒÒ�‚Rv;„xžìä[›¸i0¦Ao"-1á6·®‰Fj§.‘7J+Vv/ÈµÄ3êwóðÐéÿé?…aIiUAÙÉŒÝ—îÞtç®•g¦l¹/ŠÃø3×	!³úiiUÎpÓ] "GZÔ_
""‚+„0�H=”Ý».ëô~çš?,ÑÿŽÿÃä¹»g¡ªW„5ºÙ¸-Ì/ð¼‚pŒPµE*Ûîf{/Þöø‘ër… ûõƒÁ/ho1¬Ø_!d£›íq„Ö—<“`²c2B•¯´,lŸ¬Á3fh�À¦•âè«wDäJaF&(;é!M&ÄX4&#Ü(”±’±2f€„lm…ÄÊ+\ÓˆÞiFê§¹Þö‡ø€c3ÂuÓ+cnm…ÔR8îÚÎC…6€”räXn{Y}¯*ùžuÌˆÂTÒueö¤íËÆoe°$mÜbXU!R•<�fHïÃ”µ�dŠÐ“$Hxþ;Ç¿1Ï—„`ŒŒÕpp3cÇ/Œ7(7½YÊP=©lÙÀ{‹GÊØ@*Ãî¨®˜P#1¾V¢¾J"ñ¦J¦	]½
ÝÞ§7ÅÎ¨„LoW¨²í"!CB¹Ù.iFN4ÉMÍ6ÌÊze'+Êh‡gÆ|2CÈd�Iã%N?-ŒóNµpò1š¤–�ú2„]û\|°ÓÁë³xçC»ö)DBž0Ü|B(Z0B�›U†«WNb¶	³ $éo”ÄÛ–Wœ�L;ÎÄ•çF0ûëa4TË¡ú®>ç]‡”Òyü‘¦þ|÷¬:{V­Íà©7ÒØ°ÓAMÈ?ù=ŽìÙ‘›ëb9g¬Œ™Ä,1eAÇFaD¦’“á0WŽ|w‚0±^â¦oÇ0çœ,ß—(l`ü†S2mýÿcz O¼žÂ¯'àÔ{ e
w„º}!C%Ì°$'³‘£¼‰¤æ¬$ÝÀìï%\~FK®ªDS�Ç¹«<u�Šµß;øcò–ç•Þ�vñ\8ƒÓÉ‹%€Äq„Ø'Uñ$Å06†<ø‘&b‚E\BbÃàdÚ&üüª®›]Ñ<×ò—Bä�ßc.y­ë;mÔF%˜ï\f-,% z“ Y«ƒ`$1SpY4ƒ¼Z4ëüQ5.ùFXÿ;p{£%^}S lîÃú}6ÆÇ$2jè2É4�<ŠÙ„ºE6A{«$VRYÂý×yà×Î«V2„çú^ú,ƒ�%`� Š 3šíœd)ÌIßà±¾_zºÞ,c]HLŽÂ¾´oÓ‘"D¶nÔ³c. Ó€ŽÞZÏcÁ…Ñ²ƒÏ¥°DMöÿ^`4,±Ô6mŒ �ÎB3K~P©W¥ú>dß„¤ÀŒ:‡†e40Ä²ëì éGx‹¿Ó¡,ëèX¥M<,�ÇôJŒ‹Imx…uˆíófUL+œßÂ’s+Ñ“%m;ŠÂ„bÀ§	Ó'{Q3W¨/…8xâ97¿ë ö=×’6!«<ûÐÙ§pJ½…O«Â5FqÂ$CçÅb³ÐƒÄfîQ­óA�3Ø•?½�Æ¢e½¨0Ì>Àm&N1Ñ•ThK\ÔÂ¢©1Ô˜Boÿ¹ßŒâ'�%P.<y2‹Ô‰‹Oëïø›–öêŒ‘W?Pk�+šÃ¸ú¢(ê£Ÿo?x	à[§‡qï‹}H¤&ç	Ì'aŠÁr‚sÎI!�ÒÏXƒ¯à"Ç.À%ÿŒ <¼*'å�³ýƒ1«Ìøj‰3N´4¯…ª§,†Á™'‡Æì$xmrDh é¡2"°ü¶4ÖIí�8ŒÖ�c òydaJ² æP8åXsÄl.RÌÀ¯üû@ðüoåt–		<yk¾6Åê7�€øÞaÚd•Qo—–E R ¶Mh'1±Þ‹x
 ƒ
$ÃErÀ/Ë>xj±žŸÏ·½–&5h¨‘ú¹Bø”}‚àMuFyªüAŒp ¡ðY§ÛŸ<�>6øå·Öà«>øá¢Î ,¯~c�„ír�§>˜º*o¸BÜ‹Žü¸a^[—ÝÕ�O:\m¬!`žeð�|î¼Lµ•…jyðG¼UqnZà³�×˜×ÖƒµÙèŠ+Ì¹§;Û=!dÌ3«Óø1¯|xð‹ÌÍT9y*Z Â÷µ…0Àó¶w+,¸7ŽÕl½\ëÛÕéj!lÛãjUzúÍ4niå|Káà€ò«Fe„RoÄ‘öƒà^ýA/ÿ+ƒ£'H½ÚLUŸvºXx_\§ÐmÏ'µ`ƒ¯K,_\�%€xãÝW¨¡–•¦$°?ám�‘
ç: ! õìîž[‰Ž/ a^Ø�rµc¯‹{žMj·Æ¿]ùÒÀçòÆõIY®H�8à0€öJW€tYz„‘uäFÀ—Vàö91Í3Æ±ÿæJ1ÇÁ1ƒOù+Ï®®Tð�wâÕg´ŒÂì€,H ¦Ð'6|H¡¿;Ø ¾Ë[tÙ@!Âì‰áƒ�E$žº­ô•Ïå‰V˜WtY0OÞßa¨Û�D�ËË'„!àWcúäÒÁçàõÛ}´f”; Þzß.ª1(¯„²œàþøóæûÙò×A»«·7eud7®ÒKF
±´¹B`úå3IDC@Œ­ý­å¯c	}ÀºæC[{—Bë²Ð	ØwïÞÇguYý]1§µ¹B¸­5¦mÊhu>—^^úg»»TÈ^‰):z”·o[>¸\uW-LÃóáÅ”‚]³g¿ÂuÒËêFYVtßvýô€´¢¡2ï€~5¬ßáàÙÕÏÝy¨Œ_¦šb�wpd¹áW«j1»S3'¸(Ñöç$öÅU¿Ï/–‚|¡\àÙïÿö…>�Z(I D@Øöt)üìÉ„Æ–pUŽrå¤Ü·?‘ÐB(F÷’ÅNÌæç¹d°tUŸ6`lÈ5¹l<%pß‹}Úø)p±$KšÜÂ/þ˜Äïd¹r)œWŒcð%Î/GÃûÛEKãx~�'Lùš™†�Í*Ôny¸WW€F3¥äFèRš¾ƒsA.”Üøû8|¹¯ÿxœW£œrà±t-Ðï6aƒÇ…Î(Ù”Ö[ÈÉ9ºrå[¥¢‡	\»ž%+’¸öþ8öP0¸¯ÜW•Ñ4>‰�Å«Î‰Îüßôàîg’:µ.¼n’âNâ×¹wiÕ�ÃU„â·BÀ ×ÿòNÿÞbã†K*0gfD¯P©MRú ”ÛlüòÚŠ7ÒøÝK}ÚÚ×W	]ª/™¸?Ì0¹ÎÅ”ù+d¨êJe÷²¬�r´Éq1ôäcL\u~D¥M¨=x›\¾ ˆ#Æ—×f°âo)|ø™«õ�]])Ö~ ‘+­*©ìäÓbÊ‚ö«¥Yùx¹%yÕ¸—€ÛæÎšjécµi“Gn”dÁq	ýÝmŽ.«­Ùlcï~…hýámYz‰‰”´bÒ±û~8æ­²\da0ã\l¬•_3°U6Á­²q¥#y‹s>/Q«¬à¯Zæw,5#õ×:é.¾$QÖVù`G0ñÖµ¶è4Àeòï¬>œ`q%'(f”mÅsˆ-¿©7ÝÌ�¥[m¸Žå+\¹»MØ‰yBH·'–íìW[ò!û-¯ÃÀÑëøðÜi
×îÍº¦jë¿0±ã‘æ�•›j3Âã¾c3VÓ{,x^Áô‹ÕÎ3·c„kå¦Û¶/›°¥ÿÂZ![š`Š¾®52T9ÃÍð}¡ÃëÖ‘rŒp�©²‰uTQæÖ½pøB¥¾0�© ­÷‹”ÓJNº]Z1“_ÀaBŒEcr2{£Æ:•5NPþksVÕ*a„š«ksnv¯JÇ/Þº¼ùÝ¡×æ˜ø‹V2ø^��ŽÏTnæ?f´A_›óò…±ÖÐr×9Ž`ŒÅ±{Îži`àãaÇòæ�SÝÏV™ø¯!CY3Rg²ïä½¤/+w¤|‘¢¯Ìú¼‘b^™gæÝÉÆÅX¶?>iËÁ¯Î”sÑxò5]_‘Â¼ Ë…4›„0¼‹ÓÊñäñ¸<­XiêËÓÄ2PÎ^€^P¤ØöHýÆÁ˜¾�áÈó�ÄŽ]ÐÛî.Ñ,œ
ršATíÝ.ýÿÙ"!wò=âÕ,¥_ÛñhS»~à ×çÿÇ±
sÄÖKz    IEND®B`‚ic13  ;.‰PNG

   IHDR         \r¨f  :íIDATxœí}œÕµþwïŒFÒ6¹­�Á˜¸:6à%¤–¼„$§RHòþÆÉ{�H„šNR ”š!”„fŠMqã²n[U¦Üûÿ�;3²vYÛ»kI«‘î÷C¬·i¥™û}÷œsOaˆ$CøÜ`Ë1·ïw'´¬OZ#Ç43;s(ãÞ! ¦1`º%!’,É€: I0ÔÌž÷¡Q�$z d$�†zÈ,Û	°—¤d«ÃËÂà¯Ø;»·nh�˜éóûlîBËVB¢`C„H´­çx…ß™1¯}”w6 ŽcÒ8
‡JÆÆ1)ëY,É�A
��to¤ú(ý¯ih0®¨ÀÑ�ô‘q„kG:i!ïaRløKRŠ'c�¹ñØ3ë1bg¯Ør«´ *bPÙ°Pò¹=Ä—-;%¿ÓOüxûÈX�w4÷Äqà8G1#6ŠÇ ¥éÙ€p!á… ƒ„Ì¿O¶ë«»­¡@í
j_ÿ/$£µÃ8g$Ü3,0fÂsºH¶C²'ÁäãŒ[�Ù¶|jÝÒ‘íá3Î�û ¹ìä“±ŠÝi*“%I2òn¾ŒMu·ŸÈ¼Ÿ±q<VID÷²¾JK¸Œè-éÿ’$¼rßŸFÔ ýÿH$�’1f2%	%Òé†ôÜ-’±Û³uµ‘z70§ßõ\A¨,‚�ùtk‹ óM§)m?Œ	ïlÆØÙÌˆÎŒ:H7)ì]„ÏÛlå†T>¥/0·ÀÌp�:/J)ÿÉ[Wß<feðãç´ò¾nìp‚Uñ[?ê…ö×Ô‹¶+¥ø"“h1â#-µË{²ä]ihÂkT&¤”`ƒ4™‘TÖ�Èµç“dŒ_³ú¦1O?ÇÐRB0¼°p!.Ë›FÓ.h?†ø¤÷An51Af•ô\&Á¡œ0�ˆ@J!c†Iñ)awJ0ã¯ðøÏWÝ<â¾]®­ÿE¢Æ ˆê·2¥€Ó.Øvš4Ìor†Ó”jR€ÒcÚ¼×ˆ<$ù	‚�<Ö¨bVBâ>çòµ75? ~¤EÃujP~PoÖ'þäóß˜fÉ…àæ¹Ü° v|À£°ë°['Å…
”/ñ+ÏË|í-®êË�r¡Œ$“ÁÈÜ?è¼1óˆ/3Î¾ÉÍúQÂîðèuRŽFM@É¹a¥˜çöì�BþÐqŸ¿zÝÒS²Ê-XDû`y¬�ò€zS�ŸaÛ{aÄ¿o˜‰#…›†¶ÇÀu6žFÍAJáqÃ2¸YÏÍ<Ïþ¯UKÆÞÙ—3Ñ€À¬™=_ÆºÄöËÁã_£Œ+á¦)“‚{ÚÔ×¨ñƒnÖ*Zàæ®l4G_ú4å”Á%`åôM?ïÍC„¿Á°šNN§¡Ü|Õ×ÐAY«Ü�<Ödxvç#ÜÍÍué/ûGä-%–H (O=½œvAÛÇ˜¿ŠV³°;=0mîkhìäXM†ôr[=aiÍâ±(äŠŒâïÂêl“^(Ã´y[ÿ�Yõ¿D³pº4ù54öÆÅÈfÃ¬ÿý”yÛêïÓLæSŠ+Ö�÷Z"k¼Å´Rõrí¤ Ò*íëkhRH0.ŒøÃµ;þà8]ç¯[:)[ìà`ñH,:oçË0¬Æ3<»�ªøL}¤¯¡1(‹ß5¬¦gwÝk»�]·tR{1ƒƒÅ1)H•Z™wà…[÷�âïÜjÈÏ4ù54†eú›Ä%o<Ã2ïšxnÛxEþ"¹ûþ$¥\ÄeõÅ¹y¿aÕ-rù544öÌÙv—[�ÇYÉØ½Ó/Ú4I¹E�}sdê�Í`¹eF¼ñPE~*”ÖÐÐ(.¤py<e
»g¥—³OYûëñmûº‚xrËš3Ü?Vã¡ÂîÔä×Ð(7‰c<V?Ã°â:øÂ—±ˆ¿ªvhâ/úç’3Z¤ÅS©ßòXã	‘_›ý%óE Þp‚@óo±P˜ª¤8Ÿ+Pr�¬…2üA:�Û±¦3En§K-’†ò444	ÆL‘£À`ê}S7ì¸‘,qÅÉ!ˆÀ ¡¥E­­Ì›zÁ¦›É1—xÙ�®ê’¨¡¡Q^H¸<1Ât³Û°fÉ~—åx�‰üó¶¾Ÿ›ÉÛ¥—õ“|tO>�a qÁŒ„!ÜÌV/n¾#ähñ úM9Ã�ÜH<Å¸Ù,=[êV]ÃêoXÒk“�G­¾iÌ†Áœ0 V‚Ñ3#~#�5ŒžMÝ{uEŸ†Æp‚1.=[ðXý8é‰Å*/‡¸:ÀxÀÀ”õN]¿å»†•úÏé¢ Ÿnâ¡¡Q .zv—k&RgLk˜ó-PAÁ½cï?¤ê‘™7åÂíÇ1#ñ_Âé¦¶Çšüâ¤pz<‰…ÄU_hLÙÞ~o }üfo‚Ñán}Ä°Žñ” èÝ_C£Ò@�´�XƒáÙÝÿJ™Í'==ÞÞúîÙPçýL´;›çñ¦c<»K“_C£BA3q”¸Úánû´
îÅØ½t'=øÂmã=°ç˜aŽ†ŽúkhDãT@8Ûìxòˆu×Öo	»q!À¤ñ=#Þ4"§£þ•:™9Á­T³™íùï½µëß2Š¦Ïßq"$HRséé„�H€ÚsÉ¸)áæN~õæqÿôƒùo�EØ¿0ã2ÕÓO¸Î"fÄ% :ÛOC#" ñÚBwÃ"µÏÏX!d„©„Ó.l›Ãë!é9Ô·\'ühhD‚1&=ûäUKÆ>Ü_šð[ˆ=c†ßˆLJ¹€™	Ê(*ûÀB�b@Jâ°drA!·wo„M>.Üz”aO@�ß¯‡tjhD4–Ü“Â=zõ’±Ïö­è×´gR|Í0ëêATÖ—ª¡¡QdaÄêM)ñµþ¾»Ë”aúy[&žcŒYþhsmhhDT2Ì EÖ‘Ö¬×—¤^)´ò@‹ª „)Ï1ã)K
O…þ‡ó•k¡©4ó4–…¦1{yÐÏÐÏ†¿§@äÁ¤p=ÃJ%bÈµÐæ>ôPž÷½ïï\iN�¼õIÃª›%œ´Nü‰ ÔN„%›�"x¨Àt0´ëûdÚ…áÝ�è…bap¦Ä /�€Âç§'Ñâ@JÁcuÜ³»—¯îwTa× ³WâÏä¶c¥{»p3ºÑG¢�¤Op=	Û\—n�±üÃ2�Æ$Ã¨FŽõ	ˆ™ô`ˆ›þå\	G=€¬´÷ìèèÊHØ.`;i["ëøŒ§ß¥ç0‘ Ë�P(.Æ8qš±·OiÜrôàñ�ó½zùyŒÄ´˜—m×M>+áL;.9eŽ'‘süïÕ'êâãG˜¶¿�	Íš›öe`ÜŽæÇÈŽx°LŸ¬Y¶ëÿ��Ýmmí›¶{hë�Ø°ÍÃê�6ïHç$:zBábƒaìzÍú¹2 ¥ô«Ñ”¹ö³@ èÂä„ë“‰ŽÄ
n&&I/KóÈuòÏ0!4ç½€ˆ™ÔÎ�ªã˜8Žã°‰1r �éû˜¼¿‰Ñ�´ÓÌ[	Ùw—;´.öz]Û;%Votñê›^~ÃÅŠõ.ÞØ*Ð™Ê’¨‹ûÖYy·Ac˜ ©w —nvM¦+;sCëÄqßœ;÷!cÙ2¸ÖÎÄ)ÜŠO’nV›ÿÃ åoÓ$HÊÜÎ9IŽ)û8á0ÇjaÖcš8Ì~Ú<„£�…>}}¾¶'žû™`½Ÿ;Œ„		ÎøQô°pÒáþÏÑk'KaùZ�­tðèJëÚ:z–ï’h1.0"¿df|ŠÕ„S ÜEÜ7�“Õ·s¸Y×Íy,Œh”Ç¼@OFÂñ€T=Ã¬É1Ì�Ã‰‡ù¤'âBøÄ.KA‘›w¬¸�ÅÂ×¹;‘…‡Œ„iÿÑû�ŽãÌwÆ‘µ%žYãâ‘m<ü¢�UozØÙ-Uü€\—ð½kÃ < /’ò{áœD@Üö‰©ó¶.3bus„Ý££ÿ%FH\
°‘�Œ³§ÄpÚ‘N<ÜÂ!Ì|`�@®@ø{á«D„¢@‚@¯±0æ@ÖÁÊõ¾Ü·ÜÆò5²ŽÇˆ:^P¶Ó «ž{NúáÕ‹›çª"ôõIó6�3$_Í³Â=�b#$D&çØÆ�â8m–…³NLà˜ƒc½®:‘^ñ=p¢å6;|¡ Ñ®OîÁÿ™ÃƒÏÛÊm G’º[ß×(¤7©8ˆúúM}mñ~[”©oxÆÑÜŠ7þIþt-ƒ?íŠÝ©ø¡š8ë„8>xlB™Ì½HšóU‚ŒÆèAïí¤Ã)v`a}›‡??–Ã_Ïá•7]åÆÔ%˜ºZŠŠ,»’›u°sG¸Ã÷õ¹<Ž›õpÝ¬öÿK@üÎ´TGd'Ï´pÎœÎ˜m!øõaBMáyz5"€öEnLkà+ªÃ§ß�Ä=OÛøý²þõŠ£Ä°�ŠQµÔÈ5Ì:Sºöñ� 0:œ-…M7HoÿE@è«ñ)àuú;,µÀO˜aå†x˜aW‹W½oV!íú9!®<gãÆ»3ÊM ïQ"Ós
rýt¤Q�8.%’ˆ#ÕçSßýjœí?b3S —cq¾(°G§þ{’˜3³ñ#ì×—
¡ZA÷>cãÆ{ÒêH‘2é(1ˆ±k¿ã¹N…©É*³%xÞ@`%=oøÜµ,2èàæÖÈú1‡±C/Üq�ïEp£R ‡
Z¸éîÊÌ˜Ã‚×áýÇÄƒkti«b¿˜ ’
ÁÎâê¿¦±j“‹Æ‡Êyré¢np%DþÃ‚[Ã€9þG#Äº¸ˆåQðZ(cR:]Ò33]iOãuJF5†|–Oæ~ªžã’³ê1ÿ=uhªc½v5mW!ùCké£s8ù·Ü“Aë#YlçÎh‰ÜhÀIùä'B«]>pte�…@…¯<#aí`°v ñL‰‚¬Y!Pµ@uàbªéIL1cI.Ý´_7¬1¨…žå¿k–…KÏ©Ça™½v±b%çÔ"èúy$ €ªmhù@÷'m¬lw«2½ÀÜw{»U½.;ë€t£Dæ@ÀHK$70Ôm`0r€¬©´7Æ <:	0\»gºÉŸÂÒË�	 gþr×§‚›ï~¬œžìÜ«æˆ~¹ ÈÏ€7z~²¢K×dÐ#¤Ÿ/`÷ÉXÜ›ÐÒ}	Š`½Ðu°Df ~=”(«Á¨k€1ÁËà,3Åd“à·ýî—	�IJUy�‰ÓÞaá²s0e¼‘Ï—×Äßw¨¸^@þû7Ù¸èÑN¼Þí¢Ñâ¨£l¨}ªÂ:²À«—è8È6#Vn�Y"@QQ�6²I&FJAƒ?¤Ÿ}¡±[P®;%óP4ú¿>^�Ï¿¯®—¹¯¯Þ¾#ä‘ÿºWÒ¸ä©nxRbT‚«ë\´HÜ°ÇJì¨“H=Ï`µ3ÈX•‹€”Œ8/FR³ÀF?Sco&ÿŽ.‰™“Lüà‚FÌžjê]¿D;?yOßxºW®H£>Æãn)bÔ,øà n°ó(‰Ô@¢�Õ€% Á$Kr0$w�žjôŸÌûö‰³OŒ£õÒ”"˜¶«Ã¦Å÷ùúR~üB)+¨,5™o	h?Bª“æV3#è�	'ÞHGª#@.@Õ¾Ù¡ƒÌz¿ûŽÄÂsëñÙ3{›üÅ%?-Æ¿¬Ïâ;Ow#²ÿÊu‘™/lŸ)1ê©à„ ƒLª‹ËFp)Ñà—¨h‚ÚZõd¥JC½é«)E~U»Þ'[Mcßüžßébþc]ù¼‰²¯Jæ‹€Û´. yõ68”dH$9cŒNTõðÏ>Á¾Žn‰é˜øÝ·R8õíÖ®^m)•L¾þT¶åâFé�8@n,Ð3Uê
¨ZKŠ4Ò^×�wÁä~°�2Ï~ÿ­fLôý}½ë—Îô'?ÿŽ7²x`“�V‰~ƒ£¯/égVüë×ÆlŸ�G·Ä{�Žcñ‚&ŒIùGOšü¥‘?ëIühEZmµaq3Ÿô”'�ž •[P}V€- äßÞ%ñ¡ãã¸ö�*ÛŒ|~MþÒA•žøëúžhsÐHÅ<¡ È‹ 	€[GE¨Jhwþ.‰³OˆãšÏ5©&œa£K�Ò/¾;6äü(T¥]lÏOÎ�Òˆ+îî;j~‰‡äßÑqüßgUô_‘¿
ov%�O×¸Ý–x¬ÍAÒd*Pq`€=:¨.¬BðZ'?µ©>u–…«?×¨†XÁ�#4õÛjccÚCŒÊy+íª3ç·GJxÔÚ¡
Ý ^ËÑ~iuÌÁ&~ñ…&Õ§^µ³Öä/+–m¶‘ó*¸lZB‘ßm�þi@¥¾Î!¢&€{]Yÿœÿú/¥Ô0mö—¡•õ¦B]á3¹ÛŒUxM;9cS×¹	ãFúG}Úì/
~;rRíþË-é§S«±Ê}‘CGM	 í4”dBsí®ûR¦`èsþa„#€­Y	ñÔkÕ‡Új†Lå¹ê³Mxçô˜Šh(¨-ëÁä~ÿÄJ£4€ ï`µ¡
ßRÿ ¢ïì‘¸èÝIUÖKf¿&ÿð‚"ÿ�AÎEÅ»,žv"ô£^'Ã·?Z¯~*ú—0àú¥©•U¬ƒ€D8…wT#Ç�ç5ú£¶õqßðÞ“‚�£<?M¸RÁ(7Ä©Î@M@Æ–ª‡ß¤ýü ŸNñ~„YcÂüTtóP‰p5²¥
ßRÓ¿G¢åÄ8ZNLhòWÂ ß#M¿í*ÌbÝÕ9D„Wõy¿¼mœ�ÿwnƒ?DÂ6«Q­°SÆ[~€J´¤Ÿëd0ÒjˆnÕ¡j@q¸ß:§£}?3
çÍµ‚p3�ÞdbÖ¨²®¬ÈûÃ8ß^­��ªT BÓŸ*ü>pl\Õõk¿¿òúþ§ïoÁñdÅñ‹ÑÀW,JP�ÍA«Q Â¨óŽïüg}ðÅªïÈ#¼'çNN`B£�ÛP9ÄÈJ‰™	©,WÃˆ«U' dFR7ßÏ½7‰‰cƒ¨¥¬*�^ ûB§Öøìô$z¿.  (QI7�Ñ„WÅcÕØªªÞ™ùDþY“Mœ÷®¤
üiòW6‚)ÞøÜÁu˜Òd í, Fƒ_m��MJàð”‰‹Þ—Äø‘\Y–�°Të ¢¶ .9»I]ß	„“FÅ9.=¼^õN_›3(: ÎÀ¥G4¨×6±ÙÀgÏLªÍe¸Å©ØàUUãO{gYê¡zFdöSaÖ¼éIå
t¸Ãã
° 0I–ãÇ7aRƒ¡´ˆ>?ï´$fdªb²j
(WÍ[¡G-½>û^|Wl«"(ÌÚ´ÓÃÆ4ì`ðÊ<œ“»§#ñã£qæ„¸ÊM !¢µEåEg$‘s+¼n¡€vÛ}ú‘Ž98æ�šªŠwVý�h7ï¸à'�ø÷KÆ¯â0:Q¶1ÝœN‰°3+ðåC’øâ¡uùA¥á÷É
øðñq~Pirªd}UÅÛ ÂS‘Ïg‚á�zû�ùÏÿI^xÍEª‰Š7€QOqXm¥“ù�Ièâf7âªcšòIcù¢¥+à‚3’~0Õ^-»ÿÜ™15Íô#ÿ‘W5Fþ+ò×3xÁ„^*¿õ,GÝ:¦šqÈ"çáÁ� -yÂ ~3'…oQŸŸ’Ù—à¡ð¡ãâ8ô@»:N˜xUô—çÀ'NMªÏ+½¹„F?äÝ'¿K' 9ø„ÔJ†Ô‹F6èÊž¡v€~žHO�W¢Ë‘8y¼…¿Ÿ>-oK(³Ÿ~¦¿ç­ êýÑ9	díêˆ˜Õpî?{jsgZztw5�¿OçP‚úõ‰6Xgf‚„Gó¬=@¸€eìÚ�]È÷{(4á)!ŒL}:â£¯×Ã%‡×áÃþë*ðùw‡�ð9!Ž›þžÆöN‰˜Yá�«Y è~Ð�ýÄ)	5äƒÌGšì£QÙäß´ƒ~{ PÀpš^ê6=ã c<`ŒÞè��ÓNþ<�&0Ð”!©vtZÄÐ¸É0¡ÞÀñcc8ó€¸Úñ�€Ð-S9hNq|ð¸®¹=�‘±
�hTí@jœu€Éûx÷Q4¶àšü•Oþ�ƒ#¿íî´Ë[€‘eH­Ü×€³ß“À‘§šxr³£ºoÉ
lÌtSÛ÷Ã~Iû%¹úøÎ1&Nk!eíbºìúCñåÏ:!Ž_Þ—Q›N”#‚f”ƒéœÀïH !Ét{ï�ã?Ú¿b0äïObþäÞ?ü-‹·�lÀ§7æ$çIu~Oƒï©Ûð[^Kà*„AÀÁ‚Þ™ü<æ�|ÎFc°þ¢ˆÈiñ4%9>r‚ïÃEX„k‡üWîùœôÄ,`Á-]øù�éüß¢F£õ&Ë“ŸO‚àõ!þ¾¬��NBA‰*xdwÿ¬T½ý;HýU:ùßÜ�]È ìð”ªcøßßõàº»Òêo©cÄRáÍ"�¾¡«yú¬8Þ6Ö€íDwŠ¤ Èä:ýV>[£rw~òù‹Iþaô�\Àïÿ®7Þ“QAàR·~cÁškªg˜sxL¹¢Q>GN èâ;0º‰áÔ#h`[õ•hV�Ù_ò¿Eâßûm7®¿+Ç-ýÑœžÿÔYq5jNÇ ÊZXÔæûÈ)14ÎÐ5ÿLþóJLþB2ÒÌÃÕ·§±¥½ô‡y°éwh6‘í9€ <R^«W@F£ò|þ•e ?�þ&u€nH@�{Ÿ0&6RBB² '€N hâT†Ü - ¥-¦þEW7"’V}(‡ÏßèoR.a7|%…ó«AË‘§/ãøbSmÄ¢†HÑ‡nvÎ‘˜¶¿‰Éãý†j(Èˆ:ÊéóïŽü7}5…fÄÔß,×šà{Ž>$†QMn«£% *ûOâ¸1¿¡d%·ÊP)ä?þPŸü”^.ð`¢Ñ~#8Ž˜dª¡¨U¢Fêåá©‹š~hT�Ï¿mxÈŸFò‡P©À Ž=$æÏ6ˆ˜	 ëJ7yd©­/ Úü¯Ÿÿ§Ã³óß8Ìä'„„Ÿ5)††W¯%JF}|€¡r ü/÷«ªqò— Ã¯ÒÍþ¾7¡MœŽš[Ê£ fNŠåË€5ÿ‡÷¨¯\çü•J~…`Žhd8x‚	Û‰–À#Õ÷Ïf¾-²ŒUCþÛÎ»¢+×—�ü$þÉ8°¸’È�]=)è£
:ÑjI™—J™r¾žàßuíÿcÀï'xù�òünüJJeÞU
ùC„‡Ó0`E¬CP$@µtò$Rõ\¥]ú_îWU›ä?/ Swþº8pó‚ÊÚùîø“÷3QŸð›F<2@®ßý‡Z3k#ù×»hª+ùëÉì_�RÍ7*‘ü„pENÇÑ@Pâ4äš eºSö7üRL >ò×ù®\òB²7Õs5‘Ú‰Ðô H �üª‰cü—«ëÿKMþÁ!œD}ÐX#R¹ <*À„Å0~”¿DE]‡²ˆ*áy¸ÈoDlç/DxßÆ�¢d m´ãW» „-®Â™†²wþlDÉ_ˆýFr}XL„>?Íþ#u¿VMk×·ì¸þ®ŒÿÅ`Lõ°�ókŸP7%Ú¤1^–Ü@PùY5ÁH&:^ÙPmÔß5”¢½[â‹×vâžgl¼¹ÝÃ÷>ÙàÇ:ÊQîµó_Ù�WÊtÔgìüK¤ptDw~|¤¡!V,:¹ P£à„Tä7C¹bÕGþO_Õ�®tTéú»Ó¸ô–î|¹i©“×ÇìeCÍ~{—ÙUòB‘¦ä(¦¬:T>*^ ÂJíŸûôP5ä_á(‘£\òQ7ß[ �ß(0û_*ç9¿-Uvç’‹£ëó÷	 ­Su¿"°\+_ (PÒ…åùF�¸®"Gº€ü�»HG‚7²"îü¯oñð©+Ê›áGÍ3’K4áèéÕA~õ« ´eíÓ�@c�Oûˆ¸V{'�ÄüÀì/$ˆBøöÒâ‹€ìüD~òù_}ÓU×Ø+ÓÎß�ÿ�ÕB~æ0¦‚h8iPù@Øö9¯tà;ÿü«;ðð¾Ù¿»7�%OãÛE´ú’íf¯¬ä§�q5‘¿ ô^È
�ÉV�­B+ jÈU@þ~vþÝ‰Àâ"¹ý‘_W-#ù«jç’�î� D‘ D\ Bòw*òw˜ü…¤íÊ5Ñä/’ó�p#`DC ( Ñ&wFâ3?ëÄ²ìA‘?DßÀ ¤hò—"¸õI™‚µh@A÷Õ(\ÔÝ‘ŸfÉ�ùß"Oã›K.šüå�Ð"�„ ÐB§D˜ü÷/ß7ò÷�FŽ¥÷¥ñõÅ]ù¯ïNBò“¯OG}Úç/Xð‘J×£R¯P‘#OVâ³×�ü}-�_ÞŸÝ£’Ÿzø½¶EüÊ'˜…-«â ¼ˆ!y*]YÃºðtNâs×tâ¾g‹KþÞ�A†_=�Å%7½Uúîü¯·•�üÙ*Žöï	áÚ¤ñõ•¾N## ¤ áLÀJ‘�^e[»Àç¯éÄ½Ï”†ü}Eà×fqñ�]¾X2îüëÊD~UØCI>uK.®-òË‚ÓqgTL eíL‹|‰¥¬pÓÿáüùñ\IÉßK~÷PßÐ¥TÆ`ÕF·¬;?‘?�ÿf"ÿ´Ú!!(VEk5*£Â+¾X‹«½GªÙkF˜	S�˜^'Yg�Çº¶\q[�*Q–A	U‹ÈM"ðÛ3ª-õÇONà×vaý0ìüDþÙSk�ür—õEkÕ`ÑHªx pÆT4]M†©ð¹ ª`	À×>R!%~ò§´B)E@ÍMläh}$‹;þ•óËl‰ü¢¼;M’¿ 9Ûþ²HØÖQpwŠUG::é@”òõ³êqñGêTá	C©C$0VÌw;¨)½†r�?UÇqËÅ©š'?�vÕTÇ ŠhYAÀ­íþZé¦^óp‰€ò’dùv~
ø½cªYÓ;¿>¶uxÈ¹2_³QéàQÉ¬"Ø´Ã‹L]À°Š@iŸ^›ýý \“›¶{*¢�KdŠ’ ·”
Úçß‹ ì�*þ•òõHÃ¼y§•£DõRD€P®À`±¡£ý»G¸&7íô"U	 óõ˜É°~«oDåŒµšD@ïü{F¸ã¯ß*ü¦ ‰WGÂP!‚ÐE]³ÉUyÖÄ¨p¦jÜ��ü#êu´¿?„k‘âTk6º*+*ë3@W“z­mi—ØÒdµDå
G\z‘ÿk)?Ú/j7Úß/‚µ¸q»À¶NƒLÔˆ¬ÏH€Êd@&+°v£ˆô€Ð(‰@H~ª<$òÏš�?«¦|ÁZ$5“ó×jT–gdn%uç€W7º‘ñ›£,}w~MþÝ#\‹¯¾)Ð“£tuD‘† èê‹¯»yAˆ2*90Ø—üoŸ¤wþ=!$ü¯;Ê:ŠÒÞ!h@è¯¹ª9HT2­¢f	ô·óS=�6û÷�©Êü<•^w‚F‘ uh wxx}KÐ(B:
"°;³?J&m¹!ƒ5¸j£‡­íBG£äžFêÖ†ßZ{ùZ_ ¢2‚9
" ÈŸÓ>ÿ`ž÷/_ãªµ5K)R/—¤ÿ×ËNUÄ*Eò;£ø¡uôøËvEö¨Ø"E!2­’q†¿â mG§âª’E ×QßÅ:Ú?ÿŸvþgV¹»‚D‘€0ðævÏn@TR.+QB³”Þù‡„pí=µÊÁæ�žÊV�’ÿ9mOj¤vµ¢"’dÇR}Ô·Oxt¥£¬¨¨Õ¨DR Ôq ÅðÐó¹|ëëjD)E ù/NaæÛô9ÿP{Uæ¨µ˜ŒóÈ™ÿ„ÈÑ‡.2õ|ùÏ¿æTÕi@9D ïó“Ùq
GL2UÓÐ¨E¯+Éü_»ÉCœ* µ ”´ˆ»2BMÜ©vSÂz~:ç§ž*Ã�fèÂž!ãþå95&ª–h$_6¹	‹ã�çœüŒjF1D ßÌ£ÞŸØ3krmwï-†ùŸÉI<ðœ­Ìÿˆ�®Ì#’Ô	Ý€ë<ñ’­nHµºÅ�p\W#µîþ*5ðŒùf¿&ÿ� <_|ÞÆê�žZ‹Q‹þGZ Üð†ÒEŽF`Ë!yò³úÞLìÑfÿÐA×”.÷_Ï©Í(Êk�GY…ëâ>gcóN¡’‚¢„)¥„3›ˆü7á¨×ULá_ç×7{øç
õñÒ_)%"+ ÄuƒE	4	G}­` "’¿!Á±x�&± ƒ�·=šÅŽ.y1�¬ ì†[Î*3·Úƒ�äÏ§%ê7}µ¶¦ô–Rú×–®óŸ£³ÿè¥þöE¤)C‹ŸnÂŠõ.î~Ê·J=³ÒE€f(’ÖY7~¥	Ç¬~Å‚Èþ—Ç³X³Ù�tð¯* ©ò¯È*_¬š*‡"_ú`q†ÅR8îð+êÈ5N�g‰ß>”EÜŒÆôß½!òt¡…O�˜'_uðÀr[ùÀQÊì‹Ð"ýÆÙõ¸çû#qì!1um´Ù_È`HííOäTç
@WC!Zä@!˜Äú‹;ÓÊ×U“YªAž�ð(”ÞûAce®Öš5TRò3?…ú†»3‘êû¿7TÅQV@’á_¯8* ¬€j¹CC€"„Ï¦+"€Ûþ™Sõ'Õ²ûW� Æ®»3­*´è†E=@3ThòÜzgZâ†{ÒHX¬ªÖUÕ€²Ï¬qqë#ÙšIÒ(�ùó½¼²Á«Š£¿ª€|‘PŒáÚ¿¥U’†�bdý½±ÕÃ’{3hL0•�ZM¨* eNÆ�×6{¸þîtM»ÅcÀÏnO£­ÝŸú[mË©ª LjL2üò~ßd£¸@µl4Êä”PÚÖæÐTíœÿš Îè‘øþïºóä×–€Æ€×�ôÏU)�šÖ�çùuÕˆª ‘¾©Ž©ŽAx8«”¼š7å9F½éžž|ÕUÁåjµ"«R òñ ‹áŠÛz°iGà
hÐØÛºþq2¹�×Ü‘Vîd5¯›ª ˜(ùþº'ÿµ*¾—E2ýmøî/»Ð•ñË}«Ù}¬Z PÐ&UÏU¿€_ÝŸÑA�™þ?ûk~ÁQnd5þjF Â›J>Üå·öèS�½šþO¼ìàš;2HUiÔ¿æ€Ì7*Þ sî’›ºÐ“õ#ºÕlÖi"(œÚÖ)ðÍÅ]�RªÏka�T½ HÉ)‹‹J†¿³´[	 Ýô¸¿{�¤u Ç¾z}Vm
Ò}k`÷¯ ¸ÙÀðûeYüüoiÐ m ´�éOçýÿxÖFªüþš ©:ùv?¼5�»žÌ©OÂ QÛ~ÿÒû2X|OFmµDþš€Ðä�Å€¯ÝØ…§W;j&^­Ýtÿžj×§cbê'Q>M@>(ŒuúÂÏ»T¥—®¨Mò?·ÖÅW®ë„ÁýÊQ- 5¿j�aÃ6ŸûY'vvûQßjÎøÒèmö¯ßêáó?ïT§B1³º³ýö„š³ 
wJôxz�‹Ï]ã/Ý? 6Žû¨´÷¢ÿëÄº­žj([+ÿþP³@ ¢øyèy_üE—ªþÒ"P�P-ã°³[àÓWubÅ:M	VóAàš€PF52Üýd_¾®ÙPjxW¨VŸŸºDÍ¿ªÿ~ÕQÇ}®¾ÇZ 
Eà¯�çÔ¡�*& HÕ�Ó�ó®ìÀ£+eõiòû¨y —40ÜûŒ�óÒ�­B‰€>"Œ>ùWoôpî�ÚñÌj)"•õõÛh( í
d	<ñ’ƒOü¸Cõ¤¤E z {I÷nùÿQVmôü,?Mþ·€?ICC�v‡õ+×¹øÏtàÙÕ®ÎŒè,Ÿ›¼î{ÖV;[»‡ðëŸó9.¥L³µjô$´ÿÝ£!É°e§‡Oü¸]-$3ˆ	è«T¹PgùÌßùó@Ÿ¾ºYÛï¥­¸·N:$î“ÐÍ´'ðÐ‚¡d¡ŒÌ¿º×Ý•V1�Z>¥c>×ý¦ßº¹K‰6µòÖ÷ë­`jÓG7‡DÐ@¿ŸŸªqÐÂ±š°ËÔ¢úÒ/:ÑÞ-t\ Âö²|v_›‡O^Ñ¡†ÄR�Ý¹(K‰í;9ý/ð´ìa0$ÅZÉáœË;ðtP‹O_µaŸÜCDÿÇ36Zþ·�¼h«ÓÕïAß›ÝA’ Hð4ãÝú0``�%:!xyƒ‹�ý ¿¸3“Ç­MÌòB†&?Ò9©¬³‹®êPÁ>JïÖgüuD'—]z�üÀOh44	Â÷~Ó�ó®èÌjk < â“½J×üÙ5.>z9‰qZúâ1ì(7HH»L)åZÆLHÆ(´¥ó82jDÃ?–çðüë.þp=>ù®„Z˜¡YªOVKÓº‹ˆŸµ%®¹=�ÿžQ Yf:¹g`äP¿s¬á�|µôººšüƒt	(±„Ò†¿±¤Ÿ¼¢+×»½N
´Z¼kúú�¿dã¬ÿiÇ·¥•Ÿ¯Î÷urÏà %—žM×˜Œ‰UÒMSÞ+‡C^�J81ü áËsxf•ƒO�–À§ÿ££šüËúªú¢v�îê×g0`íf×Ý™Æm�æà¸#ý2^,¨å±Á¤›`XÃ½pÇA¼™a4@¸Z †Õ_Ð£öãSÆ›øÌ™I|lnR�Cæ¥kœøjÖ²äÞ4~y_mMIFl]¨5dH	FP¼nÎáì ó^KÄÌ†—8·Þ&ENÀ> < 5ë GN1ñéw×áÇÆó:LXÑvÖž‰Osh°ëÒd°j£‹†×I=Å€”’™	&ÝìYß|e ±iný;·ON—Ð(†P—!:’š=•,‚:œyT<à¢…ÀGx^¿;+ÑúˆO|Ð™°€„¥Ïõ‹éñX£!œî{W-û&À¤DÛSŒ[§KI‡Eü[µ¸’þ‘!]Oj>ùÙ«;1kŠ‰O¾+‰÷Wß+$@-Å	ÂÝžÞ3	%½ñ-íz4‹?,Ë©\">�´ÐÏi?¿xPçíûË)Lí{¨‚=.ÜUG&
ñoÖ,T–` tEŸÍUÓg®¿+ƒsæÄñþ£ã8`Œ‘¿Úá7ù¸¬‡pï��=ÂËoxøÓcYüù±,6lj¢35ì£ÿÅ„”ÄqáÐ´lñ0}EÝ†Ió6�3$_ÍSKˆÐ÷§–ä97’cÎá1eÌ™i©D–y1ˆp¼ 09ª0 ÚÞ#qÿòn"‡¿â¨ÏýDž]‘F©€1&…ÝnÇã“×ÿbÄNk‚ÄÔy[—±º9Âî`´i”Zh]ONª‚£éLœv¤…SgY8rrL/†P¤ ArX…'ë¨`Þ.ÃF!cK<¶ÒÁýËm<ô‚�u[üÃ{²Žè½jâ—Rn5ra÷ücÕ’æ3È 0çÎæ²eÌe��3nÍ‘èÃ*Çë©u×ÀrèóUoº*«ðÆ»38ô@§¾=Žc�áˆI¦ªlSÎYÁï«ŒÄÐ:QP›´ìÄ­•pñPÎ§W9xüe>—ÃÚÍBu^&Ò7Öù©déhS¿<PÙ¾,ÆÃcôùìÏ<mšÀCê›ž‡‡™›þfï¥¦QŽ`!!n1Õ€ÈðÜë.þý*}1ŒÍqÔ´Þ9ÍÄìi1LÚÏP®ïs—Â�Wµz!ï:Ù É]øo¥YÁsç–´X
ž”N=(rO#×þõ²ƒåklëÈPSŽ¸Í'ò‡¦Q^0Ééö0&™€†Wº(&@&',XŸLt$Vp31IzÙÀàÔ„;;‰�ãÙœTŸS¥Ûþ£9fM‰áí“L<ÁÄ”ñ†Š–Ç
™¸„þu_7;¯T	ÚÉ·´K¬Ùèâ•7]U˜óÂë.¶¶u†O"A~=™÷a‡eíÛ'¤`F‚Óù¦+;sCëÄŒ²	Ô÷Z¤�VæM�·íJÃjºØËµ»Œ*„4*&§€@™†Ž'U›+µ-£É6ãGqLÝßÀ�ÍšS\÷ÉÑÜÄ1¢�«à�¿
Ÿgo á±]
TJlï”ŠÔ›Û…j‘ÖÖ!UãJÎÙÖ!U1NO–š¤0µÃáÃ€Ÿöë+RJ×ˆ�0½\û•«—Œ½$ä|o’3´
§kc:¨Ý"0™ÿIkQ)qæ¥7\uÄHâ@D$ÂÓÏY&SÙs4}T#Gª.¨ïÑƒžÚv¤Ê¯·=ÿ„¢½[bG·@wÆÿzÎõw|zÐ"‰þsP§$ú7=w!áµO_y N§KJˆÛz}½×OµHcjÃ–§«a–pÒú4 (ô÷Ug·‚X@þ£�Š”áçêQàô}ÿœÞo©Z êÑwgžG£Â!¥à±:îÙéå«×®x'–�â†ßÊûù-�I ÎÿÌR{l‘@Ht"8¹ª9<{g~µ¢óƒoä2P�,:} „zÐ¿ékô=ú™:‹ÁŠù¿†èoÐóÓ#ôç5ù£â2eÿ1ÎÿHäŸ;÷Aó-Ð:Ã¿ŸÜe·º¹N›q:¤Ò÷8ÊwùP$ÂòÙ==D?–‚F¤!7ÏîÌÚnN™ÿËN>9³+Ò¿ˆ	,”üÕ¥Í/KáýÉˆ5¨Èá0½h�¢@â²â¶uKx™8®¸ ß£>ãWznš*õQ †F¤Á¹çöxBºWõûÝ^ŸVÀÚšŸžw7·©*C7\ÒÐˆ"¤ô˜ÕÈˆË¯Ý²ÿ“}wÂ[wø•þÉ€!ðSéf‘¢¡¡QY`ÔúKr?.äv¯ŸØmÕ ¦\Ø¶Ì´ON·n¢¡ÁÆžÝùÐê%ãNñ9ÍÞÓíßÇ?§•N€%û®ô4	Òa�h@µý–ž-�ý?õ•súçzÿÐzŽGþÂª%cöœÜRk &âúD@C# ÄŸƒ¸»ê¦Q�(ßŸr|úÁ^¢ü’™œ}×ËumcÜâ”QT¢W¬¡¡QG¹Å‰³Ä]¿Øo÷Ø½ P´°ü•%Í¹PuÕÙ�â('®Jç2ÅÝ¼%ò_ˆ½Dø%ÃB°Ù›`t¸[5¬†wzv—`,Ì
×ÐÐ¨HHÏ ÓßîþWÊl>ééñð°ˆbwoþ…Ø‘™ÄÊVöôÌL.žã2#¦»¶ihT(ßß„p©�ÛX@œ%îî‰ü„��ñ…BSÎßt©™õ¿žÝéR�I±^º††Æ¾�jµ«Éô²í—®¾yÜBÎîí÷fÊ·BPµàš[ö¿Ü³Ûï¤?$¥Ð‚ â"qÒÍuÜAä÷+{1 €ý }y&ýjAÉr’ÏN÷Fn$}* ¡QµþfÂv×F×“óéK>W÷lú‡x0o--·ò7–4o®{¡(ÄÐÐ6ìâ ð¼×-·¹¥åVcOQÿ¾|ž?5XvŠ;í‚¶ïðäˆÿ¹ê.¢ãå‡Ëã)SdÚ¿»êæ±ÿrs0O0øã¼e'{äcÐô2;oäVÊ„”ƒú£û	—¸G$.*¿ÙÉƒŽË±ÒO²––VÞ:£EN}cÛ�DêÃ^VwÖÐ(¤tyb„)r·­š0æœ…ä¡ïå¼wbBWHJ2èHˆOy¹Î‡ÕÉ ´% ¡QJH)”Ùïå:î6ìO]64ò†žÑ·h‘ ,Á­×Žë¹öÏîy‰D Rhw@C£�Âïíow½ r-›n8 Mì¯Ìw Ø·”Þ°ƒÐ¯§¶Áí~¿çd^äñ:& ¡Q
³ŸÈïô¼ÈDÏ‡çúéð3X§ÛOðB&žÛ6ÞJš­F¬áa·»€ž.¤¡±ïÈow>jgº[Öÿæm›ŠA~BqŠzTåà­ÆúßŒÝdï=Âîü›a� £AWO„ÓÐ*Ô„×ˆ�4E®óo†ØúEþAžõï	Åí÷ªÒ\iN�ºãF3Þx¾—ëôh.!˜î0¬¡1¨º~Æ%�7"×½dÕê‘ŸÁ2ækçQü†Ÿêršƒ)n»Üˆ%¾áB
š<§gjhìÒcÜ2Èƒö¼ì×,ó-EÕ…¢¨ä'”¨ã¯ßG€^ìäy[>bðøÏ¹‘ØOØXßÉö>TV¯Ç­&CxöfÏÉ~aí-ãþäoªC?êÛJÛò;(IœôÉÓ+q£a5ÍN§á1TVÒ¿­¡%HA&?¸•âžÝù „7Íâq«•¿O=:K„Ò÷üë’>hNÝ0órn$.¡I4yˆÎê¹µ)%¤0ÌzƒÜ~)Ü­êùmÅ™!äöåúQ¸˜:oëû·þÛ0G§B¸Í./ËëÐÐ¨°^œ™�ÕÃs³Ï{^úÛk—Œ¿Sñr¡T.t©_C§þìŠŒŸÿf]ƒ—\ àëÜªO‰\»£7«…@£ =êÝÉã)&œt;$®è62?õ3ûÔf©;—ã•”ìWA«¢ƒæm;Ô„ü¾a$Î"#@8ÝŒ:™¨#C=’L£Ú"|œÇ�Ü^¶Õ•ø¯×—4¿¢~b€m¼Š‰a"™dª]qðf§Íßñ^)�opÆæ0#!Pæ‘ŽhT‡�J„1x¬�¦õ@@>Â˜øáªFÝ¹‹øjã+ûô­áÝeÉÜ¡J¦ ˜aÚ¼íg2Î?'…÷^šL,œ.
ŽRR¦†”j«@#*íù¥">ç&�5BØdÝò¿	)®]³xô=þOI†Ë|·x¸^heª�é3yÞ–˜4>Ï Î6£-áe Ý]U—I-Lz¦v{“™	p£nn»-ÿ£”ìÚµ‹G?šÿéa0÷+W 
/Ê­¡E0ùüÍ37Z“ïaÌ8Êˆ5A‰�—Sm�É•Ü„Ê{/µàÓƒvy2Ý©M>3â`FÂé$)xZJy·^ëÚ[ö{ÁÿÉÔ�Î
 ~ˆÊ$¹„Ð4j¹Õ˜Üô®c¹ô>ð2Ž)<ÖÄèÚK7)_—ÑPs
#ªáæå6hh£(ŠïŒ>	Ïc �žö átéWI!þ
füyM×ýÿÎ'ðô]Ï„Ê&ÈBÉç|Ù"–O†8è¼×±Xã,ï$.Íã ÅñÌ0Ç`TwäPõ¤ß±\ztãü‹N·NAKÑ¡ÑÁÉòâp´•øà`SµlÌ 3,Ð‰•gwSÒÎpö¸€÷æ?Yý¨gVÿŒåÂg�»PšËhýU ñ£! }rZV‚µö1Ÿ¦ž»­IÆål0Ìå`³¥SØxÉ�äÌ´”B“!@â@Z „�Üµàßå9nÕ¨X0uêì<ø7y•T²"%Y˜Òµ™”	lb0VIæ=n.CZ<»ú7c:Ÿ�šsª¾ü%ÊÝ¯Qè{„ØÊçÎhaË.ƒ×·ÒÔ/É¸ØÙ�2b¹I€˜Î'ÈIrš¤d)úFÿ–#ÙqZjŒ6‡1¶�èdLvHú7cÛ8Økž`kÈµ^<þ�5tîð
R²¹—ÁX¶²U¢µeXŽòöÿ¼Ã©ÜEÐG1    IEND®B`‚ic14  Bü‰PNG

   IHDR         ôxÔú  B»IDATxœíÝ˜Tå½Çñß{ff+lawAd±×ØbbAc®ýª71š¨	‚šfºM5E¯“hôjb ±aK¢±ÄX‚š˜X£Q#ˆ,X va[gwæ½Ï™
Ò¶Ì™Ó¾ŸçY��y™�=ÿßy«BmÜ‰¶´¤¢q#³£•ê�4ÒJåF¶ÌJeÆšþÏR™•-ïÿ¬2É”£
¿ÛÀ_ÖªM²�Fê´R§‘éèÿ¬Nkl§±ê°&÷çîÿ_m¤+;¿aæèøÞ…›ñ»˜mÏZUéôÙ�¤ÌN’ÙÑí(Ù­Ì6Frx’•²’],™ùVšïX3¿ÏhžI8_7ª•ïFð hÂÔæ	)'3Å*»·dvr½1f¿Û a­}W2óŒÌ¿%½`óHÃŒš¥¼zÁB HÁO$2;6;EÒ3Áï6@>YÙÉ<&«Çä8�üG ð@ÜüG ( 
> l� ð Ùú3-ÕE%}Ÿ1²Ÿ“Ñ>^= D’Õ³Ö˜Ùé®ä­oÍ©jö»9QD È§)6Y?©éHcíç$s¬ŒŠòúø 7ViÉÞ+kf/|½öÏzÌôùÝ¤¨  äÁ¤é«v1ÊL“µ§cFçã1 ë²Ö®�1·X%f-š9Ê]a€a  ÑvgµÕf3=§åîö�Ù}8ß À Yû¢•™�îNÝÀÁÐ iâícÙÎ¯Ë˜/©rˆ¯;  ¬Ô*Ùk2¦ìÊ×gŒXÎ‹:p€ÚæŒ–‰)Û{®¬=ÝS2ˆ× à1km·Œfõš¢ËßœQõ:/øæ 6cÛ©«vu™óeu’1Jà5 øÄZe$Ý–Í&.]<{ÔË|#6Ž °ÛN[q@Bæ|½‰× TV÷gd/Y<kô~7%ˆ °íôÆ£Öž/cðç[ È+kŸÈJ/š5ú^Ù÷ þcâ´æÝê»Ò¼Öë ˆkõx_Ö|á�Ùµ¯úÝ– ˆ} 7½uT©Ò[éLŽÕ€Èë³ÒUÝ*úéÒ™•«cñ Z§þÍ•Ÿ7Žý©¤Q~7 PP«dõÝ…[×^§M6Ž¯},ÀäÓ›ö“Éþ†|  æ¬}QÖùüÂëkŸVÌÄ* L:mõhSÔ}¹¬N5&^ÿv À†Yëî'do²½¥ç.ºiäŠ¸¼Nñ(‚SlrÒ¶M_3ÒŒQ…ßÍ �µj“Ñ…‹j¯ŠÃ¡C‘ õ§7lŒ~-£ün  ¬^µV_h¸¾îqE˜£È²¦~zãdôŠ? `ÀŒvpkÇäi�ßwkIT_9á{n4Æü—ßm „—µö¡ŒSöÙ(4d¢¸…¯cô;#3Æï¶  ÂÏÊ.ÏZ}2j[
G' œhõMß•ÍMôãÐ @^2Ò�®®½Xw÷À¡Ð‹D ˜túÊñŽÉÌaÿ~ €§¬}¢Ï)ûd†B ê§­ü/™ìmFªö»- €x	È&>Û0«æ!…XxÀY65¹¯é"+�Ã¦>  6º¬!Y÷}]gzÃøê‡2 Œ9Í–�L5ÝkŒñ»- €ø²V�®î­=vùM¦C!cÂ¸�¯SÔ}¯¤}ýn  ’žÉ¦KŽÛ6Â&l“ýŒ“™kdêýn  kXÙ›Mºèúš%ayUB³à¶SWíjLöï @Ð™z·F¹µJ!Š€‰Ó›öMXû 1ªò»-  lŒµjÉsøë3kŸQÀ¾`òé�Ç$mv.Å tÆ¨Ê­Y“¦5~’z À¤é�'ËÑ]2¦Üï¶  0 Æ”cÈÕ° l ˜4½ñc5GRÒï¶  0F¦Ø­a“¦5ž©€
d ˜<½ñgŽô36ø „•12ŽÑuõÓV|G¸I€“§5~AF×úÝ  òÅZsvÃ¬ÚÿS€˜ Mø³ŽþhÚ3 ÀPX)+«fÕÝ£€L ¨?£qŠ²öcL‰ßm  ß¬µÝÖ:G/º¾v® `Û©Mû$û�ô»-  xÆjuÖ$>²hæ¨+î`ò´–m¥ô32¦Æï¶  à9«·m&uPÃU‹ä#_ÇÚÇOk+¥¦ø bÃh¬’é·úl[M,{ ¶ŸÖ82cô¤‘vö«  øèÇê°³êVÇ¦`ÂT[’1º‡â ˆ±}3ÒÝšb“ñ Z'å4Ýi¤)n  ÄZ?©éz·6ú¹þ„õo5ý@FÇúy "#�š«�…Þë+ëŽû³Ñ  kmd²æ#¯¯}ZR°B<aj³{Dâí  Ö•«�NöÖ­?ÓR­¨€”Ó;KÆL(Ôó .fbqIú·‘
 ýü˜
ñ\  „–1ŸÈÕÌB<•×OPæÊ�•Í<cdÊ¼~.  BÏÚŽ¬I~Øëí‚=í{–-SÖ÷§ø 0 Æ”Ûwë˜Ól¹Â Ê3�×°Ù  ƒcŒÙ¥¢¨éçž>‡W<izãÉŽt«W� @äYç“gÕü>4`ÂÔæ	I§ïcTåÅã Vjî5©½ÞœQõz(† ’Nï¯)þ  �‘ªSÙôµò@ÞÀ¤éMÇcÏ÷ã GÆ˜ÃÝÚš÷ÇÍû¿Ò+Æh|> €8³VKÒÎù<:8¯= ÙïRü È/·¶º56¯�™¯š8­qû„±/™â|=&  ège{ú2ÎoÌ®}UAêHH×Rü ð†[c“NöŠ|=ž“¯5ÿÆè�|<  ð~Bà°‡ ˜ø @ø&»€‰  „oBà°z ˜ø @8'«€‰  „sBà�{ êÏhœb¬Î“ €¡³F‡4Ì¨{¬°= Y]8ä¯  Ã7ŒZ<¤€ú3V~ØØì“C}R  �Ö8û7Ì¨yª0= 6{þ�¾  ä×kò { ¶�ºb²ã˜Æä÷ !  0xÖÊfÚañoë^ó´ ‘�{àÅ € pkr"k¿3è¯ìÝ"aæIJö‰  €gúº­¶Y2«îmOz 	ó-Š?  �“,2æ<Oz ¶9«qËTŸ]dŒ)RÓ  €g¬µ]=2õíp@2c¾Mñ  ˜Ü],ûÕÿý�ü¥	S›«’NïÛ   ‚ËJÍé®Ô¤·æT5ç¥ éôM¥ø lFª.*éýÜ@þî€€‘�:ìV  Ïéäþ½M›0µi‡TÂÎÏK«  €çYc·[4stÃ°z ’ŽP’   ÁØÈXsêæþÞf€5Fö´<¶  xÍØSr‡5 ÔŸÑt°ŒÙ6ï  ž12õõg¬ÚoSg“[ú;°‰ üU[aT[á¨¦ÂÑ¨‘ýŸG–•%¥¢”éÿp�4*N)÷ÿ2Y)ÝgÕÓÛÿ9Ý'¥{mÿGŸÔ•¶ZÝeÕÔ–Õª¶¬V®Îje[VMm–o9pÖæ†ð7zLðÆ»Î²©ú¾Æ¥Æ˜Ñ^5À¦¹…z\mBck�•ÐÕŽ¶ªMhL•£ÑUýÅ¾z„?gs5·Û\hlÍêÝæ¬–­ÌèÝUY½½*£wVeµè�Œ/íÐÏÊ.oHÔ�×u¦Wƒé˜”Yy4Å(ŒñµŽ¶—Ôöã’Úië¤Æ×%4v”£Êòà¼é�ê	Õ�Mlôï´tX½µ"£%M½º¤O¯-ËhÁÒ>½½2[Ð¶qddÆLÊ¬úØ"éÏƒ
 FÌþòÍí‚ßmbJÛ�KäŠýä­ú~iQ4_ëªr£ª‰Ií61©£÷)~ïÏ;z¬æ½Ù§…Ë2zui_.ükqŸ¯m¢ÈQÆØ` ØàíEÝ—VŒ¨êÑ;’áyë€ˆ2FÚn«D®à»Ðýìþ>1¨38ã£7£\ïÀK‹ûôâë½zéõ>†€á²ZíH[-˜U·z@= UÝÎ'e,Å¤ï�Ò;iÏIIí2!Ù;{/¤Ò.Û$sŸ9¤$÷gÝ6^XÔ«¿þ;­çè% ÅhdÖšOHš½þÿÚ€úé�wé¸Á=?n�?h×"¶G±¦ìVè1û(XÙf5÷Å=ò¯´žx%­^ò °YVúcÃÌºã?øçë_­.´Îä%M�’Fmþa�ø©©0úøžÅúØEÚÇ¢Ü¸>
¯+­\øËý� ­“¥‰ÀY»ráÖu£u¡Én2 Lžºb%Ì~ ž¶�Ðá{å
¿;žïŽï#8Üýþ¹°W½�ÖÃÏ÷ä–!XKÆî¹pöè­ýGëÝ»XÇLáÚ¸³õ“:lÏþ¢?iË�/uƒÿÜ‰•ûnŸÊ}|ïärÍ{«O=ß¾Í~€uÌI› 2rÿKî,ýOX¢#ö)ÖèJ¦ë‡•»´ÒýøúñeZÒ˜ÕŸÿÙ£ÛëÒ’&zS&WÛ¯X÷�ÖÆø?b(™�ŽØ«X§Zª½êÐ�*kÝ9½ºyn—})íws ßç¬ ÿGœ¸wøîr³OTšÛKñáöÜúh—î|¢[­LD<ç¬s»Ãø?â²Vÿ´�•êã{²H?Î[/Ÿwbyîãî'{4ûá®Ü¼ Nó Öíïdüå.Õ;~ÿ}ö°ÒÜ8?°Æñûç>ÜM†nx¤K=ß“[U D}ÀûýžŒÿ#‚ÜÓóÜ»ý,ÉíKlÎòæ¬ny´[·>ÞÅð ¢ÅÚ•]«ëÆ/½Ót¹¿}ïŠÈø?¢dŸíR¹»ýÃö(bï}IO¯tßÓÝšñ`g 2¬qöo˜QóÔ:C Œÿ#
Ø9¥¯W®Ý·e6?†§8%}â€’ÜÇã/§õ‹»:5Ÿy9“Íî!iÝ `ŒÝc#G ¡˜Ø÷µãËYÆO¼kQîã‘Òºâî½¶ŒÍ…RÆ~XÒ¯×í°fÛ›"lÜ;ýoŸX®½'§ün
bÀÝÒ=âÁ¦õË»:ôúr‚ ÂÅ­õk~ý~?©±;Ð€°Øy›¤ÎùD¹>º……åÞ(±wQîã¾gzrAÀÝm…\­ÿÏ/ÝÿL˜Ú\•Jô5ûÚ(` ªG�÷ÉrýÏGK8��àI<ãÁN]{§ºó¼Á`&!Ù")[de2’“–i†j1<½™dõ³«[r= Édv÷À` ¨#�zh©¾v|™F–rDp¤’Ò�.Ëí3qñíí¹á�Áè©’z«­2ÅVY·Ø§Ü‚/eK7öV&mþ$ÓÓÿ9¹Ú¨x¥•“áç›–R¯;ð¯\ 0Y»óÿTªOê¢Ï�äD>Ú–£]õÅ
=9¿WÞÜ¾ÑùYGJ�²ê©µê©‘lñàŸËYeŠ¤uŸÁJY)µÊª¤É¨¸Éä‚ðAÙ„Ùá½ `e'�4£F}ïä:f¿!\!Ÿì¿cJ÷ý¸:·«àÕ÷t¨³GÊ$¥t­Uw]ñ—W›Q:Ro­ûaÕf­RmRq£É‚d§GÏ‰Ð1V;¼?	Ðôÿ
÷�žs?Q®ò¢)Â'•�Î8¼T|¨HŸþc‹—¸ø…Ÿ¬ØWé~XuÔ[­’F,2J­æg*öÌZÀXw€7‚qHËÏÏªÐläƒkï³úÕ¼N]ýj§:Ê‚1Á*=JZYmUÒh5b±C�@Œåjþš `�a þ¾!MÿÓW�+ÏíÀ„Q:+Íx­S—¿Ò¡•=Á(üü9ë-u×fUúŽÑˆ×™'GnÍw?›	SWl‘J˜wünâË=�ïgÓGjÇ­Ù¾á”µÒm¯wëâ—Ûµ¤#D{d¤²¥Feo%89Vz3vËd2iXß|õ¸2�}lß„V[oV§ýµU�-ïUè$¤Îm¬º·°ªzÑ(ÕÎPp\¸µ?i­¶à[?Æú¯úR…vâ®!öf{FŸx¬EÛÂ½%p¶XZµ—UÅ«Rér*B¸µ?éXU± 
é¤ƒJtÁI#TÆê>„Ø£ï¦uú­jNo¬HRÛÎV}#úW¢Í­ýI+SeØPUntÉ´‘:t÷"^o„Ú¬…]úÖs«scÿQã	dÊ¬*_12Yb@T¹µ?)e«8…ØågV¨¦‚
Â+“µ¹Â}C·¢¬§®H êEÎˆ.[’´Æ)¡ ^:ïÄòÜ? ÌVõds]þ¡œì7}#¥UûXU¾,µÜ£Ç–$Ù¿›�èžÜwíÙ•¹½ü�°»r~glŠÿÚ“Woo5êŸî™1„€(1ÆT9Vªò»!ˆž='%uß�ª)þˆ„»ÞêÖóâ¹™¾ÛÐºc';Äœ[û“²¶Šm€‘O§¼Tç~²\I¯<
è©Æ´¾ðd[¬_óž1R{§Ííˆˆ°¶*idè@^”I¿8«BÛƒYþˆ†¥}æ¯­ê÷2ÿ¼è˜h•ì�JV¢À­ýîà, Ã¶U�£_¯Ô¤-¹íG4tõY�üxk ÷ô÷‹;�è;F‚-q¬“ 1ìñþ»PMñG¤¸Ýþ/·°Aþ:RËnVÙ¡(üL‰ã¦ ¿›�ð:bï"Ýr^•*ËéDtÜ·´Gw/éñ»�”-‘Ú¶# „�5–! Ý7ÿ§L_8Šƒ|½Í~.z±Ýïf~R`ï›–¡€pËMdGvJQRºâó:lO&û!zn{£GóZ™õ·9í¥ê—ò-�ÜÚÏ-ô~þ3¿Q©]'ðÖAôtg¬.}™»ÿ�H×Y¥+¥¢V†ÿÂÊñ»�Q#�îøNÅ‘>äçÍŽ¬ßÍ�öm™f ÈèJGw~·ZÆ°ÌÑÔšÎêó:ünF¨ôVKÝ5„€°" `³¶åäîüÇ×òvAt]³ K�Ý³Áê  ´¸¢c“ÆÕöÿ±5¼U]ÖZ]¿°Ëïf„ö¬€tÁ)Œ¸ªc£¶�Ð�ß©Ö˜*Þ&ˆ¶çVöiy7cÿCÕS—×o
„+;6Èë¿íü*ÕT0ÃñØøC×]K@ °ž-ªÝ|^%Å±q»þK¶\êcO°Ð! `Õ#ŒnùvUnÖ?î²¿†Õlü3\ô„Wy¼gD©Ñœo3ÛñòÈÛtÿçCOÃ aC @NI‘tã9ç‹ø¹Ÿñÿ¼è«�²	B@˜  TBšùõJí²Ûû"^Úz³úëò´ßÍˆ#õÔ0i8L ÐU_ªÐ>Û¥x%;/®Ê¨—ÕyÓ[É‹&€˜»ès#tèîœê‡xbí~e¹”„
 ÆÎ>¶L'Xâw3 ß¬èbö> Â… Sÿýáb}õ8î"ÞèÈ¯Ližž" ÄÐ�»¤té´‘~7ðÝò.Æ¬ó‰€p! ÄÌn“ºæË•Jð�´‚ýÿóË‘2œ”�qOô›ñõJ3áÈ¡ ÿl1o®°  ÄD*)ýæ+•ª*g�.°Æ[LÌ·+Bƒ —œ>RÛ�£oX£;ãnÄÎuùÆ<€ð  ÄÀ§,Ñ±ûÑ/¬­$!�/ç˜o‰nBUXðî�¸�¶Nê‡§Žð»@ �.á˜oNšaÆ°àÝa•åF¿ùjEn¯ ëSÊG^e¥D= aA ˆ°+>_¡1U|‹��C@^™>#céªCD�yD©>ºëý€MSÊ%0ŸœÞoaÂ»?‚&�Mè'”ûÝ ð˜�_	NV@Ä%¥«¿\¡$C›ÀfÑ�_† *€ˆ¹à¤š8†ês ò‹€p! DÈGvLé”C8Þ¨Ý«“ªH1i-_’«y-Ã„ Õ#Œ~ùù
¿›„JQÂè€1ì]›Y©x%K Ã„ —L™ ç°-	 ùPÔläd¸…	 ŽÜ»X‡ìÆEŠ£¶âg'Šyÿ… äF”]ÈV¿À�mY–Ð^5I^Áá°RI/aØ Bî‚O•ÓõÓ1ã˜<;É6w ÝÿaC ±}¶KéÄ¹pÃuÌxNËŽâFŠ BÊ=àçÒi#ýn	ÛU$T?’ý3†ª¤‰ F€�:û¿Ë4®–o�/ìÆ±ÙCQÛá(ÙÉû0Œ¨ !4iË„¾xt™ßÍ "å“Ûk§JzÃ1Ò•ÒV€úéçø�¼ðãñ³5'M(Ñ1;ëÓS˜‹F€�9|¯"íUÏ’%Àß²HÍ1ÚQìHìÚêè7O(WEó Â† "©¤ô�“§¼ôýÝ8J{ ¾¸C™¶Ñ?dRYnôõãyÝÂ† "î¸ÿ–£ø–^Út‘ŽÇ²ÀM™4úÖÎëÎCr‡ÜùIªIH¸…ÿìc™øÂ÷v+ÏMpÃ†}sçrU¤Ö-	GúÉgé¡@H|çd~°€BÙ¹*©ï³,pƒö©Mê+;–nðÿí=9•;›á@ ÉŽ‡ˆK€BúæÎe:akŠÙÚÆ–:ºý *¥6Ñ=rþ§˜€8ïD~  ?\ûá
�ÿ@Ww\•$¤;§T©¦dÓ¯‡;\yê¡,ÞÙ÷Ñ�RÚ}"Ëþ ?Üó�u=fåtÇûõwï÷¯Û¿B»TìZô…£ËrÛ•#Ø ÷õ¸ûüpû_»õýÛ•è1ªzÉH™ø~~°û·õÀïêGW::ù`z‚Ž `îÂÝ?àgñ_#ÕnT9?žËþ{|qn>Ä`}ž^€À# Ø9Ÿ`æ?àwñ_£d…QÙ›ñ
;W%r]ÿCáö|zÊ†W  uð®EÚq<ƒh@Šÿ#UÆd8àôú=vø(•&‡zÎ:ª”¹ F ¨oþcÿ@�Šÿ%MF£þiät)’Ü~¿Üg¤®Ø·BE‰áõxäz¡ ¨ �ùÏÝ?¼â¿öœ€šg�R­Š”ê"£?R¥i“óW´Ï<¼4·K ‚‡oK �q[þA-þk8}FÕÏ•¼«H˜\‘ÐãGŒÒ![äwÓ±1ÕŽŽÝ�•‚ˆ 0“Ç&r=  ‚[ü×0Ö¨rž£‘Œ¬UhµU‘æ^ýÞé~ùæî€à! Ìç�âCñ_[Ù2£š§5)T¶™ÐŒ�VhÎÁUëî“×çÙ‚› b‹¹ q'Ìµ]e@˜Šÿ©N©ú%Gé
«öIV½Õ
¬ñåŽÎßu„NžX¢aLòôÐæßçElÒDÈ dú¥J²ò]ñ_[Q›Ñ¨ŒÒUV«'[õ�T`Ô›ÜQ¾gmW¦¢÷ÿºC›Û�KhÁÒ¬¡	† ¢¼ØèÓ³\sñ_[Q‹»RÀÉí�ôùÆw‹RGìZ®—Ž«ÕÙ;¾ø¯qÆáq	= ñé)%*áÄ_À37ÏíÖ�ç¦øpß ÷#SdÕ]'�ÝÙÑÙŒÒYoŸw×ê¤ŽÜªXGlU¬Õ$súøí¸ý‹uÙï:ÔØêñ?B ˆSåîðòÎß�â¿¶DÚ¨|™ÔºÌêû'ŒÐÄÝz`Y�þ¼¬G+{†¿„À½«?hLQ®à=¾XcKƒÙÁ{â�%ºæ¾N¿›@0|x‡”ÆÖó‡»BvûÔÕwuê[¦\×Õ¿Ï~cwVK;³ZÖ™Ñ2÷s‡û9“û³·;3z·+«ê"G[•9Úª<¡±eŽÆ•¹ŸçþYYB[–9›Ð7€à   >uÇf^¸in·~âó�ÿÆüü¹ÏŸ?ªTu%NîcÏQÑ¿$oUãä&þ}^¯ßM‰=n;}V^btÄ^,ýâTü×³Žè¡›ÀMO0 ÐÆÒ? ~Å�‹o�_8lÏbU�ÁxEÄ |vÊ!tÿq-þq©„tÂG¸öù� à£½ê“Úf4;ÿ q.þq'L ðÀG'|”  _®¸+´Åíàþ;â`â˜„vŸýI�AF ðë…7ÒÑìûäíÎÿoïŸUvî¿cÎ£ÝŠƒ£öe´Ÿ >9`çTn €øvûoÌ…·´Ç"C ðÀ'GíC÷?0\Q,þq
u•ŽöØ–a ¿ |à.û;|/6þ†#ÊÅ?N!€#ÐýC ðÁ;ÑýÃ¬‡Â?áo0!àž§zUGìÍ< ¿ |p$“ÿ€aÝù_rG4&üt¶ü�»D·Çp‹jG{NbÀ ºÿÿëCÑýa¼‡nÿÿÛ.¨Šü®yGÒà@�}dGfÿC1ãÁøtû»êÇ&tëùÑ/þ.€? 6e7Æ»€¡Üù_vg¼ºýo9¯J£FF¿ø»ÆT;¹ÀƒÂ" ØÇéþ%nÝþn!ŒC·ÿMÙ•¡ÑB# Ð¶[$4¦Š—¨8ÿ[¿¿âï:ˆ PpT£:˜780`q-þ•åñ+þ®}¶K©”N€‚" ÐÁ»ñî‚â?	ÇÝ"�kd! 
¤¤HÚoûT¡ž-Š|q“TX€q“­›plÅ?ÞŠð†GADI*��ìÈØ”Ž×:ÿíÇ%4'ÆcþÛÐ�,�Â  ÈÞÛÑýlr�ÿï:b5áïæs«TEñ_ÏÞ“¹V
  Ê‹�¶ÛŠTlÝþXÛ‡ê	 …B (€MNÊ¡—XÅë]/ë9¨P °‰XÅ2aL"–!ù� P tiëŠåÁ>Lø0®™…A ð˜1Òž“ÓÖ.þq:Ø‡â?xôšÀc;o�T1õÈ¡øc è(f[xlÏI¼Ä€ëººtùïãsç¿ãø„n:·JeŒgƒ �í¸5 pïüãTüÝnÿÏ¡øÇä±,�öÀcÛ�#  ÞèöÇPl?žk§× Û�71b,nÅßíög¶~l¿Àk¼Â¯gMÑ‹…˜Šcñ¿å¼*�(eÌ?¶ÇÅÓkô x|ØG= Þ# xˆñÄÅù0¶ÆQ)‡¨zŠ à! â†â�|b•· Ú� ˆŠ?ò�›(o ¼za�4¾Ž—ñ@ñ‡&Ža•—¨P_Çñ@ñ‡WÆÕrõÀ#ãjyi}xi+€§¨R¡ QGñ‡×ðÀ#t]!Ê(þ(„’"q˜’‡ a QEñG!q3å€G»Š†õùÝ„@¡ø£Ð¸™òÀ#ãj˜½vOÎïÕIÿÛ¢ÓÑªÞŒß­ñÅ~ À; %¥š
	³¿ÏëÕ™W¶¾÷ëÏÿªÿ×quíý�±:Øg—m’šómö	‚±£(S^á•õ@m%/kØïüÝ‚Ÿ^«÷ÿ‰WzuêÏÖý³8Ýùÿò®NÅéT¿Ï©Ty	!>F�äzê^YT�àesñwïü7TèŸYÐ«i¿ŒW Û~«& x†Jå�ªrî¢Vüã(þ®§Þ! x€ÄÍâ§·â¿ë„¤n9�1ÿ ª¢GÕ3 ŒâÙâ‡Çâã¹•QJÏ]U�àûâ€xÃF»øG9\uOg,‹y1E&¨Üï�»²
ùG ð “ Ãá¹…C/þQ—ÞÙ‘ qAñ�ªrJ•xU=PM—U(Š¾
wB€[üg>Ø¥¸ ø‡½ªÞ  x ŒõÃ�öìký»;�¿ÇtCÀš�ƒÂæçˆWñß}Ûdÿ:ºýC£¢ŒRå^U0šì;ÿéWä·ø¯=Ÿ l›¹wþ¿ùS¼îüg‹M~Âf7Už  x k½xTä«Ûß‹âÆá ºýôªzƒ à@,‹˜B@ÜŠÿîéö³R†k<A ð õ?¾Å?! nÅ?×íÏÞþ¡Æ€7 Èf½xT„¥ø9Ä±ø³Î?ü8˜É Ð/.îó­ø1PüVex‚ à&£øîç-¾ÿ … Š?ÂŒ o ¼@€¯^y³¿øwö(0Ö„ ?	ÅaWÉ	«ž  x 7Cð³øŸvyk ŠÿÚ! Ð½D—TO <Ð€ñÞ8ÿö®à^-^XT¸¡	Š?¢"sh¢ˆ àz 
/Åÿƒ! £Ç»¶Rü%é¾àÿ\‡Àé^/Q(þk‡€Ïþ¬Õ“ðã9í,õC¤ ¼A ð = …Æâ¿ÆËoä?¸Åÿæ¹ÝŠÖùÇC Þ  x€€ÂX°4ÚâïE ø#ªÒ½áý2€è(Lñ?õg-¡.þÃù·Püeô xƒ àV¦ø·v„¿ø¯N¹lh�†â�¨c€7 è¡»ÊÛnÿˆÿ5æ/qƒM«Ú:þo»è¶ŽX�ùçNõ;·Rål+=éèý¼À«#Ð-ä;ÿ–ÿ5æ½Õ—8é	pïüox$>ûì9é?§úQüc§½;º?ó~" x ¹�ã ómEkVŸ½<šwþê	øô¥›þ·þ$f³ýÝâÃ·ª(þ1Õ¼:ú?÷~  x EªÐFW::bïbÅ©·cc!à{7´ë¦ÿ’"¿[¿pSå€x³zãG§ŽÐ§§”(.Þ^?¸ÅÿŽ¿Qü/Íôªz� à€wâšÛ-Å±Å€7’=n¬­lcÀë`Œ4çÑîØ„€Ã.X«É¥tûck™Xíz <…j‚ìÂSâÕ@ñG\­b g if" çâ6ÜùãƒRõÀ#«Ú˜´R¨ð™CQ°÷ä”n<‡ÙþX×ÊÕ\K½B ðÈÛ«2^=4b>Õ;ÿYß¨TqÊï– hÞ^I ð
À#ËšxÓÃáE·?6ei7S^! xd	oÚ‚#„Å›C ðÀ#Ë ¾ „Å±”ÞTÏ <Â›Ö?„€à£øc –42à€G–­Ìä6°€?ÁEñÇ@e²Ò»ÍÌ§ò
À#=½RK}EŠ?ƒño <´Œå+¾#ÅƒÅPª· Zü.cWA@ðÅCÁ5Ô[ ½¶´ÏË‡Ç üCñÇP-XÂ5ÔK -  
! ð(þ®¡Þ" xˆ7oð
gßíSºá[ìí�¡[°Œ / <ÔÔfÕÂ©€�C(Lñw÷ö/)*À“!’ÞZ‘UwÚïVDÀc¯2†H„ ï‹QÒÃ'Aäq÷ï=€Ç˜\„€ü£ø#_BõÀc–±0ÈùCñG>±À{tÒyŒ!€p„ c¤9�vûÝ”Ðúð)ÝxN¥ßÍ@„ÌcøÔsô xlþ’>&²„À…§ŒÐ§§”øÝŒÐÞùÏø:ÅùÓÜnµ¤‘3 ¼F ðX_Fzù�^¯ŸyÀpÀàÑí/<·�kf! 
àùÖ²†!`à(þðÊó€B   oæp!lÅ^ú'= A (€g^#Í†!`ã(þð~Ø”^ÓB  @G·Õ¢wX6„€õQüáµ-îU†ùA (†Â‰ð>Š?
�9S…C (fµ†;|æ�x/t×ùÏü:ÛûÂ{Ï1dZ0€ùÇ|æ„Yœ÷	X³Î¿8åwKun×ÿS8¨P ²¼9«K™fq Û…ôô‚^6N+ @=þ2É6ìâ(þ(´Ç_âYH€" DCB Å~àYX€onÑÙSÈg„W¢(þðÃò–¬¿Ë0i! 
(k¥¿ý›.®¨ˆbøèN)Íú³ýQx?Ïµ±Ð öó "%J!À-þ×}�âÐý_xIž3ÖþJ ˆd0Fšóh·ÂêÀ]ú×ù~èé•žœO@¡ÑP`�­Y½°ˆ}®£&Ìû¸wþ¿þ
ÅþöŒ¦¹,À<ÇLÀ(
ãpÀšnÿTÂï– Îx–k¢ >àÍ]aÚ6˜â� èNKùÀ Ÿ–»0]ap÷öçÎAðØKéÜ À'¢Ë+Ò‚<àÿßÒí�€øÓsá�<v ŸÜÿoú¨bXSü9ØAéþôEfÿû… à“¦6Ë¹×1¤°W}’â�@™ûbÝÿ>" øèO¬ˆ… LÜ{rJ³¾YÅ�?åþg˜üç'€�î}ª[½l}~Ntïüg~£R¥E¾<=°AÍíVséþ÷Àç€G^ Ç…Ãnñwïü)þš»þÑ­LÖïVÄÀgwü•É€qRÈ°ûDŠ?‚kÎc]~7!ö >ûû¼^-[IŽ“B„ ·øÏ>‡nÓ³¯õê­\÷üF €;ÿF/@ÜxÖÿòbãÉãÃu×¼@  $ d­ß­@B ÅA×ÞeÙ-  9!ðñ—Ø#Žò(þƒ»žìQ/'ÿ  nc2`låcŸ€]'$uÃ9Utû#ðæ<Êä¿   „»æ’&&ÅÄÕpö	Øië¤f«ReÅyo�WO¼Ò«Eï°ùIP äº?uúÝ„l8À-þ7�[©‘¥LøCðÍø3×¸ ! ÈþÞ­ÖfÆÙ`B ÅaòÚ²Œþ1Ÿsƒ„  î¶À³a|,î¶Û*Á�?Bå×ôp `núKWîˆLÄÛ¦B€[üo>¯Šn„Æò–¬x–mÏƒ† 0m�V¿ÿ;aÃ!`Mñ¯*gÌá1óÁ.öý @ Í|°“��°^ ø#Œ:º­neßÿ@JúÝ ¬oiSV÷>Õ£ãög]úCÀ–£�tP)wþ�v©‡¹�D@@ýê�t™á=_8ªLÕ#èöG¸´tXÍz�¥AE (wS ß=Á\  áõ›?uª‹IÍ�E °ÿ»·“=³„RS›Í­jBp ìÝæ¬æ0y@]uO‡Òúh€ô0�@Øn^nœ!Ì # „`Íõ3‰@xüâ,e@\÷@W. @Ð½º4£»Ÿd×¿0  „@{—ÕÕ÷Ð  ø~2§Ýï&`€ !qóÜ.½¹‚s´×£/¦õìkìú€�ÈZéâÛ;ün lP&+]t;wÿaB Yº~fé@ðÜ2·Ko­ÈúÝ d~xs»,óHk‡Õ¯˜§:€�YôNFw²E0€ ¹êÞÎÜQæ@ýò®u²Ê@@nJn|„-Ãˆ B+Û¬.¹ƒÉ6 üwþ¬Õ~7CD ©ÛïÖ‹Øh€¿×¡_ç:V€�'ï>¶ àÓiôD† Ä^_žÑ¯ÿÄ� 
ïÂ›W3)ä !wíý�Zü.Ý  
»'ÉCÏ§yÉCŽ r½}LÂP8=Vß¹�‰Q@ ˆ€-îËMÆ ¯]zGGn%Â� ÿ{{»–4²' ïü}^/7B ˆˆ®´ô•kÛr‡@¾5·[}óº6^Ø! DÈ¼·útûqðÀ7~Ó–ˆ@Ä\s_§^y“�9 äÏ­�uëó9‰4j ãžøÕkÛXŸ /–4euÑml=E€ˆþÀþäV~`�»ÓèÙ×´)M§b$ "ê÷Otë¾g82ÀÐ]ö»Í‹êU€ûö¬ÕZ°”]ÞýÏöhöÃóe€ˆïxÖ¯ZÕÒÁÌ] ƒ[QtÞLvû‹:@Ä½³*«/ÿ_›2ì` V­¶:óÊ¶Ü¢� Ï¾Ö«ÏaR €MëÍô÷6¶rÇ€­ãu'ÀÆ|ï†Õzéunýã‚ #Ìn×óüpXß�té®°r(N 1ãvï-m¢{Àû{9­‹oïà%‰@Ì´uZ�þ‹Vµ²2 €”[*ü•kÚr»ˆ"^ 1ôæŠŒÎ¼²57á@|-oÎjê/ZÔÃ6ÿ±D ˆ©-îËm ž:{¤Ïý¼U+Û¸õ�+@ŒÝ÷t�®¾·Óïf (0w_�/]ÝªÅïÒg€˜ûÕ;uïÓÌüâäÂ›Û9Þ (·åç¯0ÄÁwwêö¿²' øOwà®je�  ânšÛ­kîcØý@Ž{Þ÷ô_¶jþÆ�(ºûÉý„-Á± ÞÓÑcõ¹Ë[ôúrB %¿�fÕÖC À:Ü£ƒO»¬UKÙ-ˆÊ._½–�~°> Ö³¢5«Ï^Þ’û ¼žYÐ«³9A À-[™Õ‰µh	ç ¡ä®ì9ý—­¹ù=À† °Qï¬rC@³^]Êœ  Lî{¦§»oŠ?6� €MZµÚêÓ—´ä¶|îÿo^·:·¼Ø 6«£Ûê´Ÿµèñ—Ó¼Z@Àwöüþ�í~7!A À€¸§…}áª6=ðÛAãåû½Ú9ÛƒB À€¹]Š_ûõjÝ<—mD� ùúoVëŽ¿ñs‰Á! `Ð~<§]—ÿ¾#w×À?îðÜ)—µÒ3‡!q¬,}º´ëèÒ×~Ó¦^ ¾hlÍêÄ‹[ôìkä…Ásk¿ÛÐ2„¯ôççÒšúóÖÜ]€ÂYøvFÿóÓ5¼MÇ�µ8’aàCæÞ}¸w!îÝ€Âìî÷©‹Z´¼™Ÿ9‡évŒ ÃâÞ…|â§-Zôw#€—î{ºG§þ¬5wp0níg yñnsVÿó“fýå_ì ä[_FºäŽ}ó·«yq‘/-î$@æ  /ºÒÒ¯nÓÅ·wä.X †Ï^;å²Íz¨‹—yãÖ~G†9 È¯Ùwå.Xî6Â †îù†>óÃf½°ˆ­¸‘gÆ¸“ ™€üs/XÇüpUî`ðf>Ø¥Ï\Ú¢æv‚4òÏÈv;†e€ðHS›ÕÉ—´ä.d ¦½Ëæ¶Ý¾ôÎe©ýðŒév¬e ¼å^È>÷óV­lãjlŠÛcvä÷›5÷E&ÓÂ[níw$‡I€ðÜ“ó{uä÷Wé¯ÿf×2àƒÜI³WÜÝ©O_Ú¢å-¬ïG!8n °ì€‚hé°:ãŠVýðævusƒä,iÌêµèšû:9_cÜU †I€(°[ëÖ±6kÁRÖ
"Þîü[·Žþá*Í‹É²(4Óíd�óFÁŸ±÷æŠL.üúO�±-?îÌ~wÏŒïÞ@oü‘5æ]3ajó„T¢ïuŸÚ hÇñ	ýâ¬
MÚ2Á«�È»ë=ºè¶vµu2)þéÍ$'�hõ#›zŒW_ø&™�Î:²L_>¦L©$ßD�»]ö¹3VëéL„…ßlûÂ¶º*GwšŒ‘ünâÍ�íN‚:êÍzùÆCÖJ7ÍíÖáß]EñG0X-rk¿» ¬Ñ«~·X37À=Yð§·uäÎ Âì�å}ê[ô“9í¼ŸÖ˜ÜÜ¿\ �µ Ê��téã¬ÒÝOö°4
¡ãŽï»§÷¹=Z/.¦GóŸšŸ F �³¢5«óf®Öñ?æ"ŠpèÍô‡×CÏ_•;½�S1Dkj~nº•uÌ«Æ¨hþ’ŒN¼¸E‡íY¤ó>Y®	c˜¯Šàyø…´.¹£=·±dnÍ/ ôõ9¯¦¼il�¼�Öc/¥õ™CJuö±eª*7~7	Èmâó£9íœ|‰Ðpk¾ûù½+hýôÆ#UúÚ*`€ÊKŒÎ8¼TS?^šû5Phogô«{:ôçç˜­Šð°²ËfŽÞÂýõ{+®�Õ«2ÚÏ×–ÔÑmuå;5û‘.�qx™NûX©ÊŠyùà½Åïftõ½�ºïé^n„�íïþw½¿åŠqg B¥µÃêçèÐ¬‡:s	�rH©JŠün¢è­Y]}o‡îyªGY¦L!¤Œ±ïmÿï¼¿*ÀüË·yØ[ýÒ;;ô±Vå6]òeiSVç_¿Z‡}§Y*Åa¶v­oðtòÔ{(a^ð­U@¹Ýùn�@%“1ÄÉ}¿ýs—î–½(Ö8û7Ì¨yÊýõû³§.´Îä%M�’FùÙ8 ŸÜá€“.Õ´ÿ*ÕÕïuxõ�ù½úí�úû<öìG´X«–îÕµc—ÞiºÜß¯3}º~zãÝF:Î·ÖI8Ò¸XgQ¦ÉcÙG ëÊd¥ÿÙ“;�âµe^D’•þØ0³îø5¿_÷Ü5«Çd ˆæÞ=†Õý8h—”>q@‰ŽÜ›eq·jµÕïžèÖm�wåÆú�(3V^ç÷kÿ†y ˆ“êF'|¤D'X¢I[Ò+îö¼î†Rnáw?3©qÑ›IN|cvõ{« ÖÝA…y ˆ©=¶Mæ‚ÀQû«¼˜�…¢º~ß-úø{wîÎˆ+½Ù0³nÂÚ¶Þ•Žy ˆ3w3¡Ã÷*Ö±û•è€�S~7yXzÿ3=ºï™n¶êEÌÙÎ=uí?I®ÿw˜€øêìy®€;DpÄÞn(Ö^õ):Bau—ÕÃÏ§uïÓÝzr~/]ü€Ë:�éÖ»¤1 XŸ»„ðè}‹uÌ¾ÅÚy›õs3üÕ•–}±'w·ÿØËiõöñ65þïZÿž†y À&�®t4e·"¸k‘>²cJ#KéðÃ¢w2úÛ¿Ózâ•´žzµWiŠ>0àñ×¯\Ì Æ1Ò“’:pç"°K‘v��Ìýò¯­ÓæºôÝ¢ïÎÞ_ÑÊ²=`¨ãÿ®öekî–±ll†»„ìù†¾Ü‡{:¡Û°ÿŽ)í»]JûíP¤íÇ±¼p8'>þ³¡OÏ½Ö«§¤õÂ"nñ�|�ÿ»6x¯²ý´Æ‘Yi™ŒFíÙ ¸ÊKŒöÝ>¥}¶ëÿØyë¤’d‚�ÎØöµÞ÷>æ/és·.0,¶½¥X[6^3ºýƒÿg£�•õÓo3ÒIÃ{b k+NI{NJå&NÞ*©Æ%´ÓÖñ›TØØšÕ‚¥™\‘_¸¬OóÞêc^ €Ýÿ®�^y¬ÌmF–  äQO¯rÖÜ�µ¹;ºnØ~\RÛŒNhË'ô›-oÉjYSV‹ßíËüKû‹½;žÀ{Y%nÛØÿÛøÕå,›ªÏ4.12c¼j€M«(3;ÊÑè*Gãë[“Ð–£�©rTWé¨¦Âñm‚;	oe›ÕŠ–ŒÞY•Í}¼½*£·Wº¿Î°·>à3kíŠ†dÝ8]g6x´åÆû¯3½vz“Ûð5/`ãÜ;å¶ÎŒ^]êžP×»É}
Ü0P3Òüç³£Òb“û(JJEI£â”QQªÿ×îŸ•™Ü!I=}Vé^)ÝksKézrŸm®·¢+mÕÒžUS[6·}îÊ¶¬V®Îªµƒ;x è¬qnÝXñwmrðÑs›, ºw›³¹ X§†oÂfú­©ŸÞøš‘©ßôß  �aíâ…³êês‡ o„³éG0VÖÜâAÓ  €G¬ÌM›*þ R_vÓ]   8¬{ë®Ô�›û{› oÌ®}UÖ¾˜·–  Ïé™…³ª; ¸¬Ìì¼´
  xÊJê¹P Hw§n°Öv»U  À3Öª¥/›œ�· ðÖœªfkœë†Ý2  à!û›7fW·ä- ¸ÒÖ^F/   ÁäÖèÞ¤¹r À`É¬º·�1›�U  
Ï­Ño^W÷NÞ€+ãèîÊÀ!µ  x¥/“±?Ì* ,þmÝkVúý ›  <ãÖæÅ³G/ô, ¸²V—»›öë  @þåjrV—öë Ïª{N²öë  €Œîi¸¾îyÏ@ÿW™K†ôu   ¿Œ3¤š¼™Ó 7nò´Æ§d´ßP¿  �µz¼aVÝ”¡|íÐz Ü¹ †^   üd‡x÷?¬ ×äé��HúØp  žµz´aVÝ¡¢!÷ ¸z3ælk•Îc  €ÁqkoFú¢†aXÀ=*Øsõp  Ž[{_ŸU·@~ WÒÚï[«%Ã}  °ynÍuk¯†iØ`Á¬ºÕÖè¼á>  Ø<·æºµWÃ4¬I€kcB   Ážø—×€u&Êöäëñ  ÀûÜ;Ü‰ž wB ¬®È×ã €µX]1Ü‰ž WBæ"& �_nmukl>3¯€	�  äŸ5æ«ù˜øçÉ$Àµ1! €ü°Ö>Ø0kôÊ³¼ö ¬Ñ›Iža­Z¼xl  âÂZµôeS_ðâ±=	 oÌ®~ÃÊLóâ± ˆk¦º554ÀµhVí]Y™+½z|  ¢,+seÃõµôêñ= ®â¶w‡Àg¼|  "ÇêÙE‰šs½|
OÀ¼;Mº7“<ÉÊvzù<  DiÜ¿7›ü”®3½¡ .wìÂXçË^?  Q`�¾èÕ¸A€ká¬ÚÙ’½¡Ï @xÙÍ¬»­ÏT� àêHÔ}ÉJ¯êù  k5Ï­•…z¾‚€·¯3�ræ  ð¹¹rÖ91W+£ \¿­y…ù   ¬Ë­�××ÌS4 ¬™Àþ   ôskbÿ\¹Â*x p-_óMku�Ï @P¸µÐ­‰~<·'‡Ä„©¶$é4ÝoŒõ«  øÅZÍíËÖýÆlÓíÇóûÒàrÿÁ	éxkí¿ýj  ~pkŸ[ý*þ¾ö ¬1~ZãØéY�õ»-  xÍÊ.ê±æ %³êÞ–�|ëXÃ}²&q¸¬]éw[  ð”[ëúŠ÷»ø" ¸Íõï>ãe­õ­+  /¹5Î­u7T-R " ¸^ŸYûŒdN²îŠ  ¢¥Ï­qýµ. \³êî‘5_õ»  ä“ÍšÓs5.@ \³jÿÏZýÈïv  �nMk¸¾öfŒï« 6fÒ´Æ3�ôc‚ÛF  6ÆZY{FÃÌÑ³@�.®“¦7žldg™b¿Û À@YÙI§5Ì}§*ÐÀ5iZã!Fúƒ1ªò»-  lŽ•Z•Õq××=® | pm;uÕ®ŽÓ÷ˆ1f´ßm `c¬µ�J$qO¿UÀnà†,ž=êekôQ+Ûàw[  ØØÊí†âš€5&�¶z´SÔ}¯¤}ýn  kX«çdKŽj¸~d£B"TÀ5æ4[>2Õt¯1:Äï¶  `­} 3Y÷É·¯3�az5B1°¶å7™•×)«Ûün  Þ¬ì�«ëŽ[ñeÀû¬™tzãwŒ1?2F	¿[ ˆk•1Ò�Îªý©d¬B(Ä _ýé�ËÑ�FÚÚï¶  ¢ÏZ-ÉÊ~fñ¬ÑO(ÄB \ã¦·Ž*±=7cŽô»- €è²Ö>”î.:ù­9UÍ
¹H€~	  <Ók¥o7Ì¬½"¬]þ ý  ä»Ëß::aÑŒºFé•�\ p1$  È¡.ÿX€~	  †¬7j]þ1
 ý  †�h—ì@Î›¬ßvå92Ùï™2¿› +Û)«‹×]¦ÇLŸ".à?&�¾r¼1ÙË�Ñ§ün  8¬ÕÖ:ç,º¾f‰b"V`�I§7jŒ½Êíäw[  þ±Vó¬5_Yt}íÜ¸}b r €Ø²Vm’~Ø°¸öê8t÷oH|À0,  ñëîïËÚ¯½1{ô»Š±Ø€5 €h‹swÿ† Öv¢MÔ�l:Y²ß6ÆìºÁW *ÖÚ—e�ËÚknÕ�&ãw{‚‚ °“Oo<Æ:ö|#óÑÂ~K  ù`­æJÎ¥³jâ]`3êÏXùac3çZ™ã�älîï üc¥¬±ö�Öè'3G¿À÷bã 4iúŠzcõcÌ©’Rý: @AôÊÚ[²F-š9º�×|ó ƒ4~ZãØbÙ¯Jæ‹Æ¨b°_ Èïr>kôë´Õ•KfÕ½Ík;p€!ª?ee…J2_–ô5#3f¨� <+»\V¿ROâê†[jÜ5ý$@lsFËÄ"›>EÖœ"£òñ˜ €°Z é–´“ºùÍU¯óú Ï&ŸÞ´Ÿu²§Êê$cL]¾ bæ+Ýf�n‰úé|…F ðÊ›œ4iÕaÆfO5²ÇË˜rÏž "6®odÿ�‘sËâ­kæêB“õ»MQD (€	SmIÂiÚß1æPk³‡cö•”,Äs@ôYkŸ5Æ™›ÍjnÆÖüã�Ù¦ÛïFEÀu_Z1¢¢[æ�ô1I»³Ç €8­Õ—ô¢¬æf;wu‘þÚxÍèv¿Û7€ 7½uT‰í9Ìäzt¨1šìw›  Ïæ[kçfgnÚ¦[:³r¯°¿ TæÊ�•Íîoev16»�dê	 ÂÂZ-”lƒ5ÎkN6û¢ÎSgÔÎ÷»]X ,N´‰	å-ã'SŸ�­·R½»èÀÍ’ÝÖSâwÄƒµ¶[2‹%¹;î5Èš“0i%Þl­|‹wÂ� §7o“Tï6Y9£$U:Ùl¥Œ©´R•û{ÉV™Ü¯­Q¥¬­2ÆŒö»Ý üe­]!cZŒU«¤V+Û"™Ü¯�Ô"k[³ŽÓj²j1N¶¹O©7_ŸYý&ß7…Þÿ÷��Æ5    IEND®B`‚          Í  v             C  00      Ò	  S	  @@      “  %  ``      Å  ¸   €€      t  }5          &;  ñQ  ‰PNG

   IHDR         óÿa  ”IDATxœ}“;LTA†ÿ33÷î."°j–—‚ `4V`AcgCb,0!1Úaal 1ÆG…&
)�±"ñ…	Jb|$¢¡ÀDq"ldÙ{ïÌ˜3(,˜êÞ3çûÏk@Co¶ÍK–ß¶FwÀF) $ â[ÀZÀØø¤
$¼×áÆÊåo#>QcßŸV)è•ðveL�ƒ|
�EÅß¾|�bA¿&Zÿ­µéVfXxe]ÌEJ
Å`¤�£u
MÕÒ	ÌÌkdç5 +ö•‰ŠJèü05õ-D¤¤ ­mXÔg$®ž-ÅÉv^Ì;Á+ÏVñ`ª€š›¬€µÖFŠˆ<N»ÀÁ�*P•Ô&añRX=dð@íŠàLˆ@^ìÉNÚâÆ¹RÃæš¥ |D¨“ÚS€ˆËGÄÑ-ŽÕ+t¶ú®Û	/7û‰‹Ãy¬OZLtîÁÐ©Ý¨­’Bë.8JM5Êš]Ôû¸ÎßÍcôm�ÊqpŸtï—nB|¯\â”âœØ89¢ÿþ*N´(|þáéõ4Ž7*ñH·2ã£˜cãÌœvêü¦+‰…ƒ;OþbôZmÊMBIÀ˜Ø—ö¥„/³&¦W{—N—àÝ½½æ†:gÆ§çË³bó�ÂS„Á‡k˜_6ð6Õ3ÂEfQ¶Í-Ž¬9ßí)XkCcaS>ðcI£çV/>t5Ê8£çï‹è¹™ÃÏ%�¤ïðC
©¹oi\$ÊºþÊGêš«%'‡¯sÓÙÈ‰%}‚Ö†Ÿ²2ÅÜD¼LRŒ	UR¹Ó2¥üøÂÕ½½LÝÎÚÒ›mC2=dmÔ–ì¸ÎÂ['Ro¶ÖùŸBÁ:Î«�    IEND®B`‚‰PNG

   IHDR           szzô  ×IDATxœ½W[lTU]ûÜÇ¼ZJÕ*à¥¢ "Hx¤1Æ *1’¨Ä�"õ~Lü1¢’Hð!á~Œb"~h0ÑmˆQZl�ŠÐ¡-}Ì£sï=Çì3s§ó¸ÓšTÝÉdfÎ=g¯µ×Ùgß}Ú¤ø×Üíý+²v(é®�’³ eaJFHô’0/yÊ9Ò}tÆ÷…˜äÿhl½¢týA�±CËRÞ”tyâÔðA a‚Œ¤t(ïˆ
ÇÛº7�16áe46À¤ÔÀ93\×â¦âŒ(€ÿŠ©¼O3ROnzà¢ŠÔ­ïºWàsò�ˆ¿gFêZœd_&JF%p5Dð§2ÝqŸN2ža,Ædlš÷ê�e q�J•\vA@*£�Îdcâ16©²ÏÂ6±IÿçpõãòT ’€Pr¹	%[…#éŒøKÊŒ£K¤\	4Í2°¬ÙÂüÙ&î©úyß�DÇu?t:èèõ6€ˆAš„2ËH”„ÆÌŒ´òãµÊKë …00¢ðX“…]"hYl#leu¾ûÙÁ[gèHºˆ¸sÐUä0×š
h€ôrpÅà,óhZáµMQ´=ƒ•säqh%Æ²³üµ�„îE.†3	Aˆuª¯Q‰DJzü·Á$"3h£˜ÍHZáí­Ux¥%¢É0°È%\YH 	ìøv=Cu!Ò[–˜«‰ç”("Á©@f€«,Ààh6rw¼ññ ñÙ'�§\…¾´DÌ"ðŒI$MU!»P¾ïœÙœpK›LìÝÓQ›“TÊM³	-³m$”Ô	8˜Q˜iš#&Ò^0	QæŒ ×ö<ËK=Y9òIÞ–ˆ_”¨¸/&°¤ÎÄgë¦ã�gbH¹ãÇ¶ÐÌRðä˜Âü9&Ö>dë}/Ýo+$ÄàFüåw†põ†CØ·(†­ë"zNz‘Bó,=q!‹²u1HAÐEfù|–™ÍìBóŽ?^~`W{\x¬Zlaã#!=/ãa‹ðx³¥}—ª ‚$]ø@V˜B¦>AVHä¶É‰Á¯»på'Ûj0szÖµÈªúLH@ ®:;ËŸìGÜÞíbõë8ÿS¦Ü¾›ï¸áÂSÀŠN´Õ Ê–c¿|³Õ×ý¿4(³,|®ãª|Ï{û%^<pÃ	…Ö�‡ñæ–*|z)�_{\}W€—ª7é) ‚Ž„e-çïúÂÎ§£ù:Òvt¿üéò+«ÚÁýˆÙ§7Ù¨Ü„ŽnDÆ'³CË$]˜ömŽáî¨ÂŒiB—éÕÚ8¾wZÅÈ}œ#4ÙH]Ï�Ë�2®‚eP¾ÊQ.ë÷<ÕÉ·ÿø(Ö/áØà¼–ÇÆ…ËŽö-'" r/”Î¾¹’ÁSKBù£ÆÆßì`÷Æ¨~?ù¨]\”[ûõ•®õz˜£²™(]Ä$ø­wèL2?¹¨päêÀæ'Â¨­E�I©6>®‡¾LjŸ¥ò`ç±0áÇß\ü"¡#à:_J‚É•VÅBp_¹wO'Ðþ»«}ÊB€�×VÞ?“ÄÉ©¢>À÷Ôò3­A×‰cçS8üUµÒûf*(— ÊzŽ¢:LØbÈIŸ8�ß=�Ä‡g“¨Ž×þqãqéÒ¼m}×É°f+é”	ª³Ÿ€Á„Â’F»6DÑò°­5È¸L_hÏà£sI´w¹ZEèK	‹”çÜ`§„]½E:#^¶už )õ€y¹¦táõ\ïU¶)åŠÈMi×MOËÏ{^I)@yÂª6¤“8UÚ–sNÐTÛr~”pAm9ñHã¶[‡­Ø½»�D<CDvÅ¥¹-	:v>‘àý.@W*cÅêm'qûƒ®c­ù«Rç¬ÿéjæ¤ú/":C_Í¨ôrJ;É°Íÿârª<>ò“âËi–aþzÞ¼½…‚µ]Á]©îdhjÄÝ$˜—ÎÑÎ’ëùßt—ð—Mëýñ    IEND®B`‚‰PNG

   IHDR   0   0   Wù‡  	™IDATxœÍZkŒUWþÖ>ç¾g˜aÁ>R¥Im“ÚJÒhLAmp")dÐ©?Š&FhŒ´Fyü)6>�ÚZmùÓDj‹ö�}Xû#¦-HÓ3wîûžsö2kŸs.3wfîkÀt'Ü¹çÌÞßZë[k¯µ÷!TK/[8@ž|œ÷�KKÙ½¤õç˜ô"°žÀÆµ¤†ˆÕ	VêošÝ¿é>V�-šü¼�gç[jÚ6V)+žbvÁ^à1{í„,�‘ísDê ç?2°÷úÓÕJ\Q ¸Ñ³ñüzX‰=–�l÷ÊÃ k2? ±
_3a†ü�\Ê²¢�ðÜ|^aó©½³~;Z	¾ïü+ÞµÓ+gÀÚu‰Èç¥ÿ¿03{¤lÛŠ´Ã)\þîÀ³v…˜©·—­È›ß÷áZ+Þý;]J»`­@¤ðQfRZÅ:l¯xiÝé}³Ÿì0-îºÞµè1¬\ðÆm¡ïØü›º0kR0¡àx¼ä½}ÓÏ*€Ø%w»™–Òº¬[/Ña)ÿ’ÏŽë_ò¹ú~KB¤£`µÉÝ.ØiaßÅ…šè(Q‰�f9¯‚Ð.:@¡äÛ9Rq…xÔ¦XrE�BÙÿ=#Ä#&T¡›w›	e‡ùV[kT¤-¦�Ïä¯EÆð¹"£ì7Í¶°ôæî\AÏ\3;R1ß¹ãbZãÔû.þqÂÁKýÞýÐƒmÉ8:´FbÍ©%3ªÈ´X¤œYC=/¼Lvò.vòÜ(}„ŽdòŒ;D°aYËo�aZ²1ç�ä‡_/á™‹èÏ…xJ•|%Øª£„ÄB$Iìæ_¥ù}•ew³v¦Ö±Z¦Àh‹¶¬JaÃ²„QHÄ,)ƒT�$tLòµ
žïrñ¥Ã´µÃNÚOì,Àv-%˜IÙ¤=oÐ¨ƒµÌÜøá,cÉ6ö|«‹®³Í\è*2‘„£çå:™v±üÈÛ5bDó9så.F÷k
v®–'ˆ|ÌèTDRÛÔ�¤ü]‹"8¸µÓ€w%jÐ\f‘™DÙíÿÎá\ÖCJ(-ã°O!/dzDËú#	ö†9/´¹åFûê@G’ŒÕE©fDÀËÊ“wÿt�Œ(cùJÞC¸€;�¡câ®úcÖU@,+¹¼=¡ð‹ÍÓ*àkÑ¥ñ©Äã’¶x'Œ¥F¤.P¬ÿý¯¥LªÚ´
žà	‹p÷œ(dÙ°‚Ô!÷"²ž€Ñå*X²f40�ª>[d|jak?÷-ß$mªEÆÀ+Ûc°Š€•E�QÖŒKE�nKáÐW:±à:ù-+Òç›_HTRßTJSñ^ÄþõŽ‹>žÅœ£
í7Ï´ñ‰¤…Õ7%pdÙtÜö1kî‰Ã1eY‹
˜ò Ì˜ÿqËn‹V²ÇTÀÛøu;Ò¸TÐH•ÑW+2q¼u_7þð™,î´Í¾xG7ÌR(ÕQbRl¾Ü}KÔÔ.’v[-ÂªÁg‹Ú”Z#®FÒR6ÁÑ~ŒHl·'KGëÒ¨6… “÷åöD…YüÀðÉÀ —3Œ‡W·á¡U)ó÷å.\µen¿¾œ\&mÐe@™¨g®µµ¬/ÀÃÌ$ŸC‹�¶üÚ�iS‘VÀg[W§ðà—“ãÒ²©p,˜k™Š¶VÅ:¡L=¯}7Îèð™XF<þl¯ô;•<.to8ÆòÕà·}}bð£'›Ù©�ŠôE“×E#@L’sËÿìÙ<¶>™Å��ª„�‹¿sd,mð›ïóÁ«	„3JœÄ£ä{€Zˆ³ZNâ?ùZÆÜõ§¶ÿ>‡9Ý
Ù‚ÆšÃ8vÆÅÎ¸XóÓ‰-‚·¤th ç¨Ç€ðX¥2L5½–’úÊÿb-ipîß•6ßI	)0¼+ôj`•-”ýnÎxi%Ô¤E—òÛÀÁ´�°úï�e |¯7…¬NáR†�¥ÄÚÃ96Whù¡*Ë×ÏÁd‡µ¡Ÿ`áV×iy”¥«Ÿ@Œ¢„XYž•à•W€ðkÆÒ¦žè �¾ý¾k¼0¥uàÕÎ„Ve å+ñ�P‰Œ¿ðÈó!øoß›lª$;wKë€©c„¿w¯…Ë¦ú­‘ª”�ß}&gî…à›é8ÈlÙã¥ãŽ_4ÄÁ@²õ!»Ï¿YÆŠ¥1?mN`’°+é$5”|‚o¦üÖÁÏ½QÂ»ç=tµùýGÓ
„JDmàW‡ó¸÷ÎX%p's«	6ö;üûfÀs0¶TÀ¿>\@LšÝ:¥DÝu@¨óæiO¿Xð©Rg‡](6îÍžçÓñÉ¿Lù‘JÔ¦O]B%Ú“„Ÿü1‡Óø›QõZ>ñT³¥·ÄÉÉsvÌ™=¦‰2ß¸¹ê= .””(�¼é±¤s\áûÕ/ˆ“Ë�M{FÌ¥t~õè#¢� -Aè?ëbýî4†²þâ"©q*ÂAÅ*c]ÑX¿{ÄäþpõnDË™T�¢LÔÙFxí¤ƒÞ§qâ¿n%5Š‚�X«œƒÞ>m¤vúê£i¼qÚAgªvÖ¹"r|W<�†Ù­!Tâä9+¶cï_
f�´²¥”Ñb=Ó”Œºä»ð~¸Õ^r¿üs+ÆÀ.:“Ô W™ƒmÜô”6we±ùä<}Ëøüí1t¤‹\¡às¯—±ÿ…Ž¾ãš€Î7J›Ñ›»6˜^ ²?ÍÔÈ>ØØ ›ÞF8~ÆÅƒ?ÏàÆYy³½.màÂ`{Ýl�s°½>¬qâœkÊƒ—ûË8{A#ºÚýTÙ0xÙÊ=�8ÈbxÀQ(³ÉbR‹H•»
ŠùV¶§ïÂSV¼{�[t‰TKÙaó!" ÂX0JÚèûÍýhaÖ®Ÿa{¥¡§Ní�q¿,þdÃÞê•GrJE•9lAÂÌf$©g"¶™£Äªû-	³Œ^9“µYmìª·ª_×vKP4¥ä(³U%ÆÌj\ÅJ�Ò‚‘Ýâ&Á,ØÇtÏÛp~K$1}§çd?¢ÝmpŠ—·ìŸ½;Äì§M9¶ïeKNÀ½âÐz(;cÇ»l�‰Ï÷HËŽo	3ü9=Á`°(;ã‡ÖøÞq¯Œ{Ùãü|E±‡AX¾ìí˜×&®!jÉë€Š@ ½RŒCšK?Ø;«ÆËUJÈGyÝÆR‘•ÐÞ=½€™»$Çk#*Ñe†z[)ëˆ§�Cµ^·ùÉ×$ß.‘8
    IEND®B`‚‰PNG

   IHDR   @   @   ªiqÞ  ZIDATxœÝ[{pTÕÿ�sïÝG6/’@"_u¨ µõ1ŠZG©�>â`ÇVŽS«bÿÐÖbg¬3í¤V­õ�ØQªÕ*öµ*µØ2-Š¢<U($!�lv³�{ïù:ß¹÷ÆM²	»›U>gvï=çû}ç|Ïó�a‰f¾ià­óþ×‰;Žpž%H�OD3@îQ Å aàÿJä"	a|*„XGR¾nPæÕÍMØ£n%+¡ AùÞyÇ¼“$–Åm™·oª°¬ëAô)­F	R¶þ€xÌ¼ãB€ÒÒ�‚Rv;„xžìä[›¸i0¦Ao"-1á6·®‰Fj§.‘7J+Vv/ÈµÄ3êwóðÐéÿé?…aIiUAÙÉŒÝ—îÞtç®•g¦l¹/ŠÃø3×	!³úiiUÎpÓ] "GZÔ_
""‚+„0�H=”Ý».ëô~çš?,ÑÿŽÿÃä¹»g¡ªW„5ºÙ¸-Ì/ð¼‚pŒPµE*Ûîf{/Þöø‘ër… ûõƒÁ/ho1¬Ø_!d£›íq„Ö—<“`²c2B•¯´,lŸ¬Á3fh�À¦•âè«wDäJaF&(;é!M&ÄX4&#Ü(”±’±2f€„lm…ÄÊ+\ÓˆÞiFê§¹Þö‡ø€c3ÂuÓ+cnm…ÔR8îÚÎC…6€”räXn{Y}¯*ùžuÌˆÂTÒueö¤íËÆoe°$mÜbXU!R•<�fHïÃ”µ�dŠÐ“$Hxþ;Ç¿1Ï—„`ŒŒÕpp3cÇ/Œ7(7½YÊP=©lÙÀ{‹GÊØ@*Ãî¨®˜P#1¾V¢¾J"ñ¦J¦	]½
ÝÞ§7ÅÎ¨„LoW¨²í"!CB¹Ù.iFN4ÉMÍ6ÌÊze'+Êh‡gÆ|2CÈd�Iã%N?-ŒóNµpò1š¤–�ú2„]û\|°ÓÁë³xçC»ö)DBž0Ü|B(Z0B�›U†«WNb¶	³ $éo”ÄÛ–Wœ�L;ÎÄ•çF0ûëa4TË¡ú®>ç]‡”Òyü‘¦þ|÷¬:{V­Íà©7ÒØ°ÓAMÈ?ù=ŽìÙ‘›ëb9g¬Œ™Ä,1eAÇFaD¦’“á0WŽ|w‚0±^â¦oÇ0çœ,ß—(l`ü†S2mýÿcz O¼žÂ¯'àÔ{ e
w„º}!C%Ì°$'³‘£¼‰¤æ¬$ÝÀìï%\~FK®ªDS�Ç¹«<u�Šµß;øcò–ç•Þ�vñ\8ƒÓÉ‹%€Äq„Ø'Uñ$Å06†<ø‘&b‚E\BbÃàdÚ&üüª®›]Ñ<×ò—Bä�ßc.y­ë;mÔF%˜ï\f-,% z“ Y«ƒ`$1SpY4ƒ¼Z4ëüQ5.ùFXÿ;p{£%^}S lîÃú}6ÆÇ$2jè2É4�<ŠÙ„ºE6A{«$VRYÂý×yà×Î«V2„çú^ú,ƒ�%`� Š 3šíœd)ÌIßà±¾_zºÞ,c]HLŽÂ¾´oÓ‘"D¶nÔ³c. Ó€ŽÞZÏcÁ…Ñ²ƒÏ¥°DMöÿ^`4,±Ô6mŒ �ÎB3K~P©W¥ú>dß„¤ÀŒ:‡†e40Ä²ëì éGx‹¿Ó¡,ëèX¥M<,�ÇôJŒ‹Imx…uˆíófUL+œßÂ’s+Ñ“%m;ŠÂ„bÀ§	Ó'{Q3W¨/…8xâ97¿ë ö=×’6!«<ûÐÙ§pJ½…O«Â5FqÂ$CçÅb³ÐƒÄfîQ­óA�3Ø•?½�Æ¢e½¨0Ì>Àm&N1Ñ•ThK\ÔÂ¢©1Ô˜Boÿ¹ßŒâ'�%P.<y2‹Ô‰‹Oëïø›–öêŒ‘W?Pk�+šÃ¸ú¢(ê£Ÿo?x	à[§‡qï‹}H¤&ç	Ì'aŠÁr‚sÎI!�ÒÏXƒ¯à"Ç.À%ÿŒ <¼*'å�³ýƒ1«Ìøj‰3N´4¯…ª§,†Á™'‡Æì$xmrDh é¡2"°ü¶4ÖIí�8ŒÖ�c òydaJ² æP8åXsÄl.RÌÀ¯üû@ðüoåt–		<yk¾6Åê7�€øÞaÚd•Qo—–E R ¶Mh'1±Þ‹x
 ƒ
$ÃErÀ/Ë>xj±žŸÏ·½–&5h¨‘ú¹Bø”}‚àMuFyªüAŒp ¡ðY§ÛŸ<�>6øå·Öà«>øá¢Î ,¯~c�„ír�§>˜º*o¸BÜ‹Žü¸a^[—ÝÕ�O:\m¬!`žeð�|î¼Lµ•…jyðG¼UqnZà³�×˜×ÖƒµÙèŠ+Ì¹§;Û=!dÌ3«Óø1¯|xð‹ÌÍT9y*Z Â÷µ…0Àó¶w+,¸7ŽÕl½\ëÛÕéj!lÛãjUzúÍ4niå|Káà€ò«Fe„RoÄ‘öƒà^ýA/ÿ+ƒ£'H½ÚLUŸvºXx_\§ÐmÏ'µ`ƒ¯K,_\�%€xãÝW¨¡–•¦$°?ám�‘
ç: ! õìîž[‰Ž/ a^Ø�rµc¯‹{žMj·Æ¿]ùÒÀçòÆõIY®H�8à0€öJW€tYz„‘uäFÀ—Vàö91Í3Æ±ÿæJ1ÇÁ1ƒOù+Ï®®Tð�wâÕg´ŒÂì€,H ¦Ð'6|H¡¿;Ø ¾Ë[tÙ@!Âì‰áƒ�E$žº­ô•Ïå‰V˜WtY0OÞßa¨Û�D�ËË'„!àWcúäÒÁçàõÛ}´f”; Þzß.ª1(¯„²œàþøóæûÙò×A»«·7eud7®ÒKF
±´¹B`úå3IDC@Œ­ý­å¯c	}ÀºæC[{—Bë²Ð	ØwïÞÇguYý]1§µ¹B¸­5¦mÊhu>—^^úg»»TÈ^‰):z”·o[>¸\uW-LÃóáÅ”‚]³g¿ÂuÒËêFYVtßvýô€´¢¡2ï€~5¬ßáàÙÕÏÝy¨Œ_¦šb�wpd¹áW«j1»S3'¸(Ñöç$öÅU¿Ï/–‚|¡\àÙïÿö…>�Z(I D@Øöt)üìÉ„Æ–pUŽrå¤Ü·?‘ÐB(F÷’ÅNÌæç¹d°tUŸ6`lÈ5¹l<%pß‹}Úø)p±$KšÜÂ/þ˜Äïd¹r)œWŒcð%Î/GÃûÛEKãx~�'Lùš™†�Í*Ôny¸WW€F3¥äFèRš¾ƒsA.”Üøû8|¹¯ÿxœW£œrà±t-Ðï6aƒÇ…Î(Ù”Ö[ÈÉ9ºrå[¥¢‡	\»ž%+’¸öþ8öP0¸¯ÜW•Ñ4>‰�Å«Î‰Îüßôàîg’:µ.¼n’âNâ×¹wiÕ�ÃU„â·BÀ ×ÿòNÿÞbã†K*0gfD¯P©MRú ”ÛlüòÚŠ7ÒøÝK}ÚÚ×W	]ª/™¸?Ì0¹ÎÅ”ù+d¨êJe÷²¬�r´Éq1ôäcL\u~D¥M¨=x›\¾ ˆ#Æ—×f°âo)|ø™«õ�]])Ö~ ‘+­*©ìäÓbÊ‚ö«¥Yùx¹%yÕ¸—€ÛæÎšjécµi“Gn”dÁq	ýÝmŽ.«­Ùlcï~…hýámYz‰‰”´bÒ±û~8æ­²\da0ã\l¬•_3°U6Á­²q¥#y‹s>/Q«¬à¯Zæw,5#õ×:é.¾$QÖVù`G0ñÖµ¶è4Àeòï¬>œ`q%'(f”mÅsˆ-¿©7ÝÌ�¥[m¸Žå+\¹»MØ‰yBH·'–íìW[ò!û-¯ÃÀÑëøðÜi
×îÍº¦jë¿0±ã‘æ�•›j3Âã¾c3VÓ{,x^Áô‹ÕÎ3·c„kå¦Û¶/›°¥ÿÂZ![š`Š¾®52T9ÃÍð}¡ÃëÖ‘rŒp�©²‰uTQæÖ½pøB¥¾0�© ­÷‹”ÓJNº]Z1“_ÀaBŒEcr2{£Æ:•5NPþksVÕ*a„š«ksnv¯JÇ/Þº¼ùÝ¡×æ˜ø‹V2ø^��ŽÏTnæ?f´A_›óò…±ÖÐr×9Ž`ŒÅ±{Îži`àãaÇòæ�SÝÏV™ø¯!CY3Rg²ïä½¤/+w¤|‘¢¯Ìú¼‘b^™gæÝÉÆÅX¶?>iËÁ¯Î”sÑxò5]_‘Â¼ Ë…4›„0¼‹ÓÊñäñ¸<­XiêËÓÄ2PÎ^€^P¤ØöHýÆÁ˜¾�áÈó�ÄŽ]ÐÛî.Ñ,œ
ršATíÝ.ýÿÙ"!wò=âÕ,¥_ÛñhS»~à ×çÿÇ±
sÄÖKz    IEND®B`‚‰PNG

   IHDR   `   `   â˜w8  ŒIDATxœí]y”ÅyÿUu÷;{HBB·IØ�Ã`^ Á¼Y`0�Ä©˜È&Ø +v??0 Œ$	Á!ï…p­% †` Â,‡ÑµBÇÎÎÎÑÓ]_ÞWÝµ­öœéÙÉúôF»;GOÕï»¿úºJ`¸´p¡l]õCÙÖ&<óÔÔ«vN�R'
!f	¥f�À"Õ . {1Àó,!;‰°NHù‘·F8Î«í÷ŽZoÞ×ÚJvÛ©?TX´HçúbC˜‰Âç¿Ž¾ªc¢O±ÙD4 ã¥kÂ‘¨"ˆ@La¯&!$ ˜9*ßíÄ›Bˆ–pŸø`ñ�›ôÛç�…P€ è°�$	ÍÙ£.Ût¸Š%¯èrËiCÊ…òr€ò¡ÿñ¨÷)"
gü/m)í$„tà3Û <Tô³?ûdÉ¤O{c6
Òœ9d­X!üésÞ�¹£º^@Þd9©ÑÊMC)Ï‚�&¹ï>±zED$¥mËX3|¯{;‘úIlç†;Þ_1Ó5Øt•Akm}Énk;Í›|Ég3ídËƒ2ÖøUè�‡õ‡zÄl€¯o�r3¯ù…ì¼uO|Ï`Øß'e/´.>8enÇVÃèW„å|ÅË}áy$„°÷ƒ_Jl„ÍØ0FŒ•L¤^eìÃÖ…Ôo Ò§óÚ	oê¼-,§ñ¶óä»>„´ú»Ð~*!R¾°b–�1ønfÁGKÇßk0Å h%mþækìø˜{ýbÚ‡Ra°Ÿ†LJIÒi¶”ÛyMûƒãî7ØöÏ B	ê¼�³-§åqåç|É6ôoÞO=ÄžAZJX	‹
�³Û—MzÒ`lÞ²Kª9lZ!üÉ—wLVj)—BÉß~¹ÄØ)_€±tR1¶|Æ:¤ðsÞ‡`;%-±\Z±F¥\µßìD@BHÆ’1•–3ÆŒµNlæÌ�äxuÃç[®³cNðÝ´'°ßáFEŒ%cj'8�1f¬óà5�±�¦]ºmùž¢‰¨¸f²µ&"!NºPT3Ú>`#BÈV­‚È¡­xK‹6=u¾ÐšÝë�z'![Æ˜,ÿFÆœ±×ãž|M×�V±ð!„lq”T%@R(üÔµ¾ð=<Éõ²’÷òëü¾úÒ›Ó„´ïzG®db‡ÎÐ¤›ÿ¦•Óâå¶qm§¦åcÁã	CÏ
.Áõ0-	Ä�DHÆl‹}à)B®@È»@¡HðCŽÙ@<&`‡×cÆQÍµ èÛÉ±-$¶Ïp¯[\@¾K\u­ÝÐ .z@&KüÑ�3³qô!Áãðñ%1¦Q !!à0 }B6OØž!tìTøx‹�~ïéÇúÍ>¶wlhˆ864ƒŒöŒü<WH]ÀÓænži½!“ ­°#Êš–Þl�0¦IàO�tpÚ—cøÚÌ&O°Ê6ˆòºM>~ý®‹—Þvñz{;ºH3/áìnÆF�B
�ÊAù3Å´ù[.vj³#÷Û´éÈ¹À”	Î=)ŽóON`ÊÄÝKN,±†4/úpºG´ä9Ö¨RjßèãÉ5y<õjë·øZ#âàsa¹tíH;ŸÒGLDJ8’¼üåbêü­‹-§ñJUìò1"Å6¶ñl�;»	S&Y¸òÌ$fÏJ ¹!˜µ‘L£•�¹_Çhï/WçñÀ³YlÙªÐàø`j–\­‘ìwø9«L _:M–_Ì< ¦ÎÛúké$O)`©ÏäØ&Ìýz×�Ý€Q�2ÆyV
ú`Ì0šáæó—§ñŸ[
°' ^È é±�É�Nç.ÆD­ªØ½Ú # <V¹ªÚ~ì¶4áø)6~|Y#þdšÓ<¿ÖÛdDM2, 0#Øqÿýïº±rœ‹â¨Ýý�ß ¸cÙC	Ÿ	4}BBŒµòXÞgÞ6éô*Oœ'¸³›0ïÌ$n½8…dLŒð†Èä .YÓ‰Ç×å‘ŠKØA4»ËÙ³ùãŸÈL!ø„QoE;È°i¡Ù&ˆ¡P�ä‹.ú�”ÿôŠ&\rzB?Ï>Àáãn~#ƒÇ×ç16%Qì+7(ABæ�ÜDÀÊš×
�…OàXTñel!àT+=agë»ÿàõÍ8õK±©7ÉÖHk ï;;<Üµ¶-		.ºJœ]»@÷¡„ä¦ŸP1dÄ9�S5´ä{�”/½±EƒÏÉÿ]‹B‡
>¼.‡¬GÚì™Ø?Ø@naðF“áQUÊ0K¾ä†fœ<ÝÑ¿³&ÔŠ¬ÐÎ¿ºµG
Ø+Ò1ðnA‡ÉjIWŽðÓ+ñgÇÅj>…f�%¿#§`q":œð‡¹ �ÊüT‘ô¶.Â‚³’¸à”DÍÁßƒDŸ«‚«Œ”ìX»²„ŽrpÓ©šD:a×`Œ‹KøÄ½…Ã 0+·9]ÒÕzDF‘ÂÃ€Ç�žÛ'ôrõ±²€ ÞàÄqŽNÂ†3qþœ/ ¯°ü:e ›N´®þË$ffáfH¿!3”K§$‘°<“l|�3ÇÄµ‰²T	D,å\Õœ6ÉÂµg5ôÄÜõD’%X_cã†cSH{Š›[$žê™‚Âü#’øÅ¥Í=Jêð:*Í–Q…xÙpÍYI4%EO%³žHôÊX®HèX¥Ðø…„^%ÕRS³2«h_dÎŸœÀ­Ç¦Ð˜˜ÿõ¤Žð¢òm_†œu�#²0ûäDOº_O¤Â1ñråUw¦ñô«y¼V"¹ŽÑŠ6�v	?xdŠ„í9¥Ëû¥k…˜Ö%§'qÈX‰B1!«8cIà•¬[z�Ã¯“È§/ð¯¸3�çÞp1n”Ôáñ¨µñÏ�Ä‘GÌ°°n‡¯ß;!)qÂXONâ¸1D^‹—IÏ;9�»žÎâ€¦À—ÔŒ, lÇ6œwR ÏõdzT~Þ%\ÉàÿÖÅÍBƒ¯_·�DF@ýÚÌ\q~Ù"i‡[zÓöbÂÙoÎŠcÙs9íS*¥Šd•£œî<á¤cb8è «®œ¯2àw�?¶üž{âpËòîz*«ÁçpšÁ5×0SÒQGlãø©¶ÖüJç[±±àíŒ?ŠõÔÚëü;vI>—Å{;`S˜Ëq?rX·`'Ü¸¦ÏèÏ�‹ëv™J5¾lÄßËÒÄ-"_=Æéi¢ªw³SJ&êáÒÉ÷/Lá»çB›—fÍpÐ˜7~•­¼zÌ“œ:ÉÆ!cƒˆºÖæGõþf§øÛKÀ7k‘Y5Ÿv��C”ºq¬’y—Ï ^Ôö�c·õDJ[Gjþƒ™”€ÿ­]à%zÓ…Q
ºîŽ9ØF¡B3T™`‡tHôK
þ0;×vÿÎ4žs³#¡´~ÀàŸJþ0�`'ÍtÔÁAÉ¥*›·ù1>êÅjô¬š…	½%ÿù¡š�o¥ð7!øúû†1F#ñ“'Zµ‹‚xâÜÙ0~tp‰J0•ÄÜ�¯Éë²¶YY
øóïØ%ù™#ù¾WfÒh¦:a´Ô�u•De1@£‚f×–†�¨ŒTè ïú�,æÞžÆ‚{ÒXÓÒÒø:Î¿3�†hv¾Ñî’_…“Ý$³+‹„*Ò nýNÄ*}üŒŸ=�Å�íÖÑ;Q¶ç}1Á€Ï‰Ð¼Iã…!˜-ùþ_•gvv»fø3¥{KˆZ9áJÉÁ`Éÿ‡ïÖÝÑ\Þ`i~¾&ôH~!0;+ß¢Ù¹(…ëJÀ�‚Øüô˜ 29PÑPqæX>Tèpï~&‹?Ú­]¦I�¥Ù0��fS£û‰J$ß€?É7àG¹H$‡,ô{�r?hbÿ¾&?2j{Û“Ý|–|žHé\øÚlZØ¾Ï»=­S~°�XùöÀÏì)ùQæŠ¬©üý• eñ¦æÏ¦�M�~®L-ôü�%ˆMýâ[.®º³Sßl1¶e ðHþ-¥ð�ˆÍNé\Y+¹Þ$+Ð»õËƒuàCKG5ÔÏ‡6ý{sRÚ‘ýãc�è
e¯ÉsôâÛ®þ{@Égð3»ƒùÚt8×�B�[Ù+EËš^äp	›wF›Ê¼†¯€ëÏmÀÍ¦t‚Ôß-§ü¾TBèG_Ùg©Ù¹åâÝ%?ê•™ë¦~�Œ|54\äþxs(ŠeJ€%w1�éŸëÆhÖ„>º–M	`@³ÃàŸ½Ù)%#íë7ù—"Êf€ñ|'¢¦J
Rrw&dŽ2;·~;…¿þF|UÝhÁ8Ý>–0kÆ€¸¼ÿ™W±´‰Á˜ÐßçJBM¾éCƒÏc©r+$Ï•}Ï½&¥ˆÒL˜ïÉ5f¨’”\ô2GìX.!ˆAÌŽ¿ÊfÇ�™ãºM>Ùâ÷dÂåREÃåÉò‡¯¬-ê¿£X’”%Lø;ã˜{ÝSPêp²Ù9»AKäHtâ™9®y¯ˆt6¸¼ªhÈ<Às¿-è¿£X’½˜Ð;:*-/°ä/Í�c$äŒÍçäÐ±*ß‹¢²RD¾þaQ›¢þ*—Q™#Éåf1å¢‘3;†L¹ü£�>þ·½¨çÞ_d6TªxèìðØ<ùr QvFÈ>ÌÑö*Öv#37^¯èÌFÓžXñz¢Ñ‚ÇWçqÕ_$u§@T½¡¢¸ôÁ×�ºª9œ°›}Þ/ç#éˆ`’Q,ƒÞ•äÑU¹AW±Ê5GDÐ7}pé¢ôn÷‘"c~–¯ÌáÓ¥·Ì‰$èˆbp¦LðÀ³9ìÈ¨ŠŠSý‘al-:¯�ôoíTxð¿sº<ª.Õ yû—Ï:îy&z-0TºáF-¤ŸWì6nSº%%*‹L‘¹.Ô’Xò\ÿ÷±§MD¥B=�ñ5õ<übNo,eTä7éñýW7-í‚öm×K¿h9dÌ¯yÜ´4ü�h)ò›ôØ>¾ÑîéU.Áì­ä‡�Éà��=4&£‰|J)òXB7ì6	,þ¯œVYÎPË]¶¬%™û›y½�×sªÆ<ªÌ±&ðîW?x(£›¥ö6&x!øÏü¦€Eÿš‰ÜîW�fïnZZpw«ß+î5LðBð¹ÖóÝûºtóY5©jé;,žÛÌ¹·wâÙ7M¨å–‘�ÉõxS?no7›IUs¼’|¿_U.ÎàsÅ�U‚;Ø'˜ÆÛz
Qýp¯:Ûüïü<­a¨:¤K6EÞ7$Èœª´i“¾?×‚naüÞ’n^–	š¬díµÁH=Ï÷þÞ°¸·.Ïè¬^ïìX½±é¢c/	èâÃÉªyâšÉ$G¥„NåÏûÑN�ØX¡6Œ4#ðFê_~¿ˆsíÄ¿­Êëî¼¡¬EW8}  Ò¼oèji'g�ä¶•,m¼íðÜ3¸öÛ,k²må¦íJ·E>²2§¥�+œ#(ôl[™]cƒð�Ö,æFåOÐ,dÜýLV‡z—Ÿ‘ÄE§&é+Ùõ¼Ò­éÍ�›¦˜¦+ ÷—~de^W6™	\BÑm6#¥	k€€ø æ[çyC¼<é�¹gÏŠãœãúÖŸjl]üî§žz¥€_½’Çç_(�ÙrWÃˆ‡Ç¡ønþ²ºØ¼ÛÒ÷ôŒ`iä]ùÞã“Žq0e¢]öÂ77ò¶oð´�þÍÞ\çé;oð5
ÂâÃ}²Ò÷fh°§ÍßºJ:�_SÅ.¶Â5Ù`L„&‚AaF°Tr6Íš1ópÓÝµ}ýèÔžÛ×ógx¹²c§¯‡Ö~æk‰ÿ´Ã×[%óýlœTé*mmvM/Ù7ºY*7ÝÖ¾dÜéZ×	xLX±VrÙ6ÕhXÜuÏÔÔì£ÌÌøpƒ‡w>ñçiq3X8ø¼{°»àÀÌä¦YîÛÑ­ïa‰¤ÖÅA>ZLXŽ !~É÷é×õ&}-ÂìG˜�Jû…¢>ÂDò¹Vëïkê ùK­x‹ }"sý�
cvó0û6+üàßÍ2hé{ë|-ý¾Œ·Eþ_ŸÛÖô!’îm~¡³SÊX•«••„—=Ô;ñ¹Ã1©1v¬ÛsÆ^ŸúÌ‡Š}ô‹C>'rÉx‹¬7-Ø(”~É·ß?vƒ>Èm‘P¡Å$ÁOtL‡Øðû­k¬Xó	~±Óßš^4DP¾å´XÊMÿÏ¤CÆ�ràû á¹óaª"hÅt�>ïÖ¦o“_HkSTíƒþˆH1–Œ)Ùt	cÌX‡§Ö”¬hSDÖG‹Ç¯ó‹™K!V 
“³ýT1vŒ¡pcÊØ2ÆŒµyËžáfxèð´Ë7_-“cîÓ‡ûð‘¬ût.ã@g‹ø°/¿ýêuK',nm%»­×�Î{Ö~Ú„>½}Ù„ûýüŽÒŠ[Âr$‘Úï˜‡HŒcÆØù…í×jðî	>Sÿ	×Â—l,:�Ï•Ÿ-íä!ífßíâ£­zJÔê‹ø°Tò­X³Mª˜V^nÞGKÆ?a°ìëýW?�æµ¶¾dóüüŽ“È/¾f'ÇÚ\H"ât¹¾s… ï16Œùîkª˜ù*cÇö>Ó ’ÌNƒ ž>çÝ˜7úàÜ$íÆå¦¡”ç…çOÖè`’Z’@Þ*ƒ¤´mk†*vï„¢ŸØéÏoÅL×`7ÐU†š>ô9ðÜº|m'®èRËiCÊ…òr€ò/4p±u×™dû
SÈìÇÀ³þ—¶”vBÆàÓÛAâ!øù»Û—NXß³�h ‘ go!G�š·uYÎ¹ŠÔùBà�…Œ�Òî��gR\½äM øû÷vK%ônOz‹o>–žùn'A¾.~%üâS¿[2n£~;‡™a’5Ä«“’l]µJ¶µí²kÇ,ÈV,äO§€h)2 Z À‹Œ1ìÅD€B N!­õ€üP«íXò•µ?oøÔ¼O‡˜§BEêKéÿ¶ÙÙvÁÃ•    IEND®B`‚‰PNG

   IHDR   €   €   Ã>aË  ;IDATxœí]˜]Uuþ×>çÜ×Læ•$Œ™D^Ab”ªjíW«“ª�$¥mZÁV?“Ô–¶´ŠÕj­&Dl5ˆµ­´Ÿ ‚Ö’‚ÑóBH ÉLæy_çœ½ú­}Î™Ü!™™ÜsçÜa~¸¹sÏ}œsö¿öÚk¯µöÚ„ª�©£ãakÓ¦+¼Ê£sVœ›aëtˆæ³æ© g@ÈÈÂ+öÁ( TQ1v‚ôvÒÖ–’V�={wë3•Ÿïè`{Ó&ø q5ÎO§ÿL��P6�Ypc÷[´ÆÕÄþ¯3øee§�r`î•=@Ë=3ÀrU¹�:D�ÿ ,Ù�>ÁÚû…>@ý’IýD)|oçWÛ�¾ÕÙÉÖ†Ð§+§' �l!$~Ö²ýSÓ×ƒhH]¬ìX—Á^¬=2œËùÌ½š»žDØô	Ó#Â¶"e+²3 •†öÖ[Áþ=y¶îÚ¿®¥{8cÁØHXÅ
kär‰|àùiœË}„+Uªq6û%h7/}Û™èž$û4„BÚR`)'Gd¥¡ËÏ3c­UüâŽ{Îê-ŒU ¬!» tt<dGãü‚•GW€h•rÏÖî ´_òÉè3R£ýÝIŒ ÌZäAYiK9�ÐîÀs`^³smëºcÃÂè´Áè T7í78Ÿ¬Ü—•“í`¯ í—=‘PÐdO¯	˜�†UVÊ&;í6±ŸÿÃÝwÎÚ>Ú!a„=UT+ùáù7¼x�r~ªœL‡_îõØ/1‰å2I~í@¶´½p \'ó–^fÈ®„³‘üÔ©?Âb’ÈIyÞò®ÏÙé)7³¨{íúDê=…K
ÚWÊ±Èn„Wê¿cÏú©sdlói@(E�PíMÝwÚ™–e~±Ûk¤&­ø$AÌR¾•i³½bÏ×w÷m\Ž�¡QøòBp’! ´,hoêúŽ�i]æº] ö$ù	DÐ!máÈÎ´\×Þ´dV­¦UÂáI†õòä?lÉ´¢}Å‘;íLë»½Â—NŒ·0‰*@8ò
]®�i}Oûþ�¬[#SCáòe´ý‰%£ƒml"¯}Ågg¦ÿ©HÕ$ùõ\;Óæ¸…®Û÷¬Ÿq+:²1ÌMb§ón8¸ÔÎLý–_îs	<ÙóëxVªÙö=Kwß5cÃ‰¦ˆt"ßü^œ;ó817±.Óä˜_§`Öd9âLì#¦×í\ÛòÌp�áñ6Àvã¶e&úš²³-¬ËbYNZûõ
"Å~™•ÝÐ¢uy­™Ž�A½ÔË÷ÂµVºõJ¿Ôëarž_ÿ e	—Âiûò®1C€p½mþ§ÁêÕ4g×ÍÍ©¬¿M){–x™&}úi(H“Öåå‚³pß½Í=æ8‘¸\.S¾5:•ö>bgZfk¿èO’?�@¤„S;Ó6[8â±4ÐþCN‚s®ïiNÙþS¤ì™¬]ñMFô&X“Jk÷Eß²ÎÝûÕÖ>9ª:VÁãÀ±Ý¬tóÚ/é‰D¾Ä'•’`zð°­c[Ã•ïÉw&VlS´@I[é–3”ëÝ œ÷�XjîðVåä.d¯ P·A™³DÄùð| ì±ù[ë -ú…Ÿ“ØªÉº�y_„AŽMCB}N>SÇðÉÎ*]ÎoÛ=gú"™òK¿æ¹Ã‹ÙN]È^^$¥îÈ�‚eFÑˆlÈ¦7+Ìžª0³UáÌ6ÓšmSriB*to•] _bt÷kécèòñb�Æ�.y­Ñ—XO;@&Eæ|u*{yVvjá¼ç�,Úƒé�ÛrT+î´ìFò¼n�æX]¨v!��Á"£ì„Ÿ{¶�K8xí«mó÷œéšrcÓå}yÆ¾Ã>žÚçáÉ§=<ö+»øÈÙ�‘¹†P³Ô˜á[N£ÍÅî¥ D ˜XZÂ~Ùä¥¢Nˆw= ·ÈÈ¦€Å\¾0…+.JáÂWÙC*;‚É=I’žûrc;‡ïEÃ€Î…çØæÑy)ài`ÛÓþyÙ<ž|ÚE±4f	Ž£ItN0¤ù„k&\)ÜÓ‚•çjmm#e7€½“4ÏøÂ�b¥²ôx�™­Þ¾8…ÎK3¦ÇWBÆ{ó��Ì±Þ‡„Fœ¬Ÿípñíñƒ-eîÕhÈÒö	4Âðó�«�0ƒlbí*å/´5ÛoRN¶�Ý¼NêÜ_^Œ¹ž>�sfÚøãwçÐù–fOSÇ‘nÈ­øj€†å3Wj9ÇÏuÌã¹Ã¾„on*bÿ�)Y2Âj²öE£åAR<Œ÷…ÆKˆ =­œ\ƒvo¶	t‘¤ô…‰_‰T÷=ƒŒ–ÂŸ¾·Ëß–ÅÔ&uéÑ4/öëA `¢ž~öt{o–-Éâ«ÿ�Ç½‹ðŠ€¬…ñr€ŸæÀÜÖ€*ì¼<â�5NÙZ·<‰î7y=Úý#ªÕX$TE¡bØ‰Áõ›—¤qkgfÛCÄ‹`Ô‚ô“AOÍf´(|êý�xû%i\óí^nÒàfÀ¯HÇ Ÿaå�T7!·ŸàôÁ‡y¿f‚ 'Óâ!>×&Æ|ÖžÜ…JÊð/sïž6ú×jÄÒË2‰"~8*›í¾§‹ø«§ñÂ<q<½~h0¼FÀmff3rÏ¦ì"ó™šif%œ÷6Z‰e­!Æ‘Ñ&sñ·.Já¶5âœÖÐ|;iÄGðÆ¥ö7ÛñÉ-æïœŽ©Q»V´¯
IË ``Ã›Âhù¹‚’~¨j FÛø2´Ør­f™Æ_�Š¡W,1>öÛ9Üò¾#Òë“J|%ù_Ú‘ÇŸmîGKVVÃÇOŠP T	(Îz.ÒhÝ"éü¨	çŒœÍLØ ã¦„àb™aÛ„üp®~Szh\­òrÈÅG7÷£9£‚ëÍ�HÜ¡g ýóMO8· 2Óp£${ŽŸ‚ÅÛÒ °ö¦&¼a�c4�e%ß+E¡|zëÀ�0ˆ'eÔ!wôFö àôQ`Ä
I÷ g\ÛXÈß½øæï½¥yˆ|1`’œB¸¤�¼XÆ¦ÊhrhläGÍá ù³B£±F ÆsÌ/¹�ÿþî�5nD~=€Ãçïï/ù#Nb Kä²�áÇ>Œ³ HÏ²åyÝMÍ¸h®müìõB¾@Ô½`ó×h²Q/Ì?¤çûYÀÏqÍ´À¸€wÉe|á¦WªéùIð+yuK>ãH‰«wíb˜[â9ÜÈµ@Í›]Œ»£ŒOt6à7ß�®+µ?’;UðØ”A©êLº†í¡jM~O?ã]¿–Æ‡ß™«;µ?6¡%Eð%ÀVuºƒ©zÄ&’ HI(÷¬éÊxø¤ÇÔë’
‡±ÎÈªS;}FñÃJl£òœÙ2åû‹e�ÆÇ¯ëX é—�‘‚¯e¨Âø/þ€~ÀÉ×È%\++YBºâá{ÇëÓ‰wïŽÑå¿ûì4šRêô| Q‡W@óQ–œÆ‰¢äF\hkTøóßi8iJV=AIœ‚�s›m|`n}%	¬Œõ·
>ãœ¬…»®n9µK8�] äæúóŒß‘5‰õ®ú+«n{}#æ·Ú(Œa(“„ Kq>}A:ÎKá½—eÐ7È51�Uì†Ÿ¼j¦…½5[×†ß‰ÀáP¶k§û1’:yÐ£ˆé‹)Íq´ ñ™E�èœ›1äÃ¿•Åôf2‰¯TÏ �3Pd,[’A³Ä'ˆú˜€•ýe×ÜÑ‹Â>�[¨ èÔ±ÒLB²Y·jCym‡Ï½.cÐgÜñÆ&|ò¢3¤H'™=Õ2É®’–w¶ØÀxÊ\¹…÷wd†VäLx¡óJÈ_~GŸÔ¾Fº�`wÓSÈí*´¹6p´ÄôåÐiÔç2ºKÚ<_>3…¾­7�ŸBß¡ H[]wU­�ï%E]ª;nËÙ•LkRÂò?ùòZVù’áã V	hÝFÈïf^`aÁÅvtyè)3ÂôŒÂ¢6¿1;�%gª"
%GA2I6�;ÓÂU‹ÒøÎOŠ&!6Ju¯�–Hßû.zÿDèü^Hþ#!ù~D~DŽ¨pIûv€l�Ðû3�·¾:‹{ßÙŒÞ2#céˆé°§G=¿Qyç¥iüÛÿcuÄÒ'EŠKŒ×µ«jä¢Ú‰B¾N~%Œ›&³çãw÷ãŸ( 9E†|yK|Òë…÷áäDSÊá7�çà5gÙ(”â³�â ÿ<àm¯“°Öòãê…ü_#_ÖžL-›€M
_×�û-šã¢Þ##ðd�ßNÙ„+_›2érªž@‚<bõ_ñÚ`Œ«gãÏù•Á¯®~6KØÞ|^jLÓà%§Œ¦‰+o·ê 7(+ªkÞV][ÿ^%ùŸï3½w¤äË÷ºûo¹ÀÁ�77cÖÔ ©GªÊ£!S’eæÌ°ÌŒ*Ža@Å•êõ†ö�E[�ðôØ{þqä´Ù¬–v�fíŽ– _üjE7ža ê`Ôœ·×oqQOÈWÀ�O·ç´Ù,•ï�ÅŽ´þëÚ�QÐ¸M¥ñd]ýys‚Ÿ®7ÏŸWAþŠ;ÆFþ¥j?êùc�EM·ðU62©‘]Ã¸j ùsaÊ±ÌjÝ˜7QÈ¿¬JäW¶�Ø ²nBl’j·gUÀTîðgO³L-úEügÊéöÏ¯ùë«D¾ "[<©g´‰ ûî%Ú�;+,ÜP‹˜v^çÉX§J^hí'‰üÑò¸3Z•É«H´0•º˜55aÅ½æ4Z.¾i[·ß78T)l4çõ"ò·%�|At/g¶©XfTU5£lŸ©S(öñ?
.mÞéâÿ±ºµ9ögKÁÁù½JòÇhí_¶ÐÁú›â!¿R ¦N	ò(­ââƒ%NHFÈÿ¿�.®ÿl/òeÑ:
wÜŸÇmßVêœ¢bWDþƒO†ó|œÑ�ßÇèX˜ªšÁw*47ËÎ«�ê_2I…MÄK¾�Ýg{Q(12N{˜ÚDøü¿�Z*ÉÿÝè3óm¹f=ò/JaýÍM&â'ùQ�!“¿«=¬VŸª+hFä?¾»‚|Y˜'Ï2üˆ$	5"5jÈÈÃ‘/05þH~%ä\uáÄá°�†ò·ìvqýß÷½„üÊs!ønÞ|çS8&•”©ÞÆ­eÜø…
ò9ÙäW†ˆ“ï
CÁUŸê)`ë×ý}Šú„ä'M„/|/�Ï|sÐ|WŽEä×ó9ùäÊn´»|Â5€ŒQSq¾z¿'ªïù.�ÞÞcª‰dÓ¤`�‘|ñßóð4cÍµ�øÑAÏ—ßù]ýlÊÐ®'ò¢ñâ˜VWU ¢y¸ä
ªqÁ‘oaz™"‘ŸýNÞ}#)«'BÐ6…°ö¿8Ø­ñ¿;\ó[{ôä¯¿¹ÉDæjM~Ô†G9ùÓÀ¨·ÊüXP­‹gOÊ	*…ÞÒÙ`–—›Fð]i´)9Â÷+í!ÂS/äW¶¡´©ú¤Ï¤�¤Þ~µa(5pó{ræõß|{Ðôî‘”j×a„Rˆ¯'ò‘�K›ÆqþêzÃÆu+¨æG5�ý1
ÁHg&¶�ßÇ&�m¼ÉÈyåÞ¤MåÚªmT}p,ÂóÝ>zóÕWYÃ…àKŒjép0ÒžåÅÉ ?j;)›û|—oÚ¶ÚC@ô )¡nŽUó1
�^÷’×¦°î¦ñ'¿²í¤-E0Å[™hZPdüòÙÀÇÔ¥ÚB`‡äKÏ_›ò+ÛîÏx(ë$'0‚xìâDµ„À® ?)=8ÄõWfM,I¡’ÇþønÏxã\xºB`Gj?�äG»’H9=éLQ†UµQõ[5Ž–aÏAOí†�8SÃÇ*ùW-Jù•möË}ž~Á7�*Ž [<KÃ(ØéãÁ­%óºåïG#‘µ¿$ó³	#¿â¾.”O½”l¬ˆå–£a@.>JÛBB„ 
ìˆ“g­�ŸJ&ùÑþ	¼’”ð¸Bì±Ü¶\¬ôªmÏøxbO`ÀÄµ¾}¤BP™Æ%Q½$ªýQ[ÉF•ÛŸõ!­'Z#è26<Rªim€	A4‡6ä/¿�îhG}û‘b,™À•ˆíö¥qeYÔ›KÆ�mó:BðÉ÷7`ßam²w¥ç'™|-5³eí¶”LÆ©=cËÞ®S6Ì&Ì÷>T0‘<cÙRm…@ôOÞ�3›H¿}qº&	œ§ƒh	ù×T4³Éi[ .ÄÚ’´Ñ”%|ãÁ"õÖV¢Ê\Ò¨¼<cRÅ¢Å«I„É—ä—ÝT4aìS%¾œ.bm
£œ ’õÏäcÉjMAÇÄW)åàú¾ôyîÓFƒÆÝ\±÷Q_R-äž�EãŠÒµk“T™`òu8,IEzK.^Õ_óbÑÆmß0¯°MaâÀáó_}kÐ¸k5LÕä4¢~E|ÿ±2¾÷³’ˆZøê~¸ÌMzþÆ'ÊhŠ±.àpÔÌµ/Ž—5ßÀGõ¸IƒÉö��¿ü—Á¡Š"µBÍ r<ªñ‰;û‡Ž½’e€Ã‡ôö�¯ÀÑKÒÇÉPÓ	‘Ü¨Ô¿}`sw_°~/îiN’á‡‹\?óÍlúyÙ“µk>#Ë¶­‘ð¹ïæMñDñÏ×ÂÚM¼p�êÝ?*à+Lrëx´Ã¸íØ˜!£ö~²Ý}Å	�’ÿƒ-e|êëhSÖÇã# Rö$ÜøÆèÅ“{½WŒx!ù?ÛáâÃ_îCÚŽgÙ÷H1nNQ±tÅ(”¢Ò²Ô{Ëž‰¯	¼�üŸnwqÃ½Æ°G¸L-.Œ«W\‰u÷j\{{¯)Õ	ÁDš0«Kð_ÿW2UMJe6nòñ®¤ª˜Í&eã.’;pýçúð�Ð0Œ³ÐD-¡Cÿ¾,M—ßï}¡Ï„¬u_ò%0Æ®Ißœäãç �J£K#ýÉWúñ·‚Š_fk¶:öza:œ$u|úžÜzg¿I˜_òƒ½n‰0¨”'É@HH0DâõŸ½?�knïÅ¾CÇ‚Gõ¤ty�Þù¼�¥·õ˜M#dë—h¹ûxC8g¦‚,=ì1)(	¸(i4iœiM„‡ž,ã]kz°á‘¢éE‘6Hr I‡KM"*sü÷üE�Éí“ÄŽÄ\¿ÙÃG6¹ã£R{l)[®81Ê6
!÷üOýXùù>ìx.Ð•±ýÄO�goë^üÛ^Ü²~ %�ÍÒôDÍnˆtÀ9ï¶‰±°ÞŠ’SÓÇZŒë¸döê‘¬ž•¿‘3[ÑEŸ‰R¿jUýÐù	Øû‚o_î{´d6Í�g5êWf	Ô?e3ôÏ™=9lv— H/—Ê^¢¤}ù?ó¸ÿ§%¼ÿ²®¹"cªhGˆ„AF³¸nƒÃºƒÑ²­hÙ›Œó÷l,˜-Þ$óXz¼<’G|	çÌ¼�¬<8Wkk)»,ûY%3o&êieO’K4¦·XxÇâ®~so:×9ND/wb„‚NŸpAå:G©Úõèvßýi	?ÜR25|$ÿQ´Vb‰šØ" ýÛÅ	IíËm¶œ)‹µ; �y˜`™Ö� Î”çØX²(…«.Nãü9öK*•š°kXEädy�¾÷rÃJ¡Ìf©öŸ(ãÁ­eìØï²%®Mídš¼|å4X¾;ð¿»×Íx£±G6’•ZÌ.´ÜHºWMÂ¨„–åõ/žõÌjä/ýGsÏ°°hž�×ÏwÌ†K²c¹$YŒE¬{ƒB«�Ò´[öºfj*ûøÉr-S¾5Ô8ÉîõÇÀÌLVä<,¯M_˜·òðb‹œÍ¬Ëu¶ÇG ³9s8¿ãK6­HÏœÖ¬ŒÑ(»˜œÙf™Ôð©MÊxÓ²›QçAQ‹î~�#}º´YÏ eY$7_âÒ(BzÚ¡¡Tó$ÌçGfR)øì¾aÏÚé�Kþ	í™�'ÚŸ;ôå4\È^A&,5Ø¹¾z0D„d±¹`¿JÓ+õhì?â›¿#	Ññc½qÛVxŽM¦ä�XóÑy"Ã´Ná“Ý typÛž9ÓŸîíŽU°6­!+ŽÜ©¬ôç<WÜ°‰F,±Äï©µ“…^©â½Èø3„×‰z?˜5,+EƒwbéŽU,›˜ÊvÇÀ9×÷4§,ïWd9ÓY»ÑDqš”Cì»‡Ê¾}î³w·ôÊA™53:¶ž½»µ„R©)Ä<ÞAÊITÂ©á–øË†ëŽ‡%%'èýb`õj:ÿŠ–2rÛ”rÎd_,Ÿ:&qÌš¬4iíL!¿pûYëz°zµðËÑæ~Œí«iûº9ÝÐÞ­dgIl¢ŠŸ˜DC¸N…[ÃñöÕ–4ÖÎñS¾N¶°�üöå‡6Zéæ+u©Ç©ºšLbXû*Ýjùåž�»×Í¸*â8zûx¾“å;+´;xTÔ†1'Qßªßì¶<g¥1øÇÇp¼ ¬!�N¨_ÝÝú<w%ÙRõáàœÄ0˜R#¢ú•ï~×pÚ	e8®ÀK�<QÙ»îšy¿_ì½ÍJ·ÚŠ·ìç$ªáL¸ó‹=·í½kÖýÂi¥ê�ðrn_Â*¶°†¼ù+¯³2mË½B—KDõ»'ü+ÌìÚÙ©Ž_ì^·kÝô•XÅ6Öò_¢ÊOâ÷gÂ*Ö€ÛWtÝogZ¯ö
]Å¸+à$NÌìÙÙi¶W:zÿîµmï‹84þžà$ó|bóÅU Ý}¾Ï+öÜeg§
ù¸>Ã l8ñ„#¯xô®Ý½—žŠ|Á"¡³Äí+ŽÜn¥¦|œ½AhßõirŠ˜°Lõ”c‘Ó ]ê¿}×úi·çžaîåÉŒÀÓþÀ*V»×M»Å/õ]ËlõZéf‹äUëF&1†à>Ø3\�Õã—û®1ä¯b5òÍ'FuÂÐ‰0Ù�ó8�ûŠåä.c/í—=IÔÕ_.Aý_Y)›œürþÇTÊÿþ®{f=5ÜÑs*Œš°ŽŽ‡ìM›®0uàç¯ì¹Qæ–Ó8K»ý"¾Yú0Cˆ,=³²R–ršà»ýÀ¼z×ÚÖ¯çf¤[�¯¾öà•ÍýA/·ìÆY¬KÐ^^âè2c�psÂ´%&KQ›4.Y9gç é\~yà ÖëBñ‹{¿qæ¡c3¶Ñ¯í8=b*ÔÍ‚ŸŸÆœù�®ÔÅÊ™I1c¿ö]-ËPÌéã$2,'Ã ´£d{`¤1ÿYŽ"+Iáè­¾—Šwíü—ÙGÌwF©ò‡£
0uvBm¨¸ˆù+Ž\ÂÊz'´ßAÌ‘�i&%>$-±	€å¡Ã0Ã+Ý†¤`Ä4+Œ½)°v¥óô0h”µÉýûÓ_kÙ}«³“­$b{jCïäg¯˜::¶†�A¯Z~àœÙoÔL´a>SnhŠì
‹W0(ÜÐ ]Ì´àÝŠx›gÙÿ³÷«mû*?Œó—Kùªôœÿ½~´Y¦»l    IEND®B`‚‰PNG

   IHDR         \r¨f  :íIDATxœí}œÕµþwïŒFÒ6¹­�Á˜¸:6à%¤–¼„$§RHòþÆÉ{�H„šNR ”š!”„fŠMqã²n[U¦Üûÿ�;3²vYÛ»kI«‘î÷C¬·i¥™û}÷œsOaˆ$CøÜ`Ë1·ïw'´¬OZ#Ç43;s(ãÞ! ¦1`º%!’,É€: I0ÔÌž÷¡Q�$z d$�†zÈ,Û	°—¤d«ÃËÂà¯Ø;»·nh�˜éóûlîBËVB¢`C„H´­çx…ß™1¯}”w6 ŽcÒ8
‡JÆÆ1)ëY,É�A
��to¤ú(ý¯ih0®¨ÀÑ�ô‘q„kG:i!ïaRløKRŠ'c�¹ñØ3ë1bg¯Ør«´ *bPÙ°Pò¹=Ä—-;%¿ÓOüxûÈX�w4÷Äqà8G1#6ŠÇ ¥éÙ€p!á… ƒ„Ì¿O¶ë«»­¡@í
j_ÿ/$£µÃ8g$Ü3,0fÂsºH¶C²'ÁäãŒ[�Ù¶|jÝÒ‘íá3Î�û ¹ìä“±ŠÝi*“%I2òn¾ŒMu·ŸÈ¼Ÿ±q<VID÷²¾JK¸Œè-éÿ’$¼rßŸFÔ ýÿH$�’1f2%	%Òé†ôÜ-’±Û³uµ‘z70§ßõ\A¨,‚�ùtk‹ óM§)m?Œ	ïlÆØÙÌˆÎŒ:H7)ì]„ÏÛlå†T>¥/0·ÀÌp�:/J)ÿÉ[Wß<feðãç´ò¾nìp‚Uñ[?ê…ö×Ô‹¶+¥ø"“h1â#-µË{²ä]ihÂkT&¤”`ƒ4™‘TÖ�Èµç“dŒ_³ú¦1O?ÇÐRB0¼°p!.Ë›FÓ.h?†ø¤÷An51Af•ô\&Á¡œ0�ˆ@J!c†Iñ)awJ0ã¯ðøÏWÝ<â¾]®­ÿE¢Æ ˆê·2¥€Ó.Øvš4Ìor†Ó”jR€ÒcÚ¼×ˆ<$ù	‚�<Ö¨bVBâ>çòµ75? ~¤EÃujP~PoÖ'þäóß˜fÉ…àæ¹Ü° v|À£°ë°['Å…
”/ñ+ÏË|í-®êË�r¡Œ$“ÁÈÜ?è¼1óˆ/3Î¾ÉÍúQÂîðèuRŽFM@É¹a¥˜çöì�BþÐqŸ¿zÝÒS²Ê-XDû`y¬�ò€zS�ŸaÛ{aÄ¿o˜‰#…›†¶ÇÀu6žFÍAJáqÃ2¸YÏÍ<Ïþ¯UKÆÞÙ—3Ñ€À¬™=_ÆºÄöËÁã_£Œ+á¦)“‚{ÚÔ×¨ñƒnÖ*Zàæ®l4G_ú4å”Á%`åôM?ïÍC„¿Á°šNN§¡Ü|Õ×ÐAY«Ü�<Ödxvç#ÜÍÍué/ûGä-%–H (O=½œvAÛÇ˜¿ŠV³°;=0mîkhìäXM†ôr[=aiÍâ±(äŠŒâïÂêl“^(Ã´y[ÿ�Yõ¿D³pº4ù54öÆÅÈfÃ¬ÿý”yÛêïÓLæSŠ+Ö�÷Z"k¼Å´Rõrí¤ Ò*íëkhRH0.ŒøÃµ;þà8]ç¯[:)[ìà`ñH,:oçË0¬Æ3<»�ªøL}¤¯¡1(‹ß5¬¦gwÝk»�]·tR{1ƒƒÅ1)H•Z™wà…[÷�âïÜjÈÏ4ù54†eú›Ä%o<Ã2ïšxnÛxEþ"¹ûþ$¥\ÄeõÅ¹y¿aÕ-rù544öÌÙv—[�ÇYÉØ½Ó/Ú4I¹E�}sdê�Í`¹eF¼ñPE~*”ÖÐÐ(.¤py<e
»g¥—³OYûëñmûº‚xrËš3Ü?Vã¡ÂîÔä×Ð(7‰c<V?Ã°â:øÂ—±ˆ¿ªvhâ/úç’3Z¤ÅS©ßòXã	‘_›ý%óE Þp‚@óo±P˜ª¤8Ÿ+Pr�¬…2üA:�Û±¦3En§K-’†ò444	ÆL‘£À`ê}S7ì¸‘,qÅÉ!ˆÀ ¡¥E­­Ì›zÁ¦›É1—xÙ�®ê’¨¡¡Q^H¸<1Ât³Û°fÉ~—åx�‰üó¶¾Ÿ›ÉÛ¥—õ“|tO>�a qÁŒ„!ÜÌV/n¾#ähñ úM9Ã�ÜH<Å¸Ù,=[êV]ÃêoXÒk“�G­¾iÌ†Áœ0 V‚Ñ3#~#�5ŒžMÝ{uEŸ†Æp‚1.=[ðXý8é‰Å*/‡¸:ÀxÀÀ”õN]¿å»†•úÏé¢ Ÿnâ¡¡Q .zv—k&RgLk˜ó-PAÁ½cï?¤ê‘™7åÂíÇ1#ñ_Âé¦¶Çšüâ¤pz<‰…ÄU_hLÙÞ~o }üfo‚Ñán}Ä°Žñ” èÝ_C£Ò@�´�XƒáÙÝÿJ™Í'==ÞÞúîÙPçýL´;›çñ¦c<»K“_C£BA3q”¸Úánû´
îÅØ½t'=øÂmã=°ç˜aŽ†ŽúkhDãT@8Ûìxòˆu×Öo	»q!À¤ñ=#Þ4"§£þ•:™9Á­T³™íùï½µëß2Š¦Ïßq"$HRséé„�H€ÚsÉ¸)áæN~õæqÿôƒùo�EØ¿0ã2ÕÓO¸Î"fÄ% :ÛOC#" ñÚBwÃ"µÏÏX!d„©„Ó.l›Ãë!é9Ô·\'ühhD‚1&=ûäUKÆ>Ü_šð[ˆ=c†ßˆLJ¹€™	Ê(*ûÀB�b@Jâ°drA!·wo„M>.Üz”aO@�ß¯‡tjhD4–Ü“Â=zõ’±Ïö­è×´gR|Í0ëêATÖ—ª¡¡QdaÄêM)ñµþ¾»Ë”aúy[&žcŒYþhsmhhDT2Ì EÖ‘Ö¬×—¤^)´ò@‹ª „)Ï1ã)K
O…þ‡ó•k¡©4ó4–…¦1{yÐÏÐÏ†¿§@äÁ¤p=ÃJ%bÈµÐæ>ôPž÷½ïï\iN�¼õIÃª›%œ´Nü‰ ÔN„%›�"x¨Àt0´ëûdÚ…áÝ�è…bap¦Ä /�€Âç§'Ñâ@JÁcuÜ³»—¯îwTa× ³WâÏä¶c¥{»p3ºÑG¢�¤Op=	Û\—n�±üÃ2�Æ$Ã¨FŽõ	ˆ™ô`ˆ›þå\	G=€¬´÷ìèèÊHØ.`;i["ëøŒ§ß¥ç0‘ Ë�P(.Æ8qš±·OiÜrôàñ�ó½zùyŒÄ´˜—m×M>+áL;.9eŽ'‘süïÕ'êâãG˜¶¿�	Íš›öe`ÜŽæÇÈŽx°LŸ¬Y¶ëÿ��Ýmmí›¶{hë�Ø°ÍÃê�6ïHç$:zBábƒaìzÍú¹2 ¥ô«Ñ”¹ö³@ èÂä„ë“‰ŽÄ
n&&I/KóÈuòÏ0!4ç½€ˆ™ÔÎ�ªã˜8Žã°‰1r �éû˜¼¿‰Ñ�´ÓÌ[	Ùw—;´.öz]Û;%Votñê›^~ÃÅŠõ.ÞØ*Ð™Ê’¨‹ûÖYy·Ac˜ ©w —nvM¦+;sCëÄqßœ;÷!cÙ2¸ÖÎÄ)ÜŠO’nV›ÿÃ åoÓ$HÊÜÎ9IŽ)û8á0ÇjaÖcš8Ì~Ú<„£�…>}}¾¶'žû™`½Ÿ;Œ„		ÎøQô°pÒáþÏÑk'KaùZ�­tðèJëÚ:z–ï’h1.0"¿df|ŠÕ„S ÜEÜ7�“Õ·s¸Y×Íy,Œh”Ç¼@OFÂñ€T=Ã¬É1Ì�Ã‰‡ù¤'âBøÄ.KA‘›w¬¸�ÅÂ×¹;‘…‡Œ„iÿÑû�ŽãÌwÆ‘µ%žYãâ‘m<ü¢�UozØÙ-Uü€\—ð½kÃ < /’ò{áœD@Üö‰©ó¶.3bus„Ý££ÿ%FH\
°‘�Œ³§ÄpÚ‘N<ÜÂ!Ì|`�@®@ø{á«D„¢@‚@¯±0æ@ÖÁÊõ¾Ü·ÜÆò5²ŽÇˆ:^P¶Ó «ž{NúáÕ‹›çª"ôõIó6�3$_Í³Â=�b#$D&çØÆ�â8m–…³NLà˜ƒc½®:‘^ñ=p¢å6;|¡ Ñ®OîÁÿ™ÃƒÏÛÊm G’º[ß×(¤7©8ˆúúM}mñ~[”©oxÆÑÜŠ7þIþt-ƒ?íŠÝ©ø¡š8ë„8>xlB™Ì½HšóU‚ŒÆèAïí¤Ã)v`a}›‡??–Ã_Ïá•7]åÆÔ%˜ºZŠŠ,»’›u°sG¸Ã÷õ¹<Ž›õpÝ¬öÿK@üÎ´TGd'Ï´pÎœÎ˜m!øõaBMáyz5"€öEnLkà+ªÃ§ß�Ä=OÛøý²þõŠ£Ä°�ŠQµÔÈ5Ì:Sºöñ� 0:œ-…M7HoÿE@è«ñ)àuú;,µÀO˜aå†x˜aW‹W½oV!íú9!®<gãÆ»3ÊM ïQ"Ós
rýt¤Q�8.%’ˆ#ÕçSßýjœí?b3S —cq¾(°G§þ{’˜3³ñ#ì×—
¡ZA÷>cãÆ{ÒêH‘2é(1ˆ±k¿ã¹N…©É*³%xÞ@`%=oøÜµ,2èàæÖÈú1‡±C/Üq�ïEp£R ‡
Z¸éîÊÌ˜Ã‚×áýÇÄƒkti«b¿˜ ’
ÁÎâê¿¦±j“‹Æ‡Êyré¢np%DþÃ‚[Ã€9þG#Äº¸ˆåQðZ(cR:]Ò33]iOãuJF5†|–Oæ~ªžã’³ê1ÿ=uhªc½v5mW!ùCké£s8ù·Ü“Aë#YlçÎh‰ÜhÀIùä'B«]>pte�…@…¯<#aí`°v ñL‰‚¬Y!Pµ@uàbªéIL1cI.Ý´_7¬1¨…žå¿k–…KÏ©Ça™½v±b%çÔ"èúy$ €ªmhù@÷'m¬lw«2½ÀÜw{»U½.;ë€t£Dæ@ÀHK$70Ôm`0r€¬©´7Æ <:	0\»gºÉŸÂÒË�	 gþr×§‚›ï~¬œžìÜ«æˆ~¹ ÈÏ€7z~²¢K×dÐ#¤Ÿ/`÷ÉXÜ›ÐÒ}	Š`½Ðu°Df ~=”(«Á¨k€1ÁËà,3Åd“à·ýî—	�IJUy�‰ÓÞaá²s0e¼‘Ï—×Äßw¨¸^@þû7Ù¸èÑN¼Þí¢Ñâ¨£l¨}ªÂ:²À«—è8È6#Vn�Y"@QQ�6²I&FJAƒ?¤Ÿ}¡±[P®;%óP4ú¿>^�Ï¿¯®—¹¯¯Þ¾#ä‘ÿºWÒ¸ä©nxRbT‚«ë\´HÜ°ÇJì¨“H=Ï`µ3ÈX•‹€”Œ8/FR³ÀF?Sco&ÿŽ.‰™“Lüà‚FÌžjê]¿D;?yOßxºW®H£>Æãn)bÔ,øà n°ó(‰Ô@¢�Õ€% Á$Kr0$w�žjôŸÌûö‰³OŒ£õÒ”"˜¶«Ã¦Å÷ùúR~üB)+¨,5™o	h?Bª“æV3#è�	'ÞHGª#@.@Õ¾Ù¡ƒÌz¿ûŽÄÂsëñÙ3{›üÅ%?-Æ¿¬Ïâ;Ow#²ÿÊu‘™/lŸ)1ê©à„ ƒLª‹ËFp)Ñà—¨h‚ÚZõd¥JC½é«)E~U»Þ'[Mcßüžßébþc]ù¼‰²¯Jæ‹€Û´. yõ68”dH$9cŒNTõðÏ>Á¾Žn‰é˜øÝ·R8õíÖ®^m)•L¾þT¶åâFé�8@n,Ð3Uê
¨ZKŠ4Ò^×�wÁä~°�2Ï~ÿ­fLôý}½ë—Îô'?ÿŽ7²x`“�V‰~ƒ£¯/égVüë×ÆlŸ�G·Ä{�Žcñ‚&ŒIùGOšü¥‘?ëIühEZmµaq3Ÿô”'�ž •[P}V€- äßÞ%ñ¡ãã¸ö�*ÛŒ|~MþÒA•žøëúžhsÐHÅ<¡ È‹ 	€[GE¨Jhwþ.‰³OˆãšÏ5©&œa£K�Ò/¾;6äü(T¥]lÏOÎ�Òˆ+îî;j~‰‡äßÑqüßgUô_‘¿
ov%�O×¸Ý–x¬ÍAÒd*Pq`€=:¨.¬BðZ'?µ©>u–…«?×¨†XÁ�#4õÛjccÚCŒÊy+íª3ç·GJxÔÚ¡
Ý ^ËÑ~iuÌÁ&~ñ…&Õ§^µ³Öä/+–m¶‘ó*¸lZB‘ßm�þi@¥¾Î!¢&€{]Yÿœÿú/¥Ô0mö—¡•õ¦B]á3¹ÛŒUxM;9cS×¹	ãFúG}Úì/
~;rRíþË-é§S«±Ê}‘CGM	 í4”dBsí®ûR¦`èsþa„#€­Y	ñÔkÕ‡Új†Lå¹ê³Mxçô˜Šh(¨-ëÁä~ÿÄJ£4€ ï`µ¡
ßRÿ ¢ïì‘¸èÝIUÖKf¿&ÿð‚"ÿ�AÎEÅ»,žv"ô£^'Ã·?Z¯~*ú—0àú¥©•U¬ƒ€D8…wT#Ç�ç5ú£¶õqßðÞ“‚�£<?M¸RÁ(7Ä©Î@M@Æ–ª‡ß¤ýü ŸNñ~„YcÂüTtóP‰p5²¥
ßRÓ¿G¢åÄ8ZNLhòWÂ ß#M¿í*ÌbÝÕ9D„Wõy¿¼mœ�ÿwnƒ?DÂ6«Q­°SÆ[~€J´¤Ÿëd0ÒjˆnÕ¡j@q¸ß:§£}?3
çÍµ‚p3�ÞdbÖ¨²®¬ÈûÃ8ß^­��ªT BÓŸ*ü>pl\Õõk¿¿òúþ§ïoÁñdÅñ‹ÑÀW,JP�ÍA«Q Â¨óŽïüg}ðÅªïÈ#¼'çNN`B£�ÛP9ÄÈJ‰™	©,WÃˆ«U' dFR7ßÏ½7‰‰cƒ¨¥¬*�^ ûB§Öøìô$z¿.  (QI7�Ñ„WÅcÕØªªÞ™ùDþY“Mœ÷®¤
üiòW6‚)ÞøÜÁu˜Òd í, Fƒ_m��MJàð”‰‹Þ—Äø‘\Y–�°Të ¢¶ .9»I]ß	„“FÅ9.=¼^õN_›3(: ÎÀ¥G4¨×6±ÙÀgÏLªÍe¸Å©ØàUUãO{gYê¡zFdöSaÖ¼éIå
t¸Ãã
° 0I–ãÇ7aRƒ¡´ˆ>?ï´$fdªb²j
(WÍ[¡G-½>û^|Wl«"(ÌÚ´ÓÃÆ4ì`ðÊ<œ“»§#ñã£qæ„¸ÊM !¢µEåEg$‘s+¼n¡€vÛ}ú‘Ž98æ�šªŠwVý�h7ï¸à'�ø÷KÆ¯â0:Q¶1ÝœN‰°3+ðåC’øâ¡uùA¥á÷É
øðñq~Pirªd}UÅÛ ÂS‘Ïg‚á�zû�ùÏÿI^xÍEª‰Š7€QOqXm¥“ù�Ièâf7âªcšòIcù¢¥+à‚3’~0Õ^-»ÿÜ™15Íô#ÿ‘W5Fþ+ò×3xÁ„^*¿õ,GÝ:¦šqÈ"çáÁ� -yÂ ~3'…oQŸŸ’Ù—à¡ð¡ãâ8ô@»:N˜xUô—çÀ'NMªÏ+½¹„F?äÝ'¿K' 9ø„ÔJ†Ô‹F6èÊž¡v€~žHO�W¢Ë‘8y¼…¿Ÿ>-oK(³Ÿ~¦¿ç­ êýÑ9	díêˆ˜Õpî?{jsgZztw5�¿OçP‚úõ‰6Xgf‚„Gó¬=@¸€eìÚ�]È÷{(4á)!ŒL}:â£¯×Ã%‡×áÃþë*ðùw‡�ð9!Ž›þžÆöN‰˜Yá�«Y è~Ð�ýÄ)	5äƒÌGšì£QÙäß´ƒ~{ PÀpš^ê6=ã c<`ŒÞè��ÓNþ<�&0Ð”!©vtZÄÐ¸É0¡ÞÀñcc8ó€¸Úñ�€Ð-S9hNq|ð¸®¹=�‘±
�hTí@jœu€Éûx÷Q4¶àšü•Oþ�ƒ#¿íî´Ë[€‘eH­Ü×€³ß“À‘§šxr³£ºoÉ
lÌtSÛ÷Ã~Iû%¹úøÎ1&Nk!eíbºìúCñåÏ:!Ž_Þ—Q›N”#‚f”ƒéœÀïH !Ét{ï�ã?Ú¿b0äïObþäÞ?ü-‹·�lÀ§7æ$çIu~Oƒï©Ûð[^Kà*„AÀÁ‚Þ™ü<æ�|ÎFc°þ¢ˆÈiñ4%9>r‚ïÃEX„k‡üWîùœôÄ,`Á-]øù�éüß¢F£õ&Ë“ŸO‚àõ!þ¾¬��NBA‰*xdwÿ¬T½ý;HýU:ùßÜ�]È ìð”ªcøßßõàº»Òêo©cÄRáÍ"�¾¡«yú¬8Þ6Ö€íDwŠ¤ Èä:ýV>[£rw~òù‹Iþaô�\Àïÿ®7Þ“QAàR·~cÁškªg˜sxL¹¢Q>GN èâ;0º‰áÔ#h`[õ•hV�Ù_ò¿Eâßûm7®¿+Ç-ýÑœžÿÔYq5jNÇ ÊZXÔæûÈ)14ÎÐ5ÿLþóJLþB2ÒÌÃÕ·§±¥½ô‡y°éwh6‘í9€ <R^«W@F£ò|þ•e ?�þ&u€nH@�{Ÿ0&6RBB² '€N hâT†Ü - ¥-¦þEW7"’V}(‡ÏßèoR.a7|%…ó«AË‘§/ãøbSmÄ¢†HÑ‡nvÎ‘˜¶¿‰Éãý†j(Èˆ:ÊéóïŽü7}5…fÄÔß,×šà{Ž>$†QMn«£% *ûOâ¸1¿¡d%·ÊP)ä?þPŸü”^.ð`¢Ñ~#8Ž˜dª¡¨U¢Fêåá©‹š~hT�Ï¿mxÈŸFò‡P©À Ž=$æÏ6ˆ˜	 ëJ7yd©­/ Úü¯Ÿÿ§Ã³óß8Ìä'„„Ÿ5)††W¯%JF}|€¡r ü/÷«ªqò— Ã¯ÒÍþ¾7¡MœŽš[Ê£ fNŠåË€5ÿ‡÷¨¯\çü•J~…`Žhd8x‚	Û‰–À#Õ÷Ïf¾-²ŒUCþÛÎ»¢+×—�ü$þÉ8°¸’È�]=)è£
:ÑjI™—J™r¾žàßuíÿcÀï'xù�òünüJJeÞU
ùC„‡Ó0`E¬CP$@µtò$Rõ\¥]ú_îWU›ä?/ Swþº8pó‚ÊÚùîø“÷3QŸð›F<2@®ßý‡Z3k#ù×»hª+ùëÉì_�RÍ7*‘ü„pENÇÑ@Pâ4äš eºSö7üRL >ò×ù®\òB²7Õs5‘Ú‰Ðô H �üª‰cü—«ëÿKMþÁ!œD}ÐX#R¹ <*À„Å0~”¿DE]‡²ˆ*áy¸ÈoDlç/DxßÆ�¢d m´ãW» „-®Â™†²wþlDÉ_ˆýFr}XL„>?Íþ#u¿VMk×·ì¸þ®ŒÿÅ`Lõ°�ókŸP7%Ú¤1^–Ü@PùY5ÁH&:^ÙPmÔß5”¢½[â‹×vâžgl¼¹ÝÃ÷>ÙàÇ:ÊQîµó_Ù�WÊtÔgìüK¤ptDw~|¤¡!V,:¹ P£à„Tä7C¹bÕGþO_Õ�®tTéú»Ó¸ô–î|¹i©“×ÇìeCÍ~{—ÙUòB‘¦ä(¦¬:T>*^ ÂJíŸûôP5ä_á(‘£\òQ7ß[ �ß(0û_*ç9¿-Uvç’‹£ëó÷	 ­Su¿"°\+_ (PÒ…åùF�¸®"Gº€ü�»HG‚7²"îü¯oñð©+Ê›áGÍ3’K4áèéÕA~õ« ´eíÓ�@c�Oûˆ¸V{'�ÄüÀì/$ˆBøöÒâ‹€ìüD~òù_}ÓU×Ø+ÓÎß�ÿ�ÕB~æ0¦‚h8iPù@Øö9¯tà;ÿü«;ðð¾Ù¿»7�%OãÛE´ú’íf¯¬ä§�q5‘¿ ô^È
�ÉV�­B+ jÈU@þ~vþÝ‰Àâ"¹ý‘_W-#ù«jç’�î� D‘ D\ Bòw*òw˜ü…¤íÊ5Ñä/’ó�p#`DC ( Ñ&wFâ3?ëÄ²ìA‘?DßÀ ¤hò—"¸õI™‚µh@A÷Õ(\ÔÝ‘ŸfÉ�ùß"Oã›K.šüå�Ð"�„ ÐB§D˜ü÷/ß7ò÷�FŽ¥÷¥ñõÅ]ù¯ïNBò“¯OG}Úç/Xð‘J×£R¯P‘#OVâ³×�ü}-�_ÞŸÝ£’Ÿzø½¶EüÊ'˜…-«â ¼ˆ!y*]YÃºðtNâs×tâ¾g‹KþÞ�A†_=�Å%7½Uúîü¯·•�üÙ*Žöï	áÚ¤ñõ•¾N## ¤ áLÀJ‘�^e[»Àç¯éÄ½Ï”†ü}Eà×fqñ�]¾X2îüëÊD~UØCI>uK.®-òË‚ÓqgTL eíL‹|‰¥¬pÓÿáüùñ\IÉßK~÷PßÐ¥TÆ`ÕF·¬;?‘?�ÿf"ÿ´Ú!!(VEk5*£Â+¾X‹«½GªÙkF˜	S�˜^'Yg�Çº¶\q[�*Q–A	U‹ÈM"ðÛ3ª-õÇONà×vaý0ìüDþÙSk�ür—õEkÕ`ÑHªx pÆT4]M†©ð¹ ª`	À×>R!%~ò§´B)E@ÍMläh}$‹;þ•óËl‰ü¢¼;M’¿ 9Ûþ²HØÖQpwŠUG::é@”òõ³êqñGêTá	C©C$0VÌw;¨)½†r�?UÇqËÅ©š'?�vÕTÇ ŠhYAÀ­íþZé¦^óp‰€ò’dùv~
ø½cªYÓ;¿>¶uxÈ¹2_³QéàQÉ¬"Ø´Ã‹L]À°Š@iŸ^›ýý \“›¶{*¢�KdŠ’ ·”
Úçß‹ ì�*þ•òõHÃ¼y§•£DõRD€P®À`±¡£ý»G¸&7íô"U	 óõ˜É°~«oDåŒµšD@ïü{F¸ã¯ß*ü¦ ‰WGÂP!‚ÐE]³ÉUyÖÄ¨p¦jÜ��ü#êu´¿?„k‘âTk6º*+*ë3@W“z­mi—ØÒdµDå
G\z‘ÿk)?Ú/j7Úß/‚µ¸q»À¶NƒLÔˆ¬ÏH€Êd@&+°v£ˆô€Ð(‰@H~ª<$òÏš�?«¦|ÁZ$5“ó×jT–gdn%uç€W7º‘ñ›£,}w~MþÝ#\‹¯¾)Ð“£tuD‘† èê‹¯»yAˆ2*90Ø—üoŸ¤wþ=!$ü¯;Ê:ŠÒÞ!h@è¯¹ª9HT2­¢f	ô·óS=�6û÷�©Êü<•^w‚F‘ uh wxx}KÐ(B:
"°;³?J&m¹!ƒ5¸j£‡­íBG£äžFêÖ†ßZ{ùZ_ ¢2‚9
" ÈŸÓ>ÿ`ž÷/_ãªµ5K)R/—¤ÿ×ËNUÄ*Eò;£ø¡uôøËvEö¨Ø"E!2­’q†¿â mG§âª’E ×QßÅ:Ú?ÿŸvþgV¹»‚D‘€0ðævÏn@TR.+QB³”Þù‡„pí=µÊÁæ�žÊV�’ÿ9mOj¤vµ¢"’dÇR}Ô·Oxt¥£¬¨¨Õ¨DR Ôq ÅðÐó¹|ëëjD)E ù/NaæÛô9ÿP{Uæ¨µ˜ŒóÈ™ÿ„ÈÑ‡.2õ|ùÏ¿æTÕi@9D ïó“Ùq
GL2UÓÐ¨E¯+Éü_»ÉCœ* µ ”´ˆ»2BMÜ©vSÂz~:ç§ž*Ã�fèÂž!ãþå95&ª–h$_6¹	‹ã�çœüŒjF1D ßÌ£ÞŸØ3krmwï-†ùŸÉI<ðœ­Ìÿˆ�®Ì#’Ô	Ý€ë<ñ’­nHµºÅ�p\W#µîþ*5ðŒùf¿&ÿ� <_|ÞÆê�žZ‹Q‹þGZ Üð†ÒEŽF`Ë!yò³úÞLìÑfÿÐA×”.÷_Ï©Í(Êk�GY…ëâ>gcóN¡’‚¢„)¥„3›ˆü7á¨×ULá_ç×7{øç
õñÒ_)%"+ ÄuƒE	4	G}­` "’¿!Á±x�&± ƒ�·=šÅŽ.y1�¬ ì†[Î*3·Úƒ�äÏ§%ê7}µ¶¦ô–Rú×–®óŸ£³ÿè¥þöE¤)C‹ŸnÂŠõ.î~Ê·J=³ÒE€f(’ÖY7~¥	Ç¬~Å‚Èþ—Ç³X³Ù�tð¯* ©ò¯È*_¬š*‡"_ú`q†ÅR8îð+êÈ5N�g‰ß>”EÜŒÆôß½!òt¡…O�˜'_uðÀr[ùÀQÊì‹Ð"ýÆÙõ¸çû#qì!1um´Ù_È`HííOäTç
@WC!Zä@!˜Äú‹;ÓÊ×U“YªAž�ð(”ÞûAce®Öš5TRò3?…ú†»3‘êû¿7TÅQV@’á_¯8* ¬€j¹CC€"„Ï¦+"€Ûþ™Sõ'Õ²ûW� Æ®»3­*´è†E=@3ThòÜzgZâ†{ÒHX¬ªÖUÕ€²Ï¬qqë#ÙšIÒ(�ùó½¼²Á«Š£¿ª€|‘PŒáÚ¿¥U’†�bdý½±ÕÃ’{3hL0•�ZM¨* eNÆ�×6{¸þîtM»ÅcÀÏnO£­ÝŸú[mË©ª LjL2üò~ßd£¸@µl4Êä”PÚÖæÐTíœÿš Îè‘øþïºóä×–€Æ€×�ôÏU)�šÖ�çùuÕˆª ‘¾©Ž©ŽAx8«”¼š7å9F½éžž|ÕUÁåjµ"«R òñ ‹áŠÛz°iGà
hÐØÛºþq2¹�×Ü‘Vîd5¯›ª ˜(ùþº'ÿµ*¾—E2ýmøî/»Ð•ñË}«Ù}¬Z PÐ&UÏU¿€_ÝŸÑA�™þ?ûk~ÁQnd5þjF Â›J>Üå·öèS�½šþO¼ìàš;2HUiÔ¿æ€Ì7*Þ sî’›ºÐ“õ#ºÕlÖi"(œÚÖ)ðÍÅ]�RªÏka�T½ HÉ)‹‹J†¿³´[	 Ýô¸¿{�¤u Ç¾z}Vm
Ò}k`÷¯ ¸ÙÀðûeYüüoiÐ m ´�éOçýÿxÖFªüþš ©:ùv?¼5�»žÌ©OÂ QÛ~ÿÒû2X|OFmµDþš€Ðä�Å€¯ÝØ…§W;j&^­Ýtÿžj×§cbê'Q>M@>(ŒuúÂÏ»T¥—®¨Mò?·ÖÅW®ë„ÁýÊQ- 5¿j�aÃ6ŸûY'vvûQßjÎøÒèmö¯ßêáó?ïT§B1³º³ýö„š³ 
wJôxz�‹Ï]ã/Ý? 6Žû¨´÷¢ÿëÄº­žj([+ÿþP³@ ¢øyèy_üE—ªþÒ"P�P-ã°³[àÓWubÅ:M	VóAàš€PF52Üýd_¾®ÙPjxW¨VŸŸºDÍ¿ªÿ~ÕQÇ}®¾ÇZ 
Eà¯�çÔ¡�*& HÕ�Ó�ó®ìÀ£+eõiòû¨y —40ÜûŒ�óÒ�­B‰€>"Œ>ùWoôpî�ÚñÌj)"•õõÛh( í
d	<ñ’ƒOü¸Cõ¤¤E z {I÷nùÿQVmôü,?Mþ·€?ICC�v‡õ+×¹øÏtàÙÕ®ÎŒè,Ÿ›¼î{ÖV;[»‡ðëŸó9.¥L³µjô$´ÿÝ£!É°e§‡Oü¸]-$3ˆ	è«T¹PgùÌßùó@Ÿ¾ºYÛï¥­¸·N:$î“ÐÍ´'ðÐ‚¡d¡ŒÌ¿º×Ý•V1�Z>¥c>×ý¦ßº¹K‰6µòÖ÷ë­`jÓG7‡DÐ@¿ŸŸªqÐÂ±š°ËÔ¢úÒ/:ÑÞ-t\ Âö²|v_›‡O^Ñ¡†ÄR�Ý¹(K‰í;9ý/ð´ìa0$ÅZÉáœË;ðtP‹O_µaŸÜCDÿÇ36Zþ·�¼h«ÓÕïAß›ÝA’ Hð4ãÝú0``�%:!xyƒ‹�ý ¿¸3“Ç­MÌòB†&?Ò9©¬³‹®êPÁ>JïÖgüuD'—]z�üÀOh44	Â÷~Ó�ó®èÌjk < â“½J×üÙ5.>z9‰qZúâ1ì(7HH»L)åZÆLHÆ(´¥ó82jDÃ?–çðüë.þp=>ù®„Z˜¡YªOVKÓº‹ˆŸµ%®¹=�ÿžQ Yf:¹g`äP¿s¬á�|µôººšüƒt	(±„Ò†¿±¤Ÿ¼¢+×»½N
´Z¼kúú�¿dã¬ÿiÇ·¥•Ÿ¯Î÷urÏà %—žM×˜Œ‰UÒMSÞ+‡C^�J81ü áËsxf•ƒO�–À§ÿ££šüËúªú¢v�îê×g0`íf×Ý™Æm�æà¸#ý2^,¨å±Á¤›`XÃ½pÇA¼™a4@¸Z †Õ_Ð£öãSÆ›øÌ™I|lnR�Cæ¥kœøjÖ²äÞ4~y_mMIFl]¨5dH	FP¼nÎáì ó^KÄÌ†—8·Þ&ENÀ> < 5ë GN1ñéw×áÇÆó:LXÑvÖž‰Osh°ëÒd°j£‹†×I=Å€”’™	&ÝìYß|e ±iný;·ON—Ð(†P—!:’š=•,‚:œyT<à¢…ÀGx^¿;+ÑúˆO|Ð™°€„¥Ïõ‹éñX£!œî{W-û&À¤DÛSŒ[§KI‡Eü[µ¸’þ‘!]Oj>ùÙ«;1kŠ‰O¾+‰÷Wß+$@-Å	ÂÝžÞ3	%½ñ-íz4‹?,Ë©\">�´ÐÏi?¿xPçíûË)Lí{¨‚=.ÜUG&
ñoÖ,T–` tEŸÍUÓg®¿+ƒsæÄñþ£ã8`Œ‘¿Úá7ù¸¬‡pï��=ÂËoxøÓcYüù±,6lj¢35ì£ÿÅ„”ÄqáÐ´lñ0}EÝ†Ió6�3$_ÍSKˆÐ÷§–ä97’cÎá1eÌ™i©D–y1ˆp¼ 09ª0 ÚÞ#qÿòn"‡¿â¨ÏýDž]‘F©€1&…ÝnÇã“×ÿbÄNk‚ÄÔy[—±º9Âî`´i”Zh]ONª‚£éLœv¤…SgY8rrL/†P¤ ArX…'ë¨`Þ.ÃF!cK<¶ÒÁýËm<ô‚�u[üÃ{²Žè½jâ—Rn5ra÷ücÕ’æ3È 0çÎæ²eÌe��3nÍ‘èÃ*Çë©u×ÀrèóUoº*«ðÆ»38ô@§¾=Žc�áˆI¦ªlSÎYÁï«ŒÄÐ:QP›´ìÄ­•pñPÎ§W9xüe>—ÃÚÍBu^&Ò7Öù©déhS¿<PÙ¾,ÆÃcôùìÏ<mšÀCê›ž‡‡™›þfï¥¦QŽ`!!n1Õ€ÈðÜë.þý*}1ŒÍqÔ´Þ9ÍÄìi1LÚÏP®ïs—Â�Wµz!ï:Ù É]øo¥YÁsç–´X
ž”N=(rO#×þõ²ƒåklëÈPSŽ¸Í'ò‡¦Q^0Ééö0&™€†Wº(&@&',XŸLt$Vp31IzÙÀàÔ„;;‰�ãÙœTŸS¥Ûþ£9fM‰áí“L<ÁÄ”ñ†Š–Ç
™¸„þu_7;¯T	ÚÉ·´K¬Ùèâ•7]U˜óÂë.¶¶u†O"A~=™÷a‡eíÛ'¤`F‚Óù¦+;sCëÄŒ²	Ô÷Z¤�VæM�·íJÃjºØËµ»Œ*„4*&§€@™†Ž'U›+µ-£É6ãGqLÝßÀ�ÍšS\÷ÉÑÜÄ1¢�«à�¿
Ÿgo á±]
TJlï”ŠÔ›Û…j‘ÖÖ!UãJÎÙÖ!U1NO–š¤0µÃáÃ€Ÿöë+RJ×ˆ�0½\û•«—Œ½$ä|o’3´
§kc:¨Ý"0™ÿIkQ)qæ¥7\uÄHâ@D$ÂÓÏY&SÙs4}T#Gª.¨ïÑƒžÚv¤Ê¯·=ÿ„¢½[bG·@wÆÿzÎõw|zÐ"‰þsP§$ú7=w!áµO_y N§KJˆÛz}½×OµHcjÃ–§«a–pÒú4 (ô÷Ug·‚X@þ£�Š”áçêQàô}ÿœÞo©Z êÑwgžG£Â!¥à±:îÙéå«×®x'–�â†ßÊûù-�I ÎÿÌR{l‘@Ht"8¹ª9<{g~µ¢óƒoä2P�,:} „zÐ¿ékô=ú™:‹ÁŠù¿†èoÐóÓ#ôç5ù£â2eÿ1ÎÿHäŸ;÷Aó-Ð:Ã¿ŸÜe·º¹N›q:¤Ò÷8ÊwùP$ÂòÙ==D?–‚F¤!7ÏîÌÚnN™ÿËN>9³+Ò¿ˆ	,”üÕ¥Í/KáýÉˆ5¨Èá0½h�¢@â²â¶uKx™8®¸ ß£>ãWznš*õQ †F¤Á¹çöxBºWõûÝ^ŸVÀÚšŸžw7·©*C7\ÒÐˆ"¤ô˜ÕÈˆË¯Ý²ÿ“}wÂ[wø•þÉ€!ðSéf‘¢¡¡QY`ÔúKr?.äv¯ŸØmÕ ¦\Ø¶Ì´ON·n¢¡ÁÆžÝùÐê%ãNñ9ÍÞÓíßÇ?§•N€%û®ô4	Òa�h@µý–ž-�ý?õ•súçzÿÐzŽGþÂª%cöœÜRk &âúD@C# ÄŸƒ¸»ê¦Q�(ßŸr|úÁ^¢ü’™œ}×ËumcÜâ”QT¢W¬¡¡QG¹Å‰³Ä]¿Øo÷Ø½ P´°ü•%Í¹PuÕÙ�â('®Jç2ÅÝ¼%ò_ˆ½Dø%ÃB°Ù›`t¸[5¬†wzv—`,Ì
×ÐÐ¨HHÏ ÓßîþWÊl>ééñð°ˆbwoþ…Ø‘™ÄÊVöôÌL.žã2#¦»¶ihT(ßß„p©�ÛX@œ%îî‰ü„��ñ…BSÎßt©™õ¿žÝéR�I±^º††Æ¾�jµ«Éô²í—®¾yÜBÎîí÷fÊ·BPµàš[ö¿Ü³Ûï¤?$¥Ð‚ â"qÒÍuÜAä÷+{1 €ý }y&ýjAÉr’ÏN÷Fn$}* ¡QµþfÂv×F×“óéK>W÷lú‡x0o--·ò7–4o®{¡(ÄÐÐ6ìâ ð¼×-·¹¥åVcOQÿ¾|ž?5XvŠ;í‚¶ïðäˆÿ¹ê.¢ãå‡Ëã)SdÚ¿»êæ±ÿrs0O0øã¼e'{äcÐô2;oäVÊ„”ƒú£û	—¸G$.*¿ÙÉƒŽË±ÒO²––VÞ:£EN}cÛ�DêÃ^VwÖÐ(¤tyb„)r·­š0æœ…ä¡ïå¼wbBWHJ2èHˆOy¹Î‡ÕÉ ´% ¡QJH)”Ùïå:î6ìO]64ò†žÑ·h‘ ,Á­×Žë¹öÏîy‰D Rhw@C£�Âïíow½ r-›n8 Mì¯Ìw Ø·”Þ°ƒÐ¯§¶Áí~¿çd^äñ:& ¡Q
³ŸÈïô¼ÈDÏ‡çúéð3X§ÛOðB&žÛ6ÞJš­F¬áa·»€ž.¤¡±ïÈow>jgº[Öÿæm›ŠA~BqŠzTåà­ÆúßŒÝdï=Âîü›a� £AWO„ÓÐ*Ô„×ˆ�4E®óo†ØúEþAžõï	Åí÷ªÒ\iN�ºãF3Þx¾—ëôh.!˜î0¬¡1¨º~Æ%�7"×½dÕê‘ŸÁ2ækçQü†Ÿêršƒ)n»Üˆ%¾áB
š<§gjhìÒcÜ2Èƒö¼ì×,ó-EÕ…¢¨ä'”¨ã¯ßG€^ìäy[>bðøÏ¹‘ØOØXßÉö>TV¯Ç­&CxöfÏÉ~aí-ãþäoªC?êÛJÛò;(IœôÉÓ+q£a5ÍN§á1TVÒ¿­¡%HA&?¸•âžÝù „7Íâq«•¿O=:K„Ò÷üë’>hNÝ0órn$.¡I4yˆÎê¹µ)%¤0ÌzƒÜ~)Ü­êùmÅ™!äöåúQ¸˜:oëû·þÛ0G§B¸Í./ËëÐÐ¨°^œ™�ÕÃs³Ï{^úÛk—Œ¿Sñr¡T.t©_C§þìŠŒŸÿf]ƒ—\ àëÜªO‰\»£7«…@£ =êÝÉã)&œt;$®è62?õ3ûÔf©;—ã•”ìWA«¢ƒæm;Ô„ü¾a$Î"#@8ÝŒ:™¨#C=’L£Ú"|œÇ�Ü^¶Õ•ø¯×—4¿¢~b€m¼Š‰a"™dª]qðf§Íßñ^)�opÆæ0#!Pæ‘ŽhT‡�J„1x¬�¦õ@@>Â˜øáªFÝ¹‹øjã+ûô­áÝeÉÜ¡J¦ ˜aÚ¼íg2Î?'…÷^šL,œ.
ŽRR¦†”j«@#*íù¥">ç&�5BØdÝò¿	)®]³xô=þOI†Ë|·x¸^heª�é3yÞ–˜4>Ï Î6£-áe Ý]U—I-Lz¦v{“™	p£nn»-ÿ£”ìÚµ‹G?šÿéa0÷+W 
/Ê­¡E0ùüÍ37Z“ïaÌ8Êˆ5A‰�—Sm�É•Ü„Ê{/µàÓƒvy2Ý©M>3â`FÂé$)xZJy·^ëÚ[ö{ÁÿÉÔ�Î
 ~ˆÊ$¹„Ð4j¹Õ˜Üô®c¹ô>ð2Ž)<ÖÄèÚK7)_—ÑPs
#ªáæå6hh£(ŠïŒ>	Ïc �žö átéWI!þ
füyM×ýÿÎ'ðô]Ï„Ê&ÈBÉç|Ù"–O†8è¼×±Xã,ï$.Íã ÅñÌ0Ç`TwäPõ¤ß±\ztãü‹N·NAKÑ¡ÑÁÉòâp´•øà`SµlÌ 3,Ð‰•gwSÒÎpö¸€÷æ?Yý¨gVÿŒåÂg�»PšËhýU ñ£! }rZV‚µö1Ÿ¦ž»­IÆål0Ìå`³¥SØxÉ�äÌ´”B“!@â@Z „�Üµàßå9nÕ¨X0uêì<ø7y•T²"%Y˜Òµ™”	lb0VIæ=n.CZ<»ú7c:Ÿ�šsª¾ü%ÊÝ¯Qè{„ØÊçÎhaË.ƒ×·ÒÔ/É¸ØÙ�2b¹I€˜Î'ÈIrš¤d)úFÿ–#ÙqZjŒ6‡1¶�èdLvHú7cÛ8Økž`kÈµ^<þ�5tîð
R²¹—ÁX¶²U¢µeXŽòöÿ¼Ã©ÜEÐG1    IEND®B`‚<svg width="512" height="512" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="24" height="24" rx="6" fill="#2563EB"/>
  <path d="M12 4C7.58 4 4 7.58 4 12s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm-1 11.5l-3-3 1.41-1.41L11 12.67l4.59-4.58L17 9.5l-6 6z" fill="white"/>
  <circle cx="17" cy="7" r="2" fill="#0EA5E9"/>
</svg>
‰PNG

   IHDR         ôxÔú   IDATxœìÝœ”Õ¹ÇñçLÙ
[Ø]P¥,ö{lhÌµ_õK,	‚“5F�¦š¢W��^�†fCÔ$K¬A4kD4‚È‚t…]Ø^ggÎ=gÖU:[æ}ç-¿ïç3ÌlAÙÙ™÷ùŸçœ÷¼1�¯;UççUï¨Dí¤E*•È@s_¨D˜û¥U×½¹iÑ…]÷R ¢
”’"jZKƒù³ÅZÌ±ÁÜ«æ®{ó±2Ÿ×Ò¬Uúóöë�æóUæX2·jÒàY_S_uÁšâH§ÞY$inj'S¼w2oZSôÕvæ— p‘	)óçBs<škÏ�h5·SÉ�Ì[xÏ z�ç <hÄ¸ÚñHr¬–Ô>æW´³-ôJ©­ |@ký™9vÍ1]ƒÿ˜géˆz±jbÙ2�§ <Àüh4yXD§ÆšÇŠR# ÄLT™’3Ó<˜)‘ÈË‚ì# d@Ø²� à
> l�À} ‡l{f]iN^ç™Jô·Í³¼¯  zNËÛZ©©­±‡–L+©d “ÆêXåèšc”6E_Ô	æÙÍ @ßié0<)ZM�ÿIù³2Su
2‚ �£'¬ÙUIr¼h}–Rj°  2Nk½ÊL¡>¨%:yÁ¤Aÿô �¶¿ ¡<•l?'=ÚWj ¸GëÙZÌA[ü^¦ú† ÐK#ÏkMµ\jŠþwÍ“W, €¬Ñ"õæÏ;“ªà¶O&X)è1@mw^ÝÈ¸N\aRç¹¦ÍŸ'  Ï0Óm¦¢MN¨œ›O,ùD°E€-5nÍn‘hò*3OWJ¢ ð,­%iî¦§RÑNô�`“ ›0jüªƒ£¢®2ÏÐq ð-O'E_¿pòàW  ¬gÔ„êã¢Z›Â¯ €ÿiýjJäº“?#øàs#Ç×î•ÎÛL›ÿ0 Ž™x¹3¥.\4µü#`Ø„úAùÒq�9ŸËê@àušãýím’óÛe“Š×Hˆ…7 \£#•‹WGEôoÍGƒ &kDËOço[~�\£RB¡ cÎ­Ù_Tên6ð€�Óz¶èÈwæO)SB&T`ô9�ƒUNÛM&õ�mæúYÿ  °kÌ¬€¾_'ò¯XpÿÀUá(‚culô¨šKÌûSø‹ €õ˜ Ð`ªâ5UÊoÃE‡ *Ï­>Ìý?šŸtG `K´|dÂÀ…US*^– ðªw­*'TÿÂþPü =fk†©cÆWÿÜÖ	¨@þ`Ÿ_°ç>¥Ô	  }¤µ~>)øV/4¸ `·ð�(ù³5D  è'-zeJË7‚¶¥ppÀ©:ZYTóSó›úí d’½È�)˜¿šßX~�<ª’ � £Ï]=<¢’ÓØ¿ à(­_íŒ|#S¾ •ãWÿ—¨Ôtóƒ”
  ³S¢£ßªš\ö¼ø˜À:>¦³æZ-r9›ú  ÜôùæA7VÅ*~.÷¨„ø�/ç�stáÀxÍ“¦ð.  d‰	/5&ÊOXy¿jŸñ] °ÛùFrÚž4÷  ²ï­TGÞ	~ÛFØWÀ.öS‘äÓñ¯  <ÂÌTéTôˆSÊ–ŠOøf'ÀQãÖì¦Tê5Š? Àklm²5ÊÖ*ñ	_t FN¨Ù/ªõsfÎ¿D  ð(­¥.©ÔQŸL*K<Îó€1çVÓ© €×ÙZekÖèñÕž_¤îé 0zBõæ_ø˜yF  ?05K)ýLº†y˜g€yâ.WZ¦™‡1 ÀG”¨\[ÃL'à|ñ(O€1ªgþa¿cƒ €_ÙQrOåøU?ò\�3¾úBó¯ºK  ­ÕEU“ËÿO<ÄSÀ.øÓù›òÑé‰  l‰I™?N®š\ñ„x„g@åyÕc%¥ŸQJå	  £µnÓ:rÜ‚)å3Ä< F�«Ù7Ñÿ0ÿš� @PiiL©èWLôÉ²¬€1ãëF‰t¼%J•	  A§e…NÆ­º·d�dQVçÚ‡�¯jŠÿ @h(*±Žç¶ùVCVk_Ö: ;Œ¯˜Tòºùì"  „Ï[-GÎ›\Ñ(Y�•Àˆq:Ïÿ'(þ €Û/)ò¸ŒÕYÙðÎý p�ŽÄ#5�šâ?V  1¥äˆÊÑ5Slm—¹þ?¬\Ró3ñp¼   ;vº6ºÿÿuOú²¾¢_g£  ¾d7
R)õÕùSÊß—¸VˆGŒ«µ—H|˜â ÀºÒµ1’zhÛ3ëJÅ%®ãx$1ÙLvŒ  °jdn^ÇŸÄ%®€®ü¨“  lšR§¤k¦ÿ+qXåù«w‘Tò-%ª@  ÀæiÝœR±œÞ.ØÑÀÐt�¤ì¼?Å €QªPéÎ‡†œ£ÅAŽ€Âdõ�lö @ï(¥v-Ê©¹YäØÀè	Õg˜tñ�  €¾Ñ‘oÌŸ\öq€#`Ä¸Ú±Hç,¥¤D  @Ÿh‘Ú„Šï½xbÉ'’aŽLÄ"‰?Rü è3J/�§:îd< ŒžPs’™»8J  @¿Ùšjk«dXF§ Ò—øùÐŒþ‡  È­eiTd—L^:8£€¤èŸRü È,[[m�•ÊX`äøê¢JÏV¢r  d”ÝÞ™Œì¹hjùG’ë ˜ÖÄ]  œakl,’ºU2$#ÀžóoÚ‡  pL&ö{
€…  ¸'SûÝ`á  îÉÔ‚À~u Xø €û2± °_ þ à¾L,ìs ò¼ê±JËK  ²B+9¼jbÅLéƒ¾w Rr�  €ìéG-îS ò¼Õ(�z]  @Vi9°jbÙÒK}ë èÔU  ²¯�5¹×€QãV�‰DÔ<¥2{!!  Ð{Z›•þ©âãÞü½^w ¢Qù)Å  o°59šÒ?‘^êU!·£ÿhTÍ1c  ¼¢³MËvK'W¬èé_èUÀÿ	Å  ¯‰å(ueoþB�; Û]P½u¼S/PJå  ð­uk»¨ÊžvzÜˆ%Õ�)þ  x“­Ñ¹¢/îñ÷÷ä›FŒ«-‰E+   x—©íh��^2­¤vKßÛ£@,Ò9Žâ €·™Q}iN^âÛÒ=
 Jô8  žgBÀ=ü¾Í1®fÇxTÏ  àyvc ­ôö&®ÚÜ÷m±‹è%	  �}vc ¥ÕÙ[ú¾- mþ;ú  þ¡ôYé‹oÆf@åy5‡™1J  €o˜&@eåykößÜ÷lvW?¥…ö?àåEÊÜ"RfnƒvÝÌW’Ÿ£$Ç¼ËsâªëfÇ”äÆ%ýµdJ¤£SK{¢ë¾£ÓÜ't×Í<níÐÒØª¥¦!%kÌmu£¹™ûš- ¼Mëôþ&/¼éöÀ:^ÙY½L)5X d…-ÔÃÊ£2´,"CEe«Òˆlc>R‘Á%]Å¾t@v®ÍUÛ¤Óa º>%ŸÕ¦dùê¤|¶&%+Ö$åSs¿àÓ¤ È-zeU´b¸Ü£ûú&; £“«�£øî^‘í‡ÅdsÛyÛ˜¯0EPDŠ½{áM<JD¥rht“ßS×¬eÉª¤,­IÊGK;åãåI™·¬SV¬N	 g™i€!£“k¾¶@äÙ�}=¶é¿Èê Ól~÷‘qSè£éb?f›®‚ŸŸ#�TbLÉÈ˜ù™crÜ¾¹_|¾¹]ËœÅ�2ß‚�L °áà½…� ³"’´µ|£`£Ã‹Šï­PÒ.Ÿš/ }¢Ì»kûm¢é‚¿{ºÆÓG{uÎðH˜Ûxß�ÙŸ$äýO:™F úKK£9äl3orEãú_Úh ¤-òQšâôÒ;Æåà]rd¯Ñ1ÙuD<°#{'ÄÍLÂ®ÛÅÒ·3ÏK®¹M§ƒÀ¬	yå?òn] W”LiuŠy4uÃ/mDå„êÇÍN ›eü¡»åÈ‘{æÊØÝs<=g«´Ì˜Ý./¾×!¯~Ø!	ò °EZäoU“*NZÿó­®Ñ‘1KkªÍ£A`eEJ¾¾W®|mÏ9p§œô¼>Ü×Ú!éð�Y]� ¡…S��Òzõüm+Ë5j�Õ·€1ãVí)Q5K |a»ÁQ9jïœtá·óùŠ�¾§Øýþ=?!ÏÏê�ÞmOŸ†`-I½×ü©ƒß[ûSŒ]tD�åØHºÐ¹WWÑ½uTà]vaå~;ÄÓ·Ÿ�Q(s–tÊóïv…�ù+XHØÚnî6 LO`¬ !eWéŸvHž½o®.f¹¾_ÙS+ííÒ“
diuJžýw»LŸÙ*Kkè ¤ºjû­ë~jmÌÿ#„bfpôÞ¹rÖù²w%úA¥µ]3��f´ÊKïw*Y°N `þabGøöt³ÓÍOï¥�ð°�€‡^j•G_m“úf"$Ö[°Îp‡ù„�=Wÿœ¯å›¹}NÒ+»õò•§¦o�¿Þ.S_hM¯ ‚lýu ëö;™ÿG@ÙSõN:0O¾ud~zžèvÒ�¹é›ÝdèÞ[åùwÛÓg �³Þ:€/üÌÿ#€ìÕóìhÿÔCòÒûÒ[²²6%¾Ô&½ÜÊô ‚EëÕ­�Ã—=ªZí‡_™ÿG�ì»}<=Ú?rÏöÞGŸ´'Džz³M&>×Ê5	ZE¬šXö†}üÅ óÿ‚ƒw‰Ë%'Ê£XÍ�þÉ�‹œrp^úöòrËc-2—uð9•JíiîÖ Jé=7qi ÀóìÂ¾KN*ä4>8â°ÝrÒ·guÈ­�7ËÇËéÀ§”>ÀüùGûðË€V#ØÞ~cGú?>µPöÀivgH{ˆçþÝ!¿¬Y>YI€¿ØZßýøËá’Ò;Ò€_ì²]L.?¥PÚ™ÂwÙ�ÒÑûä¤oO½Õžv·AÀÒµþó‡ö�ãjKâÑÎZ<®t€’+¿Q(ÿsPä�'ØKO|®EîzºEÚ2¼Á`2jFl9"©-Ê4"æ¿íà…�þI$c¥‹¦–Ö¥; ±XjGálxXÄóÎ>"ßÌóÈÀ|€ðŽ¸9Š~÷¸‚ô>×=Ü”žè�ös@.Õ’ÌÕ¦Ð›b—®ûüMýLè
f×ÞukT’»ZK$Éû›—Äs÷^: ¨”i	ðš�G}¥2&×~{ Wäƒ§m=("··H^Ÿ›�khÚäú€TD¤c�–örs+3å<WzM›Ž@Ò„„uÿfgf"âk´äÕ˜0`nQ.y€�HE•�è
 Zôê?¼fÐ@%?;c€¿Ž�@–¸S\žúuizWÁ;×žJŠ   IDATžh–3BOš#m‡)øm]Å_œÊ²&\$ÊíMKƒÖoÉ­Vé@k MiI¯èZ¨dG<Ä^¤çŠS
¥0�h
ÿ‰›ÞQùrðWrä›«“…yÉtqv“]#ÓYloZš+µä¬°@I¼‘÷Tè©µ€Òv
€²Ï^¤åæŠdO6ò��5ujùÃœ¹ã£i.ðÆ«ŽA"«KÍô@µ–#tB,]óåó  •b
 Yeó§1]|baz6À�:ÌüÄ�[ä¦›eu»÷VVÛ÷Yû`‘¶ò”äªdÀ'¬#[óí½1nÕVñ¨úT€,±WçûÝ„�²Ó¶ŒúáO)Së§Ò&×}Ð$K›}´'€™™(X¦¤`±	ìr*‰¤Þ:‹)NDÖ\|b�\tB� ~Õ�HÉ9¯ÔËÌ•	ñ�¨HËvZÚ¶ÒR2[I¼‰^pXØÚÓZ¶âW·Ù¹þÛ¿W$;3ê‡�-nJÊ)3ëd~ƒ¿·NåŠ¬Ù[KÑG"ù+©a`k,b‚{ ÀM§š'WŸ>@
8»>öÒgrî«õRÛ�ªé4ì¢¥s@×Ù”…`³µ?¦E•(æ à‚’B%×�(Gì‘#€ŸMžß*?z§1=÷4vJ Y ¥øCRÄ€ ²µßô_S%\N³›£Ür~‘”ñZƒ%MÅ·…JU›Y{E×”@Él®=\:/¦U$� œtå©…éSü ?[ÓžJ·ü}¹Ø¯:šŸy_Ó	ø@$§�<& DÌ8À^¹ï®‹ŠÓ{ù~wÛÜ–Ðÿnvq`ãZý[˜¥TIÄŒýKÈ°½FÇä©_•Rü�-i“[ç„së<Û	¨ß‰.qÐØÚ­KØ™tî×óåŠoJŒ‹÷! Þ¨î�_o�0k"ÒÔ¢Ó;" Lí�)Qt �ù9"·\P$_Û“Uþ†eÍI9ó•zió÷iþÑ<RK¬Y$o! T×Y L ÿ¶)‹ÈÄK‹eôÖû­�ZÎx¹Þ“{úg‹�
ˆš™v�ÑJXˆ~±óý�ÿ¢”â�@±mÿêØ æ-^·»–TœPä*/"œ€~8zŸyðÊ).dD€àxjY»<¾´]°¡”©Û üN+Í úî²ÿ)��åB>»ÙÏµ³››f&k¦ü-½�ÙÑ+9&6Þú�"9r/û!x¦/j—9õ¬úÛ’¦‘"¥|ÊÖ~NÒF¯Øýü'ý°XvÁKÁÓ–ÔrÃŒþ{¢£BKG±ÔÓð«ˆ =4h ’G~RBñG`Ù‹ü,nN	z¦iküŒ €\‘GZ*#†°ÒÁTß‘’[æ4z.Qjº&e„ ¿" `‹¶I�ü‡—órApÝ9¯UªÛ(f½ÕLÀ·8¢c³†•wÿ¡e¼T\Zk™bÚÿè={­€Ž"B€qTÇ&m78*�þ¤T†”ð2A°½³ºSV¶1÷ßWíâÈŽ�²sýÓ¯*‘²"Vø"øìÆ?è»¶r: ~D À¶*�ÈWSüO±ë_¿¤
ÍT {‚ù ë( äÁ—¤Wýa`Oû«jdãŸþ¢à?åñ…ùJ¦ý˜Õþ—W0úÏ„ö
€ßp¤GZ^ŽÈ}—s9_„ÏÓÌÿgDg‘™
ˆü„  ‰›š?éÒbÙu;vøC¸4$RòÊÊA(Ó(cÝ�Ÿ  ·¯HöÝ>.@ØÌ^“”gÿeL¢˜'ÓOò…Üµß GìÁUýNœûŸY)%¾B ±‹N(�SÉ ¬Vµ²ú?“ þB ©ÿ> W.>‘wnt 2+™/ð@²k\n?P€°[ÙJ È$: þÂ"À�Ù}dLîü~±DùÍ²Š@f™ãJ’3‰}ƒ2"öŠ~/-–\üit 2Oç
|‚ q3Ùs÷Š¥¤�ót�nKšY˜iI¦|ƒ5 !qý¹e‡aôæ€nmI»;×eë üƒ@œvHžœ°?}9`my&/ä˜iÑ6B•_ðê¸�·�É/Ï  648�C`¦E:˜fô^ýVlæûï¾¸(½×?€ÉçÍ‘Q)Óh§à¬°[¿S$CJÈxÀ¦¡�QªS‰Òt ü‚ Pç�/íÌù~ÀæÉ' dR„++û
 €Æ�ÊO. ›Ç€ÌŠree_! LŽù�Þñý"‰1µ	l€ÌR _! ÌÕ§�‘C¨þ@O° ³è ø¯þ ùêNq9ëp.ïôÔ¥1)Š³h-Sb�<—~B ˆÒJ~ÿ�"Ðs9Q%aëºŒH‰ä®æ@?! Äõã¦C €Þ9rk@&äÔ*‰$9ù	  ŽÙ'Wß�ƒÐÇnÃ{'rª>C ð¹ùJ®a«_ Ï¶.ˆÊÞe¬‡îÓùÏ«øÀç®>­�Ö?ÐOÇcñlÄì ‡ü† àcûn—SáÀô×ñÃ¹ZfäVSüýˆ àSö?7Œ( úoû¢¨TdÿŒ¾Ê«! øÀ§.úïVÎ¯È”«wg-M_”7G$Ö"ð!*ˆ�Þ:*ß=®@ dÎ7¶Ë•�‹éôFÄüo;„N¤_ |è·ßæ8á×_á½Õ§�È“ãwÌ•oŽe-’ |æ¨½sdïJNYœðõ­sä Á\F»'rMõ¸z·®«Ž^vr¡°Ào >7uÿ'§3O	8éç»s)ížøîŽ²Ý€®)“âB%—žÄóæ7 ±óþ[âW8éÀÁ9rì0NÜœ�1%?ÚeÝuHvÀ®O‚PM|Âþ‹N`áà†Ÿ™.@„Žö&]¶‹iùÇ×-Qóáo¾E‡ÒO >ñ“3xcnÙ¥$f¦xÏmÌ¾å1ùÁNùýÚ>câék“À >`wü;ê+\°pÓe¦Å}ò¶³µÍ�ÈÃ‡–H|3í‘«Nc-€_ |àÊSyCÙp×E2<ÎaÒÊ3Óû�Ž-‘²¼Í?vºòì#8-Ðxe{ÜA;Çe�‘œödÃÿj—Ö™Z"mjv¼Ï�E²kiÏŽEW�Þ®ÞF ð¸KOfôdÃÃ¯´ÉÏïk’h»’’÷M	LJhýb�râ¶=Õ.ŽÈ‡Ñð:€‡²+£ º‹·x“’â¹á<-à¿‡ç¦×CôÖwèxÀÃ.?…UÈ€ÛÖ/þÝòV))X®°KI4ÝúïÛøæØ|�w <ê°Ýrd§áÄgÀM›*þÝ.0�€�Lœ[™'3�$ù±¾‡žŽÍ§àa �ºì˜ûÜ´¥âßÍ^û~Ð¿•DZ%�ì~¿ßw Üº_‘äDû×ñHw§àU ²+ÿýîéiñïf×”½­$^/�Rš£ä¯‡—Èø1™+Úç•ŸÞ%ÞÃ¯ÅƒÎ;š-·ô¶øw‹t*)}WIÞgcŠ¢òòÑƒäð­2»éØ�Òˆœ°?*yÀcÆ�¦;  œ××âßMi%Ås"2pž­Å·ŽÝ&GfUúÅÕý2Íî ï! xÌwŽå�¸¡¿ÅmËÍ”À›É©_50**’i‡•lpqŸŒþ¶b`ãEœdî!vÁÌ±ûÒ*œ–Éâß-ÞbæÐß�HG‘–¦ÑZ¥âYÃ#rÕnäŒ‘yséÌF;µùÚœ€-šð9€‡L8:_b¬ýåDñ_[Nƒ’A³”t”hi£¥s xFY®J_Ê÷‚í$Çåþ¯í ì0,*ó–…xKE�a
À#
Íó›‡qºà$§‹ÿÚrêì™‘ô¾±,|·Ê�ÈÕ»Êû'–ËE;º_ü»�wSœ^BÀ#¾96Oò¸â/à˜f´É¯§¹Sü×f÷°·dŽ–¶
‘¡»DdQ*))qÔn¥19f›\9ÚÜ¾R/ìaxâ�¹rãŸ›¥ºÞá=B ðˆ³�`ô8ÅŽü³Qü×íPR¸\¤~¹–ŸŸ<@Fî•g–·Ë³æ¶º½ÿ§ØQý¡CrÒÿ¸á¹24ß›ÞSÉ“;ŸjdÀØ1.CË˜�œàfÛ¿§îx¬E~¤
åÎc»öÙ¯nKÉ²–”,oIš›¹oN¦ÛÏ­0÷Ÿµ¦¤ÔTøm
Ì­0*CÍý°{5÷öóQÙÚÜÇ|p©€w <à´C¹l&à„ûMÛÿ7Ó¼Uü»Ýü×æôýwŽÍ—Š¼Hú¶× à’·1ƒ» ðµ9	Av1ìÌ²Â<%GïÍ©@¦y¹øw³!`ê½¨Àf0èñ@–Ùv§þ™å‡âßíº‡ÃŽÜ+WJ„ëÒÊ^D È²³'	™ä§âß-l!À^"øä¯rìË6@í]“í3ü2Å�Å¿[ØBÀé‡ ²� �E'Ä È”)¦xúµøw³!`JHBÀÈ!QÙc$ëÐ³‰ �%3ýuûþaGþÿûp³�ý9¦½Ô&apì~³‰ �%ïOŸ  üÜöß”kl
E8ž �U€,9v_Úÿ@±øwC¨(ŽÈž£˜È@ØÓþŽÚ›�ÿ�þrñï†À%Ð³‡ �ïœCûè‡ÉÏûÁ_OÙðÄíTGïC È@CâúÌŽü¯$þzÂ®–?d×àv·*�È^£™È€Ëlûÿ¿¾Bûè‹0´ý×f‹ÿô«K¿kÞ1t²‚ à²¯îÄê /&>ž¶¿U94*]üâo ²ƒ à²±»óBzËŽüo|4\mÿ¯,‘AÃ1Xb¦là�» .û:í WÂÖö·…0mÿõ�Ý�c£Û .µUT†”ð”=ÆâÿÐ�ÃWü­C	 ®£¹è0^à@�…µø†s�Ð¾ÛÇ%ŸC¤« .:lw^Ý@OPüÃ'±[¤sŒtÀ%yæu½ÿq°yÿðb�ä.v_p‰M¶Qâ°Yÿp;4Ày%É%_Ý‰6°9Ÿ×yþ;‹Ê4Šÿ:ì®€v±4ÜA pÉ>ÛÓþ6%}žÿŸÃsž¿ù?pE‰”Pü7°ÏŽ•n! ¸ 0WÉöÛ�j��¡í�µ}¥’ àÖ ¸à+cbá½l€â�õ}¥’²ä: .Ø›Dl€â��1$Ê��²� àZZÀºByaŠ�qÌtÀaÊ¼ß÷Í‹èf‹˜.ìCñï=º¦î`²Åa»l“\^Ë@Å=AÀ ‡í5š§°îy¦UnúKxŠÿNÃ£rÿ%RT@ñï-ºƒ) ‡í´-/dÀŽüÃTüíÈÿ¾Ë)þý|:«Ú   IDAT1f(§N;� à°† n´ýÑ;çØé4€ÃväEŒ[ñ·mŠfì°ÇN§ñ;ÈžÏ§‹…�
cñðÊ�OñÏ„í‡qðtÀA;ðFHQüÑ_t œÇ€ƒ˜ÿGQü‘	CË"’ÏETE p aCñG&q•³ Ú‘ €¡ø#ÓD9‹g×!öêÃ+ÈWŠ?œ0rë¨œD pÈð
^¸Š?œ2¬œã¨“ VÎèÁGñ‡“¶! 8Š à: :Š?œÆ€³¦:„Ö‚Œâ7äå×SpÀ!L ¨(þpƒ)çP¥ÂÜU0ÌZÐ)øÅnc0åžY‡+# øÝësrúÿÖÉ¹·ÔK")¡GñG6ÐpÀ91‘²"~öÚœ„œ[ý�¿ó‡z	³»žn	Uñßu»˜Lû1Åß†¢L9…gÖåÅ<­~fGþ¶àw¬ÕýõÃ„œý»u?väÿûÇZ$,ìÈÿ¾Ë‹¥0�âïƒr<u
Ï¬Jð´ú•-þvä¿±BÿÖ¼„Œÿ}¸B md[)À1<³()äàáG›+þÝÂ(þðŽ§Î! 8€Äê?=)þÝÂÂVüw£ø{T	UÇðÌ:`/X_éMñïäÆâßÅ�*ÀïÅ)T*ð‚õ�¾ÿnA·?®ÕþÝÅ¿0—÷¬WÙßM›Ö;‚ à úÃ;óû^ü»)Ü`
¿ aAñ÷�’BŽ©NàYu@) Ï³Å?S…;!ÀÿI¦õ¡«ê€
8ØÓÞþ¸«`·uHÆØÐ½q�ßÜü×pÿ=FÅºÎó§øûFQ¥Ê	<«à°â]vä?áÖÌÿnv=�ß6²#ÿ»ÿ®‘ÿÔ±É�ßà÷å€RZàAÝm'Š7?MÐö‡_ÐUuÀ	 Ïq£øwóC[ñßc$m?Ëç÷æ€¨ÿÞâfñïæåÆ‘ÿTöö÷5¦ œA p@*%ðˆlÿn^´ýáG„7g @Àf/ìÌZñïæ¥@ñ‡_ð;tÀ,Ì>[ü¿}s]V‹7/„ Š?üŒ€3 N  dÕ‡‹»ŠK»xFwÈF ¡øÃïŠ¹" # H$I Ùb‹ÿ97Õ{ªøw³!Àí®Å�À!Õ $Bp­x/ê.þM­Þ=ZÌZàÞÔÅAäKogÀt Üç‡âß­;4·;÷o¥ø#H::9¦:� à€Ž„ÀE~*þÝløÖïê	¿žÖDñG  œA p  ÷ø±øwû`QæC€-þÌh“° ø‡S Î  8€€;æ-Kú¶øwËd ø#¨:ªœ@ p  çÙâöïê|]ü»u‡€þü, g ÀY Îê.þõÍÁ	Z6œucßÅAÇ g ÐN»Ê1é¶ÀŠ·¹Km°©—†–žÿl×NoUñO_Õ�â:íS�@ p@c ÚÒ^Ô=ò¯`ñï6gIg:àô¤`Gþ÷¾žÕþ{�þüª~ÿÐijã˜ê€j›¸`¦­ªOÉ·n
æÈ}¶ðÍ6ÿ³þ&dm[üïýQ	Å?¤j	 N  8 EÊmƒ‹#rô>¹¶Û±©ð³{›äþÿ¼AH1¨rÀ¼X�ñ«³È7ÇæIXT­Ø0ØâÿÈ?)þ—ÚfŽ©N  8€ àœ°†€Ú&MñGh1àŒ˜ ãV7ðbu’ÊLO{)ÅÐ†€#¯^ªÅ¥tÓš…ÕN¡à� lPãe×œ®N Åaµ†Ñ¿c ©e! ãÂ6¬�)Uç ²¦�­l8ópB@ì3&.÷]NñÇºV7r,u
À!+Ö$îÛt@Ù‘ÿäKn\€u¬XM p
‹ ²¼†­›l'ÀzhfxVÉmlÎ²SN! 8d)/Z×ü‡â�-! 8‡ à�å¼h³‚àôÄ2º©Ž! 8„mö¼�â�žZZÍ`Ê),tÈòÕÉôÈNô.Š?z*iÆQŸÕ2˜r
À!í	‘NÌ*B€÷PüÑÌÿ;‹ à åœ¾’u„ ï ø£·˜JuÀA?#½z! û(þèŽ¡Î" 8èãe�o dÅ}5o)ÇP'q€ƒæ <…³ÜGñGpuÀA¼x½‡àžývˆËÄKŠ)þè³yË9†:‰) Õ4h©ãª€žÃt€ólñ·{ûSüÑWKV¥¤­Cà €Ã>bË“Îé.þ9ôÑŒþ�G p½‹�yd
S¨Îãmê°yË9�ÅËX�9dg 8�·ªÃ˜ð>”™ö! ¯Ø1.÷]^,@¦ÌáØé8¦ 6×¼ˆYÈâ}×œÅt@_¥Wû_JñGæÔ6iYZÍ.€N# 8¬ÓÌ |°(!ð>Öôm8á�ù3Ý@ pÁ»U´²ü‚Ðs8åÝ*€ .àÅì/„€-£øÃIÿ¦à
Þ¾.xëc^Ì~ÃÙ›Fñ‡“º¦Méšº�€šÛ´,ø”Óý†NÀ†(þpÚ{’dýŸ+ .aÀŸ_¢øÃ¬™rÀ%¬jõ/Î<<Ü!Àžç?éRŠ?œ÷S¦®áíì’ÍåEígvŸ ­Ã¹& û<Š?œf[ÿoÌcã·ÐpÉÊÚ”Ì[Æ: ?ãt m¸éÍy	6NsÀE/À+ÛïÂ(þpÛËïsŒtÀE€`C ø#8Fº‹ à"»¹EK»  ‚(þÈ†•u)YøÓ¤n" ¸(¥EþùnP1´3ÅÙñÂ»ÝF pÙLZ\�¤`‹ÿ=—Pü‘´ÿÝÇ[Ýe¯ð"”™ö’O<d×®óü�lhOˆ¼>—c£Ûè ¸¬º>%³°ÓUÐØ}üÚ	°#ÿ?þ€â�ì±�Ñ‹®# dÁ3ï°0ˆü8ÐÝö�GÈšgÞæ˜˜€,àÅ\~Ú6˜â/°ÿüã=Ž‰Ù@ È{ºÓ Áå‡é »·?Å^0óýŽô ¸� �%§h^ž°ÅÿOxÄßß	ßõ5¼‚ �%O¿Å‹>è¼º‹n\€¬³íÿ—f³ú?[ YRÓ ¹îux)ì]£øÃSfÌn§ýŸE€,ú;g„‚î3&.“/+¡øÃSž~‹c`6 ²èÉ7Ú$ÁÖ×¡�Í…�vä?é‡Å’Ÿ#€gÔ6iÓ ýŸM€,²o€g‘€Ã"Ó¶øÛ‘?Å^óØ¿Ú$™d Ëy…Å€aâfØc$ÅÞ5mf« » YöÚœ„,_M7B€-þS/§íozûã„,YÅq/Û ðè?é„�“! »øæ*¼èŽyž@ ð  RZ2N„ Š?¼®©U³šG <À^!ðå÷YF™øÁc¯·K‚-P<� àÓYZ™Ø'`·1¹÷òŠ?<oÚK,þó
€GØí0—Ö°(&¬ú³OÀÎÛš‘ÿ�Š¥ W O{õÃ„,ø”ÍO¼‚ à!÷ü½E^}™°Åÿþ+Še`>#xßÄg9Æy	ÀCþúZ›Ô7³0Ìz(þð“�—'å_sÙøßK b·žú"óca×“°ý6QŠ?|å�t8=‡ à1÷ÿ£5}‰L„ÛæB€-þ\YBñ‡o¬¬KÉ3œúç9 �ihÑò—×8# ÝÅ¿¤�âÿ˜ô\+ûþ{Àƒ&=×ÂÆ@H[;PüáGÍmZbßOŠ	<gYMJž|£]N<�óºÐ¶‘ÓÍ§øÃw&šÑ;kÿ<‰€GýáoÍ´Ìð…�-�ÒøK]³–ÉÏ±øÏ« e7úó«¬ à_wÿ½EZYÔìY û¿'[Ø3€/Õ4èôYMð.€‡}V›’i,žàC·?Ñ,`<� àq¶À ~b/¿Ì¦× <Î.¢™ò‹h øÇ-mæTf  øÀ=Ï´¦ƒ  xÝGË’òøëìúç hjÕrÇt xßo¦5	ü� àÌh•Å«¸Ž6 ïziv‡¼ý1‹–ü‚ àv>íº‡› ¼Èn\víÃŒþý„ à#6]¿5�tÀ{4]Ê%«Ø¾ÔO >óËšD³€‡Ô7kùë”|‡ à3>MÊ£lÀCn²%})søÀ‡~ÿX³´p– °ƒ’û^dÇR?" øÐê-×?Âb ÙwÕäF�? |júËm2kmÈ{šý	Ç!¿" ø˜MÞ�l  jèDúÀÇ>Y™”?þ�•· ÜwÍ�¬Eò9€ÏÝõt‹,üŒ6  ÷Ø=Iž·Cào ŸKt²€{šÛµüä^Ž9A@ €÷v¦ã €Ónx¤9}&ü� ÿûp“,­fN ÎymN‚ÁF€ ¢ÕLÇýà®†ôEƒ  Ój›´\vOƒ 8 2gI§ÜÎ~Ü ðÃ»Ò! ÁA ˜;Ÿj‘³1€Ìyhf›ük.W"@ÀØ+^l¦8?@&,­IÉµÓÙð'ˆ dß°¿yˆ7,€þ±;�^tgƒtÐT$@@ýåÕ6yê-Ú  úîÆ?7ËÜ%Tÿ " Ø�'7Ê¼eì ÷ž~»]¦¾Àe~ƒŒ `v—ÀþP/uÍ¬ÜÐsöŒ¢+'±Û_Ð îÓ5)ùþÿ5H’=‚ ôÀšF-çßÖ�@ Ø !ðöÇ	ùõ4Ø¼D²«kX]Ïˆ! !aÏãµ`S~vo£¼ÿ	Cÿ°  „ÈÕS›äÝ*ÞÜ 6tï‹­òØ¿8s(L !cÛ{ËjhïøÒÌ:äº‡›áB ™†-çÞR/õœ À°§
ÿàÎ†ô.¢@-^•”óo«O/ø^+kS2î–:ig›ÿP" „Ô{;Ó'{½�oß\/«ú‡ Äžz³]îx’Ëac÷ùÞõ²ð3Ú€aF ¹?ü­Ež|“•¿@˜\ó@—÷ ’ÞòóÕ9 apëã-òð+ì	 ¤«xáíõì Üý3ÚäÎ§˜öC Òìõ¾'ü¾^æ.eN¢Ç_o—ß°%8ÖB ÀšÛµ|û¦:ùd%! ’fupÖ6@ À:ì¥ƒÏ¹±^–V³[ v—¿‹ïb£lˆ €¬ªOÉ·L'`W|í­y	¹ˆË�c Ø¨å«Srêµu²”+¯©   IDATë ¾dÏì9÷÷õéõ=ÀÆ °IŸ®±! V>ZÆš ÀOžz«½k»oŠ?6ƒ €ÍZÓ¨å›××¥·à}öÿËîi¤í�-" `‹šÛ´œó»:yùƒà]vgÏŸßÇ©~è zÄ^-ìÂÛä™wØ6ð»Âÿg÷6qmô
 =f[Š—ü±Q˜Á6¢€—\zw£<òOÞ—è zí×Óšä¦¿4s^1�evzî¬ëéÌ¡O"Z4¯ôÚ=Ï´Ê%w7H‚€¬¨®OÉ©×ÕÉÛs!/ôž­ý¶P'@<ûN‡Œ»¹>=
àžù+’ò?¿­“ª$pôY�	 Š‰#ô™}ØQH5»®°»û�vm�¬¬å=‡þPm¥… €~±£�SÌhdÁ§ŒF '=õf»œý»úô…»€þ°µŸ) dÄgf4ò?¿©•¼Ç^@¦ušl}ý#ÍrÙŸ¸¢2¦Î.$  #ZMíÿîrÝÃÍé€þ³ÓkgÝX'“Ÿo Slí�ˆb 2kê­é–ÝF@ß½[Õ)Çÿ²Vf-`+nd˜Rv k �yö€uü/×¤` zoÒs­ræuRÛD�Fæ)ÑmÅ 8¤¦AË××¥d z¦©U§·Ý¾áÑfIQûáÕÑš5 p–=�}ûæzYÝÀÑØÛ1;æçµ2c6‹iá,[ûÍ@„  Ç½>7alkä•ÿ°k°>»höÖÇ[ä›¦å¿²Žóûá†ˆ š5 pE]³–ón­—_>Ð$mp€´¥Õ)9åÚ:¹ó©®¯×({€b \öÐÌ69ášZ™·Œsn�þ³MŽûå™»„Å²p›j‹¤Td‘ .[¼*™ü;×/GøØ•ývÏŒŸÞK7Ù‘Rê35b\íˆx´ó²d§áQ¹å‚"½uT€ {ì_íríô&ih¡ß�ìI$c#•œª£•kÚ•Ž¾Èš˜yõ]pL�|ÿø‰Ç»]öåÍy,„E¶é¦ù%yT%•H• YdWAÛEPÇþ¢V>XÄ|(‚Ã.ì»F›õÓ5xƒ–¶öGÒ�•|$€ØµöÊ‚¿�Þœ¾¶ àg‹V&å´ÿ­“ßLkâõÏÐJ-²÷‘®�4 žrß‹­òõ«×Èã¯·sj|ÇÎïÛ«÷ÙŽÖì…t´à1Ÿ×üt P! ÀsVÕ§äÊI�rÒ¯9ˆÂÉ®ðzÄUkÒWïãª˜ð¢îšŸ^n¥#ê#Å05wiRN½®NŽÜ+G®üF¡ŒÂzUxÏ³:Ì¨¿)½±àe¶æÛût èìŒ|�ò¢…·½h°3ßï�3Ï—‹N(�’B%@¶ÙM|~eæø¹ò%üÂÖ|{ÿÅ´rBu�ù X (ÌSrÞQù2îëùéÇ€ÛªV$åO4Ë³ï°ºþ¡E¯¬š4x+ûø‹3®•–�LØ_ hnÓrÛßZdª™o=ï¨9çkùR�+€ã~–”;žl‘§ÞlÀw´úbÍß—[®(»*P à+õÍZnþk³L~¾%½‘ÐYfz /G€Œ[²*e
³<ñF»¤X2ŸRJ/ê~é~ µzO Ÿ²{«ßðh³|íê5éMW€LYV“’«¦4Ê‘?é:-•â?[»Ö1y:fÜª=%ªf	 v� ]`;Å,DØÅ}z¶Už~›½(ZE¬šXö†}üå‘ñ³´¦Ú<$@@Øé€3Ë—ñÿ•/[•FØ’ÍMÈŸži‘×æ°m/‚ÅÙº¶Æò¡ËU­öãu†F•ª7Ÿ8Q€€‰šÚÿßäÊyGÈ˜¡ì#€u%S"Ïý»=}=Š�—³{‚É4²þV5©â¤î�cë}u¦‰ Ž=ÀÛË°ÚÛ¡»Æå”ƒóä˜}8m ìÖ4jùó«m2ýåÖô\?dJË³ë|¼ö¬@˜”PròWóäÔCòdôÖtÂÂnÏk7”²…ßÞ³¨a‘HÆF.šZº¨ûãuWG± !µç¨X:»_®æ²h0ˆìùû¶èÿõµ¶ôÈóŠ_lÚÿ#ÖþÜG:Ö ÌìfBGí�+'ìŸ'ïø›==ôé·Úå©·ÚØª!§ï�?ið¸µ?Ûð{X€ðjiÿr­€�"8zreïÊ¸(¾ÐØªå…w;äÉ7Ûäõ¹	Zü€¥#3×ÿÔ‡4Ö ²§g¦Ž7·]¶‹	¼¥µCä¥ÙíéÑþÌ:$Á`XÇúóÿÖ†cÖ ›5¸8"cwÏ‘CvË‘¯î—�ù´²aÁ§Iùç:äÕ;ä��ÒAÑ6jcóÿÖF�\¬ z&bÞ({ŽŽÉ!»äÈÁ»æÈn#béÏ!óZtº¥o‹¾]½¿ªžÓö€žÙpþßÚh/Siõ¸ùƒ  l��_¶‹ËìÍ^�Ðv4]�ý¶�Ëþ;æÈÃ8½°¯ìÿmž×w>NÈ›ó:dÖ†ø@ŸldþßÚèXe‡ñÕM¶^n¾:P ôYaž’ývˆË¾ÛwÝvÙ6&12ÁFÙûo›bß}›»´“=ø�~ÓMu¹²uõ�ƒ›ÖÿÊ&›•f`ºùâé crã"{�Ž§ŽÙ&&;šÁÎÛ†oQaµißÏ[–LùùË;eÎ’N¶à±ñö¿µÉ#�e€&  Ôž�ô‚5{[›Ý‰ÐÞlØaXL¶•­Ë"¾ß”he]J–×¤dág�é‚?oYW±·óù œ—’èôM}mÓG—t¼2Y½T‰" ²¢¨@ÉÐA\‘áQZf‚�ùxˆù¸¢8"eE‘¬�…`á­nÐ²ª.)Ÿ®I¥o+Ö$eÅjû8ÉÞú@–i­WUÅ*†É=j£—¶ÜtïÑü=¡Æv. YaGÊ-Iùh™m�oúò´vŸÊªÏï#’oºö–cÞå91e¦Ìãx×cû¹ü•¾HR{§–óŸîHèô©tíé{�îV´vh©kJIMC*½}îjs¿º1%õÍŒà¯Ó*òÐ¦Š¿µÙÉG¥Ôt! €Ç}V›Jß  [º†oîë²YZUN¨þØLT
  ð­ÎŸ\Q™¾ð&D6ÿ_0Q«  ø†uÿæŠ¿µ…  Ò™Ú|  x‡¶Cw‰ß·¥ïÛb X4µü#ó_›-  ÀóÌÜþ[ó'—,ÜÒ÷m1 X¦•0U  €ç™¾�:÷=
 mñ{µÖ­  <Ë´ÿë:S±©=ùÞ€%ÓJjµŠÜ#  ÀÃôÝ‹¦–Öõä;{ ¬­o¤  €7Ù�ˆ©Ûzúý= K'W¬PJmqU!  pŸ­Ñ‹ï©ø´§ßßã `%#r‹¹ã¢Ü  xKg2©oîÍ_èU Xø§Š�µÈ_  x†­Í§žß›¿Ó« `¥´Üd7  �uéšœ’¥—z N®xÇüïž  �}Jž¨šRñ®ôR¯@×ßR×  È>éSMVÒGcÆW¿aþöþ  ²Â´ÿ_®š\1Vú o #¥è  �Mº�£«Ï kÌ„êÍÝ×  ¸ÊŒþ_2£ÿ#¤�úÜ°Iu‘ù$  ¸ÆÖ^S|¿+ýÐ¯ `/¬•ºC  €klíýdrÅ<é‡~ +¦õÏMY*  Àq¶æÚÚ+ýÔï 0orE£Vr¥   ÇÙškk¯ôS¿®��  8«¿ÿÖÖï@·ô‚@Ñí  2ÎÖØþ.ü[[Æ€]hþu·
  È<Scû»ðom VTÔµ,  ³lmµ5V2(£€�  džVêâL,ü[[Æ®��  d†Öú¹ªÉƒ�–Ëh [";Ï´+ê  ô™­¥�©ø…â GÀ¢©¥‹´¨ñ  úN«q¶¦Š	 Ö‚Éå�¥DÝ&   ×l­šRþ7qˆcÀÊm(³ß  ÐsZÞ^-»Bäh ˜ó¨êH$c§kÑ-  ¶ÈÎû'R±Óä•9 ,;w¡täû  ¶H+ù®Sóþks< Xó'—O5?Ò½  6Cß»`RÅtq�+ÀjŽV|O‹|(  `¦õ?ÇÖJq‰k`Å=ªE"Ö  °žtmÔ‘SÓµÒ%® «êOe²  €uÙÚX5¥lŽ¸ÈÕ `Ùõ ì  @[»ÖÊ¹Ëõ `-^v™™ëxB  1[mM”,päb@=1bœÎ‹EjžVJŽ  BÆÿ�©òãMUm’Yé XöŽŠœ¤µþ�  "¶öÙ˜­âoe­Ðmøøê¡y"o›ÉP  à´èíZºtrÅ
É¢¬u ºÙ' ¥¢G™8´Z  2[ë:sŽÊvñ·² ¬“ý§SEŽ5-‘¬µB  p’­q¶ÖUÝ[²@<ÀÀúdRù[fFâtmÏˆ   X:m�ëªuÞà™ `UM®xB´ºX  �Rç¦kœ‡x* XU“ËÿOkù•   ¶¦UM)@<&ëglÊèñÕç›ÜÝJy÷ß À¦˜Â¯Eéóª&ž,äéâ:zBõJôT“r  Ÿ0µ¿ÝÜ�cŠÿ£âQž]›NÀáæùWÓ	(  <N‹ÔKJN¬šRñ²x˜/Úë£Æ­Ù-é|Q)5X  ð(­uµD£‡Û«ßŠÇynàÆ,œ:è­ä ÓR©  <Èîð'ÉœýPü-_-°}NãàHNÛ“æá~ €Gh-ïˆÎ;¶jÊÀjñ	ß­°rŽ.¯yR)9\  È2Óö¦%Vñ�÷¨ñ_L¬måýªY
Ë�1½–é @™¶ÿ£U�'ø­ø[>>Ç^«ÑçVÿD)õ+Óˆ
  .1-ÿ¤) ¿š?¹ü·¦”jñ!ßo²Synõa¦�qŸùA¶  fŠÿÒ”è3NüªøX vÙ6¡~PžnÀtŽ  bæûŸïhË9cÉ´’Zñ¹ m³Ë”  À1	ÓçÿqÕ¤ò[ýÚò__àöÙgJ  �I¶å¯#rò‚‰ÿ– 	ä…v˜  dB�Zþëð•ö˜  ôYàZþëü¥v™  ôFP[þë| H«c•£V_.*õs%ª@  X�Ýbþ¸¶jaÅ�2SuJÀ…# |nô¹«‡+•ºÉL	œ&  |ÎŒúÑ:rù‚)eK%$B º�>·æ¥ôí&ì, €Ð2…ŽÖê¦”Ï��	e HcZ  BËþs÷Ëª…åw„¡Ý¿1á ŸcZ  ÂÅ¶û;Sú’ES&!ú Ð�i ¶0·û7† °¶Su´r`Íæeòc¥Ôn ð=­õ¢#7V5•=$�ª¤ � °	cÎ­>^GôUJÔA ð3â7#ýÈU“Ëžl€ °•ç­>ü@  `IDAT@éäZÔIæÉŠ À³´HJiý7­ä7U“Ïl ‡FOXU©´Ø­…Ï6Æ à%	3ä0¥äÚ“W	¶ˆ ÐKÃÇWÍ}±yê¾«”	  kìé|f´ÿÇ-·-�\±BÐc€>ª<ku‘ä%¿o^¢D €k´è•æ�?H{ôŽªË½F È€íÎ«™£;Î­Î2ÏèŽ È<-óÌŸvDâ,žXò‰ _ 6æÜšýu$u¶y¡ž®”ª @|ªE¦›6ÿƒA¿:ŸÛ N«c£G¯9RéÔÙJôI¢T¡  ¶ÈÎë›ãæ_“ypá¶e3ä•dÀ#Æé¼h¤æÀˆRGh�:Âtö3ŸŽ	 ÀêÔZ¿­TdF*%3’ºì_‹¦ª6�£ YPñ½UŠÚä�t ùšùÔì1  ,ì¹úæn¶y0#Ñ3sä•ê;7	\E ð€aêåéö#UºC ¦C c ‚e®å›‚™Ñ¡ã3—M*^#È*€Už¿zI¥Ô¢vU:µ½ù5U
 ø…ÈÌ7Viù8’JÍ–hä�ùËç
<… à§êèˆÂºá‘H²2*ºÒ´Ð*Ígm(0÷z”éä	 ¸ÀŒäÍü¼ZhV¥oZU©¨ªê�hÕâúâ%\pÇ 1rBív1Il—’È óa±IÝÅ¢T±	
%öcó–-V¢Ò�µ2k]bBÃ`j¦˜¯2ÇŠ:¥¥Þ|X¯E×™Ò�~l
D�ù†zÓ¶¯W)©S‘Tm§Ä2©t±À÷þ  ÿÿO<   IDAT Ïx&Úgv8    IEND®B`‚(function () {
  'use strict'
  document.addEventListener('mouseup', () => {
    const selection = window.getSelection().toString().trim()
    if (!selection || selection.length > 200) return
    // å®žé™…æ‰©å±•ä¸­åº”è°ƒç”¨ç¿»è¯‘ APIï¼Œè¿™é‡Œä»…å�šæ¼”ç¤º
    console.log('[æ™ºç‹�åˆ’è¯�ç¿»è¯‘] é€‰ä¸­æ–‡æœ¬:', selection)
  })
})()
<svg width="128" height="128" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="24" height="24" rx="4" fill="#2563EB"/>
  <path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z" fill="white"/>
</svg>
{
  "manifest_version": 3,
  "id": "zhihu-translator",
  "name": "æ™ºç‹�åˆ’è¯�ç¿»è¯‘",
  "version": "1.0.0",
  "description": "é€‰ä¸­æ–‡å­—å�Žå¿«é€Ÿç¿»è¯‘ï¼Œæ”¯æŒ�å¸¸è§�è¯­è¨€ã€‚",
  "permissions": ["activeTab", "scripting", "storage"],
  "host_permissions": ["<all_urls>"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ],
  "icons": {
    "16": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  }
}
<svg width="128" height="128" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="24" height="24" rx="4" fill="#10B981"/>
  <path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 13c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" fill="white"/>
</svg>
{
  "manifest_version": 3,
  "id": "zhihu-screenshot",
  "name": "æ™ºç‹�ç½‘é¡µæˆªå›¾",
  "version": "1.0.0",
  "description": "æˆªå�–å½“å‰�ç½‘é¡µå�¯è§�åŒºåŸŸï¼Œä¿�å­˜ä¸ºå›¾ç‰‡ã€‚",
  "permissions": ["activeTab", "scripting"],
  "host_permissions": ["<all_urls>"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon.png",
      "48": "icon.png",
      "128": "icon.png"
    }
  },
  "icons": {
    "16": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { width: 160px; padding: 12px; font-family: sans-serif; }
    button { width: 100%; padding: 8px; background: #2563eb; color: white; border: none; border-radius: 6px; cursor: pointer; }
    button:hover { background: #1d4ed8; }
  </style>
</head>
<body>
  <button id="capture">æˆªå�–å�¯è§�åŒºåŸŸ</button>
  <script src="popup.js"></script>
</body>
</html>
document.getElementById('capture').addEventListener('click', () => {
  // å®žé™…å®žçŽ°ä¸­åº”é€šè¿‡ chrome.tabs.captureVisibleTab æˆªå›¾
  alert('æˆªå›¾åŠŸèƒ½éœ€åœ¨æµ�è§ˆå™¨çŽ¯å¢ƒä¸­è°ƒç”¨ chrome.tabs.captureVisibleTab')
})
(function () {
  'use strict'
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    const style = document.createElement('style')
    style.textContent = `
      html { filter: invert(1) hue-rotate(180deg) !important; }
      img, video, iframe, canvas, svg { filter: invert(1) hue-rotate(180deg) !important; }
    `
    document.documentElement.appendChild(style)
  }
})()
<svg width="128" height="128" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="24" height="24" rx="4" fill="#4B5563"/>
  <path d="M12 3a9 9 0 109 9c0-.46-.04-.92-.1-1.36a5.389 5.389 0 01-4.4 2.26 5.403 5.403 0 01-3.14-9.8c-.44-.06-.9-.1-1.36-.1z" fill="white"/>
</svg>
{
  "manifest_version": 3,
  "id": "zhihu-dark-mode",
  "name": "æ™ºç‹�æš—è‰²æ¨¡å¼�",
  "version": "1.0.0",
  "description": "ä¸ºæœªé€‚é…�æš—è‰²æ¨¡å¼�çš„ç½‘ç«™å¼ºåˆ¶å�¯ç”¨æš—è‰²ä¸»é¢˜ã€‚",
  "permissions": ["activeTab", "scripting"],
  "host_permissions": ["<all_urls>"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ],
  "icons": {
    "16": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  }
}
<svg width="128" height="128" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="24" height="24" rx="4" fill="#EF4444"/>
  <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z" fill="white"/>
</svg>
{
  "manifest_version": 3,
  "id": "zhihu-ad-blocker",
  "name": "æ™ºç‹�å¹¿å‘Šæ‹¦æˆª",
  "version": "1.0.0",
  "description": "å†…ç½®åŸºç¡€å¹¿å‘Šæ‹¦æˆªè§„åˆ™ï¼Œæ��å�‡ç½‘é¡µæµ�è§ˆä½“éªŒã€‚",
  "permissions": ["declarativeNetRequest", "activeTab"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules.json"
      }
    ]
  },
  "icons": {
    "16": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  }
}
[
  {
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "*://*.googleadservices.com/*",
      "resourceTypes": ["script", "image", "xmlhttprequest"]
    }
  },
  {
    "id": 2,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "*://*.doubleclick.net/*",
      "resourceTypes": ["script", "image", "xmlhttprequest"]
    }
  }
]
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';">
    <title>æ™ºç‹�æµ�è§ˆå™¨</title>
    <script type="module" crossorigin src="./assets/main-BrdiVs7r.js"></script>
    <link rel="stylesheet" crossorigin href="./assets/main-CPnYvJoG.css">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
function Yc(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const l in r)if(l!=="default"&&!(l in e)){const o=Object.getOwnPropertyDescriptor(r,l);o&&Object.defineProperty(e,l,o.get?o:{enumerable:!0,get:()=>r[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const o of l)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(l){const o={};return l.integrity&&(o.integrity=l.integrity),l.referrerPolicy&&(o.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?o.credentials="include":l.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(l){if(l.ep)return;l.ep=!0;const o=n(l);fetch(l.href,o)}})();function Su(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Cu={exports:{}},ml={},Eu={exports:{}},D={};/**
 * @license React
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var sr=Symbol.for("react.element"),Xc=Symbol.for("react.portal"),Zc=Symbol.for("react.fragment"),Jc=Symbol.for("react.strict_mode"),qc=Symbol.for("react.profiler"),ed=Symbol.for("react.provider"),td=Symbol.for("react.context"),nd=Symbol.for("react.forward_ref"),rd=Symbol.for("react.suspense"),ld=Symbol.for("react.memo"),od=Symbol.for("react.lazy"),ts=Symbol.iterator;function id(e){return e===null||typeof e!="object"?null:(e=ts&&e[ts]||e["@@iterator"],typeof e=="function"?e:null)}var ju={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Nu=Object.assign,Pu={};function vn(e,t,n){this.props=e,this.context=t,this.refs=Pu,this.updater=n||ju}vn.prototype.isReactComponent={};vn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};vn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _u(){}_u.prototype=vn.prototype;function li(e,t,n){this.props=e,this.context=t,this.refs=Pu,this.updater=n||ju}var oi=li.prototype=new _u;oi.constructor=li;Nu(oi,vn.prototype);oi.isPureReactComponent=!0;var ns=Array.isArray,zu=Object.prototype.hasOwnProperty,ii={current:null},Iu={key:!0,ref:!0,__self:!0,__source:!0};function Lu(e,t,n){var r,l={},o=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(o=""+t.key),t)zu.call(t,r)&&!Iu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1<u){for(var s=Array(u),c=0;c<u;c++)s[c]=arguments[c+2];l.children=s}if(e&&e.defaultProps)for(r in u=e.defaultProps,u)l[r]===void 0&&(l[r]=u[r]);return{$$typeof:sr,type:e,key:o,ref:i,props:l,_owner:ii.current}}function sd(e,t){return{$$typeof:sr,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function si(e){return typeof e=="object"&&e!==null&&e.$$typeof===sr}function ud(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var rs=/\/+/g;function Dl(e,t){return typeof e=="object"&&e!==null&&e.key!=null?ud(""+e.key):t.toString(36)}function Lr(e,t,n,r,l){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var i=!1;if(e===null)i=!0;else switch(o){case"string":case"number":i=!0;break;case"object":switch(e.$$typeof){case sr:case Xc:i=!0}}if(i)return i=e,l=l(i),e=r===""?"."+Dl(i,0):r,ns(l)?(n="",e!=null&&(n=e.replace(rs,"$&/")+"/"),Lr(l,t,n,"",function(c){return c})):l!=null&&(si(l)&&(l=sd(l,n+(!l.key||i&&i.key===l.key?"":(""+l.key).replace(rs,"$&/")+"/")+e)),t.push(l)),1;if(i=0,r=r===""?".":r+":",ns(e))for(var u=0;u<e.length;u++){o=e[u];var s=r+Dl(o,u);i+=Lr(o,t,n,s,l)}else if(s=id(e),typeof s=="function")for(e=s.call(e),u=0;!(o=e.next()).done;)o=o.value,s=r+Dl(o,u++),i+=Lr(o,t,n,s,l);else if(o==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return i}function hr(e,t,n){if(e==null)return e;var r=[],l=0;return Lr(e,r,"","",function(o){return t.call(n,o,l++)}),r}function ad(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ce={current:null},Tr={transition:null},cd={ReactCurrentDispatcher:ce,ReactCurrentBatchConfig:Tr,ReactCurrentOwner:ii};function Tu(){throw Error("act(...) is not supported in production builds of React.")}D.Children={map:hr,forEach:function(e,t,n){hr(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return hr(e,function(){t++}),t},toArray:function(e){return hr(e,function(t){return t})||[]},only:function(e){if(!si(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};D.Component=vn;D.Fragment=Zc;D.Profiler=qc;D.PureComponent=li;D.StrictMode=Jc;D.Suspense=rd;D.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=cd;D.act=Tu;D.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Nu({},e.props),l=e.key,o=e.ref,i=e._owner;if(t!=null){if(t.ref!==void 0&&(o=t.ref,i=ii.current),t.key!==void 0&&(l=""+t.key),e.type&&e.type.defaultProps)var u=e.type.defaultProps;for(s in t)zu.call(t,s)&&!Iu.hasOwnProperty(s)&&(r[s]=t[s]===void 0&&u!==void 0?u[s]:t[s])}var s=arguments.length-2;if(s===1)r.children=n;else if(1<s){u=Array(s);for(var c=0;c<s;c++)u[c]=arguments[c+2];r.children=u}return{$$typeof:sr,type:e.type,key:l,ref:o,props:r,_owner:i}};D.createContext=function(e){return e={$$typeof:td,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:ed,_context:e},e.Consumer=e};D.createElement=Lu;D.createFactory=function(e){var t=Lu.bind(null,e);return t.type=e,t};D.createRef=function(){return{current:null}};D.forwardRef=function(e){return{$$typeof:nd,render:e}};D.isValidElement=si;D.lazy=function(e){return{$$typeof:od,_payload:{_status:-1,_result:e},_init:ad}};D.memo=function(e,t){return{$$typeof:ld,type:e,compare:t===void 0?null:t}};D.startTransition=function(e){var t=Tr.transition;Tr.transition={};try{e()}finally{Tr.transition=t}};D.unstable_act=Tu;D.useCallback=function(e,t){return ce.current.useCallback(e,t)};D.useContext=function(e){return ce.current.useContext(e)};D.useDebugValue=function(){};D.useDeferredValue=function(e){return ce.current.useDeferredValue(e)};D.useEffect=function(e,t){return ce.current.useEffect(e,t)};D.useId=function(){return ce.current.useId()};D.useImperativeHandle=function(e,t,n){return ce.current.useImperativeHandle(e,t,n)};D.useInsertionEffect=function(e,t){return ce.current.useInsertionEffect(e,t)};D.useLayoutEffect=function(e,t){return ce.current.useLayoutEffect(e,t)};D.useMemo=function(e,t){return ce.current.useMemo(e,t)};D.useReducer=function(e,t,n){return ce.current.useReducer(e,t,n)};D.useRef=function(e){return ce.current.useRef(e)};D.useState=function(e){return ce.current.useState(e)};D.useSyncExternalStore=function(e,t,n){return ce.current.useSyncExternalStore(e,t,n)};D.useTransition=function(){return ce.current.useTransition()};D.version="18.3.1";Eu.exports=D;var S=Eu.exports;const ui=Su(S),dd=Yc({__proto__:null,default:ui},[S]);/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var fd=S,pd=Symbol.for("react.element"),hd=Symbol.for("react.fragment"),md=Object.prototype.hasOwnProperty,gd=fd.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,vd={key:!0,ref:!0,__self:!0,__source:!0};function Ru(e,t,n){var r,l={},o=null,i=null;n!==void 0&&(o=""+n),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)md.call(t,r)&&!vd.hasOwnProperty(r)&&(l[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)l[r]===void 0&&(l[r]=t[r]);return{$$typeof:pd,type:e,key:o,ref:i,props:l,_owner:gd.current}}ml.Fragment=hd;ml.jsx=Ru;ml.jsxs=Ru;Cu.exports=ml;var a=Cu.exports,uo={},Du={exports:{}},Ee={},Mu={exports:{}},Au={};/**
 * @license React
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */(function(e){function t(j,L){var I=j.length;j.push(L);e:for(;0<I;){var T=I-1>>>1,M=j[T];if(0<l(M,L))j[T]=L,j[I]=M,I=T;else break e}}function n(j){return j.length===0?null:j[0]}function r(j){if(j.length===0)return null;var L=j[0],I=j.pop();if(I!==L){j[0]=I;e:for(var T=0,M=j.length,Nt=M>>>1;T<Nt;){var xe=2*(T+1)-1,Ne=j[xe],re=xe+1,pr=j[re];if(0>l(Ne,I))re<M&&0>l(pr,Ne)?(j[T]=pr,j[re]=I,T=re):(j[T]=Ne,j[xe]=I,T=xe);else if(re<M&&0>l(pr,I))j[T]=pr,j[re]=I,T=re;else break e}}return L}function l(j,L){var I=j.sortIndex-L.sortIndex;return I!==0?I:j.id-L.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var i=Date,u=i.now();e.unstable_now=function(){return i.now()-u}}var s=[],c=[],m=1,f=null,p=3,y=!1,v=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,h=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(j){for(var L=n(c);L!==null;){if(L.callback===null)r(c);else if(L.startTime<=j)r(c),L.sortIndex=L.expirationTime,t(s,L);else break;L=n(c)}}function k(j){if(x=!1,g(j),!v)if(n(s)!==null)v=!0,kn(E);else{var L=n(c);L!==null&&jt(k,L.startTime-j)}}function E(j,L){v=!1,x&&(x=!1,h(P),P=-1),y=!0;var I=p;try{for(g(L),f=n(s);f!==null&&(!(f.expirationTime>L)||j&&!fe());){var T=f.callback;if(typeof T=="function"){f.callback=null,p=f.priorityLevel;var M=T(f.expirationTime<=L);L=e.unstable_now(),typeof M=="function"?f.callback=M:f===n(s)&&r(s),g(L)}else r(s);f=n(s)}if(f!==null)var Nt=!0;else{var xe=n(c);xe!==null&&jt(k,xe.startTime-L),Nt=!1}return Nt}finally{f=null,p=I,y=!1}}var _=!1,z=null,P=-1,U=5,R=-1;function fe(){return!(e.unstable_now()-R<U)}function rt(){if(z!==null){var j=e.unstable_now();R=j;var L=!0;try{L=z(!0,j)}finally{L?Be():(_=!1,z=null)}}else _=!1}var Be;if(typeof d=="function")Be=function(){d(rt)};else if(typeof MessageChannel<"u"){var wn=new MessageChannel,Ue=wn.port2;wn.port1.onmessage=rt,Be=function(){Ue.postMessage(null)}}else Be=function(){w(rt,0)};function kn(j){z=j,_||(_=!0,Be())}function jt(j,L){P=w(function(){j(e.unstable_now())},L)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(j){j.callback=null},e.unstable_continueExecution=function(){v||y||(v=!0,kn(E))},e.unstable_forceFrameRate=function(j){0>j||125<j?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):U=0<j?Math.floor(1e3/j):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_getFirstCallbackNode=function(){return n(s)},e.unstable_next=function(j){switch(p){case 1:case 2:case 3:var L=3;break;default:L=p}var I=p;p=L;try{return j()}finally{p=I}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(j,L){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var I=p;p=j;try{return L()}finally{p=I}},e.unstable_scheduleCallback=function(j,L,I){var T=e.unstable_now();switch(typeof I=="object"&&I!==null?(I=I.delay,I=typeof I=="number"&&0<I?T+I:T):I=T,j){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=I+M,j={id:m++,callback:L,priorityLevel:j,startTime:I,expirationTime:M,sortIndex:-1},I>T?(j.sortIndex=I,t(c,j),n(s)===null&&j===n(c)&&(x?(h(P),P=-1):x=!0,jt(k,I-T))):(j.sortIndex=M,t(s,j),v||y||(v=!0,kn(E))),j},e.unstable_shouldYield=fe,e.unstable_wrapCallback=function(j){var L=p;return function(){var I=p;p=L;try{return j.apply(this,arguments)}finally{p=I}}}})(Au);Mu.exports=Au;var yd=Mu.exports;/**
 * @license React
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var xd=S,Ce=yd;function C(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Ou=new Set,Hn={};function Ft(e,t){an(e,t),an(e+"Capture",t)}function an(e,t){for(Hn[e]=t,e=0;e<t.length;e++)Ou.add(t[e])}var Je=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ao=Object.prototype.hasOwnProperty,wd=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ls={},os={};function kd(e){return ao.call(os,e)?!0:ao.call(ls,e)?!1:wd.test(e)?os[e]=!0:(ls[e]=!0,!1)}function Sd(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Cd(e,t,n,r){if(t===null||typeof t>"u"||Sd(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function de(e,t,n,r,l,o,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=i}var ne={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ne[e]=new de(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ne[t]=new de(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ne[e]=new de(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ne[e]=new de(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ne[e]=new de(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ne[e]=new de(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ne[e]=new de(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ne[e]=new de(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ne[e]=new de(e,5,!1,e.toLowerCase(),null,!1,!1)});var ai=/[\-:]([a-z])/g;function ci(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ai,ci);ne[t]=new de(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ai,ci);ne[t]=new de(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ai,ci);ne[t]=new de(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ne[e]=new de(e,1,!1,e.toLowerCase(),null,!1,!1)});ne.xlinkHref=new de("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ne[e]=new de(e,1,!1,e.toLowerCase(),null,!0,!0)});function di(e,t,n,r){var l=ne.hasOwnProperty(t)?ne[t]:null;(l!==null?l.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(Cd(t,n,l,r)&&(n=null),r||l===null?kd(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,""+n)):l.mustUseProperty?e[l.propertyName]=n===null?l.type===3?!1:"":n:(t=l.attributeName,r=l.attributeNamespace,n===null?e.removeAttribute(t):(l=l.type,n=l===3||l===4&&n===!0?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}var nt=xd.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,mr=Symbol.for("react.element"),Wt=Symbol.for("react.portal"),Ht=Symbol.for("react.fragment"),fi=Symbol.for("react.strict_mode"),co=Symbol.for("react.profiler"),$u=Symbol.for("react.provider"),Fu=Symbol.for("react.context"),pi=Symbol.for("react.forward_ref"),fo=Symbol.for("react.suspense"),po=Symbol.for("react.suspense_list"),hi=Symbol.for("react.memo"),ot=Symbol.for("react.lazy"),Bu=Symbol.for("react.offscreen"),is=Symbol.iterator;function Sn(e){return e===null||typeof e!="object"?null:(e=is&&e[is]||e["@@iterator"],typeof e=="function"?e:null)}var Q=Object.assign,Ml;function In(e){if(Ml===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);Ml=t&&t[1]||""}return`
`+Ml+e}var Al=!1;function Ol(e,t){if(!e||Al)return"";Al=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(c){var r=c}Reflect.construct(e,[],t)}else{try{t.call()}catch(c){r=c}e.call(t.prototype)}else{try{throw Error()}catch(c){r=c}e()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var l=c.stack.split(`
`),o=r.stack.split(`
`),i=l.length-1,u=o.length-1;1<=i&&0<=u&&l[i]!==o[u];)u--;for(;1<=i&&0<=u;i--,u--)if(l[i]!==o[u]){if(i!==1||u!==1)do if(i--,u--,0>u||l[i]!==o[u]){var s=`
`+l[i].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}while(1<=i&&0<=u);break}}}finally{Al=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?In(e):""}function Ed(e){switch(e.tag){case 5:return In(e.type);case 16:return In("Lazy");case 13:return In("Suspense");case 19:return In("SuspenseList");case 0:case 2:case 15:return e=Ol(e.type,!1),e;case 11:return e=Ol(e.type.render,!1),e;case 1:return e=Ol(e.type,!0),e;default:return""}}function ho(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ht:return"Fragment";case Wt:return"Portal";case co:return"Profiler";case fi:return"StrictMode";case fo:return"Suspense";case po:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Fu:return(e.displayName||"Context")+".Consumer";case $u:return(e._context.displayName||"Context")+".Provider";case pi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case hi:return t=e.displayName||null,t!==null?t:ho(e.type)||"Memo";case ot:t=e._payload,e=e._init;try{return ho(e(t))}catch{}}return null}function jd(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ho(t);case 8:return t===fi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Uu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Nd(e){var t=Uu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function gr(e){e._valueTracker||(e._valueTracker=Nd(e))}function Vu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Uu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Wr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function mo(e,t){var n=t.checked;return Q({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ss(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Wu(e,t){t=t.checked,t!=null&&di(e,"checked",t,!1)}function go(e,t){Wu(e,t);var n=wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?vo(e,t.type,n):t.hasOwnProperty("defaultValue")&&vo(e,t.type,wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function us(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function vo(e,t,n){(t!=="number"||Wr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ln=Array.isArray;function tn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(n=""+wt(n),t=null,l=0;l<e.length;l++){if(e[l].value===n){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}t!==null||e[l].disabled||(t=e[l])}t!==null&&(t.selected=!0)}}function yo(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(C(91));return Q({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function as(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(C(92));if(Ln(n)){if(1<n.length)throw Error(C(93));n=n[0]}t=n}t==null&&(t=""),n=t}e._wrapperState={initialValue:wt(n)}}function Hu(e,t){var n=wt(t.value),r=wt(t.defaultValue);n!=null&&(n=""+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),r!=null&&(e.defaultValue=""+r)}function cs(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function Qu(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function xo(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?Qu(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var vr,bu=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,n,r,l){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,l)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(vr=vr||document.createElement("div"),vr.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=vr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Qn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Mn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Pd=["Webkit","ms","Moz","O"];Object.keys(Mn).forEach(function(e){Pd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Mn[t]=Mn[e]})});function Ku(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Mn.hasOwnProperty(e)&&Mn[e]?(""+t).trim():t+"px"}function Gu(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Ku(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var _d=Q({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function wo(e,t){if(t){if(_d[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(C(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(C(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(C(61))}if(t.style!=null&&typeof t.style!="object")throw Error(C(62))}}function ko(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var So=null;function mi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Co=null,nn=null,rn=null;function ds(e){if(e=cr(e)){if(typeof Co!="function")throw Error(C(280));var t=e.stateNode;t&&(t=wl(t),Co(e.stateNode,e.type,t))}}function Yu(e){nn?rn?rn.push(e):rn=[e]:nn=e}function Xu(){if(nn){var e=nn,t=rn;if(rn=nn=null,ds(e),t)for(e=0;e<t.length;e++)ds(t[e])}}function Zu(e,t){return e(t)}function Ju(){}var $l=!1;function qu(e,t,n){if($l)return e(t,n);$l=!0;try{return Zu(e,t,n)}finally{$l=!1,(nn!==null||rn!==null)&&(Ju(),Xu())}}function bn(e,t){var n=e.stateNode;if(n===null)return null;var r=wl(n);if(r===null)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(C(231,t,typeof n));return n}var Eo=!1;if(Je)try{var Cn={};Object.defineProperty(Cn,"passive",{get:function(){Eo=!0}}),window.addEventListener("test",Cn,Cn),window.removeEventListener("test",Cn,Cn)}catch{Eo=!1}function zd(e,t,n,r,l,o,i,u,s){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(m){this.onError(m)}}var An=!1,Hr=null,Qr=!1,jo=null,Id={onError:function(e){An=!0,Hr=e}};function Ld(e,t,n,r,l,o,i,u,s){An=!1,Hr=null,zd.apply(Id,arguments)}function Td(e,t,n,r,l,o,i,u,s){if(Ld.apply(this,arguments),An){if(An){var c=Hr;An=!1,Hr=null}else throw Error(C(198));Qr||(Qr=!0,jo=c)}}function Bt(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function ea(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function fs(e){if(Bt(e)!==e)throw Error(C(188))}function Rd(e){var t=e.alternate;if(!t){if(t=Bt(e),t===null)throw Error(C(188));return t!==e?null:e}for(var n=e,r=t;;){var l=n.return;if(l===null)break;var o=l.alternate;if(o===null){if(r=l.return,r!==null){n=r;continue}break}if(l.child===o.child){for(o=l.child;o;){if(o===n)return fs(l),e;if(o===r)return fs(l),t;o=o.sibling}throw Error(C(188))}if(n.return!==r.return)n=l,r=o;else{for(var i=!1,u=l.child;u;){if(u===n){i=!0,n=l,r=o;break}if(u===r){i=!0,r=l,n=o;break}u=u.sibling}if(!i){for(u=o.child;u;){if(u===n){i=!0,n=o,r=l;break}if(u===r){i=!0,r=o,n=l;break}u=u.sibling}if(!i)throw Error(C(189))}}if(n.alternate!==r)throw Error(C(190))}if(n.tag!==3)throw Error(C(188));return n.stateNode.current===n?e:t}function ta(e){return e=Rd(e),e!==null?na(e):null}function na(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=na(e);if(t!==null)return t;e=e.sibling}return null}var ra=Ce.unstable_scheduleCallback,ps=Ce.unstable_cancelCallback,Dd=Ce.unstable_shouldYield,Md=Ce.unstable_requestPaint,K=Ce.unstable_now,Ad=Ce.unstable_getCurrentPriorityLevel,gi=Ce.unstable_ImmediatePriority,la=Ce.unstable_UserBlockingPriority,br=Ce.unstable_NormalPriority,Od=Ce.unstable_LowPriority,oa=Ce.unstable_IdlePriority,gl=null,Qe=null;function $d(e){if(Qe&&typeof Qe.onCommitFiberRoot=="function")try{Qe.onCommitFiberRoot(gl,e,void 0,(e.current.flags&128)===128)}catch{}}var Oe=Math.clz32?Math.clz32:Ud,Fd=Math.log,Bd=Math.LN2;function Ud(e){return e>>>=0,e===0?32:31-(Fd(e)/Bd|0)|0}var yr=64,xr=4194304;function Tn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Kr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=Tn(u):(o&=i,o!==0&&(r=Tn(o)))}else i=n&~l,i!==0?r=Tn(i):o!==0&&(r=Tn(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)n=31-Oe(t),l=1<<n,r|=e[n],t&=~l;return r}function Vd(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Wd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,o=e.pendingLanes;0<o;){var i=31-Oe(o),u=1<<i,s=l[i];s===-1?(!(u&n)||u&r)&&(l[i]=Vd(u,t)):s<=t&&(e.expiredLanes|=u),o&=~u}}function No(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function ia(){var e=yr;return yr<<=1,!(yr&4194240)&&(yr=64),e}function Fl(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function ur(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Oe(t),e[t]=n}function Hd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var l=31-Oe(n),o=1<<l;t[l]=0,r[l]=-1,e[l]=-1,n&=~o}}function vi(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-Oe(n),l=1<<r;l&t|e[r]&t&&(e[r]|=t),n&=~l}}var O=0;function sa(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var ua,yi,aa,ca,da,Po=!1,wr=[],ft=null,pt=null,ht=null,Kn=new Map,Gn=new Map,st=[],Qd="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function hs(e,t){switch(e){case"focusin":case"focusout":ft=null;break;case"dragenter":case"dragleave":pt=null;break;case"mouseover":case"mouseout":ht=null;break;case"pointerover":case"pointerout":Kn.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Gn.delete(t.pointerId)}}function En(e,t,n,r,l,o){return e===null||e.nativeEvent!==o?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:o,targetContainers:[l]},t!==null&&(t=cr(t),t!==null&&yi(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,l!==null&&t.indexOf(l)===-1&&t.push(l),e)}function bd(e,t,n,r,l){switch(t){case"focusin":return ft=En(ft,e,t,n,r,l),!0;case"dragenter":return pt=En(pt,e,t,n,r,l),!0;case"mouseover":return ht=En(ht,e,t,n,r,l),!0;case"pointerover":var o=l.pointerId;return Kn.set(o,En(Kn.get(o)||null,e,t,n,r,l)),!0;case"gotpointercapture":return o=l.pointerId,Gn.set(o,En(Gn.get(o)||null,e,t,n,r,l)),!0}return!1}function fa(e){var t=zt(e.target);if(t!==null){var n=Bt(t);if(n!==null){if(t=n.tag,t===13){if(t=ea(n),t!==null){e.blockedOn=t,da(e.priority,function(){aa(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Rr(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=_o(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);So=r,n.target.dispatchEvent(r),So=null}else return t=cr(n),t!==null&&yi(t),e.blockedOn=n,!1;t.shift()}return!0}function ms(e,t,n){Rr(e)&&n.delete(t)}function Kd(){Po=!1,ft!==null&&Rr(ft)&&(ft=null),pt!==null&&Rr(pt)&&(pt=null),ht!==null&&Rr(ht)&&(ht=null),Kn.forEach(ms),Gn.forEach(ms)}function jn(e,t){e.blockedOn===t&&(e.blockedOn=null,Po||(Po=!0,Ce.unstable_scheduleCallback(Ce.unstable_NormalPriority,Kd)))}function Yn(e){function t(l){return jn(l,e)}if(0<wr.length){jn(wr[0],e);for(var n=1;n<wr.length;n++){var r=wr[n];r.blockedOn===e&&(r.blockedOn=null)}}for(ft!==null&&jn(ft,e),pt!==null&&jn(pt,e),ht!==null&&jn(ht,e),Kn.forEach(t),Gn.forEach(t),n=0;n<st.length;n++)r=st[n],r.blockedOn===e&&(r.blockedOn=null);for(;0<st.length&&(n=st[0],n.blockedOn===null);)fa(n),n.blockedOn===null&&st.shift()}var ln=nt.ReactCurrentBatchConfig,Gr=!0;function Gd(e,t,n,r){var l=O,o=ln.transition;ln.transition=null;try{O=1,xi(e,t,n,r)}finally{O=l,ln.transition=o}}function Yd(e,t,n,r){var l=O,o=ln.transition;ln.transition=null;try{O=4,xi(e,t,n,r)}finally{O=l,ln.transition=o}}function xi(e,t,n,r){if(Gr){var l=_o(e,t,n,r);if(l===null)Yl(e,t,r,Yr,n),hs(e,r);else if(bd(l,e,t,n,r))r.stopPropagation();else if(hs(e,r),t&4&&-1<Qd.indexOf(e)){for(;l!==null;){var o=cr(l);if(o!==null&&ua(o),o=_o(e,t,n,r),o===null&&Yl(e,t,r,Yr,n),o===l)break;l=o}l!==null&&r.stopPropagation()}else Yl(e,t,r,null,n)}}var Yr=null;function _o(e,t,n,r){if(Yr=null,e=mi(r),e=zt(e),e!==null)if(t=Bt(e),t===null)e=null;else if(n=t.tag,n===13){if(e=ea(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Yr=e,null}function pa(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Ad()){case gi:return 1;case la:return 4;case br:case Od:return 16;case oa:return 536870912;default:return 16}default:return 16}}var at=null,wi=null,Dr=null;function ha(){if(Dr)return Dr;var e,t=wi,n=t.length,r,l="value"in at?at.value:at.textContent,o=l.length;for(e=0;e<n&&t[e]===l[e];e++);var i=n-e;for(r=1;r<=i&&t[n-r]===l[o-r];r++);return Dr=l.slice(e,1<r?1-r:void 0)}function Mr(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function kr(){return!0}function gs(){return!1}function je(e){function t(n,r,l,o,i){this._reactName=n,this._targetInst=l,this.type=r,this.nativeEvent=o,this.target=i,this.currentTarget=null;for(var u in e)e.hasOwnProperty(u)&&(n=e[u],this[u]=n?n(o):o[u]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?kr:gs,this.isPropagationStopped=gs,this}return Q(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=kr)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=kr)},persist:function(){},isPersistent:kr}),t}var yn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ki=je(yn),ar=Q({},yn,{view:0,detail:0}),Xd=je(ar),Bl,Ul,Nn,vl=Q({},ar,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Si,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Nn&&(Nn&&e.type==="mousemove"?(Bl=e.screenX-Nn.screenX,Ul=e.screenY-Nn.screenY):Ul=Bl=0,Nn=e),Bl)},movementY:function(e){return"movementY"in e?e.movementY:Ul}}),vs=je(vl),Zd=Q({},vl,{dataTransfer:0}),Jd=je(Zd),qd=Q({},ar,{relatedTarget:0}),Vl=je(qd),ef=Q({},yn,{animationName:0,elapsedTime:0,pseudoElement:0}),tf=je(ef),nf=Q({},yn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),rf=je(nf),lf=Q({},yn,{data:0}),ys=je(lf),of={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},sf={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},uf={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function af(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=uf[e])?!!t[e]:!1}function Si(){return af}var cf=Q({},ar,{key:function(e){if(e.key){var t=of[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Mr(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?sf[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Si,charCode:function(e){return e.type==="keypress"?Mr(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Mr(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),df=je(cf),ff=Q({},vl,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),xs=je(ff),pf=Q({},ar,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Si}),hf=je(pf),mf=Q({},yn,{propertyName:0,elapsedTime:0,pseudoElement:0}),gf=je(mf),vf=Q({},vl,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),yf=je(vf),xf=[9,13,27,32],Ci=Je&&"CompositionEvent"in window,On=null;Je&&"documentMode"in document&&(On=document.documentMode);var wf=Je&&"TextEvent"in window&&!On,ma=Je&&(!Ci||On&&8<On&&11>=On),ws=" ",ks=!1;function ga(e,t){switch(e){case"keyup":return xf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function va(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Qt=!1;function kf(e,t){switch(e){case"compositionend":return va(t);case"keypress":return t.which!==32?null:(ks=!0,ws);case"textInput":return e=t.data,e===ws&&ks?null:e;default:return null}}function Sf(e,t){if(Qt)return e==="compositionend"||!Ci&&ga(e,t)?(e=ha(),Dr=wi=at=null,Qt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return ma&&t.locale!=="ko"?null:t.data;default:return null}}var Cf={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ss(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Cf[e.type]:t==="textarea"}function ya(e,t,n,r){Yu(r),t=Xr(t,"onChange"),0<t.length&&(n=new ki("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var $n=null,Xn=null;function Ef(e){za(e,0)}function yl(e){var t=Gt(e);if(Vu(t))return e}function jf(e,t){if(e==="change")return t}var xa=!1;if(Je){var Wl;if(Je){var Hl="oninput"in document;if(!Hl){var Cs=document.createElement("div");Cs.setAttribute("oninput","return;"),Hl=typeof Cs.oninput=="function"}Wl=Hl}else Wl=!1;xa=Wl&&(!document.documentMode||9<document.documentMode)}function Es(){$n&&($n.detachEvent("onpropertychange",wa),Xn=$n=null)}function wa(e){if(e.propertyName==="value"&&yl(Xn)){var t=[];ya(t,Xn,e,mi(e)),qu(Ef,t)}}function Nf(e,t,n){e==="focusin"?(Es(),$n=t,Xn=n,$n.attachEvent("onpropertychange",wa)):e==="focusout"&&Es()}function Pf(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return yl(Xn)}function _f(e,t){if(e==="click")return yl(t)}function zf(e,t){if(e==="input"||e==="change")return yl(t)}function If(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fe=typeof Object.is=="function"?Object.is:If;function Zn(e,t){if(Fe(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var l=n[r];if(!ao.call(t,l)||!Fe(e[l],t[l]))return!1}return!0}function js(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ns(e,t){var n=js(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=js(n)}}function ka(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ka(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Sa(){for(var e=window,t=Wr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Wr(e.document)}return t}function Ei(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Lf(e){var t=Sa(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ka(n.ownerDocument.documentElement,n)){if(r!==null&&Ei(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=Ns(n,o);var i=Ns(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Tf=Je&&"documentMode"in document&&11>=document.documentMode,bt=null,zo=null,Fn=null,Io=!1;function Ps(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Io||bt==null||bt!==Wr(r)||(r=bt,"selectionStart"in r&&Ei(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Fn&&Zn(Fn,r)||(Fn=r,r=Xr(zo,"onSelect"),0<r.length&&(t=new ki("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=bt)))}function Sr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var Kt={animationend:Sr("Animation","AnimationEnd"),animationiteration:Sr("Animation","AnimationIteration"),animationstart:Sr("Animation","AnimationStart"),transitionend:Sr("Transition","TransitionEnd")},Ql={},Ca={};Je&&(Ca=document.createElement("div").style,"AnimationEvent"in window||(delete Kt.animationend.animation,delete Kt.animationiteration.animation,delete Kt.animationstart.animation),"TransitionEvent"in window||delete Kt.transitionend.transition);function xl(e){if(Ql[e])return Ql[e];if(!Kt[e])return e;var t=Kt[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Ca)return Ql[e]=t[n];return e}var Ea=xl("animationend"),ja=xl("animationiteration"),Na=xl("animationstart"),Pa=xl("transitionend"),_a=new Map,_s="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function St(e,t){_a.set(e,t),Ft(t,[e])}for(var bl=0;bl<_s.length;bl++){var Kl=_s[bl],Rf=Kl.toLowerCase(),Df=Kl[0].toUpperCase()+Kl.slice(1);St(Rf,"on"+Df)}St(Ea,"onAnimationEnd");St(ja,"onAnimationIteration");St(Na,"onAnimationStart");St("dblclick","onDoubleClick");St("focusin","onFocus");St("focusout","onBlur");St(Pa,"onTransitionEnd");an("onMouseEnter",["mouseout","mouseover"]);an("onMouseLeave",["mouseout","mouseover"]);an("onPointerEnter",["pointerout","pointerover"]);an("onPointerLeave",["pointerout","pointerover"]);Ft("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Ft("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Ft("onBeforeInput",["compositionend","keypress","textInput","paste"]);Ft("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Ft("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Ft("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Rn="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Mf=new Set("cancel close invalid load scroll toggle".split(" ").concat(Rn));function zs(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,Td(r,t,void 0,e),e.currentTarget=null}function za(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var r=e[n],l=r.event;r=r.listeners;e:{var o=void 0;if(t)for(var i=r.length-1;0<=i;i--){var u=r[i],s=u.instance,c=u.currentTarget;if(u=u.listener,s!==o&&l.isPropagationStopped())break e;zs(l,u,c),o=s}else for(i=0;i<r.length;i++){if(u=r[i],s=u.instance,c=u.currentTarget,u=u.listener,s!==o&&l.isPropagationStopped())break e;zs(l,u,c),o=s}}}if(Qr)throw e=jo,Qr=!1,jo=null,e}function F(e,t){var n=t[Mo];n===void 0&&(n=t[Mo]=new Set);var r=e+"__bubble";n.has(r)||(Ia(t,e,2,!1),n.add(r))}function Gl(e,t,n){var r=0;t&&(r|=4),Ia(n,e,r,t)}var Cr="_reactListening"+Math.random().toString(36).slice(2);function Jn(e){if(!e[Cr]){e[Cr]=!0,Ou.forEach(function(n){n!=="selectionchange"&&(Mf.has(n)||Gl(n,!1,e),Gl(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Cr]||(t[Cr]=!0,Gl("selectionchange",!1,t))}}function Ia(e,t,n,r){switch(pa(t)){case 1:var l=Gd;break;case 4:l=Yd;break;default:l=xi}n=l.bind(null,t,n,e),l=void 0,!Eo||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(l=!0),r?l!==void 0?e.addEventListener(t,n,{capture:!0,passive:l}):e.addEventListener(t,n,!0):l!==void 0?e.addEventListener(t,n,{passive:l}):e.addEventListener(t,n,!1)}function Yl(e,t,n,r,l){var o=r;if(!(t&1)&&!(t&2)&&r!==null)e:for(;;){if(r===null)return;var i=r.tag;if(i===3||i===4){var u=r.stateNode.containerInfo;if(u===l||u.nodeType===8&&u.parentNode===l)break;if(i===4)for(i=r.return;i!==null;){var s=i.tag;if((s===3||s===4)&&(s=i.stateNode.containerInfo,s===l||s.nodeType===8&&s.parentNode===l))return;i=i.return}for(;u!==null;){if(i=zt(u),i===null)return;if(s=i.tag,s===5||s===6){r=o=i;continue e}u=u.parentNode}}r=r.return}qu(function(){var c=o,m=mi(n),f=[];e:{var p=_a.get(e);if(p!==void 0){var y=ki,v=e;switch(e){case"keypress":if(Mr(n)===0)break e;case"keydown":case"keyup":y=df;break;case"focusin":v="focus",y=Vl;break;case"focusout":v="blur",y=Vl;break;case"beforeblur":case"afterblur":y=Vl;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":y=vs;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":y=Jd;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":y=hf;break;case Ea:case ja:case Na:y=tf;break;case Pa:y=gf;break;case"scroll":y=Xd;break;case"wheel":y=yf;break;case"copy":case"cut":case"paste":y=rf;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":y=xs}var x=(t&4)!==0,w=!x&&e==="scroll",h=x?p!==null?p+"Capture":null:p;x=[];for(var d=c,g;d!==null;){g=d;var k=g.stateNode;if(g.tag===5&&k!==null&&(g=k,h!==null&&(k=bn(d,h),k!=null&&x.push(qn(d,k,g)))),w)break;d=d.return}0<x.length&&(p=new y(p,v,null,n,m),f.push({event:p,listeners:x}))}}if(!(t&7)){e:{if(p=e==="mouseover"||e==="pointerover",y=e==="mouseout"||e==="pointerout",p&&n!==So&&(v=n.relatedTarget||n.fromElement)&&(zt(v)||v[qe]))break e;if((y||p)&&(p=m.window===m?m:(p=m.ownerDocument)?p.defaultView||p.parentWindow:window,y?(v=n.relatedTarget||n.toElement,y=c,v=v?zt(v):null,v!==null&&(w=Bt(v),v!==w||v.tag!==5&&v.tag!==6)&&(v=null)):(y=null,v=c),y!==v)){if(x=vs,k="onMouseLeave",h="onMouseEnter",d="mouse",(e==="pointerout"||e==="pointerover")&&(x=xs,k="onPointerLeave",h="onPointerEnter",d="pointer"),w=y==null?p:Gt(y),g=v==null?p:Gt(v),p=new x(k,d+"leave",y,n,m),p.target=w,p.relatedTarget=g,k=null,zt(m)===c&&(x=new x(h,d+"enter",v,n,m),x.target=g,x.relatedTarget=w,k=x),w=k,y&&v)t:{for(x=y,h=v,d=0,g=x;g;g=Ut(g))d++;for(g=0,k=h;k;k=Ut(k))g++;for(;0<d-g;)x=Ut(x),d--;for(;0<g-d;)h=Ut(h),g--;for(;d--;){if(x===h||h!==null&&x===h.alternate)break t;x=Ut(x),h=Ut(h)}x=null}else x=null;y!==null&&Is(f,p,y,x,!1),v!==null&&w!==null&&Is(f,w,v,x,!0)}}e:{if(p=c?Gt(c):window,y=p.nodeName&&p.nodeName.toLowerCase(),y==="select"||y==="input"&&p.type==="file")var E=jf;else if(Ss(p))if(xa)E=zf;else{E=Pf;var _=Nf}else(y=p.nodeName)&&y.toLowerCase()==="input"&&(p.type==="checkbox"||p.type==="radio")&&(E=_f);if(E&&(E=E(e,c))){ya(f,E,n,m);break e}_&&_(e,p,c),e==="focusout"&&(_=p._wrapperState)&&_.controlled&&p.type==="number"&&vo(p,"number",p.value)}switch(_=c?Gt(c):window,e){case"focusin":(Ss(_)||_.contentEditable==="true")&&(bt=_,zo=c,Fn=null);break;case"focusout":Fn=zo=bt=null;break;case"mousedown":Io=!0;break;case"contextmenu":case"mouseup":case"dragend":Io=!1,Ps(f,n,m);break;case"selectionchange":if(Tf)break;case"keydown":case"keyup":Ps(f,n,m)}var z;if(Ci)e:{switch(e){case"compositionstart":var P="onCompositionStart";break e;case"compositionend":P="onCompositionEnd";break e;case"compositionupdate":P="onCompositionUpdate";break e}P=void 0}else Qt?ga(e,n)&&(P="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(P="onCompositionStart");P&&(ma&&n.locale!=="ko"&&(Qt||P!=="onCompositionStart"?P==="onCompositionEnd"&&Qt&&(z=ha()):(at=m,wi="value"in at?at.value:at.textContent,Qt=!0)),_=Xr(c,P),0<_.length&&(P=new ys(P,e,null,n,m),f.push({event:P,listeners:_}),z?P.data=z:(z=va(n),z!==null&&(P.data=z)))),(z=wf?kf(e,n):Sf(e,n))&&(c=Xr(c,"onBeforeInput"),0<c.length&&(m=new ys("onBeforeInput","beforeinput",null,n,m),f.push({event:m,listeners:c}),m.data=z))}za(f,t)})}function qn(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Xr(e,t){for(var n=t+"Capture",r=[];e!==null;){var l=e,o=l.stateNode;l.tag===5&&o!==null&&(l=o,o=bn(e,n),o!=null&&r.unshift(qn(e,o,l)),o=bn(e,t),o!=null&&r.push(qn(e,o,l))),e=e.return}return r}function Ut(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Is(e,t,n,r,l){for(var o=t._reactName,i=[];n!==null&&n!==r;){var u=n,s=u.alternate,c=u.stateNode;if(s!==null&&s===r)break;u.tag===5&&c!==null&&(u=c,l?(s=bn(n,o),s!=null&&i.unshift(qn(n,s,u))):l||(s=bn(n,o),s!=null&&i.push(qn(n,s,u)))),n=n.return}i.length!==0&&e.push({event:t,listeners:i})}var Af=/\r\n?/g,Of=/\u0000|\uFFFD/g;function Ls(e){return(typeof e=="string"?e:""+e).replace(Af,`
`).replace(Of,"")}function Er(e,t,n){if(t=Ls(t),Ls(e)!==t&&n)throw Error(C(425))}function Zr(){}var Lo=null,To=null;function Ro(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Do=typeof setTimeout=="function"?setTimeout:void 0,$f=typeof clearTimeout=="function"?clearTimeout:void 0,Ts=typeof Promise=="function"?Promise:void 0,Ff=typeof queueMicrotask=="function"?queueMicrotask:typeof Ts<"u"?function(e){return Ts.resolve(null).then(e).catch(Bf)}:Do;function Bf(e){setTimeout(function(){throw e})}function Xl(e,t){var n=t,r=0;do{var l=n.nextSibling;if(e.removeChild(n),l&&l.nodeType===8)if(n=l.data,n==="/$"){if(r===0){e.removeChild(l),Yn(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=l}while(n);Yn(t)}function mt(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Rs(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var xn=Math.random().toString(36).slice(2),He="__reactFiber$"+xn,er="__reactProps$"+xn,qe="__reactContainer$"+xn,Mo="__reactEvents$"+xn,Uf="__reactListeners$"+xn,Vf="__reactHandles$"+xn;function zt(e){var t=e[He];if(t)return t;for(var n=e.parentNode;n;){if(t=n[qe]||n[He]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Rs(e);e!==null;){if(n=e[He])return n;e=Rs(e)}return t}e=n,n=e.parentNode}return null}function cr(e){return e=e[He]||e[qe],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Gt(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(C(33))}function wl(e){return e[er]||null}var Ao=[],Yt=-1;function Ct(e){return{current:e}}function B(e){0>Yt||(e.current=Ao[Yt],Ao[Yt]=null,Yt--)}function $(e,t){Yt++,Ao[Yt]=e.current,e.current=t}var kt={},se=Ct(kt),me=Ct(!1),Dt=kt;function cn(e,t){var n=e.type.contextTypes;if(!n)return kt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function ge(e){return e=e.childContextTypes,e!=null}function Jr(){B(me),B(se)}function Ds(e,t,n){if(se.current!==kt)throw Error(C(168));$(se,t),$(me,n)}function La(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(C(108,jd(e)||"Unknown",l));return Q({},n,r)}function qr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kt,Dt=se.current,$(se,e),$(me,me.current),!0}function Ms(e,t,n){var r=e.stateNode;if(!r)throw Error(C(169));n?(e=La(e,t,Dt),r.__reactInternalMemoizedMergedChildContext=e,B(me),B(se),$(se,e)):B(me),$(me,n)}var Ge=null,kl=!1,Zl=!1;function Ta(e){Ge===null?Ge=[e]:Ge.push(e)}function Wf(e){kl=!0,Ta(e)}function Et(){if(!Zl&&Ge!==null){Zl=!0;var e=0,t=O;try{var n=Ge;for(O=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Ge=null,kl=!1}catch(l){throw Ge!==null&&(Ge=Ge.slice(e+1)),ra(gi,Et),l}finally{O=t,Zl=!1}}return null}var Xt=[],Zt=0,el=null,tl=0,Pe=[],_e=0,Mt=null,Ye=1,Xe="";function Pt(e,t){Xt[Zt++]=tl,Xt[Zt++]=el,el=e,tl=t}function Ra(e,t,n){Pe[_e++]=Ye,Pe[_e++]=Xe,Pe[_e++]=Mt,Mt=e;var r=Ye;e=Xe;var l=32-Oe(r)-1;r&=~(1<<l),n+=1;var o=32-Oe(t)+l;if(30<o){var i=l-l%5;o=(r&(1<<i)-1).toString(32),r>>=i,l-=i,Ye=1<<32-Oe(t)+l|n<<l|r,Xe=o+e}else Ye=1<<o|n<<l|r,Xe=e}function ji(e){e.return!==null&&(Pt(e,1),Ra(e,1,0))}function Ni(e){for(;e===el;)el=Xt[--Zt],Xt[Zt]=null,tl=Xt[--Zt],Xt[Zt]=null;for(;e===Mt;)Mt=Pe[--_e],Pe[_e]=null,Xe=Pe[--_e],Pe[_e]=null,Ye=Pe[--_e],Pe[_e]=null}var Se=null,ke=null,V=!1,Ae=null;function Da(e,t){var n=ze(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function As(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,Se=e,ke=mt(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,Se=e,ke=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=Mt!==null?{id:Ye,overflow:Xe}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=ze(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,Se=e,ke=null,!0):!1;default:return!1}}function Oo(e){return(e.mode&1)!==0&&(e.flags&128)===0}function $o(e){if(V){var t=ke;if(t){var n=t;if(!As(e,t)){if(Oo(e))throw Error(C(418));t=mt(n.nextSibling);var r=Se;t&&As(e,t)?Da(r,n):(e.flags=e.flags&-4097|2,V=!1,Se=e)}}else{if(Oo(e))throw Error(C(418));e.flags=e.flags&-4097|2,V=!1,Se=e}}}function Os(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Se=e}function jr(e){if(e!==Se)return!1;if(!V)return Os(e),V=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Ro(e.type,e.memoizedProps)),t&&(t=ke)){if(Oo(e))throw Ma(),Error(C(418));for(;t;)Da(e,t),t=mt(t.nextSibling)}if(Os(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(C(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"){if(t===0){ke=mt(e.nextSibling);break e}t--}else n!=="$"&&n!=="$!"&&n!=="$?"||t++}e=e.nextSibling}ke=null}}else ke=Se?mt(e.stateNode.nextSibling):null;return!0}function Ma(){for(var e=ke;e;)e=mt(e.nextSibling)}function dn(){ke=Se=null,V=!1}function Pi(e){Ae===null?Ae=[e]:Ae.push(e)}var Hf=nt.ReactCurrentBatchConfig;function Pn(e,t,n){if(e=n.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(C(309));var r=n.stateNode}if(!r)throw Error(C(147,e));var l=r,o=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===o?t.ref:(t=function(i){var u=l.refs;i===null?delete u[o]:u[o]=i},t._stringRef=o,t)}if(typeof e!="string")throw Error(C(284));if(!n._owner)throw Error(C(290,e))}return e}function Nr(e,t){throw e=Object.prototype.toString.call(t),Error(C(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function $s(e){var t=e._init;return t(e._payload)}function Aa(e){function t(h,d){if(e){var g=h.deletions;g===null?(h.deletions=[d],h.flags|=16):g.push(d)}}function n(h,d){if(!e)return null;for(;d!==null;)t(h,d),d=d.sibling;return null}function r(h,d){for(h=new Map;d!==null;)d.key!==null?h.set(d.key,d):h.set(d.index,d),d=d.sibling;return h}function l(h,d){return h=xt(h,d),h.index=0,h.sibling=null,h}function o(h,d,g){return h.index=g,e?(g=h.alternate,g!==null?(g=g.index,g<d?(h.flags|=2,d):g):(h.flags|=2,d)):(h.flags|=1048576,d)}function i(h){return e&&h.alternate===null&&(h.flags|=2),h}function u(h,d,g,k){return d===null||d.tag!==6?(d=lo(g,h.mode,k),d.return=h,d):(d=l(d,g),d.return=h,d)}function s(h,d,g,k){var E=g.type;return E===Ht?m(h,d,g.props.children,k,g.key):d!==null&&(d.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===ot&&$s(E)===d.type)?(k=l(d,g.props),k.ref=Pn(h,d,g),k.return=h,k):(k=Vr(g.type,g.key,g.props,null,h.mode,k),k.ref=Pn(h,d,g),k.return=h,k)}function c(h,d,g,k){return d===null||d.tag!==4||d.stateNode.containerInfo!==g.containerInfo||d.stateNode.implementation!==g.implementation?(d=oo(g,h.mode,k),d.return=h,d):(d=l(d,g.children||[]),d.return=h,d)}function m(h,d,g,k,E){return d===null||d.tag!==7?(d=Rt(g,h.mode,k,E),d.return=h,d):(d=l(d,g),d.return=h,d)}function f(h,d,g){if(typeof d=="string"&&d!==""||typeof d=="number")return d=lo(""+d,h.mode,g),d.return=h,d;if(typeof d=="object"&&d!==null){switch(d.$$typeof){case mr:return g=Vr(d.type,d.key,d.props,null,h.mode,g),g.ref=Pn(h,null,d),g.return=h,g;case Wt:return d=oo(d,h.mode,g),d.return=h,d;case ot:var k=d._init;return f(h,k(d._payload),g)}if(Ln(d)||Sn(d))return d=Rt(d,h.mode,g,null),d.return=h,d;Nr(h,d)}return null}function p(h,d,g,k){var E=d!==null?d.key:null;if(typeof g=="string"&&g!==""||typeof g=="number")return E!==null?null:u(h,d,""+g,k);if(typeof g=="object"&&g!==null){switch(g.$$typeof){case mr:return g.key===E?s(h,d,g,k):null;case Wt:return g.key===E?c(h,d,g,k):null;case ot:return E=g._init,p(h,d,E(g._payload),k)}if(Ln(g)||Sn(g))return E!==null?null:m(h,d,g,k,null);Nr(h,g)}return null}function y(h,d,g,k,E){if(typeof k=="string"&&k!==""||typeof k=="number")return h=h.get(g)||null,u(d,h,""+k,E);if(typeof k=="object"&&k!==null){switch(k.$$typeof){case mr:return h=h.get(k.key===null?g:k.key)||null,s(d,h,k,E);case Wt:return h=h.get(k.key===null?g:k.key)||null,c(d,h,k,E);case ot:var _=k._init;return y(h,d,g,_(k._payload),E)}if(Ln(k)||Sn(k))return h=h.get(g)||null,m(d,h,k,E,null);Nr(d,k)}return null}function v(h,d,g,k){for(var E=null,_=null,z=d,P=d=0,U=null;z!==null&&P<g.length;P++){z.index>P?(U=z,z=null):U=z.sibling;var R=p(h,z,g[P],k);if(R===null){z===null&&(z=U);break}e&&z&&R.alternate===null&&t(h,z),d=o(R,d,P),_===null?E=R:_.sibling=R,_=R,z=U}if(P===g.length)return n(h,z),V&&Pt(h,P),E;if(z===null){for(;P<g.length;P++)z=f(h,g[P],k),z!==null&&(d=o(z,d,P),_===null?E=z:_.sibling=z,_=z);return V&&Pt(h,P),E}for(z=r(h,z);P<g.length;P++)U=y(z,h,P,g[P],k),U!==null&&(e&&U.alternate!==null&&z.delete(U.key===null?P:U.key),d=o(U,d,P),_===null?E=U:_.sibling=U,_=U);return e&&z.forEach(function(fe){return t(h,fe)}),V&&Pt(h,P),E}function x(h,d,g,k){var E=Sn(g);if(typeof E!="function")throw Error(C(150));if(g=E.call(g),g==null)throw Error(C(151));for(var _=E=null,z=d,P=d=0,U=null,R=g.next();z!==null&&!R.done;P++,R=g.next()){z.index>P?(U=z,z=null):U=z.sibling;var fe=p(h,z,R.value,k);if(fe===null){z===null&&(z=U);break}e&&z&&fe.alternate===null&&t(h,z),d=o(fe,d,P),_===null?E=fe:_.sibling=fe,_=fe,z=U}if(R.done)return n(h,z),V&&Pt(h,P),E;if(z===null){for(;!R.done;P++,R=g.next())R=f(h,R.value,k),R!==null&&(d=o(R,d,P),_===null?E=R:_.sibling=R,_=R);return V&&Pt(h,P),E}for(z=r(h,z);!R.done;P++,R=g.next())R=y(z,h,P,R.value,k),R!==null&&(e&&R.alternate!==null&&z.delete(R.key===null?P:R.key),d=o(R,d,P),_===null?E=R:_.sibling=R,_=R);return e&&z.forEach(function(rt){return t(h,rt)}),V&&Pt(h,P),E}function w(h,d,g,k){if(typeof g=="object"&&g!==null&&g.type===Ht&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case mr:e:{for(var E=g.key,_=d;_!==null;){if(_.key===E){if(E=g.type,E===Ht){if(_.tag===7){n(h,_.sibling),d=l(_,g.props.children),d.return=h,h=d;break e}}else if(_.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===ot&&$s(E)===_.type){n(h,_.sibling),d=l(_,g.props),d.ref=Pn(h,_,g),d.return=h,h=d;break e}n(h,_);break}else t(h,_);_=_.sibling}g.type===Ht?(d=Rt(g.props.children,h.mode,k,g.key),d.return=h,h=d):(k=Vr(g.type,g.key,g.props,null,h.mode,k),k.ref=Pn(h,d,g),k.return=h,h=k)}return i(h);case Wt:e:{for(_=g.key;d!==null;){if(d.key===_)if(d.tag===4&&d.stateNode.containerInfo===g.containerInfo&&d.stateNode.implementation===g.implementation){n(h,d.sibling),d=l(d,g.children||[]),d.return=h,h=d;break e}else{n(h,d);break}else t(h,d);d=d.sibling}d=oo(g,h.mode,k),d.return=h,h=d}return i(h);case ot:return _=g._init,w(h,d,_(g._payload),k)}if(Ln(g))return v(h,d,g,k);if(Sn(g))return x(h,d,g,k);Nr(h,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,d!==null&&d.tag===6?(n(h,d.sibling),d=l(d,g),d.return=h,h=d):(n(h,d),d=lo(g,h.mode,k),d.return=h,h=d),i(h)):n(h,d)}return w}var fn=Aa(!0),Oa=Aa(!1),nl=Ct(null),rl=null,Jt=null,_i=null;function zi(){_i=Jt=rl=null}function Ii(e){var t=nl.current;B(nl),e._currentValue=t}function Fo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function on(e,t){rl=e,_i=Jt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(he=!0),e.firstContext=null)}function Le(e){var t=e._currentValue;if(_i!==e)if(e={context:e,memoizedValue:t,next:null},Jt===null){if(rl===null)throw Error(C(308));Jt=e,rl.dependencies={lanes:0,firstContext:e}}else Jt=Jt.next=e;return t}var It=null;function Li(e){It===null?It=[e]:It.push(e)}function $a(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Li(t)):(n.next=l.next,l.next=n),t.interleaved=n,et(e,r)}function et(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var it=!1;function Ti(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Fa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ze(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,A&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,et(e,n)}return l=r.interleaved,l===null?(t.next=t,Li(r)):(t.next=l.next,l.next=t),r.interleaved=t,et(e,n)}function Ar(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vi(e,n)}}function Fs(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=i:o=o.next=i,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function ll(e,t,n,r){var l=e.updateQueue;it=!1;var o=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var s=u,c=s.next;s.next=null,i===null?o=c:i.next=c,i=s;var m=e.alternate;m!==null&&(m=m.updateQueue,u=m.lastBaseUpdate,u!==i&&(u===null?m.firstBaseUpdate=c:u.next=c,m.lastBaseUpdate=s))}if(o!==null){var f=l.baseState;i=0,m=c=s=null,u=o;do{var p=u.lane,y=u.eventTime;if((r&p)===p){m!==null&&(m=m.next={eventTime:y,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var v=e,x=u;switch(p=t,y=n,x.tag){case 1:if(v=x.payload,typeof v=="function"){f=v.call(y,f,p);break e}f=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=x.payload,p=typeof v=="function"?v.call(y,f,p):v,p==null)break e;f=Q({},f,p);break e;case 2:it=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,p=l.effects,p===null?l.effects=[u]:p.push(u))}else y={eventTime:y,lane:p,tag:u.tag,payload:u.payload,callback:u.callback,next:null},m===null?(c=m=y,s=f):m=m.next=y,i|=p;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;p=u,u=p.next,p.next=null,l.lastBaseUpdate=p,l.shared.pending=null}}while(!0);if(m===null&&(s=f),l.baseState=s,l.firstBaseUpdate=c,l.lastBaseUpdate=m,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);Ot|=i,e.lanes=i,e.memoizedState=f}}function Bs(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var r=e[t],l=r.callback;if(l!==null){if(r.callback=null,r=n,typeof l!="function")throw Error(C(191,l));l.call(r)}}}var dr={},be=Ct(dr),tr=Ct(dr),nr=Ct(dr);function Lt(e){if(e===dr)throw Error(C(174));return e}function Ri(e,t){switch($(nr,t),$(tr,e),$(be,dr),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:xo(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=xo(t,e)}B(be),$(be,t)}function pn(){B(be),B(tr),B(nr)}function Ba(e){Lt(nr.current);var t=Lt(be.current),n=xo(t,e.type);t!==n&&($(tr,e),$(be,n))}function Di(e){tr.current===e&&(B(be),B(tr))}var W=Ct(0);function ol(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jl=[];function Mi(){for(var e=0;e<Jl.length;e++)Jl[e]._workInProgressVersionPrimary=null;Jl.length=0}var Or=nt.ReactCurrentDispatcher,ql=nt.ReactCurrentBatchConfig,At=0,H=null,X=null,J=null,il=!1,Bn=!1,rr=0,Qf=0;function le(){throw Error(C(321))}function Ai(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Fe(e[n],t[n]))return!1;return!0}function Oi(e,t,n,r,l,o){if(At=o,H=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,Or.current=e===null||e.memoizedState===null?Yf:Xf,e=n(r,l),Bn){o=0;do{if(Bn=!1,rr=0,25<=o)throw Error(C(301));o+=1,J=X=null,t.updateQueue=null,Or.current=Zf,e=n(r,l)}while(Bn)}if(Or.current=sl,t=X!==null&&X.next!==null,At=0,J=X=H=null,il=!1,t)throw Error(C(300));return e}function $i(){var e=rr!==0;return rr=0,e}function We(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return J===null?H.memoizedState=J=e:J=J.next=e,J}function Te(){if(X===null){var e=H.alternate;e=e!==null?e.memoizedState:null}else e=X.next;var t=J===null?H.memoizedState:J.next;if(t!==null)J=t,X=e;else{if(e===null)throw Error(C(310));X=e,e={memoizedState:X.memoizedState,baseState:X.baseState,baseQueue:X.baseQueue,queue:X.queue,next:null},J===null?H.memoizedState=J=e:J=J.next=e}return J}function lr(e,t){return typeof t=="function"?t(e):t}function eo(e){var t=Te(),n=t.queue;if(n===null)throw Error(C(311));n.lastRenderedReducer=e;var r=X,l=r.baseQueue,o=n.pending;if(o!==null){if(l!==null){var i=l.next;l.next=o.next,o.next=i}r.baseQueue=l=o,n.pending=null}if(l!==null){o=l.next,r=r.baseState;var u=i=null,s=null,c=o;do{var m=c.lane;if((At&m)===m)s!==null&&(s=s.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),r=c.hasEagerState?c.eagerState:e(r,c.action);else{var f={lane:m,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};s===null?(u=s=f,i=r):s=s.next=f,H.lanes|=m,Ot|=m}c=c.next}while(c!==null&&c!==o);s===null?i=r:s.next=u,Fe(r,t.memoizedState)||(he=!0),t.memoizedState=r,t.baseState=i,t.baseQueue=s,n.lastRenderedState=r}if(e=n.interleaved,e!==null){l=e;do o=l.lane,H.lanes|=o,Ot|=o,l=l.next;while(l!==e)}else l===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function to(e){var t=Te(),n=t.queue;if(n===null)throw Error(C(311));n.lastRenderedReducer=e;var r=n.dispatch,l=n.pending,o=t.memoizedState;if(l!==null){n.pending=null;var i=l=l.next;do o=e(o,i.action),i=i.next;while(i!==l);Fe(o,t.memoizedState)||(he=!0),t.memoizedState=o,t.baseQueue===null&&(t.baseState=o),n.lastRenderedState=o}return[o,r]}function Ua(){}function Va(e,t){var n=H,r=Te(),l=t(),o=!Fe(r.memoizedState,l);if(o&&(r.memoizedState=l,he=!0),r=r.queue,Fi(Qa.bind(null,n,r,e),[e]),r.getSnapshot!==t||o||J!==null&&J.memoizedState.tag&1){if(n.flags|=2048,or(9,Ha.bind(null,n,r,l,t),void 0,null),q===null)throw Error(C(349));At&30||Wa(n,t,l)}return l}function Wa(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=H.updateQueue,t===null?(t={lastEffect:null,stores:null},H.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function Ha(e,t,n,r){t.value=n,t.getSnapshot=r,ba(t)&&Ka(e)}function Qa(e,t,n){return n(function(){ba(t)&&Ka(e)})}function ba(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fe(e,n)}catch{return!0}}function Ka(e){var t=et(e,1);t!==null&&$e(t,e,1,-1)}function Us(e){var t=We();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:lr,lastRenderedState:e},t.queue=e,e=e.dispatch=Gf.bind(null,H,e),[t.memoizedState,e]}function or(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},t=H.updateQueue,t===null?(t={lastEffect:null,stores:null},H.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e)),e}function Ga(){return Te().memoizedState}function $r(e,t,n,r){var l=We();H.flags|=e,l.memoizedState=or(1|t,n,void 0,r===void 0?null:r)}function Sl(e,t,n,r){var l=Te();r=r===void 0?null:r;var o=void 0;if(X!==null){var i=X.memoizedState;if(o=i.destroy,r!==null&&Ai(r,i.deps)){l.memoizedState=or(t,n,o,r);return}}H.flags|=e,l.memoizedState=or(1|t,n,o,r)}function Vs(e,t){return $r(8390656,8,e,t)}function Fi(e,t){return Sl(2048,8,e,t)}function Ya(e,t){return Sl(4,2,e,t)}function Xa(e,t){return Sl(4,4,e,t)}function Za(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Ja(e,t,n){return n=n!=null?n.concat([e]):null,Sl(4,4,Za.bind(null,t,e),n)}function Bi(){}function qa(e,t){var n=Te();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Ai(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function ec(e,t){var n=Te();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Ai(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function tc(e,t,n){return At&21?(Fe(n,t)||(n=ia(),H.lanes|=n,Ot|=n,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,he=!0),e.memoizedState=n)}function bf(e,t){var n=O;O=n!==0&&4>n?n:4,e(!0);var r=ql.transition;ql.transition={};try{e(!1),t()}finally{O=n,ql.transition=r}}function nc(){return Te().memoizedState}function Kf(e,t,n){var r=yt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},rc(e))lc(t,n);else if(n=$a(e,t,n,r),n!==null){var l=ae();$e(n,e,r,l),oc(n,t,r)}}function Gf(e,t,n){var r=yt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(rc(e))lc(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var i=t.lastRenderedState,u=o(i,n);if(l.hasEagerState=!0,l.eagerState=u,Fe(u,i)){var s=t.interleaved;s===null?(l.next=l,Li(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=$a(e,t,l,r),n!==null&&(l=ae(),$e(n,e,r,l),oc(n,t,r))}}function rc(e){var t=e.alternate;return e===H||t!==null&&t===H}function lc(e,t){Bn=il=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vi(e,n)}}var sl={readContext:Le,useCallback:le,useContext:le,useEffect:le,useImperativeHandle:le,useInsertionEffect:le,useLayoutEffect:le,useMemo:le,useReducer:le,useRef:le,useState:le,useDebugValue:le,useDeferredValue:le,useTransition:le,useMutableSource:le,useSyncExternalStore:le,useId:le,unstable_isNewReconciler:!1},Yf={readContext:Le,useCallback:function(e,t){return We().memoizedState=[e,t===void 0?null:t],e},useContext:Le,useEffect:Vs,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,$r(4194308,4,Za.bind(null,t,e),n)},useLayoutEffect:function(e,t){return $r(4194308,4,e,t)},useInsertionEffect:function(e,t){return $r(4,2,e,t)},useMemo:function(e,t){var n=We();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=We();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Kf.bind(null,H,e),[r.memoizedState,e]},useRef:function(e){var t=We();return e={current:e},t.memoizedState=e},useState:Us,useDebugValue:Bi,useDeferredValue:function(e){return We().memoizedState=e},useTransition:function(){var e=Us(!1),t=e[0];return e=bf.bind(null,e[1]),We().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=H,l=We();if(V){if(n===void 0)throw Error(C(407));n=n()}else{if(n=t(),q===null)throw Error(C(349));At&30||Wa(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Vs(Qa.bind(null,r,o,e),[e]),r.flags|=2048,or(9,Ha.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=We(),t=q.identifierPrefix;if(V){var n=Xe,r=Ye;n=(r&~(1<<32-Oe(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=rr++,0<n&&(t+="H"+n.toString(32)),t+=":"}else n=Qf++,t=":"+t+"r"+n.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},Xf={readContext:Le,useCallback:qa,useContext:Le,useEffect:Fi,useImperativeHandle:Ja,useInsertionEffect:Ya,useLayoutEffect:Xa,useMemo:ec,useReducer:eo,useRef:Ga,useState:function(){return eo(lr)},useDebugValue:Bi,useDeferredValue:function(e){var t=Te();return tc(t,X.memoizedState,e)},useTransition:function(){var e=eo(lr)[0],t=Te().memoizedState;return[e,t]},useMutableSource:Ua,useSyncExternalStore:Va,useId:nc,unstable_isNewReconciler:!1},Zf={readContext:Le,useCallback:qa,useContext:Le,useEffect:Fi,useImperativeHandle:Ja,useInsertionEffect:Ya,useLayoutEffect:Xa,useMemo:ec,useReducer:to,useRef:Ga,useState:function(){return to(lr)},useDebugValue:Bi,useDeferredValue:function(e){var t=Te();return X===null?t.memoizedState=e:tc(t,X.memoizedState,e)},useTransition:function(){var e=to(lr)[0],t=Te().memoizedState;return[e,t]},useMutableSource:Ua,useSyncExternalStore:Va,useId:nc,unstable_isNewReconciler:!1};function De(e,t){if(e&&e.defaultProps){t=Q({},t),e=e.defaultProps;for(var n in e)t[n]===void 0&&(t[n]=e[n]);return t}return t}function Bo(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:Q({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var Cl={isMounted:function(e){return(e=e._reactInternals)?Bt(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=ae(),l=yt(e),o=Ze(r,l);o.payload=t,n!=null&&(o.callback=n),t=gt(e,o,l),t!==null&&($e(t,e,l,r),Ar(t,e,l))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=ae(),l=yt(e),o=Ze(r,l);o.tag=1,o.payload=t,n!=null&&(o.callback=n),t=gt(e,o,l),t!==null&&($e(t,e,l,r),Ar(t,e,l))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=ae(),r=yt(e),l=Ze(n,r);l.tag=2,t!=null&&(l.callback=t),t=gt(e,l,r),t!==null&&($e(t,e,r,n),Ar(t,e,r))}};function Ws(e,t,n,r,l,o,i){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,o,i):t.prototype&&t.prototype.isPureReactComponent?!Zn(n,r)||!Zn(l,o):!0}function ic(e,t,n){var r=!1,l=kt,o=t.contextType;return typeof o=="object"&&o!==null?o=Le(o):(l=ge(t)?Dt:se.current,r=t.contextTypes,o=(r=r!=null)?cn(e,l):kt),t=new t(n,o),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=Cl,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=o),t}function Hs(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Cl.enqueueReplaceState(t,t.state,null)}function Uo(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs={},Ti(e);var o=t.contextType;typeof o=="object"&&o!==null?l.context=Le(o):(o=ge(t)?Dt:se.current,l.context=cn(e,o)),l.state=e.memoizedState,o=t.getDerivedStateFromProps,typeof o=="function"&&(Bo(e,t,o,n),l.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof l.getSnapshotBeforeUpdate=="function"||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(t=l.state,typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount(),t!==l.state&&Cl.enqueueReplaceState(l,l.state,null),ll(e,n,l,r),l.state=e.memoizedState),typeof l.componentDidMount=="function"&&(e.flags|=4194308)}function hn(e,t){try{var n="",r=t;do n+=Ed(r),r=r.return;while(r);var l=n}catch(o){l=`
Error generating stack: `+o.message+`
`+o.stack}return{value:e,source:t,stack:l,digest:null}}function no(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Vo(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var Jf=typeof WeakMap=="function"?WeakMap:Map;function sc(e,t,n){n=Ze(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){al||(al=!0,Jo=r),Vo(e,t)},n}function uc(e,t,n){n=Ze(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){Vo(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(n.callback=function(){Vo(e,t),typeof r!="function"&&(vt===null?vt=new Set([this]):vt.add(this));var i=t.stack;this.componentDidCatch(t.value,{componentStack:i!==null?i:""})}),n}function Qs(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Jf;var l=new Set;r.set(t,l)}else l=r.get(t),l===void 0&&(l=new Set,r.set(t,l));l.has(n)||(l.add(n),e=fp.bind(null,e,t,n),t.then(e,e))}function bs(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ks(e,t,n,r,l){return e.mode&1?(e.flags|=65536,e.lanes=l,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Ze(-1,1),t.tag=2,gt(n,t,1))),n.lanes|=1),e)}var qf=nt.ReactCurrentOwner,he=!1;function ue(e,t,n,r){t.child=e===null?Oa(t,null,n,r):fn(t,e.child,n,r)}function Gs(e,t,n,r,l){n=n.render;var o=t.ref;return on(t,l),r=Oi(e,t,n,r,o,l),n=$i(),e!==null&&!he?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,tt(e,t,l)):(V&&n&&ji(t),t.flags|=1,ue(e,t,r,l),t.child)}function Ys(e,t,n,r,l){if(e===null){var o=n.type;return typeof o=="function"&&!Gi(o)&&o.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=o,ac(e,t,o,r,l)):(e=Vr(n.type,null,r,t,t.mode,l),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,!(e.lanes&l)){var i=o.memoizedProps;if(n=n.compare,n=n!==null?n:Zn,n(i,r)&&e.ref===t.ref)return tt(e,t,l)}return t.flags|=1,e=xt(o,r),e.ref=t.ref,e.return=t,t.child=e}function ac(e,t,n,r,l){if(e!==null){var o=e.memoizedProps;if(Zn(o,r)&&e.ref===t.ref)if(he=!1,t.pendingProps=r=o,(e.lanes&l)!==0)e.flags&131072&&(he=!0);else return t.lanes=e.lanes,tt(e,t,l)}return Wo(e,t,n,r,l)}function cc(e,t,n){var r=t.pendingProps,l=r.children,o=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},$(en,we),we|=n;else{if(!(n&1073741824))return e=o!==null?o.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,$(en,we),we|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:n,$(en,we),we|=r}else o!==null?(r=o.baseLanes|n,t.memoizedState=null):r=n,$(en,we),we|=r;return ue(e,t,l,n),t.child}function dc(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Wo(e,t,n,r,l){var o=ge(n)?Dt:se.current;return o=cn(t,o),on(t,l),n=Oi(e,t,n,r,o,l),r=$i(),e!==null&&!he?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,tt(e,t,l)):(V&&r&&ji(t),t.flags|=1,ue(e,t,n,l),t.child)}function Xs(e,t,n,r,l){if(ge(n)){var o=!0;qr(t)}else o=!1;if(on(t,l),t.stateNode===null)Fr(e,t),ic(t,n,r),Uo(t,n,r,l),r=!0;else if(e===null){var i=t.stateNode,u=t.memoizedProps;i.props=u;var s=i.context,c=n.contextType;typeof c=="object"&&c!==null?c=Le(c):(c=ge(n)?Dt:se.current,c=cn(t,c));var m=n.getDerivedStateFromProps,f=typeof m=="function"||typeof i.getSnapshotBeforeUpdate=="function";f||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==r||s!==c)&&Hs(t,i,r,c),it=!1;var p=t.memoizedState;i.state=p,ll(t,r,i,l),s=t.memoizedState,u!==r||p!==s||me.current||it?(typeof m=="function"&&(Bo(t,n,m,r),s=t.memoizedState),(u=it||Ws(t,n,u,r,p,s,c))?(f||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(t.flags|=4194308)):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=s),i.props=r,i.state=s,i.context=c,r=u):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{i=t.stateNode,Fa(e,t),u=t.memoizedProps,c=t.type===t.elementType?u:De(t.type,u),i.props=c,f=t.pendingProps,p=i.context,s=n.contextType,typeof s=="object"&&s!==null?s=Le(s):(s=ge(n)?Dt:se.current,s=cn(t,s));var y=n.getDerivedStateFromProps;(m=typeof y=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==f||p!==s)&&Hs(t,i,r,s),it=!1,p=t.memoizedState,i.state=p,ll(t,r,i,l);var v=t.memoizedState;u!==f||p!==v||me.current||it?(typeof y=="function"&&(Bo(t,n,y,r),v=t.memoizedState),(c=it||Ws(t,n,c,r,p,v,s)||!1)?(m||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,v,s),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,v,s)),typeof i.componentDidUpdate=="function"&&(t.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=v),i.props=r,i.state=v,i.context=s,r=c):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),r=!1)}return Ho(e,t,n,r,o,l)}function Ho(e,t,n,r,l,o){dc(e,t);var i=(t.flags&128)!==0;if(!r&&!i)return l&&Ms(t,n,!1),tt(e,t,o);r=t.stateNode,qf.current=t;var u=i&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&i?(t.child=fn(t,e.child,null,o),t.child=fn(t,null,u,o)):ue(e,t,u,o),t.memoizedState=r.state,l&&Ms(t,n,!0),t.child}function fc(e){var t=e.stateNode;t.pendingContext?Ds(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Ds(e,t.context,!1),Ri(e,t.containerInfo)}function Zs(e,t,n,r,l){return dn(),Pi(l),t.flags|=256,ue(e,t,n,r),t.child}var Qo={dehydrated:null,treeContext:null,retryLane:0};function bo(e){return{baseLanes:e,cachePool:null,transitions:null}}function pc(e,t,n){var r=t.pendingProps,l=W.current,o=!1,i=(t.flags&128)!==0,u;if((u=i)||(u=e!==null&&e.memoizedState===null?!1:(l&2)!==0),u?(o=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),$(W,l&1),e===null)return $o(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(i=r.children,e=r.fallback,o?(r=t.mode,o=t.child,i={mode:"hidden",children:i},!(r&1)&&o!==null?(o.childLanes=0,o.pendingProps=i):o=Nl(i,r,0,null),e=Rt(e,r,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=bo(n),t.memoizedState=Qo,e):Ui(t,i));if(l=e.memoizedState,l!==null&&(u=l.dehydrated,u!==null))return ep(e,t,i,r,u,l,n);if(o){o=r.fallback,i=t.mode,l=e.child,u=l.sibling;var s={mode:"hidden",children:r.children};return!(i&1)&&t.child!==l?(r=t.child,r.childLanes=0,r.pendingProps=s,t.deletions=null):(r=xt(l,s),r.subtreeFlags=l.subtreeFlags&14680064),u!==null?o=xt(u,o):(o=Rt(o,i,n,null),o.flags|=2),o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,i=e.child.memoizedState,i=i===null?bo(n):{baseLanes:i.baseLanes|n,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~n,t.memoizedState=Qo,r}return o=e.child,e=o.sibling,r=xt(o,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function Ui(e,t){return t=Nl({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Pr(e,t,n,r){return r!==null&&Pi(r),fn(t,e.child,null,n),e=Ui(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function ep(e,t,n,r,l,o,i){if(n)return t.flags&256?(t.flags&=-257,r=no(Error(C(422))),Pr(e,t,i,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(o=r.fallback,l=t.mode,r=Nl({mode:"visible",children:r.children},l,0,null),o=Rt(o,l,i,null),o.flags|=2,r.return=t,o.return=t,r.sibling=o,t.child=r,t.mode&1&&fn(t,e.child,null,i),t.child.memoizedState=bo(i),t.memoizedState=Qo,o);if(!(t.mode&1))return Pr(e,t,i,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var u=r.dgst;return r=u,o=Error(C(419)),r=no(o,r,void 0),Pr(e,t,i,r)}if(u=(i&e.childLanes)!==0,he||u){if(r=q,r!==null){switch(i&-i){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=l&(r.suspendedLanes|i)?0:l,l!==0&&l!==o.retryLane&&(o.retryLane=l,et(e,l),$e(r,e,l,-1))}return Ki(),r=no(Error(C(421))),Pr(e,t,i,r)}return l.data==="$?"?(t.flags|=128,t.child=e.child,t=pp.bind(null,e),l._reactRetry=t,null):(e=o.treeContext,ke=mt(l.nextSibling),Se=t,V=!0,Ae=null,e!==null&&(Pe[_e++]=Ye,Pe[_e++]=Xe,Pe[_e++]=Mt,Ye=e.id,Xe=e.overflow,Mt=t),t=Ui(t,r.children),t.flags|=4096,t)}function Js(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Fo(e.return,t,n)}function ro(e,t,n,r,l){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=l)}function hc(e,t,n){var r=t.pendingProps,l=r.revealOrder,o=r.tail;if(ue(e,t,r.children,n),r=W.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Js(e,n,t);else if(e.tag===19)Js(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if($(W,r),!(t.mode&1))t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;n!==null;)e=n.alternate,e!==null&&ol(e)===null&&(l=n),n=n.sibling;n=l,n===null?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),ro(t,!1,l,n,o);break;case"backwards":for(n=null,l=t.child,t.child=null;l!==null;){if(e=l.alternate,e!==null&&ol(e)===null){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}ro(t,!0,n,null,o);break;case"together":ro(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Fr(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function tt(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Ot|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(C(153));if(t.child!==null){for(e=t.child,n=xt(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=xt(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function tp(e,t,n){switch(t.tag){case 3:fc(t),dn();break;case 5:Ba(t);break;case 1:ge(t.type)&&qr(t);break;case 4:Ri(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,l=t.memoizedProps.value;$(nl,r._currentValue),r._currentValue=l;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?($(W,W.current&1),t.flags|=128,null):n&t.child.childLanes?pc(e,t,n):($(W,W.current&1),e=tt(e,t,n),e!==null?e.sibling:null);$(W,W.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return hc(e,t,n);t.flags|=128}if(l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),$(W,W.current),r)break;return null;case 22:case 23:return t.lanes=0,cc(e,t,n)}return tt(e,t,n)}var mc,Ko,gc,vc;mc=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};Ko=function(){};gc=function(e,t,n,r){var l=e.memoizedProps;if(l!==r){e=t.stateNode,Lt(be.current);var o=null;switch(n){case"input":l=mo(e,l),r=mo(e,r),o=[];break;case"select":l=Q({},l,{value:void 0}),r=Q({},r,{value:void 0}),o=[];break;case"textarea":l=yo(e,l),r=yo(e,r),o=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Zr)}wo(n,r);var i;n=null;for(c in l)if(!r.hasOwnProperty(c)&&l.hasOwnProperty(c)&&l[c]!=null)if(c==="style"){var u=l[c];for(i in u)u.hasOwnProperty(i)&&(n||(n={}),n[i]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(Hn.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in r){var s=r[c];if(u=l!=null?l[c]:void 0,r.hasOwnProperty(c)&&s!==u&&(s!=null||u!=null))if(c==="style")if(u){for(i in u)!u.hasOwnProperty(i)||s&&s.hasOwnProperty(i)||(n||(n={}),n[i]="");for(i in s)s.hasOwnProperty(i)&&u[i]!==s[i]&&(n||(n={}),n[i]=s[i])}else n||(o||(o=[]),o.push(c,n)),n=s;else c==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,u=u?u.__html:void 0,s!=null&&u!==s&&(o=o||[]).push(c,s)):c==="children"?typeof s!="string"&&typeof s!="number"||(o=o||[]).push(c,""+s):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(Hn.hasOwnProperty(c)?(s!=null&&c==="onScroll"&&F("scroll",e),o||u===s||(o=[])):(o=o||[]).push(c,s))}n&&(o=o||[]).push("style",n);var c=o;(t.updateQueue=c)&&(t.flags|=4)}};vc=function(e,t,n,r){n!==r&&(t.flags|=4)};function _n(e,t){if(!V)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function oe(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function np(e,t,n){var r=t.pendingProps;switch(Ni(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return oe(t),null;case 1:return ge(t.type)&&Jr(),oe(t),null;case 3:return r=t.stateNode,pn(),B(me),B(se),Mi(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(jr(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Ae!==null&&(ti(Ae),Ae=null))),Ko(e,t),oe(t),null;case 5:Di(t);var l=Lt(nr.current);if(n=t.type,e!==null&&t.stateNode!=null)gc(e,t,n,r,l),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(C(166));return oe(t),null}if(e=Lt(be.current),jr(t)){r=t.stateNode,n=t.type;var o=t.memoizedProps;switch(r[He]=t,r[er]=o,e=(t.mode&1)!==0,n){case"dialog":F("cancel",r),F("close",r);break;case"iframe":case"object":case"embed":F("load",r);break;case"video":case"audio":for(l=0;l<Rn.length;l++)F(Rn[l],r);break;case"source":F("error",r);break;case"img":case"image":case"link":F("error",r),F("load",r);break;case"details":F("toggle",r);break;case"input":ss(r,o),F("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!o.multiple},F("invalid",r);break;case"textarea":as(r,o),F("invalid",r)}wo(n,o),l=null;for(var i in o)if(o.hasOwnProperty(i)){var u=o[i];i==="children"?typeof u=="string"?r.textContent!==u&&(o.suppressHydrationWarning!==!0&&Er(r.textContent,u,e),l=["children",u]):typeof u=="number"&&r.textContent!==""+u&&(o.suppressHydrationWarning!==!0&&Er(r.textContent,u,e),l=["children",""+u]):Hn.hasOwnProperty(i)&&u!=null&&i==="onScroll"&&F("scroll",r)}switch(n){case"input":gr(r),us(r,o,!0);break;case"textarea":gr(r),cs(r);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(r.onclick=Zr)}r=l,t.updateQueue=r,r!==null&&(t.flags|=4)}else{i=l.nodeType===9?l:l.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=Qu(n)),e==="http://www.w3.org/1999/xhtml"?n==="script"?(e=i.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[He]=t,e[er]=r,mc(e,t,!1,!1),t.stateNode=e;e:{switch(i=ko(n,r),n){case"dialog":F("cancel",e),F("close",e),l=r;break;case"iframe":case"object":case"embed":F("load",e),l=r;break;case"video":case"audio":for(l=0;l<Rn.length;l++)F(Rn[l],e);l=r;break;case"source":F("error",e),l=r;break;case"img":case"image":case"link":F("error",e),F("load",e),l=r;break;case"details":F("toggle",e),l=r;break;case"input":ss(e,r),l=mo(e,r),F("invalid",e);break;case"option":l=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},l=Q({},r,{value:void 0}),F("invalid",e);break;case"textarea":as(e,r),l=yo(e,r),F("invalid",e);break;default:l=r}wo(n,l),u=l;for(o in u)if(u.hasOwnProperty(o)){var s=u[o];o==="style"?Gu(e,s):o==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,s!=null&&bu(e,s)):o==="children"?typeof s=="string"?(n!=="textarea"||s!=="")&&Qn(e,s):typeof s=="number"&&Qn(e,""+s):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(Hn.hasOwnProperty(o)?s!=null&&o==="onScroll"&&F("scroll",e):s!=null&&di(e,o,s,i))}switch(n){case"input":gr(e),us(e,r,!1);break;case"textarea":gr(e),cs(e);break;case"option":r.value!=null&&e.setAttribute("value",""+wt(r.value));break;case"select":e.multiple=!!r.multiple,o=r.value,o!=null?tn(e,!!r.multiple,o,!1):r.defaultValue!=null&&tn(e,!!r.multiple,r.defaultValue,!0);break;default:typeof l.onClick=="function"&&(e.onclick=Zr)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return oe(t),null;case 6:if(e&&t.stateNode!=null)vc(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(C(166));if(n=Lt(nr.current),Lt(be.current),jr(t)){if(r=t.stateNode,n=t.memoizedProps,r[He]=t,(o=r.nodeValue!==n)&&(e=Se,e!==null))switch(e.tag){case 3:Er(r.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Er(r.nodeValue,n,(e.mode&1)!==0)}o&&(t.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[He]=t,t.stateNode=r}return oe(t),null;case 13:if(B(W),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(V&&ke!==null&&t.mode&1&&!(t.flags&128))Ma(),dn(),t.flags|=98560,o=!1;else if(o=jr(t),r!==null&&r.dehydrated!==null){if(e===null){if(!o)throw Error(C(318));if(o=t.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(C(317));o[He]=t}else dn(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;oe(t),o=!1}else Ae!==null&&(ti(Ae),Ae=null),o=!0;if(!o)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,t.mode&1&&(e===null||W.current&1?Z===0&&(Z=3):Ki())),t.updateQueue!==null&&(t.flags|=4),oe(t),null);case 4:return pn(),Ko(e,t),e===null&&Jn(t.stateNode.containerInfo),oe(t),null;case 10:return Ii(t.type._context),oe(t),null;case 17:return ge(t.type)&&Jr(),oe(t),null;case 19:if(B(W),o=t.memoizedState,o===null)return oe(t),null;if(r=(t.flags&128)!==0,i=o.rendering,i===null)if(r)_n(o,!1);else{if(Z!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(i=ol(e),i!==null){for(t.flags|=128,_n(o,!1),r=i.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;n!==null;)o=n,e=r,o.flags&=14680066,i=o.alternate,i===null?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=i.childLanes,o.lanes=i.lanes,o.child=i.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=i.memoizedProps,o.memoizedState=i.memoizedState,o.updateQueue=i.updateQueue,o.type=i.type,e=i.dependencies,o.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return $(W,W.current&1|2),t.child}e=e.sibling}o.tail!==null&&K()>mn&&(t.flags|=128,r=!0,_n(o,!1),t.lanes=4194304)}else{if(!r)if(e=ol(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),_n(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!V)return oe(t),null}else 2*K()-o.renderingStartTime>mn&&n!==1073741824&&(t.flags|=128,r=!0,_n(o,!1),t.lanes=4194304);o.isBackwards?(i.sibling=t.child,t.child=i):(n=o.last,n!==null?n.sibling=i:t.child=i,o.last=i)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=K(),t.sibling=null,n=W.current,$(W,r?n&1|2:n&1),t):(oe(t),null);case 22:case 23:return bi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?we&1073741824&&(oe(t),t.subtreeFlags&6&&(t.flags|=8192)):oe(t),null;case 24:return null;case 25:return null}throw Error(C(156,t.tag))}function rp(e,t){switch(Ni(t),t.tag){case 1:return ge(t.type)&&Jr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pn(),B(me),B(se),Mi(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Di(t),null;case 13:if(B(W),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(C(340));dn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return B(W),null;case 4:return pn(),null;case 10:return Ii(t.type._context),null;case 22:case 23:return bi(),null;case 24:return null;default:return null}}var _r=!1,ie=!1,lp=typeof WeakSet=="function"?WeakSet:Set,N=null;function qt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){b(e,t,r)}else n.current=null}function Go(e,t,n){try{n()}catch(r){b(e,t,r)}}var qs=!1;function op(e,t){if(Lo=Gr,e=Sa(),Ei(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var i=0,u=-1,s=-1,c=0,m=0,f=e,p=null;t:for(;;){for(var y;f!==n||l!==0&&f.nodeType!==3||(u=i+l),f!==o||r!==0&&f.nodeType!==3||(s=i+r),f.nodeType===3&&(i+=f.nodeValue.length),(y=f.firstChild)!==null;)p=f,f=y;for(;;){if(f===e)break t;if(p===n&&++c===l&&(u=i),p===o&&++m===r&&(s=i),(y=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=y}n=u===-1||s===-1?null:{start:u,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(To={focusedElem:e,selectionRange:n},Gr=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var x=v.memoizedProps,w=v.memoizedState,h=t.stateNode,d=h.getSnapshotBeforeUpdate(t.elementType===t.type?x:De(t.type,x),w);h.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(C(163))}}catch(k){b(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return v=qs,qs=!1,v}function Un(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&Go(t,n,o)}l=l.next}while(l!==r)}}function El(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Yo(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function yc(e){var t=e.alternate;t!==null&&(e.alternate=null,yc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[He],delete t[er],delete t[Mo],delete t[Uf],delete t[Vf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function xc(e){return e.tag===5||e.tag===3||e.tag===4}function eu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||xc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Xo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Zr));else if(r!==4&&(e=e.child,e!==null))for(Xo(e,t,n),e=e.sibling;e!==null;)Xo(e,t,n),e=e.sibling}function Zo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Zo(e,t,n),e=e.sibling;e!==null;)Zo(e,t,n),e=e.sibling}var ee=null,Me=!1;function lt(e,t,n){for(n=n.child;n!==null;)wc(e,t,n),n=n.sibling}function wc(e,t,n){if(Qe&&typeof Qe.onCommitFiberUnmount=="function")try{Qe.onCommitFiberUnmount(gl,n)}catch{}switch(n.tag){case 5:ie||qt(n,t);case 6:var r=ee,l=Me;ee=null,lt(e,t,n),ee=r,Me=l,ee!==null&&(Me?(e=ee,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ee.removeChild(n.stateNode));break;case 18:ee!==null&&(Me?(e=ee,n=n.stateNode,e.nodeType===8?Xl(e.parentNode,n):e.nodeType===1&&Xl(e,n),Yn(e)):Xl(ee,n.stateNode));break;case 4:r=ee,l=Me,ee=n.stateNode.containerInfo,Me=!0,lt(e,t,n),ee=r,Me=l;break;case 0:case 11:case 14:case 15:if(!ie&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,i=o.destroy;o=o.tag,i!==void 0&&(o&2||o&4)&&Go(n,t,i),l=l.next}while(l!==r)}lt(e,t,n);break;case 1:if(!ie&&(qt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){b(n,t,u)}lt(e,t,n);break;case 21:lt(e,t,n);break;case 22:n.mode&1?(ie=(r=ie)||n.memoizedState!==null,lt(e,t,n),ie=r):lt(e,t,n);break;default:lt(e,t,n)}}function tu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new lp),t.forEach(function(r){var l=hp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Re(e,t){var n=t.deletions;if(n!==null)for(var r=0;r<n.length;r++){var l=n[r];try{var o=e,i=t,u=i;e:for(;u!==null;){switch(u.tag){case 5:ee=u.stateNode,Me=!1;break e;case 3:ee=u.stateNode.containerInfo,Me=!0;break e;case 4:ee=u.stateNode.containerInfo,Me=!0;break e}u=u.return}if(ee===null)throw Error(C(160));wc(o,i,l),ee=null,Me=!1;var s=l.alternate;s!==null&&(s.return=null),l.return=null}catch(c){b(l,t,c)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)kc(t,e),t=t.sibling}function kc(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Re(t,e),Ve(e),r&4){try{Un(3,e,e.return),El(3,e)}catch(x){b(e,e.return,x)}try{Un(5,e,e.return)}catch(x){b(e,e.return,x)}}break;case 1:Re(t,e),Ve(e),r&512&&n!==null&&qt(n,n.return);break;case 5:if(Re(t,e),Ve(e),r&512&&n!==null&&qt(n,n.return),e.flags&32){var l=e.stateNode;try{Qn(l,"")}catch(x){b(e,e.return,x)}}if(r&4&&(l=e.stateNode,l!=null)){var o=e.memoizedProps,i=n!==null?n.memoizedProps:o,u=e.type,s=e.updateQueue;if(e.updateQueue=null,s!==null)try{u==="input"&&o.type==="radio"&&o.name!=null&&Wu(l,o),ko(u,i);var c=ko(u,o);for(i=0;i<s.length;i+=2){var m=s[i],f=s[i+1];m==="style"?Gu(l,f):m==="dangerouslySetInnerHTML"?bu(l,f):m==="children"?Qn(l,f):di(l,m,f,c)}switch(u){case"input":go(l,o);break;case"textarea":Hu(l,o);break;case"select":var p=l._wrapperState.wasMultiple;l._wrapperState.wasMultiple=!!o.multiple;var y=o.value;y!=null?tn(l,!!o.multiple,y,!1):p!==!!o.multiple&&(o.defaultValue!=null?tn(l,!!o.multiple,o.defaultValue,!0):tn(l,!!o.multiple,o.multiple?[]:"",!1))}l[er]=o}catch(x){b(e,e.return,x)}}break;case 6:if(Re(t,e),Ve(e),r&4){if(e.stateNode===null)throw Error(C(162));l=e.stateNode,o=e.memoizedProps;try{l.nodeValue=o}catch(x){b(e,e.return,x)}}break;case 3:if(Re(t,e),Ve(e),r&4&&n!==null&&n.memoizedState.isDehydrated)try{Yn(t.containerInfo)}catch(x){b(e,e.return,x)}break;case 4:Re(t,e),Ve(e);break;case 13:Re(t,e),Ve(e),l=e.child,l.flags&8192&&(o=l.memoizedState!==null,l.stateNode.isHidden=o,!o||l.alternate!==null&&l.alternate.memoizedState!==null||(Hi=K())),r&4&&tu(e);break;case 22:if(m=n!==null&&n.memoizedState!==null,e.mode&1?(ie=(c=ie)||m,Re(t,e),ie=c):Re(t,e),Ve(e),r&8192){if(c=e.memoizedState!==null,(e.stateNode.isHidden=c)&&!m&&e.mode&1)for(N=e,m=e.child;m!==null;){for(f=N=m;N!==null;){switch(p=N,y=p.child,p.tag){case 0:case 11:case 14:case 15:Un(4,p,p.return);break;case 1:qt(p,p.return);var v=p.stateNode;if(typeof v.componentWillUnmount=="function"){r=p,n=p.return;try{t=r,v.props=t.memoizedProps,v.state=t.memoizedState,v.componentWillUnmount()}catch(x){b(r,n,x)}}break;case 5:qt(p,p.return);break;case 22:if(p.memoizedState!==null){ru(f);continue}}y!==null?(y.return=p,N=y):ru(f)}m=m.sibling}e:for(m=null,f=e;;){if(f.tag===5){if(m===null){m=f;try{l=f.stateNode,c?(o=l.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(u=f.stateNode,s=f.memoizedProps.style,i=s!=null&&s.hasOwnProperty("display")?s.display:null,u.style.display=Ku("display",i))}catch(x){b(e,e.return,x)}}}else if(f.tag===6){if(m===null)try{f.stateNode.nodeValue=c?"":f.memoizedProps}catch(x){b(e,e.return,x)}}else if((f.tag!==22&&f.tag!==23||f.memoizedState===null||f===e)&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===e)break e;for(;f.sibling===null;){if(f.return===null||f.return===e)break e;m===f&&(m=null),f=f.return}m===f&&(m=null),f.sibling.return=f.return,f=f.sibling}}break;case 19:Re(t,e),Ve(e),r&4&&tu(e);break;case 21:break;default:Re(t,e),Ve(e)}}function Ve(e){var t=e.flags;if(t&2){try{e:{for(var n=e.return;n!==null;){if(xc(n)){var r=n;break e}n=n.return}throw Error(C(160))}switch(r.tag){case 5:var l=r.stateNode;r.flags&32&&(Qn(l,""),r.flags&=-33);var o=eu(e);Zo(e,o,l);break;case 3:case 4:var i=r.stateNode.containerInfo,u=eu(e);Xo(e,u,i);break;default:throw Error(C(161))}}catch(s){b(e,e.return,s)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function ip(e,t,n){N=e,Sc(e)}function Sc(e,t,n){for(var r=(e.mode&1)!==0;N!==null;){var l=N,o=l.child;if(l.tag===22&&r){var i=l.memoizedState!==null||_r;if(!i){var u=l.alternate,s=u!==null&&u.memoizedState!==null||ie;u=_r;var c=ie;if(_r=i,(ie=s)&&!c)for(N=l;N!==null;)i=N,s=i.child,i.tag===22&&i.memoizedState!==null?lu(l):s!==null?(s.return=i,N=s):lu(l);for(;o!==null;)N=o,Sc(o),o=o.sibling;N=l,_r=u,ie=c}nu(e)}else l.subtreeFlags&8772&&o!==null?(o.return=l,N=o):nu(e)}}function nu(e){for(;N!==null;){var t=N;if(t.flags&8772){var n=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:ie||El(5,t);break;case 1:var r=t.stateNode;if(t.flags&4&&!ie)if(n===null)r.componentDidMount();else{var l=t.elementType===t.type?n.memoizedProps:De(t.type,n.memoizedProps);r.componentDidUpdate(l,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var o=t.updateQueue;o!==null&&Bs(t,o,r);break;case 3:var i=t.updateQueue;if(i!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}Bs(t,i,n)}break;case 5:var u=t.stateNode;if(n===null&&t.flags&4){n=u;var s=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":s.autoFocus&&n.focus();break;case"img":s.src&&(n.src=s.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var c=t.alternate;if(c!==null){var m=c.memoizedState;if(m!==null){var f=m.dehydrated;f!==null&&Yn(f)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(C(163))}ie||t.flags&512&&Yo(t)}catch(p){b(t,t.return,p)}}if(t===e){N=null;break}if(n=t.sibling,n!==null){n.return=t.return,N=n;break}N=t.return}}function ru(e){for(;N!==null;){var t=N;if(t===e){N=null;break}var n=t.sibling;if(n!==null){n.return=t.return,N=n;break}N=t.return}}function lu(e){for(;N!==null;){var t=N;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{El(4,t)}catch(s){b(t,n,s)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount=="function"){var l=t.return;try{r.componentDidMount()}catch(s){b(t,l,s)}}var o=t.return;try{Yo(t)}catch(s){b(t,o,s)}break;case 5:var i=t.return;try{Yo(t)}catch(s){b(t,i,s)}}}catch(s){b(t,t.return,s)}if(t===e){N=null;break}var u=t.sibling;if(u!==null){u.return=t.return,N=u;break}N=t.return}}var sp=Math.ceil,ul=nt.ReactCurrentDispatcher,Vi=nt.ReactCurrentOwner,Ie=nt.ReactCurrentBatchConfig,A=0,q=null,G=null,te=0,we=0,en=Ct(0),Z=0,ir=null,Ot=0,jl=0,Wi=0,Vn=null,pe=null,Hi=0,mn=1/0,Ke=null,al=!1,Jo=null,vt=null,zr=!1,ct=null,cl=0,Wn=0,qo=null,Br=-1,Ur=0;function ae(){return A&6?K():Br!==-1?Br:Br=K()}function yt(e){return e.mode&1?A&2&&te!==0?te&-te:Hf.transition!==null?(Ur===0&&(Ur=ia()),Ur):(e=O,e!==0||(e=window.event,e=e===void 0?16:pa(e.type)),e):1}function $e(e,t,n,r){if(50<Wn)throw Wn=0,qo=null,Error(C(185));ur(e,n,r),(!(A&2)||e!==q)&&(e===q&&(!(A&2)&&(jl|=n),Z===4&&ut(e,te)),ve(e,r),n===1&&A===0&&!(t.mode&1)&&(mn=K()+500,kl&&Et()))}function ve(e,t){var n=e.callbackNode;Wd(e,t);var r=Kr(e,e===q?te:0);if(r===0)n!==null&&ps(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(n!=null&&ps(n),t===1)e.tag===0?Wf(ou.bind(null,e)):Ta(ou.bind(null,e)),Ff(function(){!(A&6)&&Et()}),n=null;else{switch(sa(r)){case 1:n=gi;break;case 4:n=la;break;case 16:n=br;break;case 536870912:n=oa;break;default:n=br}n=Ic(n,Cc.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function Cc(e,t){if(Br=-1,Ur=0,A&6)throw Error(C(327));var n=e.callbackNode;if(sn()&&e.callbackNode!==n)return null;var r=Kr(e,e===q?te:0);if(r===0)return null;if(r&30||r&e.expiredLanes||t)t=dl(e,r);else{t=r;var l=A;A|=2;var o=jc();(q!==e||te!==t)&&(Ke=null,mn=K()+500,Tt(e,t));do try{cp();break}catch(u){Ec(e,u)}while(!0);zi(),ul.current=o,A=l,G!==null?t=0:(q=null,te=0,t=Z)}if(t!==0){if(t===2&&(l=No(e),l!==0&&(r=l,t=ei(e,l))),t===1)throw n=ir,Tt(e,0),ut(e,r),ve(e,K()),n;if(t===6)ut(e,r);else{if(l=e.current.alternate,!(r&30)&&!up(l)&&(t=dl(e,r),t===2&&(o=No(e),o!==0&&(r=o,t=ei(e,o))),t===1))throw n=ir,Tt(e,0),ut(e,r),ve(e,K()),n;switch(e.finishedWork=l,e.finishedLanes=r,t){case 0:case 1:throw Error(C(345));case 2:_t(e,pe,Ke);break;case 3:if(ut(e,r),(r&130023424)===r&&(t=Hi+500-K(),10<t)){if(Kr(e,0)!==0)break;if(l=e.suspendedLanes,(l&r)!==r){ae(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=Do(_t.bind(null,e,pe,Ke),t);break}_t(e,pe,Ke);break;case 4:if(ut(e,r),(r&4194240)===r)break;for(t=e.eventTimes,l=-1;0<r;){var i=31-Oe(r);o=1<<i,i=t[i],i>l&&(l=i),r&=~o}if(r=l,r=K()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*sp(r/1960))-r,10<r){e.timeoutHandle=Do(_t.bind(null,e,pe,Ke),r);break}_t(e,pe,Ke);break;case 5:_t(e,pe,Ke);break;default:throw Error(C(329))}}}return ve(e,K()),e.callbackNode===n?Cc.bind(null,e):null}function ei(e,t){var n=Vn;return e.current.memoizedState.isDehydrated&&(Tt(e,t).flags|=256),e=dl(e,t),e!==2&&(t=pe,pe=n,t!==null&&ti(t)),e}function ti(e){pe===null?pe=e:pe.push.apply(pe,e)}function up(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var l=n[r],o=l.getSnapshot;l=l.value;try{if(!Fe(o(),l))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function ut(e,t){for(t&=~Wi,t&=~jl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-Oe(t),r=1<<n;e[n]=-1,t&=~r}}function ou(e){if(A&6)throw Error(C(327));sn();var t=Kr(e,0);if(!(t&1))return ve(e,K()),null;var n=dl(e,t);if(e.tag!==0&&n===2){var r=No(e);r!==0&&(t=r,n=ei(e,r))}if(n===1)throw n=ir,Tt(e,0),ut(e,t),ve(e,K()),n;if(n===6)throw Error(C(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,_t(e,pe,Ke),ve(e,K()),null}function Qi(e,t){var n=A;A|=1;try{return e(t)}finally{A=n,A===0&&(mn=K()+500,kl&&Et())}}function $t(e){ct!==null&&ct.tag===0&&!(A&6)&&sn();var t=A;A|=1;var n=Ie.transition,r=O;try{if(Ie.transition=null,O=1,e)return e()}finally{O=r,Ie.transition=n,A=t,!(A&6)&&Et()}}function bi(){we=en.current,B(en)}function Tt(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,$f(n)),G!==null)for(n=G.return;n!==null;){var r=n;switch(Ni(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&Jr();break;case 3:pn(),B(me),B(se),Mi();break;case 5:Di(r);break;case 4:pn();break;case 13:B(W);break;case 19:B(W);break;case 10:Ii(r.type._context);break;case 22:case 23:bi()}n=n.return}if(q=e,G=e=xt(e.current,null),te=we=t,Z=0,ir=null,Wi=jl=Ot=0,pe=Vn=null,It!==null){for(t=0;t<It.length;t++)if(n=It[t],r=n.interleaved,r!==null){n.interleaved=null;var l=r.next,o=n.pending;if(o!==null){var i=o.next;o.next=l,r.next=i}n.pending=r}It=null}return e}function Ec(e,t){do{var n=G;try{if(zi(),Or.current=sl,il){for(var r=H.memoizedState;r!==null;){var l=r.queue;l!==null&&(l.pending=null),r=r.next}il=!1}if(At=0,J=X=H=null,Bn=!1,rr=0,Vi.current=null,n===null||n.return===null){Z=1,ir=t,G=null;break}e:{var o=e,i=n.return,u=n,s=t;if(t=te,u.flags|=32768,s!==null&&typeof s=="object"&&typeof s.then=="function"){var c=s,m=u,f=m.tag;if(!(m.mode&1)&&(f===0||f===11||f===15)){var p=m.alternate;p?(m.updateQueue=p.updateQueue,m.memoizedState=p.memoizedState,m.lanes=p.lanes):(m.updateQueue=null,m.memoizedState=null)}var y=bs(i);if(y!==null){y.flags&=-257,Ks(y,i,u,o,t),y.mode&1&&Qs(o,c,t),t=y,s=c;var v=t.updateQueue;if(v===null){var x=new Set;x.add(s),t.updateQueue=x}else v.add(s);break e}else{if(!(t&1)){Qs(o,c,t),Ki();break e}s=Error(C(426))}}else if(V&&u.mode&1){var w=bs(i);if(w!==null){!(w.flags&65536)&&(w.flags|=256),Ks(w,i,u,o,t),Pi(hn(s,u));break e}}o=s=hn(s,u),Z!==4&&(Z=2),Vn===null?Vn=[o]:Vn.push(o),o=i;do{switch(o.tag){case 3:o.flags|=65536,t&=-t,o.lanes|=t;var h=sc(o,s,t);Fs(o,h);break e;case 1:u=s;var d=o.type,g=o.stateNode;if(!(o.flags&128)&&(typeof d.getDerivedStateFromError=="function"||g!==null&&typeof g.componentDidCatch=="function"&&(vt===null||!vt.has(g)))){o.flags|=65536,t&=-t,o.lanes|=t;var k=uc(o,u,t);Fs(o,k);break e}}o=o.return}while(o!==null)}Pc(n)}catch(E){t=E,G===n&&n!==null&&(G=n=n.return);continue}break}while(!0)}function jc(){var e=ul.current;return ul.current=sl,e===null?sl:e}function Ki(){(Z===0||Z===3||Z===2)&&(Z=4),q===null||!(Ot&268435455)&&!(jl&268435455)||ut(q,te)}function dl(e,t){var n=A;A|=2;var r=jc();(q!==e||te!==t)&&(Ke=null,Tt(e,t));do try{ap();break}catch(l){Ec(e,l)}while(!0);if(zi(),A=n,ul.current=r,G!==null)throw Error(C(261));return q=null,te=0,Z}function ap(){for(;G!==null;)Nc(G)}function cp(){for(;G!==null&&!Dd();)Nc(G)}function Nc(e){var t=zc(e.alternate,e,we);e.memoizedProps=e.pendingProps,t===null?Pc(e):G=t,Vi.current=null}function Pc(e){var t=e;do{var n=t.alternate;if(e=t.return,t.flags&32768){if(n=rp(n,t),n!==null){n.flags&=32767,G=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Z=6,G=null;return}}else if(n=np(n,t,we),n!==null){G=n;return}if(t=t.sibling,t!==null){G=t;return}G=t=e}while(t!==null);Z===0&&(Z=5)}function _t(e,t,n){var r=O,l=Ie.transition;try{Ie.transition=null,O=1,dp(e,t,n,r)}finally{Ie.transition=l,O=r}return null}function dp(e,t,n,r){do sn();while(ct!==null);if(A&6)throw Error(C(327));n=e.finishedWork;var l=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(C(177));e.callbackNode=null,e.callbackPriority=0;var o=n.lanes|n.childLanes;if(Hd(e,o),e===q&&(G=q=null,te=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||zr||(zr=!0,Ic(br,function(){return sn(),null})),o=(n.flags&15990)!==0,n.subtreeFlags&15990||o){o=Ie.transition,Ie.transition=null;var i=O;O=1;var u=A;A|=4,Vi.current=null,op(e,n),kc(n,e),Lf(To),Gr=!!Lo,To=Lo=null,e.current=n,ip(n),Md(),A=u,O=i,Ie.transition=o}else e.current=n;if(zr&&(zr=!1,ct=e,cl=l),o=e.pendingLanes,o===0&&(vt=null),$d(n.stateNode),ve(e,K()),t!==null)for(r=e.onRecoverableError,n=0;n<t.length;n++)l=t[n],r(l.value,{componentStack:l.stack,digest:l.digest});if(al)throw al=!1,e=Jo,Jo=null,e;return cl&1&&e.tag!==0&&sn(),o=e.pendingLanes,o&1?e===qo?Wn++:(Wn=0,qo=e):Wn=0,Et(),null}function sn(){if(ct!==null){var e=sa(cl),t=Ie.transition,n=O;try{if(Ie.transition=null,O=16>e?16:e,ct===null)var r=!1;else{if(e=ct,ct=null,cl=0,A&6)throw Error(C(331));var l=A;for(A|=4,N=e.current;N!==null;){var o=N,i=o.child;if(N.flags&16){var u=o.deletions;if(u!==null){for(var s=0;s<u.length;s++){var c=u[s];for(N=c;N!==null;){var m=N;switch(m.tag){case 0:case 11:case 15:Un(8,m,o)}var f=m.child;if(f!==null)f.return=m,N=f;else for(;N!==null;){m=N;var p=m.sibling,y=m.return;if(yc(m),m===c){N=null;break}if(p!==null){p.return=y,N=p;break}N=y}}}var v=o.alternate;if(v!==null){var x=v.child;if(x!==null){v.child=null;do{var w=x.sibling;x.sibling=null,x=w}while(x!==null)}}N=o}}if(o.subtreeFlags&2064&&i!==null)i.return=o,N=i;else e:for(;N!==null;){if(o=N,o.flags&2048)switch(o.tag){case 0:case 11:case 15:Un(9,o,o.return)}var h=o.sibling;if(h!==null){h.return=o.return,N=h;break e}N=o.return}}var d=e.current;for(N=d;N!==null;){i=N;var g=i.child;if(i.subtreeFlags&2064&&g!==null)g.return=i,N=g;else e:for(i=d;N!==null;){if(u=N,u.flags&2048)try{switch(u.tag){case 0:case 11:case 15:El(9,u)}}catch(E){b(u,u.return,E)}if(u===i){N=null;break e}var k=u.sibling;if(k!==null){k.return=u.return,N=k;break e}N=u.return}}if(A=l,Et(),Qe&&typeof Qe.onPostCommitFiberRoot=="function")try{Qe.onPostCommitFiberRoot(gl,e)}catch{}r=!0}return r}finally{O=n,Ie.transition=t}}return!1}function iu(e,t,n){t=hn(n,t),t=sc(e,t,1),e=gt(e,t,1),t=ae(),e!==null&&(ur(e,1,t),ve(e,t))}function b(e,t,n){if(e.tag===3)iu(e,e,n);else for(;t!==null;){if(t.tag===3){iu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(vt===null||!vt.has(r))){e=hn(n,e),e=uc(t,e,1),t=gt(t,e,1),e=ae(),t!==null&&(ur(t,1,e),ve(t,e));break}}t=t.return}}function fp(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),t=ae(),e.pingedLanes|=e.suspendedLanes&n,q===e&&(te&n)===n&&(Z===4||Z===3&&(te&130023424)===te&&500>K()-Hi?Tt(e,0):Wi|=n),ve(e,t)}function _c(e,t){t===0&&(e.mode&1?(t=xr,xr<<=1,!(xr&130023424)&&(xr=4194304)):t=1);var n=ae();e=et(e,t),e!==null&&(ur(e,t,n),ve(e,n))}function pp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),_c(e,n)}function hp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(C(314))}r!==null&&r.delete(t),_c(e,n)}var zc;zc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||me.current)he=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return he=!1,tp(e,t,n);he=!!(e.flags&131072)}else he=!1,V&&t.flags&1048576&&Ra(t,tl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fr(e,t),e=t.pendingProps;var l=cn(t,se.current);on(t,n),l=Oi(null,t,r,e,l,n);var o=$i();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ge(r)?(o=!0,qr(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ti(t),l.updater=Cl,t.stateNode=l,l._reactInternals=t,Uo(t,r,e,n),t=Ho(null,t,r,!0,o,n)):(t.tag=0,V&&o&&ji(t),ue(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=gp(r),e=De(r,e),l){case 0:t=Wo(null,t,r,e,n);break e;case 1:t=Xs(null,t,r,e,n);break e;case 11:t=Gs(null,t,r,e,n);break e;case 14:t=Ys(null,t,r,De(r.type,e),n);break e}throw Error(C(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:De(r,l),Wo(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:De(r,l),Xs(e,t,r,l,n);case 3:e:{if(fc(t),e===null)throw Error(C(387));r=t.pendingProps,o=t.memoizedState,l=o.element,Fa(e,t),ll(t,r,null,n);var i=t.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=hn(Error(C(423)),t),t=Zs(e,t,r,n,l);break e}else if(r!==l){l=hn(Error(C(424)),t),t=Zs(e,t,r,n,l);break e}else for(ke=mt(t.stateNode.containerInfo.firstChild),Se=t,V=!0,Ae=null,n=Oa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(dn(),r===l){t=tt(e,t,n);break e}ue(e,t,r,n)}t=t.child}return t;case 5:return Ba(t),e===null&&$o(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,i=l.children,Ro(r,l)?i=null:o!==null&&Ro(r,o)&&(t.flags|=32),dc(e,t),ue(e,t,i,n),t.child;case 6:return e===null&&$o(t),null;case 13:return pc(e,t,n);case 4:return Ri(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fn(t,null,r,n):ue(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:De(r,l),Gs(e,t,r,l,n);case 7:return ue(e,t,t.pendingProps,n),t.child;case 8:return ue(e,t,t.pendingProps.children,n),t.child;case 12:return ue(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,i=l.value,$(nl,r._currentValue),r._currentValue=i,o!==null)if(Fe(o.value,i)){if(o.children===l.children&&!me.current){t=tt(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){i=o.child;for(var s=u.firstContext;s!==null;){if(s.context===r){if(o.tag===1){s=Ze(-1,n&-n),s.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var m=c.pending;m===null?s.next=s:(s.next=m.next,m.next=s),c.pending=s}}o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),Fo(o.return,n,t),u.lanes|=n;break}s=s.next}}else if(o.tag===10)i=o.type===t.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(C(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Fo(i,n,t),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===t){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}ue(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,on(t,n),l=Le(l),r=r(l),t.flags|=1,ue(e,t,r,n),t.child;case 14:return r=t.type,l=De(r,t.pendingProps),l=De(r.type,l),Ys(e,t,r,l,n);case 15:return ac(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:De(r,l),Fr(e,t),t.tag=1,ge(r)?(e=!0,qr(t)):e=!1,on(t,n),ic(t,r,l),Uo(t,r,l,n),Ho(null,t,r,!0,e,n);case 19:return hc(e,t,n);case 22:return cc(e,t,n)}throw Error(C(156,t.tag))};function Ic(e,t){return ra(e,t)}function mp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ze(e,t,n,r){return new mp(e,t,n,r)}function Gi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function gp(e){if(typeof e=="function")return Gi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===pi)return 11;if(e===hi)return 14}return 2}function xt(e,t){var n=e.alternate;return n===null?(n=ze(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Vr(e,t,n,r,l,o){var i=2;if(r=e,typeof e=="function")Gi(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Ht:return Rt(n.children,l,o,t);case fi:i=8,l|=8;break;case co:return e=ze(12,n,t,l|2),e.elementType=co,e.lanes=o,e;case fo:return e=ze(13,n,t,l),e.elementType=fo,e.lanes=o,e;case po:return e=ze(19,n,t,l),e.elementType=po,e.lanes=o,e;case Bu:return Nl(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case $u:i=10;break e;case Fu:i=9;break e;case pi:i=11;break e;case hi:i=14;break e;case ot:i=16,r=null;break e}throw Error(C(130,e==null?e:typeof e,""))}return t=ze(i,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function Rt(e,t,n,r){return e=ze(7,e,r,t),e.lanes=n,e}function Nl(e,t,n,r){return e=ze(22,e,r,t),e.elementType=Bu,e.lanes=n,e.stateNode={isHidden:!1},e}function lo(e,t,n){return e=ze(6,e,null,t),e.lanes=n,e}function oo(e,t,n){return t=ze(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function vp(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Fl(0),this.expirationTimes=Fl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Fl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Yi(e,t,n,r,l,o,i,u,s){return e=new vp(e,t,n,u,s),t===1?(t=1,o===!0&&(t|=8)):t=0,o=ze(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ti(o),e}function yp(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Wt,key:r==null?null:""+r,children:e,containerInfo:t,implementation:n}}function Lc(e){if(!e)return kt;e=e._reactInternals;e:{if(Bt(e)!==e||e.tag!==1)throw Error(C(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(ge(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(C(171))}if(e.tag===1){var n=e.type;if(ge(n))return La(e,n,t)}return t}function Tc(e,t,n,r,l,o,i,u,s){return e=Yi(n,r,!0,e,l,o,i,u,s),e.context=Lc(null),n=e.current,r=ae(),l=yt(n),o=Ze(r,l),o.callback=t??null,gt(n,o,l),e.current.lanes=l,ur(e,l,r),ve(e,r),e}function Pl(e,t,n,r){var l=t.current,o=ae(),i=yt(l);return n=Lc(n),t.context===null?t.context=n:t.pendingContext=n,t=Ze(o,i),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=gt(l,t,i),e!==null&&($e(e,l,i,o),Ar(e,l,i)),i}function fl(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function su(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function Xi(e,t){su(e,t),(e=e.alternate)&&su(e,t)}function xp(){return null}var Rc=typeof reportError=="function"?reportError:function(e){console.error(e)};function Zi(e){this._internalRoot=e}_l.prototype.render=Zi.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(C(409));Pl(e,t,null,null)};_l.prototype.unmount=Zi.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;$t(function(){Pl(null,e,null,null)}),t[qe]=null}};function _l(e){this._internalRoot=e}_l.prototype.unstable_scheduleHydration=function(e){if(e){var t=ca();e={blockedOn:null,target:e,priority:t};for(var n=0;n<st.length&&t!==0&&t<st[n].priority;n++);st.splice(n,0,e),n===0&&fa(e)}};function Ji(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function zl(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function uu(){}function wp(e,t,n,r,l){if(l){if(typeof r=="function"){var o=r;r=function(){var c=fl(i);o.call(c)}}var i=Tc(t,r,e,0,null,!1,!1,"",uu);return e._reactRootContainer=i,e[qe]=i.current,Jn(e.nodeType===8?e.parentNode:e),$t(),i}for(;l=e.lastChild;)e.removeChild(l);if(typeof r=="function"){var u=r;r=function(){var c=fl(s);u.call(c)}}var s=Yi(e,0,!1,null,null,!1,!1,"",uu);return e._reactRootContainer=s,e[qe]=s.current,Jn(e.nodeType===8?e.parentNode:e),$t(function(){Pl(t,s,n,r)}),s}function Il(e,t,n,r,l){var o=n._reactRootContainer;if(o){var i=o;if(typeof l=="function"){var u=l;l=function(){var s=fl(i);u.call(s)}}Pl(t,i,e,l)}else i=wp(n,t,e,l,r);return fl(i)}ua=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=Tn(t.pendingLanes);n!==0&&(vi(t,n|1),ve(t,K()),!(A&6)&&(mn=K()+500,Et()))}break;case 13:$t(function(){var r=et(e,1);if(r!==null){var l=ae();$e(r,e,1,l)}}),Xi(e,1)}};yi=function(e){if(e.tag===13){var t=et(e,134217728);if(t!==null){var n=ae();$e(t,e,134217728,n)}Xi(e,134217728)}};aa=function(e){if(e.tag===13){var t=yt(e),n=et(e,t);if(n!==null){var r=ae();$e(n,e,t,r)}Xi(e,t)}};ca=function(){return O};da=function(e,t){var n=O;try{return O=e,t()}finally{O=n}};Co=function(e,t,n){switch(t){case"input":if(go(e,n),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=wl(r);if(!l)throw Error(C(90));Vu(r),go(r,l)}}}break;case"textarea":Hu(e,n);break;case"select":t=n.value,t!=null&&tn(e,!!n.multiple,t,!1)}};Zu=Qi;Ju=$t;var kp={usingClientEntryPoint:!1,Events:[cr,Gt,wl,Yu,Xu,Qi]},zn={findFiberByHostInstance:zt,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Sp={bundleType:zn.bundleType,version:zn.version,rendererPackageName:zn.rendererPackageName,rendererConfig:zn.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:nt.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=ta(e),e===null?null:e.stateNode},findFiberByHostInstance:zn.findFiberByHostInstance||xp,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Ir=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ir.isDisabled&&Ir.supportsFiber)try{gl=Ir.inject(Sp),Qe=Ir}catch{}}Ee.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=kp;Ee.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Ji(t))throw Error(C(200));return yp(e,t,null,n)};Ee.createRoot=function(e,t){if(!Ji(e))throw Error(C(299));var n=!1,r="",l=Rc;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onRecoverableError!==void 0&&(l=t.onRecoverableError)),t=Yi(e,1,!1,null,null,n,!1,r,l),e[qe]=t.current,Jn(e.nodeType===8?e.parentNode:e),new Zi(t)};Ee.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(C(188)):(e=Object.keys(e).join(","),Error(C(268,e)));return e=ta(t),e=e===null?null:e.stateNode,e};Ee.flushSync=function(e){return $t(e)};Ee.hydrate=function(e,t,n){if(!zl(t))throw Error(C(200));return Il(null,e,t,!0,n)};Ee.hydrateRoot=function(e,t,n){if(!Ji(e))throw Error(C(405));var r=n!=null&&n.hydratedSources||null,l=!1,o="",i=Rc;if(n!=null&&(n.unstable_strictMode===!0&&(l=!0),n.identifierPrefix!==void 0&&(o=n.identifierPrefix),n.onRecoverableError!==void 0&&(i=n.onRecoverableError)),t=Tc(t,null,e,1,n??null,l,!1,o,i),e[qe]=t.current,Jn(e),r)for(e=0;e<r.length;e++)n=r[e],l=n._getVersion,l=l(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,l]:t.mutableSourceEagerHydrationData.push(n,l);return new _l(t)};Ee.render=function(e,t,n){if(!zl(t))throw Error(C(200));return Il(null,e,t,!1,n)};Ee.unmountComponentAtNode=function(e){if(!zl(e))throw Error(C(40));return e._reactRootContainer?($t(function(){Il(null,null,e,!1,function(){e._reactRootContainer=null,e[qe]=null})}),!0):!1};Ee.unstable_batchedUpdates=Qi;Ee.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!zl(n))throw Error(C(200));if(e==null||e._reactInternals===void 0)throw Error(C(38));return Il(e,t,n,!1,r)};Ee.version="18.3.1-next-f1338f8080-20240426";function Dc(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Dc)}catch(e){console.error(e)}}Dc(),Du.exports=Ee;var Cp=Du.exports,au=Cp;uo.createRoot=au.createRoot,uo.hydrateRoot=au.hydrateRoot;/**
 * @remix-run/router v1.23.4
 *
 * 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
 */function pl(){return pl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},pl.apply(null,arguments)}var dt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(dt||(dt={}));const cu="popstate";function Ep(e){e===void 0&&(e={});function t(l,o){let{pathname:i="/",search:u="",hash:s=""}=fr(l.location.hash.substr(1));return!i.startsWith("/")&&!i.startsWith(".")&&(i="/"+i),ni("",{pathname:i,search:u,hash:s},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(l,o){let i=l.document.querySelector("base"),u="";if(i&&i.getAttribute("href")){let s=l.location.href,c=s.indexOf("#");u=c===-1?s:s.slice(0,c)}return u+"#"+(typeof o=="string"?o:Mc(o))}function r(l,o){qi(l.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(o)+")")}return Np(t,n,r,e)}function ye(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function qi(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function jp(){return Math.random().toString(36).substr(2,8)}function du(e,t){return{usr:e.state,key:e.key,idx:t}}function ni(e,t,n,r){return n===void 0&&(n=null),pl({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?fr(t):t,{state:n,key:t&&t.key||r||jp()})}function Mc(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function fr(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Np(e,t,n,r){r===void 0&&(r={});let{window:l=document.defaultView,v5Compat:o=!1}=r,i=l.history,u=dt.Pop,s=null,c=m();c==null&&(c=0,i.replaceState(pl({},i.state,{idx:c}),""));function m(){return(i.state||{idx:null}).idx}function f(){u=dt.Pop;let w=m(),h=w==null?null:w-c;c=w,s&&s({action:u,location:x.location,delta:h})}function p(w,h){u=dt.Push;let d=ni(x.location,w,h);n&&n(d,w),c=m()+1;let g=du(d,c),k=x.createHref(d);try{i.pushState(g,"",k)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;l.location.assign(k)}o&&s&&s({action:u,location:x.location,delta:1})}function y(w,h){u=dt.Replace;let d=ni(x.location,w,h);n&&n(d,w),c=m();let g=du(d,c),k=x.createHref(d);i.replaceState(g,"",k),o&&s&&s({action:u,location:x.location,delta:0})}function v(w){let h=l.location.origin!=="null"?l.location.origin:l.location.href,d=typeof w=="string"?w:Mc(w);return d=d.replace(/ $/,"%20"),ye(h,"No window.location.(origin|href) available to create URL for href: "+d),new URL(d,h)}let x={get action(){return u},get location(){return e(l,i)},listen(w){if(s)throw new Error("A history only accepts one active listener");return l.addEventListener(cu,f),s=w,()=>{l.removeEventListener(cu,f),s=null}},createHref(w){return t(l,w)},createURL:v,encodeLocation(w){let h=v(w);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:y,go(w){return i.go(w)}};return x}var fu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(fu||(fu={}));function Pp(e,t,n){return n===void 0&&(n="/"),_p(e,t,n)}function _p(e,t,n,r){let l=typeof t=="string"?fr(t):t,o=$c(l.pathname||"/",n);if(o==null)return null;let i=Ac(e);zp(i);let u=null,s=Up(o);for(let c=0;u==null&&c<i.length;++c)u=$p(i[c],s);return u}function Ac(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let l=(o,i,u)=>{let s={relativePath:u===void 0?o.path||"":u,caseSensitive:o.caseSensitive===!0,childrenIndex:i,route:o};s.relativePath.startsWith("/")&&(ye(s.relativePath.startsWith(r),'Absolute route path "'+s.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),s.relativePath=s.relativePath.slice(r.length));let c=un([r,s.relativePath]),m=n.concat(s);o.children&&o.children.length>0&&(ye(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),Ac(o.children,t,m,c)),!(o.path==null&&!o.index)&&t.push({path:c,score:Ap(c,o.index),routesMeta:m})};return e.forEach((o,i)=>{var u;if(o.path===""||!((u=o.path)!=null&&u.includes("?")))l(o,i);else for(let s of Oc(o.path))l(o,i,s)}),t}function Oc(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,l=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return l?[o,""]:[o];let i=Oc(r.join("/")),u=[];return u.push(...i.map(s=>s===""?o:[o,s].join("/"))),l&&u.push(...i),u.map(s=>e.startsWith("/")&&s===""?"/":s)}function zp(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Op(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Ip=/^:[\w-]+$/,Lp=3,Tp=2,Rp=1,Dp=10,Mp=-2,pu=e=>e==="*";function Ap(e,t){let n=e.split("/"),r=n.length;return n.some(pu)&&(r+=Mp),t&&(r+=Tp),n.filter(l=>!pu(l)).reduce((l,o)=>l+(Ip.test(o)?Lp:o===""?Rp:Dp),r)}function Op(e,t){return e.length===t.length&&e.slice(0,-1).every((r,l)=>r===t[l])?e[e.length-1]-t[t.length-1]:0}function $p(e,t,n){let{routesMeta:r}=e,l={},o="/",i=[];for(let u=0;u<r.length;++u){let s=r[u],c=u===r.length-1,m=o==="/"?t:t.slice(o.length)||"/",f=Fp({path:s.relativePath,caseSensitive:s.caseSensitive,end:c},m),p=s.route;if(!f)return null;Object.assign(l,f.params),i.push({params:l,pathname:un([o,f.pathname]),pathnameBase:Wp(un([o,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(o=un([o,f.pathnameBase]))}return i}function Fp(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Bp(e.path,e.caseSensitive,e.end),l=t.match(n);if(!l)return null;let o=l[0],i=o.replace(/(.)\/+$/,"$1"),u=l.slice(1);return{params:r.reduce((c,m,f)=>{let{paramName:p,isOptional:y}=m;if(p==="*"){let x=u[f]||"";i=o.slice(0,o.length-x.length).replace(/(.)\/+$/,"$1")}const v=u[f];return y&&!v?c[p]=void 0:c[p]=(v||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:i,pattern:e}}function Bp(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),qi(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],l="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,u,s)=>(r.push({paramName:u,isOptional:s!=null}),s?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),l+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?l+="\\/*$":e!==""&&e!=="/"&&(l+="(?:(?=\\/|$))"),[new RegExp(l,t?void 0:"i"),r]}function Up(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return qi(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function $c(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}const Vp=e=>e.replace(/\/\/+/g,"/"),un=e=>Vp(e.join("/")),Wp=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/");function Hp(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Fc=["post","put","patch","delete"];new Set(Fc);const Qp=["get",...Fc];new Set(Qp);/**
 * React Router v6.30.6
 *
 * 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
 */function hl(){return hl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},hl.apply(null,arguments)}const bp=S.createContext(null),Kp=S.createContext(null),Bc=S.createContext(null),Ll=S.createContext(null),Tl=S.createContext({outlet:null,matches:[],isDataRoute:!1}),Uc=S.createContext(null);function es(){return S.useContext(Ll)!=null}function Gp(){return es()||ye(!1),S.useContext(Ll).location}function Yp(e,t){return Xp(e,t)}function Xp(e,t,n,r){es()||ye(!1);let{navigator:l}=S.useContext(Bc),{matches:o}=S.useContext(Tl),i=o[o.length-1],u=i?i.params:{};i&&i.pathname;let s=i?i.pathnameBase:"/";i&&i.route;let c=Gp(),m;if(t){var f;let w=typeof t=="string"?fr(t):t;s==="/"||(f=w.pathname)!=null&&f.startsWith(s)||ye(!1),m=w}else m=c;let p=m.pathname||"/",y=p;if(s!=="/"){let w=s.replace(/^\//,"").split("/");y="/"+p.replace(/^\//,"").split("/").slice(w.length).join("/")}let v=Pp(e,{pathname:y}),x=th(v&&v.map(w=>Object.assign({},w,{params:Object.assign({},u,w.params),pathname:un([s,l.encodeLocation?l.encodeLocation(w.pathname).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?s:un([s,l.encodeLocation?l.encodeLocation(w.pathnameBase).pathname:w.pathnameBase])})),o,n,r);return t&&x?S.createElement(Ll.Provider,{value:{location:hl({pathname:"/",search:"",hash:"",state:null,key:"default"},m),navigationType:dt.Pop}},x):x}function Zp(){let e=oh(),t=Hp(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,l={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return S.createElement(S.Fragment,null,S.createElement("h2",null,"Unexpected Application Error!"),S.createElement("h3",{style:{fontStyle:"italic"}},t),n?S.createElement("pre",{style:l},n):null,null)}const Jp=S.createElement(Zp,null);class qp extends S.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?S.createElement(Tl.Provider,{value:this.props.routeContext},S.createElement(Uc.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function eh(e){let{routeContext:t,match:n,children:r}=e,l=S.useContext(bp);return l&&l.static&&l.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(l.staticContext._deepestRenderedBoundaryId=n.route.id),S.createElement(Tl.Provider,{value:t},r)}function th(e,t,n,r){var l;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if(!n)return null;if(n.errors)e=n.matches;else if((o=r)!=null&&o.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let i=e,u=(l=n)==null?void 0:l.errors;if(u!=null){let m=i.findIndex(f=>f.route.id&&(u==null?void 0:u[f.route.id])!==void 0);m>=0||ye(!1),i=i.slice(0,Math.min(i.length,m+1))}let s=!1,c=-1;if(n&&r&&r.v7_partialHydration)for(let m=0;m<i.length;m++){let f=i[m];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(c=m),f.route.id){let{loaderData:p,errors:y}=n,v=f.route.loader&&p[f.route.id]===void 0&&(!y||y[f.route.id]===void 0);if(f.route.lazy||v){s=!0,c>=0?i=i.slice(0,c+1):i=[i[0]];break}}}return i.reduceRight((m,f,p)=>{let y,v=!1,x=null,w=null;n&&(y=u&&f.route.id?u[f.route.id]:void 0,x=f.route.errorElement||Jp,s&&(c<0&&p===0?(ih("route-fallback"),v=!0,w=null):c===p&&(v=!0,w=f.route.hydrateFallbackElement||null)));let h=t.concat(i.slice(0,p+1)),d=()=>{let g;return y?g=x:v?g=w:f.route.Component?g=S.createElement(f.route.Component,null):f.route.element?g=f.route.element:g=m,S.createElement(eh,{match:f,routeContext:{outlet:m,matches:h,isDataRoute:n!=null},children:g})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?S.createElement(qp,{location:n.location,revalidation:n.revalidation,component:x,error:y,children:d(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):d()},null)}var Vc=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Vc||{});function nh(e){let t=S.useContext(Kp);return t||ye(!1),t}function rh(e){let t=S.useContext(Tl);return t||ye(!1),t}function lh(e){let t=rh(),n=t.matches[t.matches.length-1];return n.route.id||ye(!1),n.route.id}function oh(){var e;let t=S.useContext(Uc),n=nh(Vc.UseRouteError),r=lh();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}const hu={};function ih(e,t,n){hu[e]||(hu[e]=!0)}function sh(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function Dn(e){ye(!1)}function uh(e){let{basename:t="/",children:n=null,location:r,navigationType:l=dt.Pop,navigator:o,static:i=!1,future:u}=e;es()&&ye(!1);let s=t.replace(/^\/*/,"/"),c=S.useMemo(()=>({basename:s,navigator:o,static:i,future:hl({v7_relativeSplatPath:!1},u)}),[s,u,o,i]);typeof r=="string"&&(r=fr(r));let{pathname:m="/",search:f="",hash:p="",state:y=null,key:v="default"}=r,x=S.useMemo(()=>{let w=$c(m,s);return w==null?null:{location:{pathname:w,search:f,hash:p,state:y,key:v},navigationType:l}},[s,m,f,p,y,v,l]);return x==null?null:S.createElement(Bc.Provider,{value:c},S.createElement(Ll.Provider,{children:n,value:x}))}function ah(e){let{children:t,location:n}=e;return Yp(ri(t),n)}new Promise(()=>{});function ri(e,t){t===void 0&&(t=[]);let n=[];return S.Children.forEach(e,(r,l)=>{if(!S.isValidElement(r))return;let o=[...t,l];if(r.type===S.Fragment){n.push.apply(n,ri(r.props.children,o));return}r.type!==Dn&&ye(!1),!r.props.index||!r.props.children||ye(!1);let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=ri(r.props.children,o)),n.push(i)}),n}/**
 * React Router DOM v6.30.6
 *
 * 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
 */const ch="6";try{window.__reactRouterVersion=ch}catch{}const dh="startTransition",mu=dd[dh];function fh(e){let{basename:t,children:n,future:r,window:l}=e,o=S.useRef();o.current==null&&(o.current=Ep({window:l,v5Compat:!0}));let i=o.current,[u,s]=S.useState({action:i.action,location:i.location}),{v7_startTransition:c}=r||{},m=S.useCallback(f=>{c&&mu?mu(()=>s(f)):s(f)},[s,c]);return S.useLayoutEffect(()=>i.listen(m),[i,m]),S.useEffect(()=>sh(r),[r]),S.createElement(uh,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:i,future:r})}var gu;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(gu||(gu={}));var vu;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(vu||(vu={}));const ph={},yu=e=>{let t;const n=new Set,r=(m,f)=>{const p=typeof m=="function"?m(t):m;if(!Object.is(p,t)){const y=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(v=>v(t,y))}},l=()=>t,s={setState:r,getState:l,getInitialState:()=>c,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(ph?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=t=e(r,l,s);return s},hh=e=>e?yu(e):yu;var Wc={exports:{}},Hc={},Qc={exports:{}},bc={};/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var gn=S;function mh(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var gh=typeof Object.is=="function"?Object.is:mh,vh=gn.useState,yh=gn.useEffect,xh=gn.useLayoutEffect,wh=gn.useDebugValue;function kh(e,t){var n=t(),r=vh({inst:{value:n,getSnapshot:t}}),l=r[0].inst,o=r[1];return xh(function(){l.value=n,l.getSnapshot=t,io(l)&&o({inst:l})},[e,n,t]),yh(function(){return io(l)&&o({inst:l}),e(function(){io(l)&&o({inst:l})})},[e]),wh(n),n}function io(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!gh(e,n)}catch{return!0}}function Sh(e,t){return t()}var Ch=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Sh:kh;bc.useSyncExternalStore=gn.useSyncExternalStore!==void 0?gn.useSyncExternalStore:Ch;Qc.exports=bc;var Eh=Qc.exports;/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Rl=S,jh=Eh;function Nh(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ph=typeof Object.is=="function"?Object.is:Nh,_h=jh.useSyncExternalStore,zh=Rl.useRef,Ih=Rl.useEffect,Lh=Rl.useMemo,Th=Rl.useDebugValue;Hc.useSyncExternalStoreWithSelector=function(e,t,n,r,l){var o=zh(null);if(o.current===null){var i={hasValue:!1,value:null};o.current=i}else i=o.current;o=Lh(function(){function s(y){if(!c){if(c=!0,m=y,y=r(y),l!==void 0&&i.hasValue){var v=i.value;if(l(v,y))return f=v}return f=y}if(v=f,Ph(m,y))return v;var x=r(y);return l!==void 0&&l(v,x)?(m=y,v):(m=y,f=x)}var c=!1,m,f,p=n===void 0?null:n;return[function(){return s(t())},p===null?void 0:function(){return s(p())}]},[t,n,r,l]);var u=_h(e,o[0],o[1]);return Ih(function(){i.hasValue=!0,i.value=u},[u]),Th(u),u};Wc.exports=Hc;var Rh=Wc.exports;const Dh=Su(Rh),Kc={},{useDebugValue:Mh}=ui,{useSyncExternalStoreWithSelector:Ah}=Dh;let xu=!1;const Oh=e=>e;function $h(e,t=Oh,n){(Kc?"production":void 0)!=="production"&&n&&!xu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),xu=!0);const r=Ah(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Mh(r),r}const wu=e=>{(Kc?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?hh(e):e,n=(r,l)=>$h(t,r,l);return Object.assign(n,t),n},Fh=e=>e?wu(e):wu,Y=Fh(e=>({tabs:[],activeTabId:null,navigation:{url:"",title:"",canGoBack:!1,canGoForward:!1,isLoading:!1},bookmarks:[],history:[],settings:null,user:null,token:localStorage.getItem("zhihu_token"),downloads:[],sidebarOpen:!1,activeSidebar:null,isDark:!1,setTabs:t=>e({tabs:t}),setActiveTabId:t=>e({activeTabId:t}),setNavigation:t=>e({navigation:t}),setBookmarks:t=>e({bookmarks:t}),setHistory:t=>e({history:t}),setSettings:t=>e({settings:t}),setUser:t=>e({user:t}),setToken:t=>{t?localStorage.setItem("zhihu_token",t):localStorage.removeItem("zhihu_token"),e({token:t})},setDownloads:t=>e({downloads:t}),setSidebarOpen:t=>e({sidebarOpen:t}),setActiveSidebar:t=>e({activeSidebar:t,sidebarOpen:t!==null}),setIsDark:t=>e({isDark:t})}));function Bh(){const{setTabs:e,setActiveTabId:t,setNavigation:n,setBookmarks:r,setSettings:l,setDownloads:o,setUser:i,setIsDark:u}=Y();S.useEffect(()=>{if(!window.electronAPI)return;const c=window.electronAPI.onTabsUpdate(w=>{e(w);const h=w.find(d=>d.isActive);h&&t(h.id)}),m=window.electronAPI.onNavigationStateChanged(w=>{n(w)}),f=window.electronAPI.onBookmarksChanged(w=>{r(w)}),p=window.electronAPI.onSettingsChanged(w=>{l(w),s(w.theme)}),y=window.electronAPI.onDownloadsUpdate(w=>{o(w)}),v=window.electronAPI.onThemeChanged(w=>{u(w==="dark"),document.body.classList.toggle("dark",w==="dark")});window.electronAPI.getTabs().then(e),window.electronAPI.getBookmarks().then(r),window.electronAPI.getSettings().then(w=>{l(w),s(w.theme)}),window.electronAPI.getDownloads().then(o);const x=localStorage.getItem("zhihu_token");return x&&window.electronAPI.getProfile(x).then(w=>{w&&i(w)}),()=>{c(),m(),f(),p(),y(),v()}},[]);function s(c){const m=window.matchMedia("(prefers-color-scheme: dark)").matches,f=c==="dark"||c==="system"&&m;Y.getState().setIsDark(f),document.body.classList.toggle("dark",f)}}function Uh(){const{tabs:e,activeTabId:t,isDark:n}=Y(),[r,l]=S.useState(null),o=(m,f)=>{var p;m.stopPropagation(),(p=window.electronAPI)==null||p.closeTab(f)},i=(m,f)=>{var p;m.button===1&&(m.preventDefault(),(p=window.electronAPI)==null||p.closeTab(f))},u=(m,f)=>{l(f),m.dataTransfer.effectAllowed="move"},s=m=>{m.preventDefault(),m.dataTransfer.dropEffect="move"},c=(m,f)=>{var x;if(m.preventDefault(),!r||r===f)return;const p=e.map(w=>w.id),y=p.indexOf(r),v=p.indexOf(f);p.splice(y,1),p.splice(v,0,r),(x=window.electronAPI)==null||x.reorderTabs(p),l(null)};return a.jsxs("div",{className:`flex items-center h-9 px-1 overflow-hidden ${n?"bg-gray-800":"bg-white"}`,children:[a.jsx("div",{className:"flex-1 flex items-center gap-1 overflow-x-auto no-scrollbar",children:e.map(m=>a.jsxs("div",{draggable:!0,onDragStart:f=>u(f,m.id),onDragOver:s,onDrop:f=>c(f,m.id),onMouseUp:f=>i(f,m.id),onClick:()=>{var f;return(f=window.electronAPI)==null?void 0:f.activateTab(m.id)},className:`group flex items-center gap-2 px-3 h-7 min-w-[120px] max-w-[200px] rounded-t-lg cursor-pointer tab-transition select-none ${m.id===t?n?"bg-gray-700 text-gray-100":"bg-gray-100 text-gray-900":n?"text-gray-400 hover:bg-gray-700/50":"text-gray-600 hover:bg-gray-100/50"} ${m.id===r?"opacity-50":""}`,children:[m.isLoading?a.jsx("div",{className:"w-3 h-3 border-2 border-blue-500 border-t-transparent rounded-full animate-spin flex-shrink-0"}):m.favicon?a.jsx("img",{src:m.favicon,alt:"",className:"w-3 h-3 flex-shrink-0"}):a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:"flex-shrink-0 opacity-60",children:a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"})}),a.jsx("span",{className:"flex-1 text-xs truncate",children:m.title||"æ–°æ ‡ç­¾é¡µ"}),a.jsx("button",{onClick:f=>o(f,m.id),className:`w-4 h-4 flex items-center justify-center rounded-full opacity-0 group-hover:opacity-100 transition-opacity ${n?"hover:bg-gray-600 text-gray-400":"hover:bg-gray-300 text-gray-500"}`,children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]},m.id))}),a.jsx("button",{onClick:()=>{var m;return(m=window.electronAPI)==null?void 0:m.createTab()},className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${n?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"æ–°å»ºæ ‡ç­¾é¡µ",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"})})})]})}function Vh(){const{navigation:e,isDark:t}=Y(),[n,r]=S.useState(""),[l,o]=S.useState([]),[i,u]=S.useState(-1),[s,c]=S.useState(!1),m=S.useRef(null);S.useEffect(()=>{r(e.url)},[e.url]),S.useEffect(()=>{if(!n.trim()||!s){o([]);return}const v=setTimeout(async()=>{var w;const x=await((w=window.electronAPI)==null?void 0:w.getSearchSuggestions(n));o(x||[]),u(-1)},150);return()=>clearTimeout(v)},[n,s]);const f=v=>{var x,w,h,d;if(v==null||v.preventDefault(),i>=0&&l[i]){const g=l[i];g.url?(x=window.electronAPI)==null||x.navigate(g.url):(w=window.electronAPI)==null||w.navigate(g.text)}else(h=window.electronAPI)==null||h.navigate(n);c(!1),(d=m.current)==null||d.blur()},p=v=>{v.key==="ArrowDown"?(v.preventDefault(),u(x=>Math.min(x+1,l.length-1))):v.key==="ArrowUp"?(v.preventDefault(),u(x=>Math.max(x-1,-1))):v.key==="Escape"?(c(!1),r(e.url)):v.key==="Enter"&&f()},y=v=>{if(v.startsWith("zhihu://"))return v;try{const x=new URL(v);return x.hostname+x.pathname}catch{return v}};return a.jsxs("form",{onSubmit:f,className:"flex-1 relative",children:[a.jsxs("div",{className:`flex items-center gap-2 px-3 h-9 rounded-full border transition-all ${t?"bg-gray-700 border-gray-600 focus-within:border-blue-400":"bg-gray-100 border-gray-200 focus-within:border-blue-400"}`,children:[e.isLoading?a.jsx("div",{className:"w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"}):e.favicon?a.jsx("img",{src:e.favicon,alt:"",className:"w-4 h-4"}):a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:t?"text-gray-400":"text-gray-500",children:[a.jsx("circle",{cx:"11",cy:"11",r:"8"}),a.jsx("path",{d:"m21 21-4.35-4.35"})]}),a.jsx("input",{ref:m,type:"text",value:n,onChange:v=>r(v.target.value),onFocus:()=>c(!0),onBlur:()=>setTimeout(()=>c(!1),200),onKeyDown:p,placeholder:"æ�œç´¢æˆ–è¾“å…¥ç½‘å�€",className:`flex-1 bg-transparent outline-none text-sm ${t?"text-gray-100 placeholder-gray-400":"text-gray-800 placeholder-gray-500"}`}),n&&a.jsx("button",{type:"button",onClick:()=>r(""),className:`p-1 rounded-full ${t?"hover:bg-gray-600 text-gray-400":"hover:bg-gray-200 text-gray-500"}`,children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]}),s&&l.length>0&&a.jsx("div",{className:`absolute top-10 left-0 right-0 rounded-lg shadow-lg border py-1 z-50 fade-in ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:l.map((v,x)=>a.jsxs("div",{className:`px-3 py-2 flex items-center gap-3 cursor-pointer text-sm ${x===i?t?"bg-gray-700":"bg-blue-50":t?"hover:bg-gray-700":"hover:bg-gray-50"}`,onMouseDown:()=>{var w,h;v.url?(w=window.electronAPI)==null||w.navigate(v.url):(h=window.electronAPI)==null||h.navigate(v.text),c(!1)},children:[v.type==="history"&&a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",className:t?"text-gray-400":"text-gray-500",children:a.jsx("path",{d:"M13 3a9 9 0 00-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0013 21a9 9 0 000-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"})}),v.type==="bookmark"&&a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",className:t?"text-gray-400":"text-gray-500",children:a.jsx("path",{d:"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"})}),v.type==="search"&&a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:t?"text-gray-400":"text-gray-500",children:[a.jsx("circle",{cx:"11",cy:"11",r:"8"}),a.jsx("path",{d:"m21 21-4.35-4.35"})]}),a.jsx("span",{className:"truncate flex-1",children:v.type==="search"?`æ�œç´¢ "${v.text}"`:v.text}),v.url&&a.jsx("span",{className:"text-xs opacity-50 truncate max-w-[180px]",children:y(v.url)})]},x))})]})}function Wh(){const{navigation:e,isDark:t}=Y(),n=`w-8 h-8 flex items-center justify-center rounded-md transition-colors disabled:opacity-30 ${t?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`;return a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{className:n,disabled:!e.canGoBack,onClick:()=>{var r;return(r=window.electronAPI)==null?void 0:r.goBack()},title:"å�Žé€€",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"})})}),a.jsx("button",{className:n,disabled:!e.canGoForward,onClick:()=>{var r;return(r=window.electronAPI)==null?void 0:r.goForward()},title:"å‰�è¿›",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"})})}),a.jsx("button",{className:n,onClick:()=>{var r,l;return e.isLoading?(r=window.electronAPI)==null?void 0:r.stop():(l=window.electronAPI)==null?void 0:l.reload()},title:e.isLoading?"å�œæ­¢":"åˆ·æ–°",children:e.isLoading?a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}):a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"})})}),a.jsx("button",{className:n,onClick:()=>{var r;return(r=window.electronAPI)==null?void 0:r.goHome()},title:"ä¸»é¡µ",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"})})})]})}function Hh(){const{isDark:e}=Y(),[t,n]=S.useState(!1);S.useEffect(()=>{if(window.electronAPI)return window.electronAPI.onWindowMaximizeChanged(n)},[]);const r=`w-10 h-7 flex items-center justify-center rounded-md transition-colors ${e?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`;return a.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[a.jsx("button",{className:r,onClick:()=>{var l;return(l=window.electronAPI)==null?void 0:l.minimizeWindow()},title:"æœ€å°�åŒ–",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("rect",{x:"4",y:"11",width:"16",height:"2"})})}),a.jsx("button",{className:r,onClick:()=>{var l;return(l=window.electronAPI)==null?void 0:l.maximizeWindow()},title:t?"è¿˜åŽŸ":"æœ€å¤§åŒ–",children:t?a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:[a.jsx("path",{d:"M6 6h12v12H6z",fill:"none",stroke:"currentColor",strokeWidth:"2"}),a.jsx("path",{d:"M9 3h9v3H9z"})]}):a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a.jsx("rect",{x:"4",y:"4",width:"16",height:"16"})})}),a.jsx("button",{className:`w-10 h-7 flex items-center justify-center rounded-md transition-colors hover:bg-red-500 hover:text-white ${e?"text-gray-300":"text-gray-600"}`,onClick:()=>{var l;return(l=window.electronAPI)==null?void 0:l.closeWindow()},title:"å…³é—­",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M18.3 5.71a.996.996 0 00-1.41 0L12 10.59 7.11 5.7A.996.996 0 105.7 7.11L10.59 12 5.7 16.89a.996.996 0 101.41 1.41L12 13.41l4.89 4.89a.996.996 0 101.41-1.41L13.41 12l4.89-4.89c.38-.38.38-1.02 0-1.4z"})})})]})}function Qh(){const{isDark:e}=Y(),[t,n]=S.useState([{role:"assistant",content:"ä½ å¥½ï¼Œæˆ‘æ˜¯æ™ºç‹� AI åŠ©æ‰‹ã€‚ä½ å�¯ä»¥è®©æˆ‘æ€»ç»“å½“å‰�é¡µé�¢ã€�ç¿»è¯‘é¡µé�¢å†…å®¹ï¼Œæˆ–è§£é‡Šé€‰ä¸­çš„æ–‡å­—ã€‚",timestamp:Date.now()}]),[r,l]=S.useState(""),[o,i]=S.useState(!1),u=S.useRef(null);S.useEffect(()=>{var f;(f=u.current)==null||f.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},[t]);const s=(f,p)=>{n(y=>[...y,{role:f,content:p,timestamp:Date.now()}])},c=async()=>{var f;if(!(!r.trim()||o)){s("user",r),l(""),i(!0);try{const p=await((f=window.electronAPI)==null?void 0:f.aiChat(r));s("assistant",p||"æŠ±æ­‰ï¼Œæˆ‘æš‚æ—¶æ— æ³•å›žç­”ã€‚")}finally{i(!1)}}},m=async f=>{var p,y,v,x;i(!0);try{let w="";if(f==="summarize")w=await((p=window.electronAPI)==null?void 0:p.aiSummarizePage())||"",s("assistant",`é¡µé�¢æ€»ç»“ï¼š
`+w);else if(f==="translate")w=await((y=window.electronAPI)==null?void 0:y.aiTranslatePage())||"",s("assistant",`ç¿»è¯‘ç»“æžœï¼š
`+w);else if(f==="explain"){const h=((v=window.getSelection())==null?void 0:v.toString())||"";if(!h){s("assistant","è¯·å…ˆé€‰ä¸­é¡µé�¢ä¸­çš„æ–‡å­—ï¼Œå†�ç‚¹å‡»ã€Œè§£é‡Šé€‰ä¸­æ–‡å­—ã€�ã€‚"),i(!1);return}w=await((x=window.electronAPI)==null?void 0:x.aiExplainSelection(h))||"",s("assistant",`ã€Œ${h}ã€�çš„è§£é‡Šï¼š
`+w)}}finally{i(!1)}};return a.jsxs("div",{className:`flex flex-col h-full ${e?"bg-gray-800 text-gray-100":"bg-white text-gray-900"}`,children:[a.jsx("div",{className:`flex items-center justify-between p-3 border-b ${e?"border-gray-700":"border-gray-200"}`,children:a.jsxs("h2",{className:"font-semibold flex items-center gap-2",children:[a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",className:"text-blue-500",children:a.jsx("path",{d:"M12 2a2 2 0 100 4 2 2 0 000-4zm0 6a2 2 0 100 4 2 2 0 000-4zm0 6a2 2 0 100 4 2 2 0 000-4z"})}),"æ™ºç‹� AI åŠ©æ‰‹"]})}),a.jsxs("div",{className:"flex gap-2 p-3 border-b border-gray-200 dark:border-gray-700",children:[a.jsx(so,{onClick:()=>m("summarize"),label:"æ€»ç»“é¡µé�¢"}),a.jsx(so,{onClick:()=>m("translate"),label:"ç¿»è¯‘é¡µé�¢"}),a.jsx(so,{onClick:()=>m("explain"),label:"è§£é‡Šé€‰ä¸­"})]}),a.jsxs("div",{ref:u,className:"flex-1 overflow-auto p-3 space-y-3",children:[t.map((f,p)=>a.jsx("div",{className:`flex ${f.role==="user"?"justify-end":"justify-start"}`,children:a.jsx("div",{className:`max-w-[90%] rounded-2xl px-3 py-2 text-sm whitespace-pre-wrap ${f.role==="user"?"bg-blue-600 text-white rounded-br-md":e?"bg-gray-700 text-gray-100 rounded-bl-md":"bg-gray-100 text-gray-800 rounded-bl-md"}`,children:f.content})},p)),o&&a.jsx("div",{className:"flex justify-start",children:a.jsx("div",{className:`rounded-2xl rounded-bl-md px-3 py-2 text-sm ${e?"bg-gray-700":"bg-gray-100"}`,children:a.jsxs("div",{className:"flex gap-1",children:[a.jsx("span",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"0ms"}}),a.jsx("span",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"150ms"}}),a.jsx("span",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"300ms"}})]})})})]}),a.jsx("div",{className:`p-3 border-t ${e?"border-gray-700":"border-gray-200"}`,children:a.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded-full border ${e?"bg-gray-700 border-gray-600":"bg-gray-50 border-gray-200"}`,children:[a.jsx("input",{type:"text",value:r,onChange:f=>l(f.target.value),onKeyDown:f=>f.key==="Enter"&&c(),placeholder:"è¾“å…¥é—®é¢˜...",className:`flex-1 bg-transparent outline-none text-sm ${e?"text-gray-100 placeholder-gray-400":"text-gray-800 placeholder-gray-500"}`}),a.jsx("button",{onClick:c,disabled:o,className:"p-1.5 bg-blue-600 text-white rounded-full hover:bg-blue-700 disabled:opacity-50 transition-colors",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]})})]})}function so({onClick:e,label:t}){const{isDark:n}=Y();return a.jsx("button",{onClick:e,className:`flex-1 px-2 py-1.5 rounded-lg text-xs font-medium transition-colors ${n?"bg-gray-700 hover:bg-gray-600 text-gray-200":"bg-gray-100 hover:bg-gray-200 text-gray-700"}`,children:t})}function bh(){const{bookmarks:e,isDark:t}=Y(),[n,r]=S.useState(!1),[l,o]=S.useState(""),[i,u]=S.useState(""),s=e.filter(p=>p.parentId==="root"||p.parentId==="").sort((p,y)=>p.index-y.index),c=e.filter(p=>p.type==="folder"),m=()=>{var y;if(!l.trim()||!i.trim())return;const p={id:`bm_${Date.now()}`,title:l,url:i,parentId:"root",type:"bookmark",index:s.length,dateAdded:Date.now()};(y=window.electronAPI)==null||y.addBookmark(p),o(""),u(""),r(!1)},f=p=>{var y;confirm("ç¡®å®šåˆ é™¤æ­¤ä¹¦ç­¾å�—ï¼Ÿ")&&((y=window.electronAPI)==null||y.deleteBookmark(p))};return a.jsxs("div",{className:`flex flex-col h-full ${t?"bg-gray-800 text-gray-100":"bg-white text-gray-900"}`,children:[a.jsxs("div",{className:`flex items-center justify-between p-3 border-b ${t?"border-gray-700":"border-gray-200"}`,children:[a.jsx("h2",{className:"font-semibold",children:"æ”¶è—�å¤¹"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>r(!n),className:`p-1.5 rounded-md transition-colors ${t?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"æ·»åŠ ä¹¦ç­¾",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"})})}),a.jsx("button",{onClick:()=>{var p;return(p=window.electronAPI)==null?void 0:p.importBookmarks()},className:`p-1.5 rounded-md transition-colors ${t?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"å¯¼å…¥",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"})})}),a.jsx("button",{onClick:()=>{var p;return(p=window.electronAPI)==null?void 0:p.exportBookmarks()},className:`p-1.5 rounded-md transition-colors ${t?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"å¯¼å‡º",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 15v4H5v-4H3v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-4h-2zM17 8l-5 5-5-5h3V2h4v6h3z"})})})]})]}),n&&a.jsxs("div",{className:`p-3 border-b ${t?"border-gray-700 bg-gray-700/50":"border-gray-200 bg-gray-50"}`,children:[a.jsx("input",{type:"text",placeholder:"æ ‡é¢˜",value:l,onChange:p=>o(p.target.value),className:`w-full h-8 px-2 mb-2 text-sm rounded border outline-none ${t?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`}),a.jsx("input",{type:"text",placeholder:"ç½‘å�€",value:i,onChange:p=>u(p.target.value),className:`w-full h-8 px-2 mb-2 text-sm rounded border outline-none ${t?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:m,className:"flex-1 h-8 bg-blue-600 text-white rounded text-sm hover:bg-blue-700",children:"æ·»åŠ "}),a.jsx("button",{onClick:()=>r(!1),className:`flex-1 h-8 rounded text-sm ${t?"bg-gray-700 hover:bg-gray-600":"bg-gray-200 hover:bg-gray-300"}`,children:"å�–æ¶ˆ"})]})]}),a.jsxs("div",{className:"flex-1 overflow-auto p-2",children:[c.map(p=>a.jsxs("div",{className:"mb-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded text-sm font-medium ${t?"text-gray-300":"text-gray-700"}`,children:[a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",className:"text-yellow-500",children:a.jsx("path",{d:"M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})}),p.title]}),e.filter(y=>y.parentId===p.id&&y.type==="bookmark").sort((y,v)=>y.index-v.index).map(y=>a.jsx(ku,{bookmark:y,onDelete:f},y.id))]},p.id)),s.filter(p=>p.type==="bookmark").map(p=>a.jsx(ku,{bookmark:p,onDelete:f},p.id))]})]})}function ku({bookmark:e,onDelete:t}){const{isDark:n}=Y();return a.jsxs("div",{className:`group flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer text-sm ${n?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-700"}`,onClick:()=>{var r;return(r=window.electronAPI)==null?void 0:r.navigate(e.url)},children:[e.icon?a.jsx("img",{src:e.icon,alt:"",className:"w-4 h-4 flex-shrink-0"}):a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",className:"flex-shrink-0 opacity-60",children:a.jsx("path",{d:"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"})}),a.jsx("span",{className:"flex-1 truncate",children:e.title}),a.jsx("button",{onClick:r=>{r.stopPropagation(),t(e.id)},className:`opacity-0 group-hover:opacity-100 p-1 rounded transition-opacity ${n?"hover:bg-gray-600 text-gray-400":"hover:bg-gray-200 text-gray-500"}`,children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]})}function Gc({onAuthSuccess:e,defaultIsLogin:t=!0}){const{isDark:n}=Y(),[r,l]=S.useState(t),[o,i]=S.useState("phone"),[u,s]=S.useState(""),[c,m]=S.useState(""),[f,p]=S.useState(""),[y,v]=S.useState(""),[x,w]=S.useState(""),[h,d]=S.useState(""),[g,k]=S.useState(""),[E,_]=S.useState(!1),[z,P]=S.useState(""),[U,R]=S.useState(""),[fe,rt]=S.useState(!1),[Be,wn]=S.useState(0),Ue=S.useRef(null);S.useEffect(()=>()=>{Ue.current&&window.clearInterval(Ue.current)},[]);const kn=()=>{wn(60),Ue.current&&window.clearInterval(Ue.current),Ue.current=window.setInterval(()=>{wn(T=>T<=1?(Ue.current&&window.clearInterval(Ue.current),Ue.current=null,0):T-1)},1e3)},jt=()=>{P(""),R(""),d(""),k(""),v("")},j=async()=>{var T;if(P(""),R(""),!/^1[3-9]\d{9}$/.test(f.trim())){P("è¯·è¾“å…¥æ­£ç¡®çš„ 11 ä½�æ‰‹æœºå�·");return}rt(!0);try{const M=await((T=window.electronAPI)==null?void 0:T.sendVerifyCode(f.trim()));M!=null&&M.success?(kn(),R(M.code?`éªŒè¯�ç �ï¼š${M.code}ï¼ˆæœªæŽ¥å…¥çŸ­ä¿¡æœ�åŠ¡ï¼Œæ¼”ç¤ºæ¨¡å¼�ç›´æŽ¥æ˜¾ç¤ºï¼‰`:"éªŒè¯�ç �å·²å�‘é€�")):P((M==null?void 0:M.message)||"éªŒè¯�ç �å�‘é€�å¤±è´¥")}catch(M){P((M==null?void 0:M.message)||"éªŒè¯�ç �å�‘é€�å¤±è´¥")}finally{rt(!1)}},L=async T=>{var M,Nt;T.preventDefault(),P(""),R(""),_(!0);try{if(r){const re=await((M=window.electronAPI)==null?void 0:M.login({account:u.trim(),password:h}));re!=null&&re.success?e(re.token,re.profile):P((re==null?void 0:re.message)||"ç™»å½•å¤±è´¥");return}if(h!==g){P("ä¸¤æ¬¡è¾“å…¥çš„å¯†ç �ä¸�ä¸€è‡´");return}if(h.length<6){P("å¯†ç �é•¿åº¦è‡³å°‘ 6 ä½�");return}const xe=o==="phone"?{mode:"phone",phone:f.trim(),code:y.trim(),password:h,nickname:x.trim()}:{mode:"username",username:c.trim(),password:h,nickname:x.trim()},Ne=await((Nt=window.electronAPI)==null?void 0:Nt.register(xe));Ne!=null&&Ne.success?e(Ne.token,Ne.profile):P((Ne==null?void 0:Ne.message)||"æ³¨å†Œå¤±è´¥")}catch(xe){P((xe==null?void 0:xe.message)||"æ“�ä½œå¤±è´¥ï¼Œè¯·é‡�è¯•")}finally{_(!1)}},I=`w-full h-10 px-3 rounded-lg border outline-none ${n?"bg-gray-700 border-gray-600 placeholder-gray-400":"bg-gray-50 border-gray-200 placeholder-gray-400"}`;return a.jsxs(a.Fragment,{children:[!r&&a.jsxs("div",{className:`flex mb-4 p-1 rounded-lg ${n?"bg-gray-700":"bg-gray-100"}`,children:[a.jsx("button",{type:"button",onClick:()=>{i("phone"),jt()},className:`flex-1 h-8 rounded-md text-sm transition-colors ${o==="phone"?n?"bg-gray-800 text-white shadow":"bg-white text-gray-900 shadow":"text-gray-500"}`,children:"æ‰‹æœºå�·æ³¨å†Œ"}),a.jsx("button",{type:"button",onClick:()=>{i("username"),jt()},className:`flex-1 h-8 rounded-md text-sm transition-colors ${o==="username"?n?"bg-gray-800 text-white shadow":"bg-white text-gray-900 shadow":"text-gray-500"}`,children:"ç”¨æˆ·å��æ³¨å†Œ"})]}),a.jsxs("form",{onSubmit:L,className:"space-y-4",children:[r?a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"ç”¨æˆ·å�� / æ‰‹æœºå�· / é‚®ç®±"}),a.jsx("input",{type:"text",value:u,onChange:T=>s(T.target.value),className:I,placeholder:"è¯·è¾“å…¥å·²æ³¨å†Œè´¦å�·",autoFocus:!0})]}):o==="phone"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"æ‰‹æœºå�·"}),a.jsx("input",{type:"tel",value:f,onChange:T=>p(T.target.value),className:I,placeholder:"è¯·è¾“å…¥ 11 ä½�æ‰‹æœºå�·",autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"éªŒè¯�ç �"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:y,onChange:T=>v(T.target.value),className:`${I} flex-1`,placeholder:"6 ä½�éªŒè¯�ç �"}),a.jsx("button",{type:"button",onClick:j,disabled:fe||Be>0,className:`h-10 px-3 rounded-lg text-sm whitespace-nowrap transition-colors ${Be>0?n?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-500":"bg-blue-600 hover:bg-blue-700 text-white"} disabled:opacity-60`,children:Be>0?`${Be}s å�Žé‡�å�‘`:fe?"å�‘é€�ä¸­...":"èŽ·å�–éªŒè¯�ç �"})]})]})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"ç”¨æˆ·å��"}),a.jsx("input",{type:"text",value:c,onChange:T=>m(T.target.value),className:I,placeholder:"3-20 ä½�å­—æ¯�ã€�æ•°å­—æˆ–ä¸‹åˆ’çº¿",autoFocus:!0})]}),!r&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"æ˜µç§°ï¼ˆé€‰å¡«ï¼‰"}),a.jsx("input",{type:"text",value:x,onChange:T=>w(T.target.value),className:I,placeholder:"ç•™ç©ºåˆ™è‡ªåŠ¨ç”Ÿæˆ�"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"å¯†ç �"}),a.jsx("input",{type:"password",value:h,onChange:T=>d(T.target.value),className:I,placeholder:r?"è¯·è¾“å…¥å¯†ç �":"è‡³å°‘ 6 ä½�"})]}),!r&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1",children:"ç¡®è®¤å¯†ç �"}),a.jsx("input",{type:"password",value:g,onChange:T=>k(T.target.value),className:I,placeholder:"è¯·å†�æ¬¡è¾“å…¥å¯†ç �"})]}),U&&a.jsx("p",{className:"text-sm text-blue-500 break-all",children:U}),z&&a.jsx("p",{className:"text-sm text-red-500",children:z}),a.jsx("button",{type:"submit",disabled:E,className:"w-full h-10 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50",children:E?"å¤„ç�†ä¸­...":r?"ç™»å½•":"æ³¨å†Œ"})]}),a.jsx("div",{className:"mt-4 text-center text-sm",children:a.jsx("button",{onClick:()=>{l(!r),jt()},className:"text-blue-600 hover:underline",children:r?"æ²¡æœ‰è´¦å�·ï¼Ÿç«‹å�³æ³¨å†Œ":"å·²æœ‰è´¦å�·ï¼Ÿç«‹å�³ç™»å½•"})})]})}function Kh(){var u;const{user:e,isDark:t,setUser:n,setToken:r}=Y(),[l,o]=S.useState(!1);S.useEffect(()=>{var s;if((s=window.electronAPI)!=null&&s.onAuthStateChanged)return window.electronAPI.onAuthStateChanged(c=>{c!=null&&c.token&&(c!=null&&c.profile)&&(r(c.token),n(c.profile))})},[]);const i=()=>{var s;(s=window.electronAPI)!=null&&s.openLoginWindow?window.electronAPI.openLoginWindow():o(!0)};return e?a.jsxs("div",{className:`fixed top-11 right-3 z-50 flex items-center gap-2 px-3 py-1.5 rounded-full shadow-sm border ${t?"bg-gray-800 border-gray-700 text-gray-200":"bg-white border-gray-200 text-gray-700"}`,children:[a.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white flex items-center justify-center text-xs font-medium",children:((u=e.nickname)==null?void 0:u.charAt(0))||"ç”¨"}),a.jsx("span",{className:"text-xs",children:e.nickname||"å·²ç™»å½•"}),a.jsx("button",{onClick:()=>{var c;const s=localStorage.getItem("zhihu_token");s&&((c=window.electronAPI)==null||c.logout(s)),n(null),r(null)},className:`text-xs ml-1 ${t?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-800"}`,children:"é€€å‡º"})]}):l?a.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/50",children:a.jsxs("div",{className:`w-[420px] max-h-[90vh] overflow-y-auto rounded-2xl shadow-xl p-6 fade-in ${t?"bg-gray-800 text-gray-100":"bg-white text-gray-900"}`,children:[a.jsxs("div",{className:"flex items-center justify-between mb-5",children:[a.jsx("h2",{className:"text-xl font-bold",children:"ç™»å½•æ™ºç‹�æµ�è§ˆå™¨"}),a.jsx("button",{onClick:()=>o(!1),className:`p-1 rounded-md ${t?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,children:a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]}),a.jsx(Gc,{onAuthSuccess:(s,c)=>{r(s),n(c),o(!1)}})]})}):a.jsx("button",{onClick:i,className:"fixed top-11 right-3 z-50 px-4 py-1.5 rounded-full text-sm font-medium transition-colors bg-blue-600 hover:bg-blue-700 text-white",children:"ç™»å½• / æ³¨å†Œ"})}function Gh(){const{isDark:e}=Y(),[t,n]=S.useState(null);if(S.useEffect(()=>{if(window.electronAPI)return window.electronAPI.onContextMenu(l=>{n(l)})},[]),S.useEffect(()=>{const l=()=>n(null);return window.addEventListener("click",l),()=>window.removeEventListener("click",l)},[]),!t)return null;const r=[];return t.linkURL&&r.push({label:"åœ¨æ–°æ ‡ç­¾é¡µæ‰“å¼€é“¾æŽ¥",action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.createTab(t.linkURL)}},{label:"å¤�åˆ¶é“¾æŽ¥åœ°å�€",action:()=>navigator.clipboard.writeText(t.linkURL)}),t.selectionText&&r.push({label:"å¤�åˆ¶",action:()=>navigator.clipboard.writeText(t.selectionText)},{label:'æ�œç´¢ "'+t.selectionText.slice(0,20)+(t.selectionText.length>20?"...":"")+'"',action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.navigate(t.selectionText)}},{label:"è§£é‡Šé€‰ä¸­æ–‡å­—",action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.aiExplainSelection(t.selectionText)}}),t.isEditable&&r.push({label:"æ’¤é”€",action:()=>document.execCommand("undo")},{label:"é‡�å�š",action:()=>document.execCommand("redo")},{label:"å‰ªåˆ‡",action:()=>document.execCommand("cut")},{label:"å¤�åˆ¶",action:()=>document.execCommand("copy")},{label:"ç²˜è´´",action:()=>document.execCommand("paste")},{label:"å…¨é€‰",action:()=>document.execCommand("selectAll")}),r.push({label:"é‡�æ–°åŠ è½½",action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.reload()}},{label:"æŸ¥çœ‹ç½‘é¡µæº�ä»£ç �",action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.navigate("view-source:"+window.location.href)}},{label:"æ£€æŸ¥å…ƒç´ ",action:()=>{var l;return(l=window.electronAPI)==null?void 0:l.toggleDevTools()}}),a.jsx("div",{className:`fixed z-[200] min-w-[180px] rounded-lg shadow-xl border py-1 fade-in ${e?"bg-gray-800 border-gray-700 text-gray-200":"bg-white border-gray-200 text-gray-800"}`,style:{left:t.x,top:t.y},onClick:l=>l.stopPropagation(),children:r.map((l,o)=>a.jsxs("div",{children:[l.divider&&a.jsx("div",{className:`my-1 h-px ${e?"bg-gray-700":"bg-gray-200"}`}),a.jsx("button",{onClick:()=>{l.action(),n(null)},className:`w-full text-left px-4 py-1.5 text-sm transition-colors ${e?"hover:bg-gray-700":"hover:bg-gray-100"}`,children:l.label})]},o))})}function Yh(){Bh();const{isDark:e,sidebarOpen:t,activeSidebar:n}=Y();return S.useEffect(()=>{document.body.classList.toggle("dark",e)},[e]),a.jsxs("div",{className:`flex flex-col h-screen w-screen overflow-hidden ${e?"bg-gray-900 text-gray-100":"bg-gray-50 text-gray-900"}`,children:[a.jsxs("div",{className:`drag-region flex flex-col border-b ${e?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:[a.jsxs("div",{className:"flex items-center justify-between h-9 px-3",children:[a.jsxs("div",{className:"flex items-center gap-2 no-drag",children:[a.jsx(Zh,{}),a.jsx("span",{className:"font-semibold text-sm ml-1",children:"æ™ºç‹�æµ�è§ˆå™¨"})]}),a.jsx(Hh,{})]}),a.jsx("div",{className:"no-drag",children:a.jsx(Uh,{})}),a.jsxs("div",{className:"flex items-center gap-2 px-2 pb-2 no-drag",children:[a.jsx(Wh,{}),a.jsx(Vh,{}),a.jsx(Xh,{})]})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx("div",{className:"flex-1 bg-transparent"}),t&&n&&a.jsxs("div",{className:`w-80 border-l ${e?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"} flex flex-col fade-in`,children:[n==="ai"&&a.jsx(Qh,{}),n==="bookmarks"&&a.jsx(bh,{})]})]}),a.jsx(Kh,{}),a.jsx(Gh,{})]})}function Xh(){const{activeSidebar:e,isDark:t}=Y(),{setActiveSidebar:n}=Y(),r=l=>`w-8 h-8 flex items-center justify-center rounded-md transition-colors ${l?t?"bg-blue-600 text-white":"bg-blue-100 text-blue-700":t?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`;return a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{className:r(e==="bookmarks"),onClick:()=>n(e==="bookmarks"?null:"bookmarks"),title:"æ”¶è—�å¤¹",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"})})}),a.jsx("button",{className:r(e==="ai"),onClick:()=>n(e==="ai"?null:"ai"),title:"AI åŠ©æ‰‹",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M12 2a2 2 0 100 4 2 2 0 000-4zm0 6a2 2 0 100 4 2 2 0 000-4zm0 6a2 2 0 100 4 2 2 0 000-4z"})})})]})}function Zh(){return a.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15l-3-3 1.41-1.41L11 14.17l5.59-5.59L18 10l-7 7z",fill:"#2563eb"}),a.jsx("path",{d:"M12 4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z",fill:"#0ea5e9"})]})}function Jh(){const{isDark:e,bookmarks:t}=Y(),[n,r]=S.useState(""),[l,o]=S.useState([]);S.useEffect(()=>{var s;(s=window.electronAPI)==null||s.getBookmarks().then(o)},[t]);const i=s=>{var c;s.preventDefault(),n.trim()&&((c=window.electronAPI)==null||c.navigate(n))},u=s=>{var c;(c=window.electronAPI)==null||c.navigate(s)};return a.jsx("div",{className:`min-h-screen flex flex-col items-center justify-center px-4 ${e?"bg-gray-900":"bg-gradient-to-br from-blue-50 to-white"}`,children:a.jsxs("div",{className:"w-full max-w-2xl fade-in",children:[a.jsxs("div",{className:"flex flex-col items-center mb-8",children:[a.jsx("div",{className:"w-16 h-16 mb-4",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15l-3-3 1.41-1.41L11 14.17l5.59-5.59L18 10l-7 7z",fill:"#2563eb"}),a.jsx("path",{d:"M12 4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z",fill:"#0ea5e9"})]})}),a.jsx("h1",{className:`text-2xl font-bold ${e?"text-white":"text-gray-800"}`,children:"æ™ºç‹�æµ�è§ˆå™¨"}),a.jsx("p",{className:`text-sm mt-1 ${e?"text-gray-400":"text-gray-500"}`,children:"æ™ºèƒ½ã€�ç¾Žè§‚ã€�å�¯æ‰©å±•"})]}),a.jsxs("form",{onSubmit:i,className:"relative mb-10",children:[a.jsx("input",{type:"text",value:n,onChange:s=>r(s.target.value),placeholder:"æ�œç´¢æˆ–è¾“å…¥ç½‘å�€",className:`w-full h-14 pl-14 pr-6 rounded-full text-lg shadow-lg border outline-none transition-all ${e?"bg-gray-800 border-gray-700 text-white placeholder-gray-400 focus:border-blue-500":"bg-white border-gray-200 text-gray-800 placeholder-gray-400 focus:border-blue-500"}`}),a.jsxs("svg",{className:"absolute left-5 top-1/2 -translate-y-1/2 w-6 h-6 text-gray-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a.jsx("circle",{cx:"11",cy:"11",r:"8"}),a.jsx("path",{d:"m21 21-4.35-4.35"})]}),a.jsx("button",{type:"submit",className:"absolute right-2 top-1/2 -translate-y-1/2 px-6 h-10 bg-blue-600 hover:bg-blue-700 text-white rounded-full transition-colors font-medium",children:"æ�œç´¢"})]}),a.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-5 gap-4",children:l.filter(s=>s.type==="bookmark").slice(0,10).map(s=>a.jsxs("button",{onClick:()=>u(s.url),className:`flex flex-col items-center gap-2 p-4 rounded-xl transition-all hover:scale-105 ${e?"bg-gray-800 hover:bg-gray-700":"bg-white hover:bg-gray-50 shadow-sm"}`,children:[s.icon?a.jsx("img",{src:s.icon,alt:"",className:"w-10 h-10 rounded-lg"}):a.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center text-blue-600 font-bold",children:s.title.charAt(0)}),a.jsx("span",{className:`text-xs truncate w-full text-center ${e?"text-gray-300":"text-gray-700"}`,children:s.title})]},s.id))})]})})}function qh(){const{settings:e,isDark:t}=Y(),[n,r]=S.useState(null);S.useEffect(()=>{e&&r({...e})},[e]);const l=(o,i)=>{var s;if(!n)return;const u={...n,[o]:i};r(u),(s=window.electronAPI)==null||s.setSettings({[o]:i})};return n?a.jsxs("div",{className:`h-full overflow-auto p-6 ${t?"bg-gray-900 text-gray-100":"bg-white text-gray-900"}`,children:[a.jsx("h1",{className:"text-2xl font-bold mb-6",children:"è®¾ç½®"}),a.jsx(Vt,{title:"å¤–è§‚",children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-2",children:"ä¸»é¢˜æ¨¡å¼�"}),a.jsxs("select",{value:n.theme,onChange:o=>l("theme",o.target.value),className:`w-full h-10 px-3 rounded-lg border outline-none ${t?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"}`,children:[a.jsx("option",{value:"light",children:"æµ…è‰²"}),a.jsx("option",{value:"dark",children:"æ·±è‰²"}),a.jsx("option",{value:"system",children:"è·Ÿéš�ç³»ç»Ÿ"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-2",children:"è¯­è¨€"}),a.jsxs("select",{value:n.language,onChange:o=>l("language",o.target.value),className:`w-full h-10 px-3 rounded-lg border outline-none ${t?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"}`,children:[a.jsx("option",{value:"zh-CN",children:"ç®€ä½“ä¸­æ–‡"}),a.jsx("option",{value:"en",children:"English"})]})]})]})}),a.jsx(Vt,{title:"æ�œç´¢",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-2",children:"é»˜è®¤æ�œç´¢å¼•æ“Ž"}),a.jsxs("select",{value:n.searchEngine,onChange:o=>l("searchEngine",o.target.value),className:`w-full h-10 px-3 rounded-lg border outline-none ${t?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"}`,children:[a.jsx("option",{value:"baidu",children:"ç™¾åº¦"}),a.jsx("option",{value:"bing",children:"å¿…åº”"}),a.jsx("option",{value:"google",children:"Google"})]})]})}),a.jsx(Vt,{title:"å�¯åŠ¨",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-2",children:"ä¸»é¡µ"}),a.jsx("input",{type:"text",value:n.homepage,onChange:o=>l("homepage",o.target.value),className:`w-full h-10 px-3 rounded-lg border outline-none ${t?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"}`})]})}),a.jsx(Vt,{title:"ä¸‹è½½",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-2",children:"é»˜è®¤ä¸‹è½½è·¯å¾„"}),a.jsx("input",{type:"text",value:n.downloadPath,readOnly:!0,className:`w-full h-10 px-3 rounded-lg border outline-none ${t?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"}`})]})}),a.jsx(Vt,{title:"éš�ç§�ä¸Žå®‰å…¨",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:n.enableAdBlock,onChange:o=>l("enableAdBlock",o.target.checked),className:"w-4 h-4 rounded border-gray-300 text-blue-600"}),a.jsx("span",{className:"text-sm",children:"å�¯ç”¨åŸºç¡€å¹¿å‘Šæ‹¦æˆª"})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:n.enableAICopilot,onChange:o=>l("enableAICopilot",o.target.checked),className:"w-4 h-4 rounded border-gray-300 text-blue-600"}),a.jsx("span",{className:"text-sm",children:"å�¯ç”¨ AI åŠ©æ‰‹"})]})]})}),a.jsx(Vt,{title:"æ•°æ�®",children:a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:async()=>{var o;await((o=window.electronAPI)==null?void 0:o.clearHistory()),alert("åŽ†å�²è®°å½•å·²æ¸…é™¤")},className:"px-4 py-2 rounded-lg bg-red-50 text-red-600 hover:bg-red-100 transition-colors text-sm font-medium",children:"æ¸…é™¤åŽ†å�²è®°å½•"}),a.jsx("button",{onClick:async()=>{var o;await((o=window.electronAPI)==null?void 0:o.setSettings({theme:"system",language:"zh-CN",searchEngine:"baidu",homepage:"zhihu://newtab",enableAdBlock:!0,enableAICopilot:!0})),alert("è®¾ç½®å·²æ�¢å¤�é»˜è®¤")},className:"px-4 py-2 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors text-sm font-medium",children:"æ�¢å¤�é»˜è®¤è®¾ç½®"})]})})]}):a.jsx("div",{className:"p-8 text-center",children:"åŠ è½½ä¸­..."})}function Vt({title:e,children:t}){const{isDark:n}=Y();return a.jsxs("div",{className:`mb-6 pb-6 border-b ${n?"border-gray-700":"border-gray-100"}`,children:[a.jsx("h2",{className:"text-lg font-semibold mb-4",children:e}),t]})}function em(){const{isDark:e}=Y(),t=(n,r)=>{var l,o;(o=(l=window.electronAPI)==null?void 0:l.notifyAuthSuccess)==null||o.call(l,{token:n,profile:r}),setTimeout(()=>{window.close()},150)};return a.jsxs("div",{className:`flex flex-col h-screen w-screen overflow-hidden ${e?"bg-gray-900 text-gray-100":"bg-white text-gray-900"}`,children:[a.jsxs("div",{className:`drag-region flex items-center justify-between h-9 px-3 border-b ${e?"border-gray-700":"border-gray-100"}`,children:[a.jsx("span",{className:"text-xs font-medium opacity-70 pl-1",children:"æ™ºç‹�æµ�è§ˆå™¨ Â· è´¦å�·"}),a.jsx("button",{onClick:()=>window.close(),className:`no-drag w-7 h-7 flex items-center justify-center rounded-md transition-colors ${e?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"å…³é—­",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-7",children:[a.jsxs("div",{className:"flex flex-col items-center mb-6",children:[a.jsx("div",{className:"w-12 h-12 rounded-full bg-blue-600 flex items-center justify-center mb-3",children:a.jsx("svg",{width:"26",height:"26",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15l-3-3 1.41-1.41L11 14.17l5.59-5.59L18 10l-7 7z",fill:"#ffffff"})})}),a.jsx("h1",{className:"text-xl font-bold",children:"ç™»å½•æ™ºç‹�æµ�è§ˆå™¨"}),a.jsx("p",{className:`text-xs mt-1 ${e?"text-gray-400":"text-gray-500"}`,children:"æ”¯æŒ�è´¦å�·å¯†ç �ç™»å½•ã€�æ‰‹æœºå�·æ³¨å†Œä¸Žç”¨æˆ·å��æ³¨å†Œ"})]}),a.jsx(Gc,{onAuthSuccess:t})]})]})}function tm(){if(typeof window>"u"||window.electronAPI)return;const e={createTab:()=>{},closeTab:()=>{},activateTab:()=>{},reorderTabs:()=>{},getTabs:async()=>[{id:"tab-1",url:"",title:"æ–°æ ‡ç­¾é¡µ",favicon:"",isLoading:!1,isActive:!0}],onTabsUpdate:()=>()=>{},navigate:()=>{},goBack:()=>{},goForward:()=>{},reload:()=>{},stop:()=>{},goHome:()=>{},onNavigationStateChanged:()=>()=>{},minimizeWindow:()=>{},maximizeWindow:()=>{},closeWindow:()=>{},onWindowMaximizeChanged:()=>()=>{},toggleDevTools:()=>{},getBookmarks:async()=>[{id:"bm-1",title:"ç™¾åº¦",url:"https://www.baidu.com",favicon:""},{id:"bm-2",title:"å¿…åº”",url:"https://www.bing.com",favicon:""},{id:"bm-3",title:"GitHub",url:"https://github.com",favicon:""}],addBookmark:async()=>!0,updateBookmark:async()=>!0,deleteBookmark:async()=>!0,importBookmarks:async()=>({success:!0,count:0}),exportBookmarks:async()=>({success:!0}),onBookmarksChanged:()=>()=>{},getHistory:async()=>[],clearHistory:async()=>!0,getSettings:async()=>({theme:"system",language:"zh-CN",homepage:"zhihu://newtab",searchEngine:"baidu",downloadPath:"",defaultZoom:100,showBookmarkBar:!0,enableAdBlock:!0,enableAICopilot:!0}),setSettings:async()=>({}),onSettingsChanged:()=>()=>{},getDownloads:async()=>[],openDownloadFolder:()=>{},onDownloadsUpdate:()=>()=>{},getSearchSuggestions:async()=>[],getSearchEngines:async()=>({baidu:{name:"ç™¾åº¦",url:"https://www.baidu.com/s?wd=%s"},bing:{name:"å¿…åº”",url:"https://www.bing.com/search?q=%s"},google:{name:"Google",url:"https://www.google.com/search?q=%s"}}),aiSummarizePage:async()=>"å½“å‰�é¡µé�¢æ‘˜è¦�ï¼ˆæ¼”ç¤ºæ¨¡å¼�ï¼‰",aiTranslatePage:async()=>"é¡µé�¢ç¿»è¯‘ç»“æžœï¼ˆæ¼”ç¤ºæ¨¡å¼�ï¼‰",aiExplainSelection:async()=>"é€‰ä¸­æ–‡å­—è§£é‡Šï¼ˆæ¼”ç¤ºæ¨¡å¼�ï¼‰",aiChat:async t=>`AI å›žå¤�ï¼šæ”¶åˆ°ã€Œ${t}ã€�ï¼Œè¿™æ˜¯æ¼”ç¤ºæ¨¡å¼�ã€‚`,sendVerifyCode:async()=>({success:!0,code:"123456",message:"æ¼”ç¤ºæ¨¡å¼�"}),register:async()=>({success:!0}),login:async()=>({success:!0}),logout:async()=>({success:!0}),getProfile:async()=>null,updateProfile:async()=>({success:!0}),getExtensions:async()=>[],loadExtension:async()=>({}),unloadExtension:async()=>!0,toggleExtension:async()=>!0,openExternal:async()=>{},onContextMenu:()=>()=>{},onThemeChanged:()=>()=>{},platform:"win32"};window.electronAPI=e}tm();uo.createRoot(document.getElementById("root")).render(a.jsx(ui.StrictMode,{children:a.jsx(fh,{children:a.jsxs(ah,{children:[a.jsx(Dn,{path:"/",element:a.jsx(Yh,{})}),a.jsx(Dn,{path:"/newtab",element:a.jsx(Jh,{})}),a.jsx(Dn,{path:"/settings",element:a.jsx(qh,{})}),a.jsx(Dn,{path:"/login",element:a.jsx(em,{})})]})})}));
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.left-0{left:0}.left-5{left:1.25rem}.right-0{right:0}.right-2{right:.5rem}.right-3{right:.75rem}.top-1\/2{top:50%}.top-10{top:2.5rem}.top-11{top:2.75rem}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[200\]{z-index:200}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-1{margin-bottom:.25rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.block{display:block}.flex{display:flex}.grid{display:grid}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-\[90vh\]{max-height:90vh}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-80{width:20rem}.w-\[420px\]{width:420px}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[120px\]{min-width:120px}.min-w-\[180px\]{min-width:180px}.max-w-2xl{max-width:42rem}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-\[90\%\]{max-width:90%}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-t-lg{border-top-left-radius:.5rem;border-top-right-radius:.5rem}.rounded-bl-md{border-bottom-left-radius:.375rem}.rounded-br-md{border-bottom-right-radius:.375rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-t{border-top-width:1px}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-700\/50{background-color:#37415180}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-white{--tw-gradient-to: #fff var(--tw-gradient-to-position)}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-7{padding:1.75rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.pb-2{padding-bottom:.5rem}.pb-6{padding-bottom:1.5rem}.pl-1{padding-left:.25rem}.pl-14{padding-left:3.5rem}.pr-6{padding-right:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}:root{--zhihu-primary: #2563eb;--zhihu-primary-hover: #1d4ed8}*{box-sizing:border-box}html,body,#root{width:100%;height:100%;margin:0;padding:0;overflow:hidden;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}body{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}body.dark{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background-color:transparent}::-webkit-scrollbar-thumb{border-radius:9999px;--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}body.dark ::-webkit-scrollbar-thumb{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}::-webkit-scrollbar-thumb:hover{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}::-moz-selection{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}::selection{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}body.dark ::-moz-selection{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity, 1))}body.dark ::selection{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity, 1))}.fade-in{animation:fadeIn .2s ease-in-out}@keyframes fadeIn{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.drag-region{-webkit-app-region:drag}.no-drag{-webkit-app-region:no-drag}.tab-transition{transition:all .2s ease}.focus-within\:border-blue-400:focus-within{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100\/50:hover{background-color:#f3f4f680}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700\/50:hover{background-color:#37415180}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-500:hover{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-800:hover{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:opacity-100{opacity:1}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}@media (min-width: 640px){.sm\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_BOOKMARKS = exports.IPC_CHANNELS = exports.SEARCH_ENGINES = exports.DEFAULT_HOMEPAGE = exports.APP_VERSION = exports.APP_NAME_EN = exports.APP_NAME = void 0;
exports.APP_NAME = 'æ™ºç‹�æµ�è§ˆå™¨';
exports.APP_NAME_EN = 'Zhihu Browser';
exports.APP_VERSION = '0.1.0';
exports.DEFAULT_HOMEPAGE = 'zhihu://newtab';
exports.SEARCH_ENGINES = {
    baidu: {
        name: 'ç™¾åº¦',
        url: 'https://www.baidu.com/s?wd={q}'
    },
    bing: {
        name: 'å¿…åº”',
        url: 'https://www.bing.com/search?q={q}'
    },
    google: {
        name: 'Google',
        url: 'https://www.google.com/search?q={q}'
    }
};
exports.IPC_CHANNELS = {
    // æ ‡ç­¾ç®¡ç�†
    TAB_CREATE: 'tab:create',
    TAB_CLOSE: 'tab:close',
    TAB_ACTIVATE: 'tab:activate',
    TAB_REORDER: 'tab:reorder',
    TAB_UPDATE: 'tab:update',
    TABS_UPDATE: 'tabs:update',
    // å¯¼èˆª
    NAVIGATE: 'navigate',
    GO_BACK: 'navigate:back',
    GO_FORWARD: 'navigate:forward',
    RELOAD: 'navigate:reload',
    STOP: 'navigate:stop',
    GO_HOME: 'navigate:home',
    NAVIGATION_STATE_CHANGED: 'navigate:state-changed',
    // çª—å�£
    WINDOW_MINIMIZE: 'window:minimize',
    WINDOW_MAXIMIZE: 'window:maximize',
    WINDOW_CLOSE: 'window:close',
    // å¼€å�‘è€…å·¥å…·
    TOGGLE_DEVTOOLS: 'devtools:toggle',
    // ä¹¦ç­¾
    BOOKMARK_GET_ALL: 'bookmark:get-all',
    BOOKMARK_ADD: 'bookmark:add',
    BOOKMARK_UPDATE: 'bookmark:update',
    BOOKMARK_DELETE: 'bookmark:delete',
    BOOKMARK_MOVE: 'bookmark:move',
    BOOKMARK_IMPORT: 'bookmark:import',
    BOOKMARK_EXPORT: 'bookmark:export',
    BOOKMARK_CHANGED: 'bookmark:changed',
    // åŽ†å�²
    HISTORY_GET: 'history:get',
    HISTORY_ADD: 'history:add',
    HISTORY_DELETE: 'history:delete',
    HISTORY_CLEAR: 'history:clear',
    // è®¾ç½®
    SETTINGS_GET: 'settings:get',
    SETTINGS_SET: 'settings:set',
    SETTINGS_CHANGED: 'settings:changed',
    // ä¸‹è½½
    DOWNLOADS_GET: 'downloads:get',
    DOWNLOAD_PAUSE: 'download:pause',
    DOWNLOAD_RESUME: 'download:resume',
    DOWNLOAD_CANCEL: 'download:cancel',
    DOWNLOAD_OPEN_FOLDER: 'download:open-folder',
    // AI
    AI_SUMMARIZE_PAGE: 'ai:summarize-page',
    AI_TRANSLATE_PAGE: 'ai:translate-page',
    AI_EXPLAIN_SELECTION: 'ai:explain-selection',
    AI_CHAT: 'ai:chat',
    // è´¦å�·
    AUTH_SEND_CODE: 'auth:send-code',
    AUTH_REGISTER: 'auth:register',
    AUTH_LOGIN: 'auth:login',
    AUTH_LOGOUT: 'auth:logout',
    AUTH_GET_PROFILE: 'auth:get-profile',
    AUTH_UPDATE_PROFILE: 'auth:update-profile',
    AUTH_OPEN_LOGIN: 'auth:open-login',
    AUTH_NOTIFY_SUCCESS: 'auth:notify-success',
    AUTH_STATE_CHANGED: 'auth:state-changed',
    // ä¸Šä¸‹æ–‡è�œå�•
    CONTEXT_MENU_COMMAND: 'context-menu:command',
    // æ‰©å±•
    EXTENSION_GET_ALL: 'extension:get-all',
    EXTENSION_LOAD: 'extension:load',
    EXTENSION_UNLOAD: 'extension:unload',
    EXTENSION_TOGGLE: 'extension:toggle'
};
exports.DEFAULT_BOOKMARKS = [
    {
        id: 'root',
        title: 'ä¹¦ç­¾æ �',
        url: '',
        parentId: '',
        type: 'folder',
        index: 0,
        dateAdded: Date.now()
    },
    {
        id: 'bm_baidu',
        title: 'ç™¾åº¦',
        url: 'https://www.baidu.com',
        parentId: 'root',
        type: 'bookmark',
        index: 0,
        dateAdded: Date.now()
    },
    {
        id: 'bm_bing',
        title: 'å¿…åº”',
        url: 'https://www.bing.com',
        parentId: 'root',
        type: 'bookmark',
        index: 1,
        dateAdded: Date.now()
    }
];
//# sourceMappingURL=constants.js.map{"version":3,"file":"constants.js","s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;QACR,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACtB;IACD;QACE,EAAE,EAAE,SAAS;QACb,KAAK,EAAE,IAAI;QACX,GAAG,EAAE,sBAAsB;QAC3B,QAAQ,EAAE,MAAM;QAChB,IAAI,EAAE,UAAU;QAChB,KAAK,EAAE,CAAC;QACR,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACtB;CACF,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/shared/types.ts"],"names":[],"mappings":""}"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/preload/index.ts
var preload_exports = {};
module.exports = __toCommonJS(preload_exports);
var import_electron = require("electron");

// src/shared/constants.ts
var IPC_CHANNELS = {
  // æ ‡ç­¾ç®¡ç�†
  TAB_CREATE: "tab:create",
  TAB_CLOSE: "tab:close",
  TAB_ACTIVATE: "tab:activate",
  TAB_REORDER: "tab:reorder",
  TAB_UPDATE: "tab:update",
  TABS_UPDATE: "tabs:update",
  // å¯¼èˆª
  NAVIGATE: "navigate",
  GO_BACK: "navigate:back",
  GO_FORWARD: "navigate:forward",
  RELOAD: "navigate:reload",
  STOP: "navigate:stop",
  GO_HOME: "navigate:home",
  NAVIGATION_STATE_CHANGED: "navigate:state-changed",
  // çª—å�£
  WINDOW_MINIMIZE: "window:minimize",
  WINDOW_MAXIMIZE: "window:maximize",
  WINDOW_CLOSE: "window:close",
  // å¼€å�‘è€…å·¥å…·
  TOGGLE_DEVTOOLS: "devtools:toggle",
  // ä¹¦ç­¾
  BOOKMARK_GET_ALL: "bookmark:get-all",
  BOOKMARK_ADD: "bookmark:add",
  BOOKMARK_UPDATE: "bookmark:update",
  BOOKMARK_DELETE: "bookmark:delete",
  BOOKMARK_MOVE: "bookmark:move",
  BOOKMARK_IMPORT: "bookmark:import",
  BOOKMARK_EXPORT: "bookmark:export",
  BOOKMARK_CHANGED: "bookmark:changed",
  // åŽ†å�²
  HISTORY_GET: "history:get",
  HISTORY_ADD: "history:add",
  HISTORY_DELETE: "history:delete",
  HISTORY_CLEAR: "history:clear",
  // è®¾ç½®
  SETTINGS_GET: "settings:get",
  SETTINGS_SET: "settings:set",
  SETTINGS_CHANGED: "settings:changed",
  // ä¸‹è½½
  DOWNLOADS_GET: "downloads:get",
  DOWNLOAD_PAUSE: "download:pause",
  DOWNLOAD_RESUME: "download:resume",
  DOWNLOAD_CANCEL: "download:cancel",
  DOWNLOAD_OPEN_FOLDER: "download:open-folder",
  // AI
  AI_SUMMARIZE_PAGE: "ai:summarize-page",
  AI_TRANSLATE_PAGE: "ai:translate-page",
  AI_EXPLAIN_SELECTION: "ai:explain-selection",
  AI_CHAT: "ai:chat",
  // è´¦å�·
  AUTH_SEND_CODE: "auth:send-code",
  AUTH_REGISTER: "auth:register",
  AUTH_LOGIN: "auth:login",
  AUTH_LOGOUT: "auth:logout",
  AUTH_GET_PROFILE: "auth:get-profile",
  AUTH_UPDATE_PROFILE: "auth:update-profile",
  AUTH_OPEN_LOGIN: "auth:open-login",
  AUTH_NOTIFY_SUCCESS: "auth:notify-success",
  AUTH_STATE_CHANGED: "auth:state-changed",
  // ä¸Šä¸‹æ–‡è�œå�•
  CONTEXT_MENU_COMMAND: "context-menu:command",
  // æ‰©å±•
  EXTENSION_GET_ALL: "extension:get-all",
  EXTENSION_LOAD: "extension:load",
  EXTENSION_UNLOAD: "extension:unload",
  EXTENSION_TOGGLE: "extension:toggle"
};
var DEFAULT_BOOKMARKS = [
  {
    id: "root",
    title: "\u4E66\u7B7E\u680F",
    url: "",
    parentId: "",
    type: "folder",
    index: 0,
    dateAdded: Date.now()
  },
  {
    id: "bm_baidu",
    title: "\u767E\u5EA6",
    url: "https://www.baidu.com",
    parentId: "root",
    type: "bookmark",
    index: 0,
    dateAdded: Date.now()
  },
  {
    id: "bm_bing",
    title: "\u5FC5\u5E94",
    url: "https://www.bing.com",
    parentId: "root",
    type: "bookmark",
    index: 1,
    dateAdded: Date.now()
  }
];

// src/preload/index.ts
var api = {
  createTab: (url) => import_electron.ipcRenderer.send(IPC_CHANNELS.TAB_CREATE, url),
  closeTab: (id) => import_electron.ipcRenderer.send(IPC_CHANNELS.TAB_CLOSE, id),
  activateTab: (id) => import_electron.ipcRenderer.send(IPC_CHANNELS.TAB_ACTIVATE, id),
  reorderTabs: (orderedIds) => import_electron.ipcRenderer.send(IPC_CHANNELS.TAB_REORDER, orderedIds),
  getTabs: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.TABS_UPDATE),
  onTabsUpdate: (callback) => {
    const handler = (_event, tabs) => callback(tabs);
    import_electron.ipcRenderer.on(IPC_CHANNELS.TABS_UPDATE, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.TABS_UPDATE, handler);
  },
  navigate: (url) => import_electron.ipcRenderer.send(IPC_CHANNELS.NAVIGATE, url),
  goBack: () => import_electron.ipcRenderer.send(IPC_CHANNELS.GO_BACK),
  goForward: () => import_electron.ipcRenderer.send(IPC_CHANNELS.GO_FORWARD),
  reload: () => import_electron.ipcRenderer.send(IPC_CHANNELS.RELOAD),
  stop: () => import_electron.ipcRenderer.send(IPC_CHANNELS.STOP),
  goHome: () => import_electron.ipcRenderer.send(IPC_CHANNELS.GO_HOME),
  onNavigationStateChanged: (callback) => {
    const handler = (_event, state) => callback(state);
    import_electron.ipcRenderer.on(IPC_CHANNELS.NAVIGATION_STATE_CHANGED, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.NAVIGATION_STATE_CHANGED, handler);
  },
  minimizeWindow: () => import_electron.ipcRenderer.send(IPC_CHANNELS.WINDOW_MINIMIZE),
  maximizeWindow: () => import_electron.ipcRenderer.send(IPC_CHANNELS.WINDOW_MAXIMIZE),
  closeWindow: () => import_electron.ipcRenderer.send(IPC_CHANNELS.WINDOW_CLOSE),
  onWindowMaximizeChanged: (callback) => {
    const handler = (_event, isMaximized) => callback(isMaximized);
    import_electron.ipcRenderer.on(IPC_CHANNELS.WINDOW_MAXIMIZE, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.WINDOW_MAXIMIZE, handler);
  },
  toggleDevTools: () => import_electron.ipcRenderer.send(IPC_CHANNELS.TOGGLE_DEVTOOLS),
  getBookmarks: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_GET_ALL),
  addBookmark: (bookmark) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_ADD, bookmark),
  updateBookmark: (id, updates) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_UPDATE, id, updates),
  deleteBookmark: (id) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_DELETE, id),
  importBookmarks: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_IMPORT),
  exportBookmarks: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.BOOKMARK_EXPORT),
  onBookmarksChanged: (callback) => {
    const handler = (_event, bookmarks) => callback(bookmarks);
    import_electron.ipcRenderer.on(IPC_CHANNELS.BOOKMARK_CHANGED, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.BOOKMARK_CHANGED, handler);
  },
  getHistory: (limit) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.HISTORY_GET, limit),
  clearHistory: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.HISTORY_CLEAR),
  getSettings: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.SETTINGS_GET),
  setSettings: (settings) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.SETTINGS_SET, settings),
  onSettingsChanged: (callback) => {
    const handler = (_event, settings) => callback(settings);
    import_electron.ipcRenderer.on(IPC_CHANNELS.SETTINGS_CHANGED, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.SETTINGS_CHANGED, handler);
  },
  getDownloads: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.DOWNLOADS_GET),
  openDownloadFolder: (path) => import_electron.ipcRenderer.send(IPC_CHANNELS.DOWNLOAD_OPEN_FOLDER, path),
  onDownloadsUpdate: (callback) => {
    const handler = (_event, downloads) => callback(downloads);
    import_electron.ipcRenderer.on(IPC_CHANNELS.DOWNLOADS_GET, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.DOWNLOADS_GET, handler);
  },
  getSearchSuggestions: (query) => import_electron.ipcRenderer.invoke("search:suggestions", query),
  getSearchEngines: () => import_electron.ipcRenderer.invoke("app:get-search-engines"),
  aiSummarizePage: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AI_SUMMARIZE_PAGE),
  aiTranslatePage: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AI_TRANSLATE_PAGE),
  aiExplainSelection: (text) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AI_EXPLAIN_SELECTION, text),
  aiChat: (message) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AI_CHAT, message),
  sendVerifyCode: (phone) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_SEND_CODE, phone),
  register: (data) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_REGISTER, data),
  login: (data) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_LOGIN, data),
  logout: (token) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_LOGOUT, token),
  getProfile: (token) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_GET_PROFILE, token),
  updateProfile: (token, updates) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.AUTH_UPDATE_PROFILE, token, updates),
  openLoginWindow: () => import_electron.ipcRenderer.send(IPC_CHANNELS.AUTH_OPEN_LOGIN),
  notifyAuthSuccess: (payload) => import_electron.ipcRenderer.send(IPC_CHANNELS.AUTH_NOTIFY_SUCCESS, payload),
  onAuthStateChanged: (callback) => {
    const handler = (_event, payload) => callback(payload);
    import_electron.ipcRenderer.on(IPC_CHANNELS.AUTH_STATE_CHANGED, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.AUTH_STATE_CHANGED, handler);
  },
  getExtensions: () => import_electron.ipcRenderer.invoke(IPC_CHANNELS.EXTENSION_GET_ALL),
  loadExtension: (path) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.EXTENSION_LOAD, path),
  unloadExtension: (id) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.EXTENSION_UNLOAD, id),
  toggleExtension: (id, enabled) => import_electron.ipcRenderer.invoke(IPC_CHANNELS.EXTENSION_TOGGLE, id, enabled),
  openExternal: (url) => import_electron.ipcRenderer.invoke("app:open-external", url),
  onContextMenu: (callback) => {
    const handler = (_event, data) => callback(data);
    import_electron.ipcRenderer.on(IPC_CHANNELS.CONTEXT_MENU_COMMAND, handler);
    return () => import_electron.ipcRenderer.removeListener(IPC_CHANNELS.CONTEXT_MENU_COMMAND, handler);
  },
  onThemeChanged: (callback) => {
    const handler = (_event, theme) => callback(theme);
    import_electron.ipcRenderer.on("theme:changed", handler);
    return () => import_electron.ipcRenderer.removeListener("theme:changed", handler);
  },
  platform: process.platform
};
import_electron.contextBridge.exposeInMainWorld("electronAPI", api);
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/preload/index.ts"],"names":[],"mappings":";;AAAA,uCAAuE;AACvE,mDAAkD;AAsFlD,MAAM,GAAG,GAAgB;IACvB,SAAS,EAAE,CAAC,GAAY,EAAE,EAAE,CAAC,sBAAW,CAAC,IAA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E,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;QAC5E,sBAAW,CAAC,EAAE,CAAC,eAAe,EAAE,OAAO,CAAC,CAAA;QACxC,OAAO,GAAG,EAAE,CAAC,sBAAW,CAAC,cAAc,CAAC,eAAe,EAAE,OAAO,CAAC,CAAA;IACnE,CAAC;IACD,QAAQ,EAAE,OAAO,CAAC,QAAQ;CAC3B,CAAA;AAED,wBAAa,CAAC,iBAAiB,CAAC,aAAa,EAAE,GAAG,CAAC,CAAA"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthWindowManager = void 0;
const electron_1 = require("electron");
const path_1 = __importDefault(require("path"));
const constants_1 = require("../shared/constants");
/**
 * ç‹¬ç«‹ç™»å½•çª—å�£ç®¡ç�†å™¨ã€‚
 *
 * èƒŒæ™¯ï¼šä¸»çª—å�£çš„æ–°æ ‡ç­¾é¡µç­‰å†…å®¹ç”±åŽŸç”Ÿ BrowserView æ‰¿è½½ï¼ŒBrowserView æ°¸è¿œ
 * è¦†ç›–åœ¨ä¸»çª—å�£ç½‘é¡µå±‚ä¹‹ä¸Šã€‚æ­¤å‰�ç™»å½•å¼¹çª—æ¸²æŸ“åœ¨ä¸»çª—å�£ç½‘é¡µå±‚ï¼Œä¼šè¢« BrowserView
 * å®Œå…¨é�®æŒ¡ï¼ˆå�ªå‰©é¡¶éƒ¨ä¸€æ�¡å�˜æš—çš„é�®ç½©ï¼‰ï¼Œè¡¨çŽ°ä¸ºã€Œç‚¹å‡»ç™»å½•æ²¡å��åº”ã€�ã€‚
 * å› æ­¤ç™»å½•/æ³¨å†Œæ”¹ä¸ºç‹¬ç«‹åŽŸç”Ÿ BrowserWindowï¼Œå¤©ç„¶ä½�äºŽæ‰€æœ‰å±‚ä¹‹ä¸Šã€‚
 */
class AuthWindowManager {
    constructor(getMainWindow) {
        this.getMainWindow = getMainWindow;
        this.loginWindow = null;
        this.setupIpc();
    }
    setupIpc() {
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.AUTH_OPEN_LOGIN, () => {
            this.openLoginWindow();
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.AUTH_NOTIFY_SUCCESS, (_event, payload) => {
            const main = this.getMainWindow();
            if (main && !main.isDestroyed()) {
                main.webContents.send(constants_1.IPC_CHANNELS.AUTH_STATE_CHANGED, payload);
            }
            if (this.loginWindow && !this.loginWindow.isDestroyed()) {
                this.loginWindow.close();
            }
        });
    }
    openLoginWindow() {
        if (this.loginWindow && !this.loginWindow.isDestroyed()) {
            this.loginWindow.show();
            this.loginWindow.focus();
            return;
        }
        const main = this.getMainWindow();
        this.loginWindow = new electron_1.BrowserWindow({
            width: 460,
            height: 640,
            resizable: false,
            maximizable: false,
            fullscreenable: false,
            frame: false,
            title: 'ç™»å½• - æ™ºç‹�æµ�è§ˆå™¨',
            parent: main && !main.isDestroyed() ? main : undefined,
            modal: false,
            show: false,
            backgroundColor: '#ffffff',
            webPreferences: {
                preload: path_1.default.join(electron_1.app.getAppPath(), 'dist/main/preload/index.js'),
                contextIsolation: true,
                nodeIntegration: false,
                sandbox: true
            }
        });
        this.loginWindow.once('ready-to-show', () => {
            this.loginWindow?.show();
            this.loginWindow?.focus();
        });
        this.loginWindow.on('closed', () => {
            this.loginWindow = null;
        });
        this.loginWindow.loadFile(path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html'), {
            hash: '/login'
        });
    }
}
exports.AuthWindowManager = AuthWindowManager;
//# sourceMappingURL=auth-window.js.map{"version":3,"file":"auth-window.js","sourceRoot":"","sources":["../../../src/main/auth-window.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAsD;AACtD,gDAAuB;AACvB,mDAAkD;AAElD;;;;;;;GAOG;AACH,MAAa,iBAAiB;IAG5B,YAAoB,aAAyC;QAAzC,kBAAa,GAAb,aAAa,CAA4B;QAFrD,gBAAW,GAAyB,IAAI,CAAA;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WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;YACtD,KAAK,EAAE,KAAK;YACZ,IAAI,EAAE,KAAK;YACX,eAAe,EAAE,SAAS;YAC1B,cAAc,EAAE;gBACd,OAAO,EAAE,cAAI,CAAC,IAAI,CAAC,cAAG,CAAC,UAAU,EAAE,EAAE,4BAA4B,CAAC;gBAClE,gBAAgB,EAAE,IAAI;gBACtB,eAAe,EAAE,KAAK;gBACtB,OAAO,EAAE,IAAI;aACd;SACF,CAAC,CAAA;QAEF,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE;YAC1C,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAA;YACxB,IAAI,CAAC,WAAW,EAAE,KAAK,EAAE,CAAA;QAC3B,CAAC,CAAC,CAAA;QAEF,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACjC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;QACzB,CAAC,CAAC,CAAA;QAEF,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAI,CAAC,IAAI,CAAC,cAAG,CAAC,UAAU,EAAE,EAAE,0BAA0B,CAAC,EAAE;YACjF,IAAI,EAAE,QAAQ;SACf,CAAC,CAAA;IACJ,CAAC;CACF;AAhED,8CAgEC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDatabase = initDatabase;
exports.getDatabase = getDatabase;
const electron_store_1 = __importDefault(require("electron-store"));
const electron_1 = require("electron");
const constants_1 = require("../shared/constants");
function getDefaultDownloadPath() {
    try {
        return electron_1.app.getPath('downloads');
    }
    catch {
        return '';
    }
}
const defaultSettings = {
    theme: 'system',
    language: 'zh-CN',
    homepage: constants_1.DEFAULT_HOMEPAGE,
    searchEngine: 'baidu',
    downloadPath: '',
    defaultZoom: 100,
    showBookmarkBar: true,
    enableAdBlock: true,
    enableAICopilot: true
};
class DatabaseManager {
    constructor() {
        this.settingsCache = null;
        this.store = new electron_store_1.default({
            name: 'zhihu-browser-data',
            defaults: {
                bookmarks: constants_1.DEFAULT_BOOKMARKS,
                history: [],
                settings: defaultSettings,
                users: []
            }
        });
    }
    get(key) {
        return this.store.get(key);
    }
    set(key, value) {
        this.store.set(key, value);
        if (key === 'settings')
            this.settingsCache = null;
    }
    getBookmarks() {
        return this.get('bookmarks');
    }
    addBookmark(bookmark) {
        const bookmarks = this.getBookmarks();
        bookmarks.push(bookmark);
        this.set('bookmarks', bookmarks);
    }
    updateBookmark(id, updates) {
        const bookmarks = this.getBookmarks();
        const index = bookmarks.findIndex(b => b.id === id);
        if (index >= 0) {
            bookmarks[index] = { ...bookmarks[index], ...updates };
            this.set('bookmarks', bookmarks);
        }
    }
    deleteBookmark(id) {
        const bookmarks = this.getBookmarks();
        const filtered = bookmarks.filter(b => b.id !== id && b.parentId !== id);
        this.set('bookmarks', filtered);
    }
    addHistory(url, title) {
        const history = this.get('history');
        const existing = history.find(h => h.url === url);
        const now = Date.now();
        if (existing) {
            existing.title = title;
            existing.visitTime = now;
            existing.visitCount += 1;
        }
        else {
            history.unshift({
                id: `hist_${now}_${Math.random().toString(36).slice(2, 8)}`,
                url,
                title,
                visitTime: now,
                visitCount: 1
            });
        }
        if (history.length > 1000)
            history.pop();
        this.set('history', history);
    }
    getHistory(limit = 500) {
        return this.get('history').slice(0, limit);
    }
    clearHistory() {
        this.set('history', []);
    }
    getSetting(key) {
        const value = this.getSettings()[key];
        return value !== undefined ? String(value) : null;
    }
    setSetting(key, value) {
        const settings = this.getSettings();
        if (key === 'defaultZoom') {
            ;
            settings[key] = Number(value);
        }
        else if (key === 'showBookmarkBar' || key === 'enableAdBlock' || key === 'enableAICopilot') {
            ;
            settings[key] = value === 'true';
        }
        else {
            ;
            settings[key] = value;
        }
        this.set('settings', settings);
    }
    getSettings() {
        if (this.settingsCache)
            return this.settingsCache;
        const settings = this.get('settings');
        if (!settings.downloadPath) {
            settings.downloadPath = getDefaultDownloadPath();
            this.set('settings', settings);
        }
        this.settingsCache = settings;
        return settings;
    }
    setSettings(settings) {
        const current = this.getSettings();
        this.set('settings', { ...current, ...settings });
    }
    getUsers() {
        return this.get('users');
    }
    addUser(user) {
        const users = this.getUsers();
        users.push(user);
        this.set('users', users);
    }
    updateUser(predicate, updater) {
        const users = this.getUsers();
        const index = users.findIndex(predicate);
        if (index >= 0) {
            users[index] = updater(users[index]);
            this.set('users', users);
        }
    }
    findUser(predicate) {
        return this.getUsers().find(predicate);
    }
    getRawDb() {
        return this.store;
    }
    close() {
        // electron-store è‡ªåŠ¨æŒ�ä¹…åŒ–
    }
}
let dbManager = null;
function initDatabase() {
    if (!dbManager) {
        dbManager = new DatabaseManager();
    }
    return dbManager;
}
function getDatabase() {
    if (!dbManager) {
        throw new Error('Database not initialized');
    }
    return dbManager;
}
//# sourceMappingURL=database.js.map{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../src/main/database.ts"],"names":[],"mappings":";;;;;AAkLA,oCAKC;AAED,kCAKC;AA9LD,oEAAkC;AAClC,uCAA8B;AAE9B,mDAAyE;AASzE,SAAS,sBAAsB;IAC7B,IAAI,CAAC;QACH,OAAO,cAAG,CAAC,OAAO,CAAC,WAAW,CAAC,CAAA;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAA;IACX,CAAC;AACH,CAAC;AAED,MAAM,eAAe,GAAgB;IACnC,KAAK,EAAE,QAAQ;IACf,QAAQ,EAAE,OAAO;IACjB,QAAQ,EAAE,4BAAgB;IAC1B,YAAY,EAAE,OAAO;IACrB,YAAY,EAAE,EAAE;IAChB,WAAW,EAAE,GAAG;IAChB,eAAe,EAAE,IAAI;IACrB,aAAa,EAAE,IAAI;IACnB,eAAe,EAAE,IAAI;CACtB,CAAA;AAED,MAAM,eAAe;IAInB;QAFQ,kBAAa,GAAuB,IAAI,CAAA;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AY;IAC1B,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,IAAI,eAAe,EAAE,CAAA;IACnC,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED,SAAgB,WAAW;IACzB,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DownloadManager = void 0;
const electron_1 = require("electron");
const path_1 = __importDefault(require("path"));
const constants_1 = require("../shared/constants");
class DownloadManager {
    constructor(window) {
        this.downloads = new Map();
        this.window = window;
        this.setupIpc();
        window.webContents.session.on('will-download', (_event, item) => {
            this.handleDownload(item);
        });
    }
    handleDownload(item) {
        const id = `dl_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
        const savePath = path_1.default.join(electron_1.app.getPath('downloads'), item.getFilename());
        item.setSavePath(savePath);
        const info = {
            id,
            filename: item.getFilename(),
            url: item.getURL(),
            totalBytes: item.getTotalBytes(),
            receivedBytes: 0,
            state: 'progressing',
            savePath,
            startTime: Date.now()
        };
        this.downloads.set(id, info);
        this.broadcastDownloads();
        item.on('updated', (_event, state) => {
            info.receivedBytes = item.getReceivedBytes();
            info.totalBytes = item.getTotalBytes();
            info.state = state;
            this.downloads.set(id, info);
            this.broadcastDownloads();
        });
        item.once('done', (_event, state) => {
            info.state = state;
            info.receivedBytes = item.getReceivedBytes();
            info.totalBytes = item.getTotalBytes();
            this.downloads.set(id, info);
            this.broadcastDownloads();
        });
    }
    broadcastDownloads() {
        const list = Array.from(this.downloads.values());
        this.window.webContents.send(constants_1.IPC_CHANNELS.DOWNLOADS_GET, list);
    }
    setupIpc() {
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.DOWNLOADS_GET, () => {
            return Array.from(this.downloads.values());
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.DOWNLOAD_OPEN_FOLDER, (_event, savePath) => {
            electron_1.shell.showItemInFolder(savePath);
        });
    }
}
exports.DownloadManager = DownloadManager;
//# sourceMappingURL=download-manager.js.map{"version":3,"file":"download-manager.js","sourceRoot":"","sources":["../../../src/main/download-manager.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAkF;AAClF,gDAAuB;AACvB,mDAAkD;AAGlD,MAAa,eAAe;IAI1B,YAAY,MAAqB;QAHzB,cAAS,GAA8B,IAAI,GAAG,EAAE,CAAA;QAItD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,QAAQ,EAAE,CAAA;QAEf,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,eAAe,EAAE,CAAC,MAAa,EAAE,IAAkB,EAAE,EAAE;YACnF,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAA;QAC3B,CAAC,CAAC,CAAA;IACJ,CAAC;IAEO,cAAc,CAAC,IAAkB;QACvC,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAA;QACvE,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,cAAG,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAA;QACxE,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;QAE1B,MAAM,IAAI,GAAiB;YACzB,EAAE;YACF,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE;YAC5B,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE;YAClB,UAAU,EAAE,IAAI,CAAC,aAAa,EAAE;YAChC,aAAa,EAAE,CAAC;YAChB,KAAK,EAAE,aAAa;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Aa,EAAE,GAAG,EAAE;YAC9C,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;QAC5C,CAAC,CAAC,CAAA;QAEF,kBAAO,CAAC,EAAE,CAAC,wBAAY,CAAC,oBAAoB,EAAE,CAAC,MAAM,EAAE,QAAgB,EAAE,EAAE;YACzE,gBAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAA;QAClC,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA/DD,0CA+DC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensionManager = void 0;
const electron_1 = require("electron");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const constants_1 = require("../shared/constants");
class ExtensionManager {
    constructor(window) {
        this.extensions = new Map();
        this.window = window;
        this.loadBuiltinExtensions();
        this.setupIpc();
    }
    loadBuiltinExtensions() {
        const builtinDir = path_1.default.join(process.resourcesPath || electron_1.app.getAppPath(), 'extensions');
        if (!fs_1.default.existsSync(builtinDir))
            return;
        const entries = fs_1.default.readdirSync(builtinDir);
        for (const entry of entries) {
            const extPath = path_1.default.join(builtinDir, entry);
            if (fs_1.default.statSync(extPath).isDirectory()) {
                this.loadExtension(extPath, true);
            }
        }
    }
    loadExtension(extPath, builtin = false) {
        try {
            const manifestPath = path_1.default.join(extPath, 'manifest.json');
            if (!fs_1.default.existsSync(manifestPath))
                return null;
            const manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf-8'));
            const id = manifest.id || `ext_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
            const info = {
                id,
                name: manifest.name || 'æœªå‘½å��æ‰©å±•',
                version: manifest.version || '1.0',
                description: manifest.description || '',
                manifestVersion: manifest.manifest_version || 2,
                enabled: true,
                path: extPath,
                permissions: manifest.permissions || []
            };
            this.extensions.set(id, info);
            // åŠ è½½ content_scripts çš„æ³¨å…¥è§„åˆ™ï¼ˆç®€åŒ–å®žçŽ°ï¼‰
            if (manifest.content_scripts && Array.isArray(manifest.content_scripts)) {
                // å®žé™…å®žçŽ°ä¸­åº”é€šè¿‡ session æ³¨å†Œè„šæœ¬
            }
            this.broadcastExtensions();
            return info;
        }
        catch (err) {
            console.error('åŠ è½½æ‰©å±•å¤±è´¥:', extPath, err);
            return null;
        }
    }
    unloadExtension(id) {
        const ext = this.extensions.get(id);
        if (!ext)
            return false;
        this.extensions.delete(id);
        this.broadcastExtensions();
        return true;
    }
    toggleExtension(id, enabled) {
        const ext = this.extensions.get(id);
        if (!ext)
            return false;
        ext.enabled = enabled;
        this.extensions.set(id, ext);
        this.broadcastExtensions();
        return true;
    }
    getExtensions() {
        return Array.from(this.extensions.values());
    }
    broadcastExtensions() {
        this.window.webContents.send(constants_1.IPC_CHANNELS.EXTENSION_GET_ALL, this.getExtensions());
    }
    setupIpc() {
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.EXTENSION_GET_ALL, () => this.getExtensions());
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.EXTENSION_LOAD, (_event, extPath) => this.loadExtension(extPath));
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.EXTENSION_UNLOAD, (_event, id) => this.unloadExtension(id));
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.EXTENSION_TOGGLE, (_event, id, enabled) => this.toggleExtension(id, enabled));
    }
}
exports.ExtensionManager = ExtensionManager;
//# sourceMappingURL=extension-manager.js.map{"version":3,"file":"extension-manager.js","sourceRoot":"","sources":["../../../src/main/extension-manager.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAgD;AAChD,4CAAmB;AACnB,gDAAuB;AACvB,mDAAkD;AAGlD,MAAa,gBAAgB;IAI3B,YAAY,MAA8B;QAHlC,eAAU,GAA+B,IAAI,GAAG,EAAE,CAAA;QAIxD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QAC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;QACrB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAA;QAC5B,IAAI,CAAC,mBAAmB,EAAE,CAAA;QAC1B,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa;QACX,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,CAAA;IAC7C,CAAC;IAEO,mBAAmB;QACzB,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,wBAAY,CAAC,iBAAiB,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC,CAAA;IACpF,CAAC;IAEO,QAAQ;QACd,kBAAO,CAAC,MAAM,CAAC,wBAAY,CAAC,iBAAiB,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAA;QAC1E,kBAAO,CAAC,MAAM,CAAC,wBAAY,CAAC,cAAc,EAAE,CAAC,MAAM,EAAE,OAAe,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAA;QACrG,kBAAO,CAAC,MAAM,CAAC,wBAAY,CAAC,gBAAgB,EAAE,CAAC,MAAM,EAAE,EAAU,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,CAAA;QAC/F,kBAAO,CAAC,MAAM,CAAC,wBAAY,CAAC,gBAAgB,EAAE,CAAC,MAAM,EAAE,EAAU,EAAE,OAAgB,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAA;IAC5H,CAAC;CACF;AAxFD,4CAwFC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
const window_manager_1 = require("./window-manager");
const session_manager_1 = require("./session-manager");
const ipc_handlers_1 = require("./ipc-handlers");
const menu_1 = require("./menu");
const database_1 = require("./database");
let windowManager = null;
function createWindow() {
    if (windowManager)
        return;
    windowManager = new window_manager_1.WindowManager();
    const win = windowManager.createWindow();
    (0, ipc_handlers_1.setupIpcHandlers)(win);
    (0, menu_1.createApplicationMenu)(windowManager);
}
electron_1.app.whenReady().then(() => {
    (0, database_1.initDatabase)();
    (0, session_manager_1.setupSession)();
    createWindow();
    electron_1.app.on('activate', () => {
        if (electron_1.BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
    electron_1.nativeTheme.on('updated', () => {
        electron_1.BrowserWindow.getAllWindows().forEach(win => {
            win.webContents.send('theme:changed', electron_1.nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
        });
    });
});
electron_1.app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        (0, database_1.getDatabase)().close();
        electron_1.app.quit();
    }
});
electron_1.app.on('before-quit', () => {
    try {
        (0, database_1.getDatabase)().close();
    }
    catch { }
});
electron_1.app.on('web-contents-created', (_event, contents) => {
    contents.on('will-navigate', (_event, navigationUrl) => {
        const parsedUrl = new URL(navigationUrl);
        if (parsedUrl.origin !== 'file://') {
            // å…�è®¸å¤–éƒ¨å¯¼èˆªç”± BrowserView è‡ªèº«å¤„ç�†
        }
    });
    contents.setWindowOpenHandler(({ url }) => {
        // æ‰€æœ‰æ–°çª—å�£è¯·æ±‚ç”±æ ‡ç­¾ç®¡ç�†å™¨å¤„ç�†
        return { action: 'deny' };
    });
});
// å¤„ç�†æ–°çª—å�£è¯·æ±‚ï¼ˆä»Žå‘½ä»¤è¡Œæˆ–å��è®®ï¼‰
electron_1.app.on('open-url', (_event, url) => {
    windowManager?.getTabManager()?.createTab(url);
});
// å�•å®žä¾‹é”�
const gotTheLock = electron_1.app.requestSingleInstanceLock();
if (!gotTheLock) {
    electron_1.app.quit();
}
else {
    electron_1.app.on('second-instance', (_event, commandLine) => {
        const mainWindow = windowManager?.getMainWindow();
        if (mainWindow) {
            if (mainWindow.isMinimized())
                mainWindow.restore();
            mainWindow.focus();
            const url = commandLine.find(arg => arg.startsWith('http'));
            if (url) {
                windowManager?.getTabManager()?.createTab(url);
            }
        }
    });
}
// å®‰å…¨ï¼šç¦�ç”¨ remote æ¨¡å�—ï¼Œå�¯ç”¨ contextIsolation å·²åœ¨å�„ webPreferences é…�ç½®
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/main/index.ts"],"names":[],"mappings":";;AAAA,uCAAmE;AAEnE,qDAAgD;AAChD,uDAAgD;AAChD,iDAAiD;AACjD,iCAA8C;AAC9C,yCAAsD;AAGtD,IAAI,aAAa,GAAyB,IAAI,CAAA;AAE9C,SAAS,YAAY;IACnB,IAAI,aAAa;QAAE,OAAM;IACzB,aAAa,GAAG,IAAI,8BAAa,EAAE,CAAA;IACnC,MAAM,GAAG,GAAG,aAAa,CAAC,YAAY,EAAE,CAAA;IACxC,IAAA,+BAAgB,EAAC,GAAG,CAAC,CAAA;IACrB,IAAA,4BAAqB,EAAC,aAAa,CAAC,CAAA;AACtC,CAAC;AAED,cAAG,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;IACxB,IAAA,uBAAY,GAAE,CAAA;IACd,IAAA,8BAAY,GAAE,CAAA;IACd,YAAY,EAAE,CAAA;IAEd,cAAG,CAAC,EAAE,CAAC,UAAU,EAAE,GAAG,EAAE;QACtB,IAAI,wBAAa,CAAC,aAAa,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/C,YAAY,EAAE,CAAA;QAChB,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,sBAAW,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;QAC7B,wBAAa,CAAC,aAAa,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YAC1C,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,eAAe,EAAE,sBAAW,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;QAC3F,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ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AC;IAChB,cAAG,CAAC,IAAI,EAAE,CAAA;AACZ,CAAC;KAAM,CAAC;IACN,cAAG,CAAC,EAAE,CAAC,iBAAiB,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,EAAE;QAChD,MAAM,UAAU,GAAG,aAAa,EAAE,aAAa,EAAE,CAAA;QACjD,IAAI,UAAU,EAAE,CAAC;YACf,IAAI,UAAU,CAAC,WAAW,EAAE;gBAAE,UAAU,CAAC,OAAO,EAAE,CAAA;YAClD,UAAU,CAAC,KAAK,EAAE,CAAA;YAClB,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAA;YAC3D,IAAI,GAAG,EAAE,CAAC;gBACR,aAAa,EAAE,aAAa,EAAE,EAAE,SAAS,CAAC,GAAG,CAAC,CAAA;YAChD,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,4DAA4D"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupIpcHandlers = setupIpcHandlers;
const electron_1 = require("electron");
const fs_1 = __importDefault(require("fs"));
const crypto_1 = __importDefault(require("crypto"));
const database_1 = require("./database");
const constants_1 = require("../shared/constants");
/**
 * å¯†ç �å­˜å‚¨ï¼šscrypt + æ¯�ç”¨æˆ·éš�æœºç›�ã€‚
 * è¯´æ˜Žï¼šä¸�å¼•å…¥ bcrypt åŽŸç”Ÿä¾�èµ–ï¼ˆéœ€ C++ ç¼–è¯‘ï¼‰ï¼Œæ”¹ç”¨ Node å†…ç½® scryptï¼Œå¼ºåº¦ç›¸å½“ä¸”å…�ç¼–è¯‘ã€‚
 */
function hashPassword(password) {
    const salt = crypto_1.default.randomBytes(16).toString('hex');
    const derived = crypto_1.default.scryptSync(password, salt, 64).toString('hex');
    return `scrypt:${salt}:${derived}`;
}
function verifyPassword(password, stored) {
    if (!stored)
        return false;
    if (stored.startsWith('scrypt:')) {
        const [, salt, hash] = stored.split(':');
        if (!salt || !hash)
            return false;
        try {
            const a = crypto_1.default.scryptSync(password, salt, 64);
            const b = Buffer.from(hash, 'hex');
            return a.length === b.length && crypto_1.default.timingSafeEqual(a, b);
        }
        catch {
            return false;
        }
    }
    // å…¼å®¹æ—©æœŸç‰ˆæœ¬ï¼ˆsha256 + å…¨å±€ç›�ï¼‰
    const legacy = crypto_1.default.createHash('sha256').update(password + 'zhihu-salt').digest('hex');
    return legacy === stored;
}
/**
 * æ‰‹æœºéªŒè¯�ç �ï¼ˆå†…å­˜æ€�ï¼Œè¿›ç¨‹é‡�å�¯å�³å¤±æ•ˆï¼‰ã€‚
 * å½“å‰�æœªæŽ¥å…¥çŸ­ä¿¡æœ�åŠ¡å•†ï¼ŒéªŒè¯�ç �éš�å“�åº”è¿”å›žä»¥ä¾¿æœ¬åœ°æµ‹è¯•ï¼›
 * æŽ¥å…¥é˜¿é‡Œäº‘/è…¾è®¯äº‘çŸ­ä¿¡æ—¶ï¼Œå�ªéœ€åœ¨æ­¤å¤„è°ƒç”¨ SDK å�‘é€�ï¼Œå¹¶ä»Žè¿”å›žå€¼ä¸­ç§»é™¤ code å­—æ®µã€‚
 */
const phoneCodes = new Map();
const PHONE_CODE_TTL = 5 * 60 * 1000;
const PHONE_RE = /^1[3-9]\d{9}$/;
const USERNAME_RE = /^[a-zA-Z0-9_]{3,20}$/;
function setupIpcHandlers(mainWindow) {
    const db = (0, database_1.getDatabase)();
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_GET_ALL, () => {
        return db.getBookmarks();
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_ADD, (_event, bookmark) => {
        db.addBookmark(bookmark);
        mainWindow.webContents.send(constants_1.IPC_CHANNELS.BOOKMARK_CHANGED, db.getBookmarks());
        return true;
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_UPDATE, (_event, id, updates) => {
        db.updateBookmark(id, updates);
        mainWindow.webContents.send(constants_1.IPC_CHANNELS.BOOKMARK_CHANGED, db.getBookmarks());
        return true;
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_DELETE, (_event, id) => {
        db.deleteBookmark(id);
        mainWindow.webContents.send(constants_1.IPC_CHANNELS.BOOKMARK_CHANGED, db.getBookmarks());
        return true;
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_IMPORT, async () => {
        const result = await electron_1.dialog.showOpenDialog(mainWindow, {
            filters: [{ name: 'HTML ä¹¦ç­¾', extensions: ['html', 'htm'] }],
            properties: ['openFile']
        });
        if (result.canceled || result.filePaths.length === 0)
            return { success: false, count: 0 };
        const content = fs_1.default.readFileSync(result.filePaths[0], 'utf-8');
        const imported = parseNetscapeBookmarks(content);
        for (const bm of imported) {
            db.addBookmark(bm);
        }
        mainWindow.webContents.send(constants_1.IPC_CHANNELS.BOOKMARK_CHANGED, db.getBookmarks());
        return { success: true, count: imported.length };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.BOOKMARK_EXPORT, async () => {
        const result = await electron_1.dialog.showSaveDialog(mainWindow, {
            defaultPath: 'æ™ºç‹�æµ�è§ˆå™¨ä¹¦ç­¾.html',
            filters: [{ name: 'HTML ä¹¦ç­¾', extensions: ['html'] }]
        });
        if (result.canceled || !result.filePath)
            return { success: false };
        const bookmarks = db.getBookmarks();
        const html = exportNetscapeBookmarks(bookmarks);
        fs_1.default.writeFileSync(result.filePath, html, 'utf-8');
        return { success: true, path: result.filePath };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.HISTORY_GET, (_event, limit) => {
        return db.getHistory(limit);
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.HISTORY_CLEAR, () => {
        db.clearHistory();
        return true;
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.SETTINGS_GET, () => {
        return db.getSettings();
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.SETTINGS_SET, (_event, settings) => {
        db.setSettings(settings);
        const updated = db.getSettings();
        mainWindow.webContents.send(constants_1.IPC_CHANNELS.SETTINGS_CHANGED, updated);
        return updated;
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_SEND_CODE, (_event, phone) => {
        const p = (phone || '').trim();
        if (!PHONE_RE.test(p))
            return { success: false, message: 'è¯·è¾“å…¥æ­£ç¡®çš„ 11 ä½�æ‰‹æœºå�·' };
        const code = String(Math.floor(100000 + Math.random() * 900000));
        phoneCodes.set(p, { code, expiresAt: Date.now() + PHONE_CODE_TTL });
        return {
            success: true,
            code,
            message: 'éªŒè¯�ç �å·²ç”Ÿæˆ�ï¼ˆæœªæŽ¥å…¥çŸ­ä¿¡æœ�åŠ¡ï¼Œæ¼”ç¤ºæ¨¡å¼�ç›´æŽ¥æ˜¾ç¤ºï¼‰'
        };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_REGISTER, (_event, data) => {
        const password = (data?.password || '');
        if (password.length < 6)
            return { success: false, message: 'å¯†ç �é•¿åº¦è‡³å°‘ 6 ä½�' };
        let username;
        let phone;
        const email = (data.email || '').trim() || undefined;
        if (data.mode === 'phone') {
            phone = (data.phone || '').trim();
            if (!PHONE_RE.test(phone))
                return { success: false, message: 'è¯·è¾“å…¥æ­£ç¡®çš„ 11 ä½�æ‰‹æœºå�·' };
            const record = phoneCodes.get(phone);
            if (!record)
                return { success: false, message: 'è¯·å…ˆèŽ·å�–éªŒè¯�ç �' };
            if (Date.now() > record.expiresAt) {
                phoneCodes.delete(phone);
                return { success: false, message: 'éªŒè¯�ç �å·²è¿‡æœŸï¼Œè¯·é‡�æ–°èŽ·å�–' };
            }
            if (record.code !== (data.code || '').trim())
                return { success: false, message: 'éªŒè¯�ç �ä¸�æ­£ç¡®' };
            phoneCodes.delete(phone);
        }
        else {
            username = (data.username || '').trim();
            if (!USERNAME_RE.test(username)) {
                return { success: false, message: 'ç”¨æˆ·å��éœ€ä¸º 3-20 ä½�å­—æ¯�ã€�æ•°å­—æˆ–ä¸‹åˆ’çº¿' };
            }
        }
        const existing = db.findUser(u => (!!username && u.username === username) ||
            (!!phone && u.phone === phone) ||
            (!!email && u.email === email));
        if (existing)
            return { success: false, message: 'è¯¥è´¦å�·å·²æ³¨å†Œ' };
        const id = `user_${Date.now()}`;
        const token = crypto_1.default.randomBytes(32).toString('hex');
        const nickname = (data.nickname || '').trim() || username || (phone ? `ç”¨æˆ·${phone.slice(-4)}` : 'æ™ºç‹�ç”¨æˆ·');
        db.addUser({
            id,
            username: username || null,
            email: email || null,
            phone: phone || null,
            passwordHash: hashPassword(password),
            nickname,
            avatar: null,
            token,
            createdAt: Date.now()
        });
        return {
            success: true,
            token,
            profile: { id, username, email: email || null, phone: phone || null, nickname }
        };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_LOGIN, (_event, data) => {
        const account = (data?.account || '').trim();
        const user = db.findUser(u => u.username === account || u.phone === account || u.email === account);
        if (!user || !verifyPassword(data.password, user.passwordHash)) {
            return { success: false, message: 'è´¦å�·æˆ–å¯†ç �é”™è¯¯' };
        }
        const token = crypto_1.default.randomBytes(32).toString('hex');
        db.updateUser(u => u.id === user.id, u => ({ ...u, token }));
        const profile = {
            id: user.id,
            username: user.username || undefined,
            email: user.email || undefined,
            phone: user.phone || undefined,
            nickname: user.nickname,
            avatar: user.avatar || undefined
        };
        return { success: true, token, profile };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_LOGOUT, (_event, token) => {
        db.updateUser(u => u.token === token, u => ({ ...u, token: null }));
        return { success: true };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_GET_PROFILE, (_event, token) => {
        const user = db.findUser(u => u.token === token);
        if (!user)
            return null;
        return {
            id: user.id,
            username: user.username || undefined,
            email: user.email || undefined,
            phone: user.phone || undefined,
            nickname: user.nickname,
            avatar: user.avatar || undefined
        };
    });
    electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.AUTH_UPDATE_PROFILE, (_event, token, updates) => {
        if (!updates.nickname && !updates.avatar)
            return { success: false };
        db.updateUser(u => u.token === token, u => ({ ...u, ...updates }));
        return { success: true };
    });
    electron_1.ipcMain.handle('search:suggestions', (_event, query) => {
        const suggestions = [];
        if (!query.trim())
            return suggestions;
        const history = db.getHistory(100);
        const bookmarks = db.getBookmarks().filter(b => b.type === 'bookmark');
        const q = query.toLowerCase();
        history.filter(h => h.url.toLowerCase().includes(q) || h.title.toLowerCase().includes(q))
            .slice(0, 3)
            .forEach(h => suggestions.push({ text: h.title, url: h.url, type: 'history' }));
        bookmarks.filter(b => b.url.toLowerCase().includes(q) || b.title.toLowerCase().includes(q))
            .slice(0, 3)
            .forEach(b => suggestions.push({ text: b.title, url: b.url, type: 'bookmark' }));
        suggestions.push({ text: query, type: 'search' });
        return suggestions;
    });
    electron_1.ipcMain.handle('app:get-search-engines', () => constants_1.SEARCH_ENGINES);
    electron_1.ipcMain.handle('app:open-external', (_event, url) => {
        electron_1.shell.openExternal(url);
    });
}
function parseNetscapeBookmarks(html) {
    const bookmarks = [];
    const rootId = 'imported_root';
    bookmarks.push({
        id: rootId,
        title: 'å¯¼å…¥çš„ä¹¦ç­¾',
        url: '',
        parentId: 'root',
        type: 'folder',
        index: 0,
        dateAdded: Date.now()
    });
    const regex = /<DT><A HREF="([^"]+)"[^>]*>([^<]*)<\/A>/gi;
    let match;
    let index = 0;
    while ((match = regex.exec(html)) !== null) {
        bookmarks.push({
            id: `imported_${Date.now()}_${index}`,
            title: match[2] || match[1],
            url: match[1],
            parentId: rootId,
            type: 'bookmark',
            index,
            dateAdded: Date.now()
        });
        index++;
    }
    return bookmarks;
}
function exportNetscapeBookmarks(bookmarks) {
    const folders = new Map();
    for (const bm of bookmarks) {
        if (bm.type === 'bookmark') {
            if (!folders.has(bm.parentId))
                folders.set(bm.parentId, []);
            folders.get(bm.parentId).push(bm);
        }
    }
    let body = '';
    for (const [parentId, items] of folders) {
        const parent = bookmarks.find(b => b.id === parentId);
        body += `<DT><H3>${parent ? parent.title : 'ä¹¦ç­¾æ �'}</H3>\n<DL><p>\n`;
        for (const item of items) {
            body += `  <DT><A HREF="${item.url}">${item.title}</A>\n`;
        }
        body += `</DL><p>\n`;
    }
    return `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
${body}
</DL><p>
`;
}
//# sourceMappingURL=ipc-handlers.js.map{"version":3,"file":"ipc-handlers.js","sourceRoot":"","sources":["../../../src/main/ipc-handlers.ts"],"names":[],"mappings":";;;;;AA6CA,4CA8NC;AA3QD,uCAAgE;AAChE,4CAAmB;AACnB,oDAA2B;AAC3B,yCAAwC;AACxC,mDAAkE;AAGlE;;;GAGG;AACH,SAAS,YAAY,CAAC,QAAgB;IACpC,MAAM,IAAI,GAAG,gBAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACnD,MAAM,OAAO,GAAG,gBAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACrE,OAAO,UAAU,IAAI,IAAI,OAAO,EAAE,CAAA;AACpC,CAAC;AAED,SAAS,cAAc,CAAC,QAAgB,EAAE,MAAiC;IACzE,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IACzB,IAAI,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACjC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QACxC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,KAAK,CAAA;QA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C,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;IAED,IAAI,IAAI,GAAG,EAAE,CAAA;IACb,KAAK,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;QACxC,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,QAAQ,CAAC,CAAA;QACrD,IAAI,IAAI,WAAW,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,kBAAkB,CAAA;QAClE,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,kBAAkB,IAAI,CAAC,GAAG,KAAK,IAAI,CAAC,KAAK,QAAQ,CAAA;QAC3D,CAAC;QACD,IAAI,IAAI,YAAY,CAAA;IACtB,CAAC;IAED,OAAO;;;;;EAKP,IAAI;;CAEL,CAAA;AACD,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createApplicationMenu = createApplicationMenu;
const electron_1 = require("electron");
const constants_1 = require("../shared/constants");
function createApplicationMenu(windowManager) {
    const isMac = process.platform === 'darwin';
    const template = [
        {
            label: 'æ™ºç‹�æµ�è§ˆå™¨',
            submenu: [
                { role: 'about', label: 'å…³äºŽæ™ºç‹�æµ�è§ˆå™¨' },
                { type: 'separator' },
                { role: 'quit', label: 'é€€å‡º' }
            ]
        },
        {
            label: 'æ–‡ä»¶',
            submenu: [
                {
                    label: 'æ–°å»ºæ ‡ç­¾é¡µ',
                    accelerator: 'CmdOrCtrl+T',
                    click: () => windowManager.getTabManager()?.createTab()
                },
                {
                    label: 'å…³é—­æ ‡ç­¾é¡µ',
                    accelerator: 'CmdOrCtrl+W',
                    click: () => {
                        const activeId = windowManager.getTabManager()?.getActiveTabId();
                        if (activeId)
                            windowManager.getTabManager()?.closeTab(activeId);
                    }
                },
                { type: 'separator' },
                { role: 'close', label: 'å…³é—­çª—å�£' }
            ]
        },
        {
            label: 'ç¼–è¾‘',
            submenu: [
                { role: 'undo', label: 'æ’¤é”€' },
                { role: 'redo', label: 'é‡�å�š' },
                { type: 'separator' },
                { role: 'cut', label: 'å‰ªåˆ‡' },
                { role: 'copy', label: 'å¤�åˆ¶' },
                { role: 'paste', label: 'ç²˜è´´' },
                { role: 'selectAll', label: 'å…¨é€‰' }
            ]
        },
        {
            label: 'æŸ¥çœ‹',
            submenu: [
                {
                    label: 'é‡�æ–°åŠ è½½',
                    accelerator: 'CmdOrCtrl+R',
                    click: () => {
                        const win = windowManager.getMainWindow();
                        win?.webContents.send(constants_1.IPC_CHANNELS.RELOAD);
                    }
                },
                {
                    label: 'å�œæ­¢',
                    accelerator: 'Esc',
                    click: () => {
                        const win = windowManager.getMainWindow();
                        win?.webContents.send(constants_1.IPC_CHANNELS.STOP);
                    }
                },
                {
                    label: 'å¼€å�‘è€…å·¥å…·',
                    accelerator: 'F12',
                    click: () => {
                        const win = windowManager.getMainWindow();
                        win?.webContents.send(constants_1.IPC_CHANNELS.TOGGLE_DEVTOOLS);
                    }
                },
                { type: 'separator' },
                {
                    label: 'æ”¾å¤§',
                    accelerator: 'CmdOrCtrl+Plus',
                    click: () => {
                        const activeId = windowManager.getTabManager()?.getActiveTabId();
                        const wc = activeId ? windowManager.getTabManager()?.getWebContents(activeId) : undefined;
                        if (wc)
                            wc.setZoomLevel(wc.getZoomLevel() + 0.5);
                    }
                },
                {
                    label: 'ç¼©å°�',
                    accelerator: 'CmdOrCtrl+-',
                    click: () => {
                        const activeId = windowManager.getTabManager()?.getActiveTabId();
                        const wc = activeId ? windowManager.getTabManager()?.getWebContents(activeId) : undefined;
                        if (wc)
                            wc.setZoomLevel(wc.getZoomLevel() - 0.5);
                    }
                },
                {
                    label: 'å®žé™…å¤§å°�',
                    accelerator: 'CmdOrCtrl+0',
                    click: () => {
                        const activeId = windowManager.getTabManager()?.getActiveTabId();
                        const wc = activeId ? windowManager.getTabManager()?.getWebContents(activeId) : undefined;
                        if (wc)
                            wc.setZoomLevel(0);
                    }
                }
            ]
        },
        {
            label: 'çª—å�£',
            submenu: [
                { role: 'minimize', label: 'æœ€å°�åŒ–' },
                { role: 'zoom', label: 'ç¼©æ”¾' },
                { type: 'separator' },
                { role: 'front', label: 'å‰�ç½®å…¨éƒ¨çª—å�£' }
            ]
        },
        {
            label: 'å¸®åŠ©',
            submenu: [
                {
                    label: 'å®˜æ–¹ç½‘ç«™',
                    click: () => electron_1.shell.openExternal('https://www.zhihu.com')
                },
                {
                    label: 'å��é¦ˆé—®é¢˜',
                    click: () => electron_1.shell.openExternal('https://github.com/zhihu-browser/issues')
                }
            ]
        }
    ];
    const menu = electron_1.Menu.buildFromTemplate(template);
    electron_1.Menu.setApplicationMenu(menu);
}
//# sourceMappingURL=menu.js.map{"version":3,"file":"menu.js","sourceRoot":"","sources":["../../../src/main/menu.ts"],"names":[],"mappings":";;AAIA,sDA+HC;AAnID,uCAAuE;AAEvE,mDAAkD;AAElD,SAAgB,qBAAqB,CAAC,aAA4B;IAChE,MAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAA;IAE3C,MAAM,QAAQ,GAAiC;QAC7C;YACE,KAAK,EAAE,OAAO;YACd,OAAO,EAAE;gBACP,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE;gBACnC,EAAE,IAAI,EAAE,WAAW,EAAE;gBACrB,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE;aAC9B;SACF;QACD;YACE,KAAK,EAAE,IAAI;YACX,OAAO,EAAE;gBACP;oBACE,KAAK,EAAE,OAAO;oBACd,WAAW,EAAE,aAAa;oBAC1B,KAAK,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,aAAa,EAAE,EAAE,SAAS,EAAE;iBACxD;gBACD;oBACE,KAAK,EAAE,OAAO;oB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AAW,EAAE,aAAa;oBAC1B,KAAK,EAAE,GAAG,EAAE;wBACV,MAAM,QAAQ,GAAG,aAAa,CAAC,aAAa,EAAE,EAAE,cAAc,EAAE,CAAA;wBAChE,MAAM,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,aAAa,EAAE,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;wBACzF,IAAI,EAAE;4BAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;oBAC5B,CAAC;iBACF;aACF;SACF;QACD;YACE,KAAK,EAAE,IAAI;YACX,OAAO,EAAE;gBACP,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE;gBAClC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE;gBAC7B,EAAE,IAAI,EAAE,WAAW,EAAE;gBACrB,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE;aACnC;SACF;QACD;YACE,KAAK,EAAE,IAAI;YACX,OAAO,EAAE;gBACP;oBACE,KAAK,EAAE,MAAM;oBACb,KAAK,EAAE,GAAG,EAAE,CAAC,gBAAK,CAAC,YAAY,CAAC,uBAAuB,CAAC;iBACzD;gBACD;oBACE,KAAK,EAAE,MAAM;oBACb,KAAK,EAAE,GAAG,EAAE,CAAC,gBAAK,CAAC,YAAY,CAAC,yCAAyC,CAAC;iBAC3E;aACF;SACF;KACF,CAAA;IAED,MAAM,IAAI,GAAG,eAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAA;IAC7C,eAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAA;AAC/B,CAAC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupSession = setupSession;
exports.getExtensionsDir = getExtensionsDir;
const electron_1 = require("electron");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const electron_2 = require("electron");
const AD_BLOCK_RULES = [
    '*://*.googleadservices.com/*',
    '*://*.googlesyndication.com/*',
    '*://*.doubleclick.net/*',
    '*://*.facebook.com/tr/*',
    '*://*.google-analytics.com/*',
    '*://*.googletagmanager.com/*',
    '*://*.baidu.com/cpro/*',
    '*://*.pos.baidu.com/*',
    '*://*.hm.baidu.com/*'
];
function setupSession() {
    const webSession = electron_1.session.fromPartition('persist:zhihu');
    webSession.webRequest.onBeforeRequest({ urls: ['<all_urls>'] }, (details, callback) => {
        const shouldBlock = AD_BLOCK_RULES.some(rule => {
            const regex = new RegExp('^' + rule.replace(/\*\./g, '([^/]+\\.)?').replace(/\*/g, '.*') + '$');
            return regex.test(details.url);
        });
        if (shouldBlock) {
            callback({ cancel: true });
            return;
        }
        callback({ cancel: false });
    });
    webSession.setPermissionRequestHandler((_webContents, permission, callback) => {
        const allowedPermissions = ['notifications', 'clipboardRead', 'clipboardWrite', 'media'];
        callback(allowedPermissions.includes(permission));
    });
    webSession.setPermissionCheckHandler((_webContents, permission, _origin, _details) => {
        const allowedPermissions = ['notifications', 'clipboard-read', 'clipboard-write', 'media'];
        return allowedPermissions.includes(permission);
    });
    const extensionsDir = path_1.default.join(electron_2.app.getPath('userData'), 'extensions');
    if (!fs_1.default.existsSync(extensionsDir)) {
        fs_1.default.mkdirSync(extensionsDir, { recursive: true });
    }
}
function getExtensionsDir() {
    return path_1.default.join(electron_2.app.getPath('userData'), 'extensions');
}
//# sourceMappingURL=session-manager.js.map{"version":3,"file":"session-manager.js","sourceRoot":"","sources":["../../../src/main/session-manager.ts"],"names":[],"mappings":";;;;;AAiBA,oCA+BC;AAED,4CAEC;AApDD,uCAAkC;AAClC,4CAAmB;AACnB,gDAAuB;AACvB,uCAA8B;AAE9B,MAAM,cAAc,GAAG;IACrB,8BAA8B;IAC9B,+BAA+B;IAC/B,yBAAyB;IACzB,yBAAyB;IACzB,8BAA8B;IAC9B,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AiB,EAAE,OAAO,CAAC,CAAA;QAC1F,OAAO,kBAAkB,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAA;IAChD,CAAC,CAAC,CAAA;IAEF,MAAM,aAAa,GAAG,cAAI,CAAC,IAAI,CAAC,cAAG,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,YAAY,CAAC,CAAA;IACtE,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;QAClC,YAAE,CAAC,SAAS,CAAC,aAAa,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAClD,CAAC;AACH,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,cAAI,CAAC,IAAI,CAAC,cAAG,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,YAAY,CAAC,CAAA;AACzD,CAAC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TabManager = void 0;
const electron_1 = require("electron");
const path_1 = __importDefault(require("path"));
const constants_1 = require("../shared/constants");
const database_1 = require("./database");
class TabManager {
    constructor(window) {
        this.tabs = new Map();
        this.activeTabId = null;
        this.contentBounds = { x: 0, y: 80, width: 1200, height: 720 };
        this.window = window;
        this.setupIpc();
    }
    setContentBounds(bounds) {
        this.contentBounds = bounds;
        this.layoutTabs();
    }
    createTab(url, options = {}) {
        const id = `tab_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
        const targetUrl = url || constants_1.DEFAULT_HOMEPAGE;
        const isNewTab = !url || url === constants_1.DEFAULT_HOMEPAGE;
        const view = new electron_1.BrowserView({
            webPreferences: {
                preload: path_1.default.join(electron_1.app.getAppPath(), 'dist/main/preload/index.js'),
                contextIsolation: true,
                nodeIntegration: false,
                sandbox: true,
                partition: 'persist:zhihu'
            }
        });
        view.setBounds(this.contentBounds);
        view.setBackgroundColor('#ffffff');
        const tab = {
            id,
            view,
            info: {
                id,
                url: targetUrl,
                title: isNewTab ? 'æ–°æ ‡ç­¾é¡µ' : 'åŠ è½½ä¸­...',
                isLoading: true,
                canGoBack: false,
                canGoForward: false,
                isActive: false
            }
        };
        this.tabs.set(id, tab);
        this.window.addBrowserView(view);
        this.setupWebContents(tab);
        if (this.isZihuInternalUrl(targetUrl)) {
            view.webContents.loadURL(this.getInternalUrl(targetUrl));
        }
        else {
            view.webContents.loadURL(targetUrl);
        }
        if (options.activate !== false) {
            this.activateTab(id);
        }
        this.broadcastTabs();
        return id;
    }
    setupWebContents(tab) {
        const { view, info } = tab;
        const wc = view.webContents;
        wc.on('did-start-loading', () => {
            info.isLoading = true;
            this.broadcastTabs();
            if (this.activeTabId === info.id) {
                this.sendNavigationState(info.id);
            }
        });
        wc.on('did-stop-loading', () => {
            info.isLoading = false;
            info.canGoBack = wc.canGoBack();
            info.canGoForward = wc.canGoForward();
            this.broadcastTabs();
            if (this.activeTabId === info.id) {
                this.sendNavigationState(info.id);
            }
            if (!this.isZihuInternalUrl(info.url)) {
                try {
                    (0, database_1.getDatabase)().addHistory(info.url, info.title);
                }
                catch { }
            }
        });
        wc.on('did-navigate', (_event, url) => {
            info.url = url;
            info.title = wc.getTitle() || url;
            info.canGoBack = wc.canGoBack();
            info.canGoForward = wc.canGoForward();
            this.broadcastTabs();
            if (this.activeTabId === info.id) {
                this.sendNavigationState(info.id);
            }
        });
        wc.on('did-navigate-in-page', (_event, url, isMainFrame) => {
            if (isMainFrame) {
                info.url = url;
                info.title = wc.getTitle() || url;
                this.broadcastTabs();
                if (this.activeTabId === info.id) {
                    this.sendNavigationState(info.id);
                }
            }
        });
        wc.on('page-title-updated', (_event, title) => {
            info.title = title;
            this.broadcastTabs();
        });
        wc.on('page-favicon-updated', (_event, favicons) => {
            if (favicons && favicons.length > 0) {
                info.favicon = favicons[0];
                this.broadcastTabs();
            }
        });
        wc.setWindowOpenHandler(({ url }) => {
            this.createTab(url);
            return { action: 'deny' };
        });
        wc.on('context-menu', (_event, params) => {
            this.window.webContents.send(constants_1.IPC_CHANNELS.CONTEXT_MENU_COMMAND, {
                x: params.x,
                y: params.y,
                linkURL: params.linkURL,
                selectionText: params.selectionText,
                misspelledWord: params.misspelledWord,
                isEditable: params.isEditable
            });
        });
    }
    closeTab(id) {
        const tab = this.tabs.get(id);
        if (!tab)
            return false;
        tab.view.webContents.close();
        this.window.removeBrowserView(tab.view);
        tab.view.destroy?.();
        this.tabs.delete(id);
        if (this.activeTabId === id) {
            const remaining = Array.from(this.tabs.values());
            if (remaining.length > 0) {
                this.activateTab(remaining[remaining.length - 1].id);
            }
            else {
                this.activeTabId = null;
                this.window.webContents.send(constants_1.IPC_CHANNELS.NAVIGATION_STATE_CHANGED, {
                    url: '',
                    title: '',
                    canGoBack: false,
                    canGoForward: false,
                    isLoading: false
                });
            }
        }
        this.broadcastTabs();
        return true;
    }
    activateTab(id) {
        const tab = this.tabs.get(id);
        if (!tab)
            return;
        if (this.activeTabId && this.activeTabId !== id) {
            const prev = this.tabs.get(this.activeTabId);
            if (prev) {
                prev.info.isActive = false;
                this.window.removeBrowserView(prev.view);
            }
        }
        this.activeTabId = id;
        tab.info.isActive = true;
        this.window.addBrowserView(tab.view);
        tab.view.setBounds(this.contentBounds);
        this.broadcastTabs();
        this.sendNavigationState(id);
    }
    reorderTabs(orderedIds) {
        const newMap = new Map();
        for (const id of orderedIds) {
            const tab = this.tabs.get(id);
            if (tab)
                newMap.set(id, tab);
        }
        this.tabs = newMap;
        this.broadcastTabs();
    }
    navigateTo(tabId, url) {
        const tab = this.tabs.get(tabId);
        if (!tab)
            return;
        const finalUrl = this.normalizeUrl(url);
        tab.info.url = finalUrl;
        if (this.isZihuInternalUrl(finalUrl)) {
            tab.view.webContents.loadURL(this.getInternalUrl(finalUrl));
        }
        else {
            tab.view.webContents.loadURL(finalUrl);
        }
    }
    goBack(tabId) {
        const tab = this.tabs.get(tabId);
        if (tab && tab.view.webContents.canGoBack()) {
            tab.view.webContents.goBack();
        }
    }
    goForward(tabId) {
        const tab = this.tabs.get(tabId);
        if (tab && tab.view.webContents.canGoForward()) {
            tab.view.webContents.goForward();
        }
    }
    reload(tabId) {
        const tab = this.tabs.get(tabId);
        if (tab) {
            if (this.isZihuInternalUrl(tab.info.url)) {
                tab.view.webContents.loadURL(this.getInternalUrl(tab.info.url));
            }
            else {
                tab.view.webContents.reload();
            }
        }
    }
    stop(tabId) {
        const tab = this.tabs.get(tabId);
        if (tab) {
            tab.view.webContents.stop();
        }
    }
    goHome(tabId) {
        const db = (0, database_1.getDatabase)();
        const settings = db.getSettings();
        this.navigateTo(tabId, settings.homepage);
    }
    toggleDevTools(tabId) {
        const tab = this.tabs.get(tabId);
        if (tab) {
            if (tab.view.webContents.isDevToolsOpened()) {
                tab.view.webContents.closeDevTools();
            }
            else {
                tab.view.webContents.openDevTools({ mode: 'detach' });
            }
        }
    }
    getActiveTabId() {
        return this.activeTabId;
    }
    getTabCount() {
        return this.tabs.size;
    }
    getWebContents(tabId) {
        return this.tabs.get(tabId)?.view.webContents;
    }
    layoutTabs() {
        for (const tab of this.tabs.values()) {
            tab.view.setBounds(this.contentBounds);
        }
    }
    broadcastTabs() {
        const tabs = Array.from(this.tabs.values()).map(t => ({ ...t.info }));
        this.window.webContents.send(constants_1.IPC_CHANNELS.TABS_UPDATE, tabs);
    }
    sendNavigationState(tabId) {
        const tab = this.tabs.get(tabId);
        if (!tab)
            return;
        const state = {
            url: tab.info.url,
            title: tab.info.title,
            canGoBack: tab.view.webContents.canGoBack(),
            canGoForward: tab.view.webContents.canGoForward(),
            isLoading: tab.info.isLoading,
            favicon: tab.info.favicon
        };
        this.window.webContents.send(constants_1.IPC_CHANNELS.NAVIGATION_STATE_CHANGED, state);
    }
    normalizeUrl(input) {
        const trimmed = input.trim();
        if (trimmed === '' || trimmed === constants_1.DEFAULT_HOMEPAGE || trimmed.startsWith('zhihu://')) {
            return constants_1.DEFAULT_HOMEPAGE;
        }
        if (/^(https?:\/\/|file:\/\/)/i.test(trimmed)) {
            return trimmed;
        }
        if (/^[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z0-9][-a-zA-Z0-9.]*/.test(trimmed)) {
            return `https://${trimmed}`;
        }
        const engine = (0, database_1.getDatabase)().getSettings().searchEngine;
        const searchUrl = constants_1.SEARCH_ENGINES[engine].url.replace('{q}', encodeURIComponent(trimmed));
        return searchUrl;
    }
    isZihuInternalUrl(url) {
        return url.startsWith('zhihu://');
    }
    getInternalUrl(url) {
        if (url === 'zhihu://newtab') {
            return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/newtab`;
        }
        if (url === 'zhihu://settings') {
            return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/settings`;
        }
        if (url === 'zhihu://bookmarks') {
            return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/bookmarks`;
        }
        if (url === 'zhihu://history') {
            return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/history`;
        }
        if (url === 'zhihu://downloads') {
            return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/downloads`;
        }
        return `file://${path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html')}#/newtab`;
    }
    setupIpc() {
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.TAB_CREATE, (_event, url) => {
            this.createTab(url);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.TAB_CLOSE, (_event, id) => {
            this.closeTab(id);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.TAB_ACTIVATE, (_event, id) => {
            this.activateTab(id);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.TAB_REORDER, (_event, orderedIds) => {
            this.reorderTabs(orderedIds);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.NAVIGATE, (_event, url) => {
            if (this.activeTabId) {
                this.navigateTo(this.activeTabId, url);
            }
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.GO_BACK, () => {
            if (this.activeTabId)
                this.goBack(this.activeTabId);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.GO_FORWARD, () => {
            if (this.activeTabId)
                this.goForward(this.activeTabId);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.RELOAD, () => {
            if (this.activeTabId)
                this.reload(this.activeTabId);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.STOP, () => {
            if (this.activeTabId)
                this.stop(this.activeTabId);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.GO_HOME, () => {
            if (this.activeTabId)
                this.goHome(this.activeTabId);
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.TOGGLE_DEVTOOLS, () => {
            if (this.activeTabId)
                this.toggleDevTools(this.activeTabId);
        });
        electron_1.ipcMain.handle(constants_1.IPC_CHANNELS.TABS_UPDATE, () => {
            return Array.from(this.tabs.values()).map(t => ({ ...t.info }));
        });
    }
}
exports.TabManager = TabManager;
//# sourceMappingURL=tab-manager.js.map{"version":3,"file":"tab-manager.js","sourceRoot":"","sources":["../../../src/main/tab-manager.ts"],"names":[],"mappings":";;;;;;AAAA,uCAA0E;AAC1E,gDAAuB;AAEvB,mDAAoF;AACpF,yCAAwC;AAQxC,MAAa,UAAU;IAMrB,YAAY,MAAqB;QALzB,SAAI,GAAqB,IAAI,GAAG,EAAE,CAAA;QAClC,gBAAW,GAAkB,IAAI,CAAA;QAEjC,kBAAa,GAAuB,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAA;QAGnF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,QAAQ,EAAE,CAAA;IACjB,CAAC;IAED,gBAAgB,CAAC,MAA0B;QACzC,IAAI,CAAC,aAAa,GAAG,MAAM,CAAA;QAC3B,IAAI,CAAC,UAAU,EAAE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,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;QACjE,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA7YD,gCA6YC"}"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WindowManager = void 0;
const electron_1 = require("electron");
const path_1 = __importDefault(require("path"));
const tab_manager_1 = require("./tab-manager");
const download_manager_1 = require("./download-manager");
const extension_manager_1 = require("./extension-manager");
const auth_window_1 = require("./auth-window");
const constants_1 = require("../shared/constants");
const HEADER_HEIGHT = 116;
class WindowManager {
    constructor() {
        this.mainWindow = null;
        this.tabManager = null;
        this.downloadManager = null;
        this.extensionManager = null;
        this.authWindowManager = null;
    }
    createWindow() {
        const { width, height } = electron_1.screen.getPrimaryDisplay().workAreaSize;
        this.mainWindow = new electron_1.BrowserWindow({
            width: Math.min(1400, width * 0.85),
            height: Math.min(900, height * 0.85),
            minWidth: 1024,
            minHeight: 640,
            title: 'æ™ºç‹�æµ�è§ˆå™¨',
            frame: false,
            titleBarStyle: 'hidden',
            trafficLightPosition: { x: 12, y: 12 },
            webPreferences: {
                preload: path_1.default.join(electron_1.app.getAppPath(), 'dist/main/preload/index.js'),
                contextIsolation: true,
                nodeIntegration: false,
                sandbox: true
            },
            show: false,
            backgroundColor: electron_1.nativeTheme.shouldUseDarkColors ? '#1f2937' : '#ffffff'
        });
        this.mainWindow.once('ready-to-show', () => {
            this.mainWindow?.show();
            this.mainWindow?.focus();
        });
        this.mainWindow.on('closed', () => {
            this.mainWindow = null;
            this.tabManager = null;
        });
        this.mainWindow.on('resize', () => {
            this.updateContentBounds();
        });
        this.mainWindow.on('maximize', () => {
            this.mainWindow?.webContents.send(constants_1.IPC_CHANNELS.WINDOW_MAXIMIZE, true);
            this.updateContentBounds();
        });
        this.mainWindow.on('unmaximize', () => {
            this.mainWindow?.webContents.send(constants_1.IPC_CHANNELS.WINDOW_MAXIMIZE, false);
            this.updateContentBounds();
        });
        this.setupWindowIpc();
        if (process.env.NODE_ENV === 'development') {
            this.mainWindow.loadURL('http://localhost:5173');
            this.mainWindow.webContents.openDevTools({ mode: 'detach' });
        }
        else {
            this.mainWindow.loadFile(path_1.default.join(electron_1.app.getAppPath(), 'dist/renderer/index.html'));
        }
        this.tabManager = new tab_manager_1.TabManager(this.mainWindow);
        this.downloadManager = new download_manager_1.DownloadManager(this.mainWindow);
        this.extensionManager = new extension_manager_1.ExtensionManager(this.mainWindow);
        this.authWindowManager = new auth_window_1.AuthWindowManager(() => this.getMainWindow());
        this.updateContentBounds();
        setTimeout(() => {
            this.tabManager?.createTab();
        }, 300);
        return this.mainWindow;
    }
    getMainWindow() {
        return this.mainWindow;
    }
    getTabManager() {
        return this.tabManager;
    }
    updateContentBounds() {
        if (!this.mainWindow)
            return;
        const bounds = this.mainWindow.getContentBounds();
        this.tabManager?.setContentBounds({
            x: 0,
            y: HEADER_HEIGHT,
            width: bounds.width,
            height: bounds.height - HEADER_HEIGHT
        });
    }
    setupWindowIpc() {
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.WINDOW_MINIMIZE, () => {
            this.mainWindow?.minimize();
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.WINDOW_MAXIMIZE, () => {
            if (this.mainWindow?.isMaximized()) {
                this.mainWindow.unmaximize();
            }
            else {
                this.mainWindow?.maximize();
            }
        });
        electron_1.ipcMain.on(constants_1.IPC_CHANNELS.WINDOW_CLOSE, () => {
            this.mainWindow?.close();
        });
    }
}
exports.WindowManager = WindowManager;
//# sourceMappingURL=window-manager.js.map{"version":3,"file":"window-manager.js","sourceRoot":"","sources":["../../../src/main/window-manager.ts"],"names":[],"mappings":";;;;;;AAAA,uCAA2E;AAC3E,gDAAuB;AACvB,+CAA0C;AAC1C,yDAAoD;AACpD,2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AG,EAAE;YAC5C,IAAI,IAAI,CAAC,UAAU,EAAE,WAAW,EAAE,EAAE,CAAC;gBACnC,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,CAAA;YAC9B,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,CAAA;YAC7B,CAAC;QACH,CAAC,CAAC,CAAA;QAEF,kBAAO,CAAC,EAAE,CAAC,wBAAY,CAAC,YAAY,EAAE,GAAG,EAAE;YACzC,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA/GD,sCA+GC"}MIT License

Copyright (c) React Training LLC 2015-2019
Copyright (c) Remix Software Inc. 2020-2021
Copyright (c) Shopify Inc. 2022-2023

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////

/**
 * Actions represent the type of change to a location value.
 */
export enum Action {
  /**
   * A POP indicates a change to an arbitrary index in the history stack, such
   * as a back or forward navigation. It does not describe the direction of the
   * navigation, only that the current index changed.
   *
   * Note: This is the default action for newly created history objects.
   */
  Pop = "POP",

  /**
   * A PUSH indicates a new entry being added to the history stack, such as when
   * a link is clicked and a new page loads. When this happens, all subsequent
   * entries in the stack are lost.
   */
  Push = "PUSH",

  /**
   * A REPLACE indicates the entry at the current index in the history stack
   * being replaced by a new one.
   */
  Replace = "REPLACE",
}

/**
 * The pathname, search, and hash values of a URL.
 */
export interface Path {
  /**
   * A URL pathname, beginning with a /.
   */
  pathname: string;

  /**
   * A URL search string, beginning with a ?.
   */
  search: string;

  /**
   * A URL fragment identifier, beginning with a #.
   */
  hash: string;
}

// TODO: (v7) Change the Location generic default from `any` to `unknown` and
// remove Remix `useLocation` wrapper.

/**
 * An entry in a history stack. A location contains information about the
 * URL path, as well as possibly some arbitrary state and a key.
 */
export interface Location<State = any> extends Path {
  /**
   * A value of arbitrary data associated with this location.
   */
  state: State;

  /**
   * A unique string associated with this location. May be used to safely store
   * and retrieve data in some other storage API, like `localStorage`.
   *
   * Note: This value is always "default" on the initial location.
   */
  key: string;
}

/**
 * A change to the current location.
 */
export interface Update {
  /**
   * The action that triggered the change.
   */
  action: Action;

  /**
   * The new location.
   */
  location: Location;

  /**
   * The delta between this location and the former location in the history stack
   */
  delta: number | null;
}

/**
 * A function that receives notifications about location changes.
 */
export interface Listener {
  (update: Update): void;
}

/**
 * Describes a location that is the destination of some navigation, either via
 * `history.push` or `history.replace`. This may be either a URL or the pieces
 * of a URL path.
 */
export type To = string | Partial<Path>;

/**
 * A history is an interface to the navigation stack. The history serves as the
 * source of truth for the current location, as well as provides a set of
 * methods that may be used to change it.
 *
 * It is similar to the DOM's `window.history` object, but with a smaller, more
 * focused API.
 */
export interface History {
  /**
   * The last action that modified the current location. This will always be
   * Action.Pop when a history instance is first created. This value is mutable.
   */
  readonly action: Action;

  /**
   * The current location. This value is mutable.
   */
  readonly location: Location;

  /**
   * Returns a valid href for the given `to` value that may be used as
   * the value of an <a href> attribute.
   *
   * @param to - The destination URL
   */
  createHref(to: To): string;

  /**
   * Returns a URL for the given `to` value
   *
   * @param to - The destination URL
   */
  createURL(to: To): URL;

  /**
   * Encode a location the same way window.history would do (no-op for memory
   * history) so we ensure our PUSH/REPLACE navigations for data routers
   * behave the same as POP
   *
   * @param to Unencoded path
   */
  encodeLocation(to: To): Path;

  /**
   * Pushes a new location onto the history stack, increasing its length by one.
   * If there were any entries in the stack after the current one, they are
   * lost.
   *
   * @param to - The new URL
   * @param state - Data to associate with the new location
   */
  push(to: To, state?: any): void;

  /**
   * Replaces the current location in the history stack with a new one.  The
   * location that was replaced will no longer be available.
   *
   * @param to - The new URL
   * @param state - Data to associate with the new location
   */
  replace(to: To, state?: any): void;

  /**
   * Navigates `n` entries backward/forward in the history stack relative to the
   * current index. For example, a "back" navigation would use go(-1).
   *
   * @param delta - The delta in the stack index
   */
  go(delta: number): void;

  /**
   * Sets up a listener that will be called whenever the current location
   * changes.
   *
   * @param listener - A function that will be called when the location changes
   * @returns unlisten - A function that may be used to stop listening
   */
  listen(listener: Listener): () => void;
}

type HistoryState = {
  usr: any;
  key?: string;
  idx: number;
};

const PopStateEventType = "popstate";
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Memory History
////////////////////////////////////////////////////////////////////////////////

/**
 * A user-supplied object that describes a location. Used when providing
 * entries to `createMemoryHistory` via its `initialEntries` option.
 */
export type InitialEntry = string | Partial<Location>;

export type MemoryHistoryOptions = {
  initialEntries?: InitialEntry[];
  initialIndex?: number;
  v5Compat?: boolean;
};

/**
 * A memory history stores locations in memory. This is useful in stateful
 * environments where there is no web browser, such as node tests or React
 * Native.
 */
export interface MemoryHistory extends History {
  /**
   * The current index in the history stack.
   */
  readonly index: number;
}

/**
 * Memory history stores the current location in memory. It is designed for use
 * in stateful non-browser environments like tests and React Native.
 */
export function createMemoryHistory(
  options: MemoryHistoryOptions = {}
): MemoryHistory {
  let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
  let entries: Location[]; // Declare so we can access from createMemoryLocation
  entries = initialEntries.map((entry, index) =>
    createMemoryLocation(
      entry,
      typeof entry === "string" ? null : entry.state,
      index === 0 ? "default" : undefined
    )
  );
  let index = clampIndex(
    initialIndex == null ? entries.length - 1 : initialIndex
  );
  let action = Action.Pop;
  let listener: Listener | null = null;

  function clampIndex(n: number): number {
    return Math.min(Math.max(n, 0), entries.length - 1);
  }
  function getCurrentLocation(): Location {
    return entries[index];
  }
  function createMemoryLocation(
    to: To,
    state: any = null,
    key?: string
  ): Location {
    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: To) {
    return typeof to === "string" ? to : createPath(to);
  }

  let history: MemoryHistory = {
    get index() {
      return index;
    },
    get action() {
      return action;
    },
    get location() {
      return getCurrentLocation();
    },
    createHref,
    createURL(to) {
      return new URL(createHref(to), "http://localhost");
    },
    encodeLocation(to: 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) {
      listener = fn;
      return () => {
        listener = null;
      };
    },
  };

  return history;
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Browser History
////////////////////////////////////////////////////////////////////////////////

/**
 * A browser history stores the current location in regular URLs in a web
 * browser environment. This is the standard for most web apps and provides the
 * cleanest URLs the browser's address bar.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
 */
export interface BrowserHistory extends UrlHistory {}

export type BrowserHistoryOptions = UrlHistoryOptions;

/**
 * Browser history stores the location in regular URLs. This is the standard for
 * most web apps, but it requires some configuration on the server to ensure you
 * serve the same app at multiple URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
 */
export function createBrowserHistory(
  options: BrowserHistoryOptions = {}
): BrowserHistory {
  function createBrowserLocation(
    window: Window,
    globalHistory: Window["history"]
  ) {
    let { pathname, search, hash } = window.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(window: Window, to: To) {
    return typeof to === "string" ? to : createPath(to);
  }

  return getUrlBasedHistory(
    createBrowserLocation,
    createBrowserHref,
    null,
    options
  );
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Hash History
////////////////////////////////////////////////////////////////////////////////

/**
 * A hash history stores the current location in the fragment identifier portion
 * of the URL in a web browser environment.
 *
 * This is ideal for apps that do not control the server for some reason
 * (because the fragment identifier is never sent to the server), including some
 * shared hosting environments that do not provide fine-grained controls over
 * which pages are served at which URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
 */
export interface HashHistory extends UrlHistory {}

export type HashHistoryOptions = UrlHistoryOptions;

/**
 * Hash history stores the location in window.location.hash. This makes it ideal
 * for situations where you don't want to send the location to the server for
 * some reason, either because you do cannot configure it or the URL space is
 * reserved for something else.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
 */
export function createHashHistory(
  options: HashHistoryOptions = {}
): HashHistory {
  function createHashLocation(
    window: Window,
    globalHistory: Window["history"]
  ) {
    let {
      pathname = "/",
      search = "",
      hash = "",
    } = parsePath(window.location.hash.substr(1));

    // Hash URL should always have a leading / just like window.location.pathname
    // does, so if an app ends up at a route like /#something then we add a
    // leading slash so all of our path-matching behaves the same as if it would
    // in a browser router.  This is particularly important when there exists a
    // root splat route (<Route path="*">) since that matches internally against
    // "/*" and we'd expect /#something to 404 in a hash router app.
    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(window: Window, to: To) {
    let base = window.document.querySelector("base");
    let href = "";

    if (base && base.getAttribute("href")) {
      let url = window.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: Location, to: To) {
    warning(
      location.pathname.charAt(0) === "/",
      `relative pathnames are not supported in hash history.push(${JSON.stringify(
        to
      )})`
    );
  }

  return getUrlBasedHistory(
    createHashLocation,
    createHashHref,
    validateHashLocation,
    options
  );
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region UTILS
////////////////////////////////////////////////////////////////////////////////

/**
 * @private
 */
export function invariant(value: boolean, message?: string): asserts value;
export function invariant<T>(
  value: T | null | undefined,
  message?: string
): asserts value is T;
export function invariant(value: any, message?: string) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}

export function warning(cond: any, message: string) {
  if (!cond) {
    // eslint-disable-next-line no-console
    if (typeof console !== "undefined") console.warn(message);

    try {
      // Welcome to debugging history!
      //
      // This error is thrown as a convenience, so you can more easily
      // find the source for a warning that appears in the console by
      // enabling "pause on exceptions" in your JavaScript debugger.
      throw new Error(message);
      // eslint-disable-next-line no-empty
    } catch (e) {}
  }
}

function createKey() {
  return Math.random().toString(36).substr(2, 8);
}

/**
 * For browser-based histories, we combine the state and key into an object
 */
function getHistoryState(location: Location, index: number): HistoryState {
  return {
    usr: location.state,
    key: location.key,
    idx: index,
  };
}

/**
 * Creates a Location object with a unique key from the given Path
 */
export function createLocation(
  current: string | Location,
  to: To,
  state: any = null,
  key?: string
): Readonly<Location> {
  let location: Readonly<Location> = {
    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 as Location).key) || key || createKey(),
  };
  return location;
}

/**
 * Creates a string URL path from the given pathname, search, and hash components.
 */
export function createPath({
  pathname = "/",
  search = "",
  hash = "",
}: Partial<Path>) {
  if (search && search !== "?")
    pathname += search.charAt(0) === "?" ? search : "?" + search;
  if (hash && hash !== "#")
    pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  return pathname;
}

/**
 * Parses a string URL path into its separate pathname, search, and hash components.
 */
export function parsePath(path: string): Partial<Path> {
  let parsedPath: Partial<Path> = {};

  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;
}

export interface UrlHistory extends History {}

export type UrlHistoryOptions = {
  window?: Window;
  v5Compat?: boolean;
};

function getUrlBasedHistory(
  getLocation: (window: Window, globalHistory: Window["history"]) => Location,
  createHref: (window: Window, to: To) => string,
  validateLocation: ((location: Location, to: To) => void) | null,
  options: UrlHistoryOptions = {}
): UrlHistory {
  let { window = document.defaultView!, v5Compat = false } = options;
  let globalHistory = window.history;
  let action = Action.Pop;
  let listener: Listener | null = null;

  let index = getIndex()!;
  // Index should only be null when we initialize. If not, it's because the
  // user called history.pushState or history.replaceState directly, in which
  // case we should log a warning as it will result in bugs.
  if (index == null) {
    index = 0;
    globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  }

  function getIndex(): number {
    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: To, state?: any) {
    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...catch because iOS limits us to 100 pushState calls :/
    try {
      globalHistory.pushState(historyState, "", url);
    } catch (error) {
      // If the exception is because `state` can't be serialized, let that throw
      // outwards just like a replace call would so the dev knows the cause
      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
      if (error instanceof DOMException && error.name === "DataCloneError") {
        throw error;
      }
      // They are going to lose state here, but there is no real
      // way to warn them about it since the page will refresh...
      window.location.assign(url);
    }

    if (v5Compat && listener) {
      listener({ action, location: history.location, delta: 1 });
    }
  }

  function replace(to: To, state?: any) {
    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: To): URL {
    // window.location.origin is "null" (the literal string value) in Firefox
    // under certain conditions, notably when serving from a local HTML file
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
    let base =
      window.location.origin !== "null"
        ? window.location.origin
        : window.location.href;

    let href = typeof to === "string" ? to : createPath(to);
    // Treating this as a full URL will strip any trailing spaces so we need to
    // pre-encode them since they might be part of a matching splat param from
    // an ancestor route
    href = href.replace(/ $/, "%20");
    invariant(
      base,
      `No window.location.(origin|href) available to create URL for href: ${href}`
    );
    return new URL(href, base);
  }

  let history: History = {
    get action() {
      return action;
    },
    get location() {
      return getLocation(window, globalHistory);
    },
    listen(fn: Listener) {
      if (listener) {
        throw new Error("A history only accepts one active listener");
      }
      window.addEventListener(PopStateEventType, handlePop);
      listener = fn;

      return () => {
        window.removeEventListener(PopStateEventType, handlePop);
        listener = null;
      };
    },
    createHref(to) {
      return createHref(window, to);
    },
    createURL,
    encodeLocation(to) {
      // Encode a Location the same way window.location would
      let url = createURL(to);
      return {
        pathname: url.pathname,
        search: url.search,
        hash: url.hash,
      };
    },
    push,
    replace,
    go(n) {
      return globalHistory.go(n);
    },
  };

  return history;
}

//#endregion
export type {
  ActionFunction,
  ActionFunctionArgs,
  AgnosticDataIndexRouteObject,
  AgnosticDataNonIndexRouteObject,
  AgnosticDataRouteMatch,
  AgnosticDataRouteObject,
  AgnosticIndexRouteObject,
  AgnosticNonIndexRouteObject,
  AgnosticPatchRoutesOnNavigationFunction,
  AgnosticPatchRoutesOnNavigationFunctionArgs,
  AgnosticRouteMatch,
  AgnosticRouteObject,
  DataStrategyFunction,
  DataStrategyFunctionArgs,
  DataStrategyMatch,
  DataStrategyResult,
  ErrorResponse,
  FormEncType,
  FormMethod,
  HTMLFormMethod,
  JsonFunction,
  LazyRouteFunction,
  LoaderFunction,
  LoaderFunctionArgs,
  ParamParseKey,
  Params,
  PathMatch,
  PathParam,
  PathPattern,
  RedirectFunction,
  ShouldRevalidateFunction,
  ShouldRevalidateFunctionArgs,
  TrackedPromise,
  UIMatch,
  V7_FormMethod,
  DataWithResponseInit as UNSAFE_DataWithResponseInit,
} from "./utils";

export {
  AbortedDeferredError,
  data,
  defer,
  generatePath,
  getToPathname,
  isRouteErrorResponse,
  joinPaths,
  json,
  matchPath,
  matchRoutes,
  normalizePathname,
  redirect,
  redirectDocument,
  replace,
  resolvePath,
  resolveTo,
  stripBasename,
} from "./utils";

export type {
  BrowserHistory,
  BrowserHistoryOptions,
  HashHistory,
  HashHistoryOptions,
  History,
  InitialEntry,
  Location,
  MemoryHistory,
  MemoryHistoryOptions,
  Path,
  To,
} from "./history";

export {
  Action,
  createBrowserHistory,
  createHashHistory,
  createMemoryHistory,
  createPath,
  parsePath,
} from "./history";

export * from "./router";

///////////////////////////////////////////////////////////////////////////////
// DANGER! PLEASE READ ME!
// We consider these exports an implementation detail and do not guarantee
// against any breaking changes, regardless of the semver release. Use with
// extreme caution and only if you understand the consequences. Godspeed.
///////////////////////////////////////////////////////////////////////////////

/** @internal */
export type { RouteManifest as UNSAFE_RouteManifest } from "./utils";
export {
  DeferredData as UNSAFE_DeferredData,
  ErrorResponseImpl as UNSAFE_ErrorResponseImpl,
  convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes,
  convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch,
  decodePath as UNSAFE_decodePath,
  getResolveToMatches as UNSAFE_getResolveToMatches,
} from "./utils";

export {
  invariant as UNSAFE_invariant,
  warning as UNSAFE_warning,
} from "./history";
{
  "name": "@remix-run/router",
  "version": "1.23.4",
  "description": "Nested/Data-driven/Framework-agnostic Routing",
  "repository": {
    "type": "git",
    "url": "https://github.com/remix-run/react-router",
    "directory": "packages/router"
  },
  "license": "MIT",
  "author": "Remix Software <hello@remix.run>",
  "sideEffects": false,
  "main": "./dist/router.cjs.js",
  "unpkg": "./dist/router.umd.min.js",
  "module": "./dist/router.js",
  "types": "./dist/index.d.ts",
  "files": [
    "dist/",
    "*.ts",
    "CHANGELOG.md"
  ],
  "engines": {
    "node": ">=14.0.0"
  },
  "publishConfig": {
    "access": "public"
  }
}import type { History, Location, Path, To } from "./history";
import {
  Action as HistoryAction,
  createLocation,
  createPath,
  invariant,
  parsePath,
  warning,
} from "./history";
import type {
  AgnosticDataRouteMatch,
  AgnosticDataRouteObject,
  DataStrategyMatch,
  AgnosticRouteObject,
  DataResult,
  DataStrategyFunction,
  DataStrategyFunctionArgs,
  DeferredData,
  DeferredResult,
  DetectErrorBoundaryFunction,
  ErrorResult,
  FormEncType,
  FormMethod,
  HTMLFormMethod,
  DataStrategyResult,
  ImmutableRouteKey,
  MapRoutePropertiesFunction,
  MutationFormMethod,
  RedirectResult,
  RouteData,
  RouteManifest,
  ShouldRevalidateFunctionArgs,
  Submission,
  SuccessResult,
  UIMatch,
  V7_FormMethod,
  V7_MutationFormMethod,
  AgnosticPatchRoutesOnNavigationFunction,
  DataWithResponseInit,
} from "./utils";
import {
  ErrorResponseImpl,
  ResultType,
  convertRouteMatchToUiMatch,
  convertRoutesToDataRoutes,
  getPathContributingMatches,
  getResolveToMatches,
  immutableRouteKeys,
  isRouteErrorResponse,
  joinPaths,
  matchRoutes,
  matchRoutesImpl,
  removeDoubleSlashes,
  resolveTo,
  stripBasename,
} from "./utils";

////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////

/**
 * A Router instance manages all navigation and data loading/mutations
 */
export interface Router {
  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Return the basename for the router
   */
  get basename(): RouterInit["basename"];

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Return the future config for the router
   */
  get future(): FutureConfig;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Return the current state of the router
   */
  get state(): RouterState;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Return the routes for this router instance
   */
  get routes(): AgnosticDataRouteObject[];

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Return the window associated with the router
   */
  get window(): RouterInit["window"];

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Initialize the router, including adding history listeners and kicking off
   * initial data fetches.  Returns a function to cleanup listeners and abort
   * any in-progress loads
   */
  initialize(): Router;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Subscribe to router.state updates
   *
   * @param fn function to call with the new state
   */
  subscribe(fn: RouterSubscriber): () => void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Enable scroll restoration behavior in the router
   *
   * @param savedScrollPositions Object that will manage positions, in case
   *                             it's being restored from sessionStorage
   * @param getScrollPosition    Function to get the active Y scroll position
   * @param getKey               Function to get the key to use for restoration
   */
  enableScrollRestoration(
    savedScrollPositions: Record<string, number>,
    getScrollPosition: GetScrollPositionFunction,
    getKey?: GetScrollRestorationKeyFunction
  ): () => void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Navigate forward/backward in the history stack
   * @param to Delta to move in the history stack
   */
  navigate(to: number): Promise<void>;

  /**
   * Navigate to the given path
   * @param to Path to navigate to
   * @param opts Navigation options (method, submission, etc.)
   */
  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Trigger a fetcher load/submission
   *
   * @param key     Fetcher key
   * @param routeId Route that owns the fetcher
   * @param href    href to fetch
   * @param opts    Fetcher options, (method, submission, etc.)
   */
  fetch(
    key: string,
    routeId: string,
    href: string | null,
    opts?: RouterFetchOptions
  ): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Trigger a revalidation of all current route loaders and fetcher loads
   */
  revalidate(): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Utility function to create an href for the given location
   * @param location
   */
  createHref(location: Location | URL): string;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Utility function to URL encode a destination path according to the internal
   * history implementation
   * @param to
   */
  encodeLocation(to: To): Path;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Get/create a fetcher for the given key
   * @param key
   */
  getFetcher<TData = any>(key: string): Fetcher<TData>;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Delete the fetcher for a given key
   * @param key
   */
  deleteFetcher(key: string): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Cleanup listeners and abort any in-progress loads
   */
  dispose(): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Get a navigation blocker
   * @param key The identifier for the blocker
   * @param fn The blocker function implementation
   */
  getBlocker(key: string, fn: BlockerFunction): Blocker;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Delete a navigation blocker
   * @param key The identifier for the blocker
   */
  deleteBlocker(key: string): void;

  /**
   * @internal
   * PRIVATE DO NOT USE
   *
   * Patch additional children routes into an existing parent route
   * @param routeId The parent route id or a callback function accepting `patch`
   *                to perform batch patching
   * @param children The additional children routes
   */
  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * HMR needs to pass in-flight route updates to React Router
   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
   */
  _internalSetRoutes(routes: AgnosticRouteObject[]): void;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Internal fetch AbortControllers accessed by unit tests
   */
  _internalFetchControllers: Map<string, AbortController>;

  /**
   * @internal
   * PRIVATE - DO NOT USE
   *
   * Internal pending DeferredData instances accessed by unit tests
   */
  _internalActiveDeferreds: Map<string, DeferredData>;
}

/**
 * State maintained internally by the router.  During a navigation, all states
 * reflect the the "old" location unless otherwise noted.
 */
export interface RouterState {
  /**
   * The action of the most recent navigation
   */
  historyAction: HistoryAction;

  /**
   * The current location reflected by the router
   */
  location: Location;

  /**
   * The current set of route matches
   */
  matches: AgnosticDataRouteMatch[];

  /**
   * Tracks whether we've completed our initial data load
   */
  initialized: boolean;

  /**
   * Current scroll position we should start at for a new view
   *  - number -> scroll position to restore to
   *  - false -> do not restore scroll at all (used during submissions)
   *  - null -> don't have a saved position, scroll to hash or top of page
   */
  restoreScrollPosition: number | false | null;

  /**
   * Indicate whether this navigation should skip resetting the scroll position
   * if we are unable to restore the scroll position
   */
  preventScrollReset: boolean;

  /**
   * Tracks the state of the current navigation
   */
  navigation: Navigation;

  /**
   * Tracks any in-progress revalidations
   */
  revalidation: RevalidationState;

  /**
   * Data from the loaders for the current matches
   */
  loaderData: RouteData;

  /**
   * Data from the action for the current matches
   */
  actionData: RouteData | null;

  /**
   * Errors caught from loaders for the current matches
   */
  errors: RouteData | null;

  /**
   * Map of current fetchers
   */
  fetchers: Map<string, Fetcher>;

  /**
   * Map of current blockers
   */
  blockers: Map<string, Blocker>;
}

/**
 * Data that can be passed into hydrate a Router from SSR
 */
export type HydrationState = Partial<
  Pick<RouterState, "loaderData" | "actionData" | "errors">
>;

/**
 * Future flags to toggle new feature behavior
 */
export interface FutureConfig {
  v7_fetcherPersist: boolean;
  v7_normalizeFormMethod: boolean;
  v7_partialHydration: boolean;
  v7_prependBasename: boolean;
  v7_relativeSplatPath: boolean;
  v7_skipActionErrorRevalidation: boolean;
}

/**
 * Initialization options for createRouter
 */
export interface RouterInit {
  routes: AgnosticRouteObject[];
  history: History;
  basename?: string;
  /**
   * @deprecated Use `mapRouteProperties` instead
   */
  detectErrorBoundary?: DetectErrorBoundaryFunction;
  mapRouteProperties?: MapRoutePropertiesFunction;
  future?: Partial<FutureConfig>;
  hydrationData?: HydrationState;
  window?: Window;
  dataStrategy?: DataStrategyFunction;
  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
}

/**
 * State returned from a server-side query() call
 */
export interface StaticHandlerContext {
  basename: Router["basename"];
  location: RouterState["location"];
  matches: RouterState["matches"];
  loaderData: RouterState["loaderData"];
  actionData: RouterState["actionData"];
  errors: RouterState["errors"];
  statusCode: number;
  loaderHeaders: Record<string, Headers>;
  actionHeaders: Record<string, Headers>;
  activeDeferreds: Record<string, DeferredData> | null;
  _deepestRenderedBoundaryId?: string | null;
}

/**
 * A StaticHandler instance manages a singular SSR navigation/fetch event
 */
export interface StaticHandler {
  dataRoutes: AgnosticDataRouteObject[];
  query(
    request: Request,
    opts?: {
      requestContext?: unknown;
      skipLoaderErrorBubbling?: boolean;
      dataStrategy?: DataStrategyFunction;
    }
  ): Promise<StaticHandlerContext | Response>;
  queryRoute(
    request: Request,
    opts?: {
      routeId?: string;
      requestContext?: unknown;
      dataStrategy?: DataStrategyFunction;
    }
  ): Promise<any>;
}

type ViewTransitionOpts = {
  currentLocation: Location;
  nextLocation: Location;
};

/**
 * Subscriber function signature for changes to router state
 */
export interface RouterSubscriber {
  (
    state: RouterState,
    opts: {
      deletedFetchers: string[];
      viewTransitionOpts?: ViewTransitionOpts;
      flushSync: boolean;
    }
  ): void;
}

/**
 * Function signature for determining the key to be used in scroll restoration
 * for a given location
 */
export interface GetScrollRestorationKeyFunction {
  (location: Location, matches: UIMatch[]): string | null;
}

/**
 * Function signature for determining the current scroll position
 */
export interface GetScrollPositionFunction {
  (): number;
}

export type RelativeRoutingType = "route" | "path";

// Allowed for any navigation or fetch
type BaseNavigateOrFetchOptions = {
  preventScrollReset?: boolean;
  relative?: RelativeRoutingType;
  flushSync?: boolean;
};

// Only allowed for navigations
type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
  replace?: boolean;
  state?: any;
  fromRouteId?: string;
  viewTransition?: boolean;
};

// Only allowed for submission navigations
type BaseSubmissionOptions = {
  formMethod?: HTMLFormMethod;
  formEncType?: FormEncType;
} & (
  | { formData: FormData; body?: undefined }
  | { formData?: undefined; body: any }
);

/**
 * Options for a navigate() call for a normal (non-submission) navigation
 */
type LinkNavigateOptions = BaseNavigateOptions;

/**
 * Options for a navigate() call for a submission navigation
 */
type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;

/**
 * Options to pass to navigate() for a navigation
 */
export type RouterNavigateOptions =
  | LinkNavigateOptions
  | SubmissionNavigateOptions;

/**
 * Options for a fetch() load
 */
type LoadFetchOptions = BaseNavigateOrFetchOptions;

/**
 * Options for a fetch() submission
 */
type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;

/**
 * Options to pass to fetch()
 */
export type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;

/**
 * Potential states for state.navigation
 */
export type NavigationStates = {
  Idle: {
    state: "idle";
    location: undefined;
    formMethod: undefined;
    formAction: undefined;
    formEncType: undefined;
    formData: undefined;
    json: undefined;
    text: undefined;
  };
  Loading: {
    state: "loading";
    location: Location;
    formMethod: Submission["formMethod"] | undefined;
    formAction: Submission["formAction"] | undefined;
    formEncType: Submission["formEncType"] | undefined;
    formData: Submission["formData"] | undefined;
    json: Submission["json"] | undefined;
    text: Submission["text"] | undefined;
  };
  Submitting: {
    state: "submitting";
    location: Location;
    formMethod: Submission["formMethod"];
    formAction: Submission["formAction"];
    formEncType: Submission["formEncType"];
    formData: Submission["formData"];
    json: Submission["json"];
    text: Submission["text"];
  };
};

export type Navigation = NavigationStates[keyof NavigationStates];

export type RevalidationState = "idle" | "loading";

/**
 * Potential states for fetchers
 */
type FetcherStates<TData = any> = {
  Idle: {
    state: "idle";
    formMethod: undefined;
    formAction: undefined;
    formEncType: undefined;
    text: undefined;
    formData: undefined;
    json: undefined;
    data: TData | undefined;
  };
  Loading: {
    state: "loading";
    formMethod: Submission["formMethod"] | undefined;
    formAction: Submission["formAction"] | undefined;
    formEncType: Submission["formEncType"] | undefined;
    text: Submission["text"] | undefined;
    formData: Submission["formData"] | undefined;
    json: Submission["json"] | undefined;
    data: TData | undefined;
  };
  Submitting: {
    state: "submitting";
    formMethod: Submission["formMethod"];
    formAction: Submission["formAction"];
    formEncType: Submission["formEncType"];
    text: Submission["text"];
    formData: Submission["formData"];
    json: Submission["json"];
    data: TData | undefined;
  };
};

export type Fetcher<TData = any> =
  FetcherStates<TData>[keyof FetcherStates<TData>];

interface BlockerBlocked {
  state: "blocked";
  reset(): void;
  proceed(): void;
  location: Location;
}

interface BlockerUnblocked {
  state: "unblocked";
  reset: undefined;
  proceed: undefined;
  location: undefined;
}

interface BlockerProceeding {
  state: "proceeding";
  reset: undefined;
  proceed: undefined;
  location: Location;
}

export type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;

export type BlockerFunction = (args: {
  currentLocation: Location;
  nextLocation: Location;
  historyAction: HistoryAction;
}) => boolean;

interface ShortCircuitable {
  /**
   * startNavigation does not need to complete the navigation because we
   * redirected or got interrupted
   */
  shortCircuited?: boolean;
}

type PendingActionResult = [string, SuccessResult | ErrorResult];

interface HandleActionResult extends ShortCircuitable {
  /**
   * Route matches which may have been updated from fog of war discovery
   */
  matches?: RouterState["matches"];
  /**
   * Tuple for the returned or thrown value from the current action.  The routeId
   * is the action route for success and the bubbled boundary route for errors.
   */
  pendingActionResult?: PendingActionResult;
}

interface HandleLoadersResult extends ShortCircuitable {
  /**
   * Route matches which may have been updated from fog of war discovery
   */
  matches?: RouterState["matches"];
  /**
   * loaderData returned from the current set of loaders
   */
  loaderData?: RouterState["loaderData"];
  /**
   * errors thrown from the current set of loaders
   */
  errors?: RouterState["errors"];
}

/**
 * Cached info for active fetcher.load() instances so they can participate
 * in revalidation
 */
interface FetchLoadMatch {
  routeId: string;
  path: string;
}

/**
 * Identified fetcher.load() calls that need to be revalidated
 */
interface RevalidatingFetcher extends FetchLoadMatch {
  key: string;
  match: AgnosticDataRouteMatch | null;
  matches: AgnosticDataRouteMatch[] | null;
  controller: AbortController | null;
}

const validMutationMethodsArr: MutationFormMethod[] = [
  "post",
  "put",
  "patch",
  "delete",
];
const validMutationMethods = new Set<MutationFormMethod>(
  validMutationMethodsArr
);

const validRequestMethodsArr: FormMethod[] = [
  "get",
  ...validMutationMethodsArr,
];
const validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);

const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
const redirectPreserveMethodStatusCodes = new Set([307, 308]);

export const IDLE_NAVIGATION: NavigationStates["Idle"] = {
  state: "idle",
  location: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined,
};

export const IDLE_FETCHER: FetcherStates["Idle"] = {
  state: "idle",
  data: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined,
};

export const IDLE_BLOCKER: BlockerUnblocked = {
  state: "unblocked",
  proceed: undefined,
  reset: undefined,
  location: undefined,
};

const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;

const defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary),
});

const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////

/**
 * Create a router and listen to history POP navigations
 */
export function createRouter(init: RouterInit): Router {
  const routerWindow = init.window
    ? init.window
    : typeof window !== "undefined"
    ? window
    : undefined;
  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: MapRoutePropertiesFunction;
  if (init.mapRouteProperties) {
    mapRouteProperties = init.mapRouteProperties;
  } else if (init.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = init.detectErrorBoundary;
    mapRouteProperties = (route) => ({
      hasErrorBoundary: detectErrorBoundary(route),
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }

  // Routes keyed by ID
  let manifest: RouteManifest = {};
  // Routes in tree format for matching
  let dataRoutes = convertRoutesToDataRoutes(
    init.routes,
    mapRouteProperties,
    undefined,
    manifest
  );
  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;
  let basename = init.basename || "/";
  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;

  // Config driven behavior flags
  let future: FutureConfig = {
    v7_fetcherPersist: false,
    v7_normalizeFormMethod: false,
    v7_partialHydration: false,
    v7_prependBasename: false,
    v7_relativeSplatPath: false,
    v7_skipActionErrorRevalidation: false,
    ...init.future,
  };
  // Cleanup function for history
  let unlistenHistory: (() => void) | null = null;
  // Externally-provided functions to call on all state changes
  let subscribers = new Set<RouterSubscriber>();
  // Externally-provided object to hold scroll restoration locations during routing
  let savedScrollPositions: Record<string, number> | null = null;
  // Externally-provided function to get scroll restoration keys
  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;
  // Externally-provided function to get current scroll position
  let getScrollPosition: GetScrollPositionFunction | null = null;
  // One-time flag to control the initial hydration scroll restoration.  Because
  // we don't get the saved positions from <ScrollRestoration /> until _after_
  // the initial render, we need to manually trigger a separate updateState to
  // send along the restoreScrollPosition
  // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  // SSR did the initial scroll restoration.
  let initialScrollRestored = init.hydrationData != null;

  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  let initialMatchesIsFOW = false;
  let initialErrors: RouteData | null = null;

  if (initialMatches == null && !patchRoutesOnNavigationImpl) {
    // If we do not match a user-provided-route, fall back to the root
    // to allow the error boundary to take over
    let error = getInternalRouterError(404, {
      pathname: init.history.location.pathname,
    });
    let { matches, route } = getShortCircuitMatches(dataRoutes);
    initialMatches = matches;
    initialErrors = { [route.id]: error };
  }

  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
  // our initial match is a splat route, clear them out so we run through lazy
  // discovery on hydration in case there's a more accurate lazy route match.
  // In SSR apps (with `hydrationData`), we expect that the server will send
  // up the proper matched routes so we don't want to run lazy discovery on
  // initial hydration and want to hydrate into the splat route.
  if (initialMatches && !init.hydrationData) {
    let fogOfWar = checkFogOfWar(
      initialMatches,
      dataRoutes,
      init.history.location.pathname
    );
    if (fogOfWar.active) {
      initialMatches = null;
    }
  }

  let initialized: boolean;
  if (!initialMatches) {
    initialized = false;
    initialMatches = [];

    // If partial hydration and fog of war is enabled, we will be running
    // `patchRoutesOnNavigation` during hydration so include any partial matches as
    // the initial matches so we can properly render `HydrateFallback`'s
    if (future.v7_partialHydration) {
      let fogOfWar = checkFogOfWar(
        null,
        dataRoutes,
        init.history.location.pathname
      );
      if (fogOfWar.active && fogOfWar.matches) {
        initialMatchesIsFOW = true;
        initialMatches = fogOfWar.matches;
      }
    }
  } else if (initialMatches.some((m) => m.route.lazy)) {
    // All initialMatches need to be loaded before we're ready.  If we have lazy
    // functions around still then we'll need to run them in initialize()
    initialized = false;
  } else if (!initialMatches.some((m) => m.route.loader)) {
    // If we've got no loaders to run, then we're good to go
    initialized = true;
  } else if (future.v7_partialHydration) {
    // If partial hydration is enabled, we're initialized so long as we were
    // provided with hydrationData for every route with a loader, and no loaders
    // were marked for explicit hydration
    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
    let errors = init.hydrationData ? init.hydrationData.errors : null;
    // If errors exist, don't consider routes below the boundary
    if (errors) {
      let idx = initialMatches.findIndex(
        (m) => errors![m.route.id] !== undefined
      );
      initialized = initialMatches
        .slice(0, idx + 1)
        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
    } else {
      initialized = initialMatches.every(
        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
      );
    }
  } else {
    // Without partial hydration - we're initialized if we were provided any
    // hydrationData - which is expected to be complete
    initialized = init.hydrationData != null;
  }

  let router: Router;
  let state: RouterState = {
    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: new Map(),
    blockers: new Map(),
  };

  // -- Stateful internal variables to manage navigations --
  // Current navigation in progress (to be committed in completeNavigation)
  let pendingAction: HistoryAction = HistoryAction.Pop;

  // Should the current navigation prevent the scroll reset if scroll cannot
  // be restored?
  let pendingPreventScrollReset = false;

  // AbortController for the active navigation
  let pendingNavigationController: AbortController | null;

  // Should the current navigation enable document.startViewTransition?
  let pendingViewTransitionEnabled = false;

  // Store applied view transitions so we can apply them on POP
  let appliedViewTransitions: Map<string, Set<string>> = new Map<
    string,
    Set<string>
  >();

  // Cleanup function for persisting applied transitions to sessionStorage
  let removePageHideEventListener: (() => void) | null = null;

  // We use this to avoid touching history in completeNavigation if a
  // revalidation is entirely uninterrupted
  let isUninterruptedRevalidation = false;

  // Use this internal flag to force revalidation of all loaders:
  //  - submissions (completed or interrupted)
  //  - useRevalidator()
  //  - X-Remix-Revalidate (from redirect)
  let isRevalidationRequired = false;

  // Use this internal array to capture routes that require revalidation due
  // to a cancelled deferred on action submission
  let cancelledDeferredRoutes: string[] = [];

  // Use this internal array to capture fetcher loads that were cancelled by an
  // action navigation and require revalidation
  let cancelledFetcherLoads: Set<string> = new Set();

  // AbortControllers for any in-flight fetchers
  let fetchControllers = new Map<string, AbortController>();

  // Track loads based on the order in which they started
  let incrementingLoadId = 0;

  // Track the outstanding pending navigation data load to be compared against
  // the globally incrementing load when a fetcher load lands after a completed
  // navigation
  let pendingNavigationLoadId = -1;

  // Fetchers that triggered data reloads as a result of their actions
  let fetchReloadIds = new Map<string, number>();

  // Fetchers that triggered redirect navigations
  let fetchRedirectIds = new Set<string>();

  // Most recent href/match for fetcher.load calls for fetchers
  let fetchLoadMatches = new Map<string, FetchLoadMatch>();

  // Ref-count mounted fetchers so we know when it's ok to clean them up
  let activeFetchers = new Map<string, number>();

  // Fetchers that have requested a delete when using v7_fetcherPersist,
  // they'll be officially removed after they return to idle
  let deletedFetchers = new Set<string>();

  // Store DeferredData instances for active route matches.  When a
  // route loader returns defer() we stick one in here.  Then, when a nested
  // promise resolves we update loaderData.  If a new navigation starts we
  // cancel active deferreds for eliminated routes.
  let activeDeferreds = new Map<string, DeferredData>();

  // Store blocker functions in a separate Map outside of router state since
  // we don't need to update UI state if they change
  let blockerFunctions = new Map<string, BlockerFunction>();

  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so
  // that we only kick them off once for a given combo
  let pendingPatchRoutes = new Map<
    string,
    ReturnType<AgnosticPatchRoutesOnNavigationFunction>
  >();

  // Flag to ignore the next history update, so we can revert the URL change on
  // a POP navigation that was blocked by the user without touching router state
  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;

  // Initialize the router, all side effects should be kicked off from here.
  // Implemented as a Fluent API for ease of:
  //   let router = createRouter(init).initialize();
  function initialize() {
    // If history informs us of a POP navigation, start the navigation but do not update
    // state.  We'll update our own state once the navigation completes
    unlistenHistory = init.history.listen(
      ({ action: historyAction, location, delta }) => {
        // Ignore this event if it was just us resetting the URL from a
        // blocked POP navigation
        if (unblockBlockerHistoryUpdate) {
          unblockBlockerHistoryUpdate();
          unblockBlockerHistoryUpdate = undefined;
          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) {
          // Restore the URL to match the current UI, but don't update router state
          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {
            unblockBlockerHistoryUpdate = resolve;
          });
          init.history.go(delta * -1);

          // Put the blocker into a blocked state
          updateBlocker(blockerKey, {
            state: "blocked",
            location,
            proceed() {
              updateBlocker(blockerKey!, {
                state: "proceeding",
                proceed: undefined,
                reset: undefined,
                location,
              });
              // Re-do the same POP navigation we just blocked, after the url
              // restoration is also complete.  See:
              // https://github.com/remix-run/react-router/issues/11613
              nextHistoryUpdatePromise.then(() => init.history.go(delta));
            },
            reset() {
              let blockers = new Map(state.blockers);
              blockers.set(blockerKey!, IDLE_BLOCKER);
              updateState({ blockers });
            },
          });
          return;
        }

        return startNavigation(historyAction, location);
      }
    );

    if (isBrowser) {
      // FIXME: This feels gross.  How can we cleanup the lines between
      // scrollRestoration/appliedTransitions persistance?
      restoreAppliedTransitions(routerWindow, appliedViewTransitions);
      let _saveAppliedTransitions = () =>
        persistAppliedTransitions(routerWindow, appliedViewTransitions);
      routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
      removePageHideEventListener = () =>
        routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
    }

    // Kick off initial data load if needed.  Use Pop to avoid modifying history
    // Note we don't do any handling of lazy here.  For SPA's it'll get handled
    // in the normal navigation flow.  For SSR it's expected that lazy modules are
    // resolved prior to router creation since we can't go into a fallbackElement
    // UI for SSR'd apps
    if (!state.initialized) {
      startNavigation(HistoryAction.Pop, state.location, {
        initialHydration: true,
      });
    }

    return router;
  }

  // Clean up a router and it's side effects
  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));
  }

  // Subscribe to state updates for the router
  function subscribe(fn: RouterSubscriber) {
    subscribers.add(fn);
    return () => subscribers.delete(fn);
  }

  // Update our state and notify the calling context of the change
  function updateState(
    newState: Partial<RouterState>,
    opts: {
      flushSync?: boolean;
      viewTransitionOpts?: ViewTransitionOpts;
    } = {}
  ): void {
    state = {
      ...state,
      ...newState,
    };

    // Prep fetcher cleanup so we can tell the UI which fetcher data entries
    // can be removed
    let completedFetchers: string[] = [];
    let deletedFetchersKeys: string[] = [];

    if (future.v7_fetcherPersist) {
      state.fetchers.forEach((fetcher, key) => {
        if (fetcher.state === "idle") {
          if (deletedFetchers.has(key)) {
            // Unmounted from the UI and can be totally removed
            deletedFetchersKeys.push(key);
          } else {
            // Returned to idle but still mounted in the UI, so semi-remains for
            // revalidations and such
            completedFetchers.push(key);
          }
        }
      });
    }

    // Remove any lingering deleted fetchers that have already been removed
    // from state.fetchers
    deletedFetchers.forEach((key) => {
      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
        deletedFetchersKeys.push(key);
      }
    });

    // Iterate over a local copy so that if flushSync is used and we end up
    // removing and adding a new subscriber due to the useCallback dependencies,
    // we don't get ourselves into a loop calling the new subscriber immediately
    [...subscribers].forEach((subscriber) =>
      subscriber(state, {
        deletedFetchers: deletedFetchersKeys,
        viewTransitionOpts: opts.viewTransitionOpts,
        flushSync: opts.flushSync === true,
      })
    );

    // Remove idle fetchers from state since we only care about in-flight fetchers.
    if (future.v7_fetcherPersist) {
      completedFetchers.forEach((key) => state.fetchers.delete(key));
      deletedFetchersKeys.forEach((key) => deleteFetcher(key));
    } else {
      // We already called deleteFetcher() on these, can remove them from this
      // Set now that we've handed the keys off to the data layer
      deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));
    }
  }

  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  // and setting state.[historyAction/location/matches] to the new route.
  // - Location is a required param
  // - Navigation will always be set to IDLE_NAVIGATION
  // - Can pass any other state in newState
  function completeNavigation(
    location: Location,
    newState: Partial<Omit<RouterState, "action" | "location" | "navigation">>,
    { flushSync }: { flushSync?: boolean } = {}
  ): void {
    // Deduce if we're in a loading/actionReload state:
    // - We have committed actionData in the store
    // - The current navigation was a mutation submission
    // - We're past the submitting state and into the loading state
    // - The location being loaded is not the result of a redirect
    let isActionReload =
      state.actionData != null &&
      state.navigation.formMethod != null &&
      isMutationMethod(state.navigation.formMethod) &&
      state.navigation.state === "loading" &&
      location.state?._isRedirect !== true;

    let actionData: RouteData | null;
    if (newState.actionData) {
      if (Object.keys(newState.actionData).length > 0) {
        actionData = newState.actionData;
      } else {
        // Empty actionData -> clear prior actionData due to an action error
        actionData = null;
      }
    } else if (isActionReload) {
      // Keep the current data if we're wrapping up the action reload
      actionData = state.actionData;
    } else {
      // Clear actionData on any other completed navigations
      actionData = null;
    }

    // Always preserve any existing loaderData from re-used routes
    let loaderData = newState.loaderData
      ? mergeLoaderData(
          state.loaderData,
          newState.loaderData,
          newState.matches || [],
          newState.errors
        )
      : state.loaderData;

    // On a successful navigation we can assume we got through all blockers
    // so we can start fresh
    let blockers = state.blockers;
    if (blockers.size > 0) {
      blockers = new Map(blockers);
      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
    }

    // Always respect the user flag.  Otherwise don't reset on mutation
    // submission navigations unless they redirect
    let preventScrollReset =
      pendingPreventScrollReset === true ||
      (state.navigation.formMethod != null &&
        isMutationMethod(state.navigation.formMethod) &&
        location.state?._isRedirect !== true);

    // Commit any in-flight routes at the end of the HMR revalidation "navigation"
    if (inFlightDataRoutes) {
      dataRoutes = inFlightDataRoutes;
      inFlightDataRoutes = undefined;
    }

    if (isUninterruptedRevalidation) {
      // If this was an uninterrupted revalidation then do not touch history
    } else if (pendingAction === HistoryAction.Pop) {
      // Do nothing for POP - URL has already been updated
    } else if (pendingAction === HistoryAction.Push) {
      init.history.push(location, location.state);
    } else if (pendingAction === HistoryAction.Replace) {
      init.history.replace(location, location.state);
    }

    let viewTransitionOpts: ViewTransitionOpts | undefined;

    // On POP, enable transitions if they were enabled on the original navigation
    if (pendingAction === HistoryAction.Pop) {
      // Forward takes precedence so they behave like the original navigation
      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)) {
        // If we don't have a previous forward nav, assume we're popping back to
        // the new location and enable if that location previously enabled
        viewTransitionOpts = {
          currentLocation: location,
          nextLocation: state.location,
        };
      }
    } else if (pendingViewTransitionEnabled) {
      // Store the applied transition on PUSH/REPLACE
      let toPaths = appliedViewTransitions.get(state.location.pathname);
      if (toPaths) {
        toPaths.add(location.pathname);
      } else {
        toPaths = new Set<string>([location.pathname]);
        appliedViewTransitions.set(state.location.pathname, toPaths);
      }
      viewTransitionOpts = {
        currentLocation: state.location,
        nextLocation: location,
      };
    }

    updateState(
      {
        ...newState, // matches, errors, fetchers go through as-is
        actionData,
        loaderData,
        historyAction: pendingAction,
        location,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        revalidation: "idle",
        restoreScrollPosition: getSavedScrollPosition(
          location,
          newState.matches || state.matches
        ),
        preventScrollReset,
        blockers,
      },
      {
        viewTransitionOpts,
        flushSync: flushSync === true,
      }
    );

    // Reset stateful navigation vars
    pendingAction = HistoryAction.Pop;
    pendingPreventScrollReset = false;
    pendingViewTransitionEnabled = false;
    isUninterruptedRevalidation = false;
    isRevalidationRequired = false;
    cancelledDeferredRoutes = [];
  }

  // Trigger a navigation event, which can either be a numerical POP or a PUSH
  // replace with an optional submission
  async function navigate(
    to: number | To | null,
    opts?: RouterNavigateOptions
  ): Promise<void> {
    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?.fromRouteId,
      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);

    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
    // URL from window.location, so we need to encode it here so the behavior
    // remains the same as POP and non-data-router usages.  new URL() does all
    // the same encoding we'd get from a history.pushState/window.location read
    // without having to touch history
    nextLocation = {
      ...nextLocation,
      ...init.history.encodeLocation(nextLocation),
    };

    let userReplace = opts && opts.replace != null ? opts.replace : undefined;

    let historyAction = HistoryAction.Push;

    if (userReplace === true) {
      historyAction = HistoryAction.Replace;
    } else if (userReplace === false) {
      // no-op
    } else if (
      submission != null &&
      isMutationMethod(submission.formMethod) &&
      submission.formAction === state.location.pathname + state.location.search
    ) {
      // By default on submissions to the current location we REPLACE so that
      // users don't have to double-click the back button to get to the prior
      // location.  If the user redirects to a different location from the
      // action/loader this will be ignored and the redirect will be a PUSH
      historyAction = HistoryAction.Replace;
    }

    let preventScrollReset =
      opts && "preventScrollReset" in opts
        ? opts.preventScrollReset === true
        : undefined;

    let flushSync = (opts && opts.flushSync) === true;

    let blockerKey = shouldBlockNavigation({
      currentLocation,
      nextLocation,
      historyAction,
    });

    if (blockerKey) {
      // Put the blocker into a blocked state
      updateBlocker(blockerKey, {
        state: "blocked",
        location: nextLocation,
        proceed() {
          updateBlocker(blockerKey!, {
            state: "proceeding",
            proceed: undefined,
            reset: undefined,
            location: nextLocation,
          });
          // Send the same navigation through
          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.viewTransition,
      flushSync,
    });
  }

  // Revalidate all current loaders.  If a navigation is in progress or if this
  // is interrupted by a navigation, allow this to "succeed" by calling all
  // loaders during the next loader round
  function revalidate() {
    interruptActiveLoads();
    updateState({ revalidation: "loading" });

    // If we're currently submitting an action, we don't need to start a new
    // navigation, we'll just let the follow up loader execution call all loaders
    if (state.navigation.state === "submitting") {
      return;
    }

    // If we're currently in an idle state, start a new navigation for the current
    // action/location and mark it as uninterrupted, which will skip the history
    // update in completeNavigation
    if (state.navigation.state === "idle") {
      startNavigation(state.historyAction, state.location, {
        startUninterruptedRevalidation: true,
      });
      return;
    }

    // Otherwise, if we're currently in a loading state, just start a new
    // navigation to the navigation.location but do not trigger an uninterrupted
    // revalidation so that history correctly updates once the navigation completes
    startNavigation(
      pendingAction || state.historyAction,
      state.navigation.location,
      {
        overrideNavigation: state.navigation,
        // Proxy through any rending view transition
        enableViewTransition: pendingViewTransitionEnabled === true,
      }
    );
  }

  // Start a navigation to the given action/location.  Can optionally provide a
  // overrideNavigation which will override the normalLoad in the case of a redirect
  // navigation
  async function startNavigation(
    historyAction: HistoryAction,
    location: Location,
    opts?: {
      initialHydration?: boolean;
      submission?: Submission;
      fetcherSubmission?: Submission;
      overrideNavigation?: Navigation;
      pendingError?: ErrorResponseImpl;
      startUninterruptedRevalidation?: boolean;
      preventScrollReset?: boolean;
      replace?: boolean;
      enableViewTransition?: boolean;
      flushSync?: boolean;
    }
  ): Promise<void> {
    // Abort any in-progress navigations and start a new one. Unset any ongoing
    // uninterrupted revalidations unless told otherwise, since we want this
    // new navigation to update history normally
    pendingNavigationController && pendingNavigationController.abort();
    pendingNavigationController = null;
    pendingAction = historyAction;
    isUninterruptedRevalidation =
      (opts && opts.startUninterruptedRevalidation) === true;

    // Save the current scroll position every time we start a new navigation,
    // and track whether we should reset scroll on completion
    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 =
      opts?.initialHydration &&
      state.matches &&
      state.matches.length > 0 &&
      !initialMatchesIsFOW
        ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`
          state.matches
        : matchRoutes(routesToUse, location, basename);
    let flushSync = (opts && opts.flushSync) === true;

    // Short circuit if it's only a hash change and not a revalidation or
    // mutation submission.
    //
    // Ignore on initial page loads because since the initial hydration will always
    // be "same hash".  For example, on /page#hash and submit a <Form method="post">
    // which will default to a navigation to /page
    if (
      matches &&
      state.initialized &&
      !isRevalidationRequired &&
      isHashChangeOnly(state.location, location) &&
      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))
    ) {
      completeNavigation(location, { matches }, { flushSync });
      return;
    }

    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }

    // Short circuit with a 404 on the root error boundary if we match nothing
    if (!matches) {
      let { error, notFoundMatches, route } = handleNavigational404(
        location.pathname
      );
      completeNavigation(
        location,
        {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error,
          },
        },
        { flushSync }
      );
      return;
    }

    // Create a controller/Request for this navigation
    pendingNavigationController = new AbortController();
    let request = createClientSideRequest(
      init.history,
      location,
      pendingNavigationController.signal,
      opts && opts.submission
    );
    let pendingActionResult: PendingActionResult | undefined;

    if (opts && opts.pendingError) {
      // If we have a pendingError, it means the user attempted a GET submission
      // with binary FormData so assign here and skip to handleLoaders.  That
      // way we handle calling loaders above the boundary etc.  It's not really
      // different from an actionError in that sense.
      pendingActionResult = [
        findNearestBoundary(matches).route.id,
        { type: ResultType.error, error: opts.pendingError },
      ];
    } else if (
      opts &&
      opts.submission &&
      isMutationMethod(opts.submission.formMethod)
    ) {
      // Call action if we received an action submission
      let actionResult = await handleAction(
        request,
        location,
        opts.submission,
        matches,
        fogOfWar.active,
        { replace: opts.replace, flushSync }
      );

      if (actionResult.shortCircuited) {
        return;
      }

      // If we received a 404 from handleAction, it's because we couldn't lazily
      // discover the destination route so we don't want to call loaders
      if (actionResult.pendingActionResult) {
        let [routeId, result] = actionResult.pendingActionResult;
        if (
          isErrorResult(result) &&
          isRouteErrorResponse(result.error) &&
          result.error.status === 404
        ) {
          pendingNavigationController = null;

          completeNavigation(location, {
            matches: actionResult.matches,
            loaderData: {},
            errors: {
              [routeId]: result.error,
            },
          });
          return;
        }
      }

      matches = actionResult.matches || matches;
      pendingActionResult = actionResult.pendingActionResult;
      loadingNavigation = getLoadingNavigation(location, opts.submission);
      flushSync = false;
      // No need to do fog of war matching again on loader execution
      fogOfWar.active = false;

      // Create a GET request for the loaders
      request = createClientSideRequest(
        init.history,
        request.url,
        request.signal
      );
    }

    // Call loaders
    let {
      shortCircuited,
      matches: updatedMatches,
      loaderData,
      errors,
    } = await handleLoaders(
      request,
      location,
      matches,
      fogOfWar.active,
      loadingNavigation,
      opts && opts.submission,
      opts && opts.fetcherSubmission,
      opts && opts.replace,
      opts && opts.initialHydration === true,
      flushSync,
      pendingActionResult
    );

    if (shortCircuited) {
      return;
    }

    // Clean up now that the action/loaders have completed.  Don't clean up if
    // we short circuited because pendingNavigationController will have already
    // been assigned to a new controller for the next navigation
    pendingNavigationController = null;

    completeNavigation(location, {
      matches: updatedMatches || matches,
      ...getActionDataForCommit(pendingActionResult),
      loaderData,
      errors,
    });
  }

  // Call the action matched by the leaf route for this navigation and handle
  // redirects/errors
  async function handleAction(
    request: Request,
    location: Location,
    submission: Submission,
    matches: AgnosticDataRouteMatch[],
    isFogOfWar: boolean,
    opts: { replace?: boolean; flushSync?: boolean } = {}
  ): Promise<HandleActionResult> {
    interruptActiveLoads();

    // Put us in a submitting state
    let navigation = getSubmittingNavigation(location, submission);
    updateState({ navigation }, { flushSync: opts.flushSync === true });

    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        matches,
        location.pathname,
        request.signal
      );
      if (discoverResult.type === "aborted") {
        return { shortCircuited: true };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches)
          .route.id;
        return {
          matches: discoverResult.partialMatches,
          pendingActionResult: [
            boundaryId,
            {
              type: ResultType.error,
              error: discoverResult.error,
            },
          ],
        };
      } else if (!discoverResult.matches) {
        let { notFoundMatches, error, route } = handleNavigational404(
          location.pathname
        );
        return {
          matches: notFoundMatches,
          pendingActionResult: [
            route.id,
            {
              type: ResultType.error,
              error,
            },
          ],
        };
      } else {
        matches = discoverResult.matches;
      }
    }

    // Call our action and get the result
    let result: DataResult;
    let actionMatch = getTargetMatch(matches, location);

    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      result = {
        type: ResultType.error,
        error: getInternalRouterError(405, {
          method: request.method,
          pathname: location.pathname,
          routeId: actionMatch.route.id,
        }),
      };
    } else {
      let results = await callDataStrategy(
        "action",
        state,
        request,
        [actionMatch],
        matches,
        null
      );
      result = results[actionMatch.route.id];

      if (request.signal.aborted) {
        return { shortCircuited: true };
      }
    }

    if (isRedirectResult(result)) {
      let replace: boolean;
      if (opts && opts.replace != null) {
        replace = opts.replace;
      } else {
        // If the user didn't explicity indicate replace behavior, replace if
        // we redirected to the exact same location we're currently at to avoid
        // double back-buttons
        let location = normalizeRedirectLocation(
          result.response.headers.get("Location")!,
          new URL(request.url),
          basename,
          init.history,
        );
        replace = location === state.location.pathname + state.location.search;
      }
      await startRedirectNavigation(request, result, true, {
        submission,
        replace,
      });
      return { shortCircuited: true };
    }

    if (isDeferredResult(result)) {
      throw getInternalRouterError(400, { type: "defer-action" });
    }

    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);

      // By default, all submissions to the current location are REPLACE
      // navigations, but if the action threw an error that'll be rendered in
      // an errorElement, we fall back to PUSH so that the user can use the
      // back button to get back to the pre-submission form location to try
      // again
      if ((opts && opts.replace) !== true) {
        pendingAction = HistoryAction.Push;
      }

      return {
        matches,
        pendingActionResult: [boundaryMatch.route.id, result],
      };
    }

    return {
      matches,
      pendingActionResult: [actionMatch.route.id, result],
    };
  }

  // Call all applicable loaders for the given matches, handling redirects,
  // errors, etc.
  async function handleLoaders(
    request: Request,
    location: Location,
    matches: AgnosticDataRouteMatch[],
    isFogOfWar: boolean,
    overrideNavigation?: Navigation,
    submission?: Submission,
    fetcherSubmission?: Submission,
    replace?: boolean,
    initialHydration?: boolean,
    flushSync?: boolean,
    pendingActionResult?: PendingActionResult
  ): Promise<HandleLoadersResult> {
    // Figure out the right navigation we want to use for data loading
    let loadingNavigation =
      overrideNavigation || getLoadingNavigation(location, submission);

    // If this was a redirect from an action we don't have a "submission" but
    // we have it on the loading navigation so use that if available
    let activeSubmission =
      submission ||
      fetcherSubmission ||
      getSubmissionFromNavigation(loadingNavigation);

    // If this is an uninterrupted revalidation, we remain in our current idle
    // state.  If not, we need to switch to our loading state and load data,
    // preserving any new action data or existing action data (in the case of
    // a revalidation interrupting an actionReload)
    // If we have partialHydration enabled, then don't update the state for the
    // initial data load since it's not a "navigation"
    let shouldUpdateNavigationState =
      !isUninterruptedRevalidation &&
      (!future.v7_partialHydration || !initialHydration);

    // When fog of war is enabled, we enter our `loading` state earlier so we
    // can discover new routes during the `loading` state.  We skip this if
    // we've already run actions since we would have done our matching already.
    // If the children() function threw then, we want to proceed with the
    // partial matches it discovered.
    if (isFogOfWar) {
      if (shouldUpdateNavigationState) {
        let actionData = getUpdatedActionData(pendingActionResult);
        updateState(
          {
            navigation: loadingNavigation,
            ...(actionData !== undefined ? { actionData } : {}),
          },
          {
            flushSync,
          }
        );
      }

      let discoverResult = await discoverRoutes(
        matches,
        location.pathname,
        request.signal
      );

      if (discoverResult.type === "aborted") {
        return { shortCircuited: true };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches)
          .route.id;
        return {
          matches: discoverResult.partialMatches,
          loaderData: {},
          errors: {
            [boundaryId]: discoverResult.error,
          },
        };
      } else if (!discoverResult.matches) {
        let { error, notFoundMatches, route } = handleNavigational404(
          location.pathname
        );
        return {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error,
          },
        };
      } else {
        matches = discoverResult.matches;
      }
    }

    let routesToUse = inFlightDataRoutes || dataRoutes;
    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(
      init.history,
      state,
      matches,
      activeSubmission,
      location,
      future.v7_partialHydration && initialHydration === true,
      future.v7_skipActionErrorRevalidation,
      isRevalidationRequired,
      cancelledDeferredRoutes,
      cancelledFetcherLoads,
      deletedFetchers,
      fetchLoadMatches,
      fetchRedirectIds,
      routesToUse,
      basename,
      pendingActionResult
    );

    // Cancel pending deferreds for no-longer-matched routes or routes we're
    // about to reload.  Note that if this is an action reload we would have
    // already cancelled all pending deferreds so this would be a no-op
    cancelActiveDeferreds(
      (routeId) =>
        !(matches && matches.some((m) => m.route.id === routeId)) ||
        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))
    );

    pendingNavigationLoadId = ++incrementingLoadId;

    // Short circuit if we have no loaders to run
    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
      let updatedFetchers = markFetchRedirectsDone();
      completeNavigation(
        location,
        {
          matches,
          loaderData: {},
          // Commit pending error if we're short circuiting
          errors:
            pendingActionResult && isErrorResult(pendingActionResult[1])
              ? { [pendingActionResult[0]]: pendingActionResult[1].error }
              : null,
          ...getActionDataForCommit(pendingActionResult),
          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),
        },
        { flushSync }
      );
      return { shortCircuited: true };
    }

    if (shouldUpdateNavigationState) {
      let updates: Partial<RouterState> = {};
      if (!isFogOfWar) {
        // Only update navigation/actionNData if we didn't already do it above
        updates.navigation = loadingNavigation;
        let actionData = getUpdatedActionData(pendingActionResult);
        if (actionData !== undefined) {
          updates.actionData = actionData;
        }
      }
      if (revalidatingFetchers.length > 0) {
        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
      }
      updateState(updates, { flushSync });
    }

    revalidatingFetchers.forEach((rf) => {
      abortFetcher(rf.key);
      if (rf.controller) {
        // Fetchers use an independent AbortController so that aborting a fetcher
        // (via deleteFetcher) does not abort the triggering navigation that
        // triggered the revalidation
        fetchControllers.set(rf.key, rf.controller);
      }
    });

    // Proxy navigation abort through to revalidation fetchers
    let abortPendingFetchRevalidations = () =>
      revalidatingFetchers.forEach((f) => abortFetcher(f.key));
    if (pendingNavigationController) {
      pendingNavigationController.signal.addEventListener(
        "abort",
        abortPendingFetchRevalidations
      );
    }

    let { loaderResults, fetcherResults } =
      await callLoadersAndMaybeResolveData(
        state,
        matches,
        matchesToLoad,
        revalidatingFetchers,
        request
      );

    if (request.signal.aborted) {
      return { shortCircuited: true };
    }

    // Clean up _after_ loaders have completed.  Don't clean up if we short
    // circuited because fetchControllers would have been aborted and
    // reassigned to new controllers for the next navigation
    if (pendingNavigationController) {
      pendingNavigationController.signal.removeEventListener(
        "abort",
        abortPendingFetchRevalidations
      );
    }

    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));

    // If any loaders returned a redirect Response, start a new REPLACE navigation
    let redirect = findRedirect(loaderResults);
    if (redirect) {
      await startRedirectNavigation(request, redirect.result, true, {
        replace,
      });
      return { shortCircuited: true };
    }

    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      await startRedirectNavigation(request, redirect.result, true, {
        replace,
      });
      return { shortCircuited: true };
    }

    // Process and commit output from loaders
    let { loaderData, errors } = processLoaderData(
      state,
      matches,
      loaderResults,
      pendingActionResult,
      revalidatingFetchers,
      fetcherResults,
      activeDeferreds
    );

    // Wire up subscribers to update loaderData as promises settle
    activeDeferreds.forEach((deferredData, routeId) => {
      deferredData.subscribe((aborted) => {
        // Note: No need to updateState here since the TrackedPromise on
        // loaderData is stable across resolve/reject
        // Remove this instance if we were aborted or if promises have settled
        if (aborted || deferredData.done) {
          activeDeferreds.delete(routeId);
        }
      });
    });

    // Preserve SSR errors during partial hydration
    if (future.v7_partialHydration && initialHydration && state.errors) {
      errors = { ...state.errors, ...errors };
    }

    let updatedFetchers = markFetchRedirectsDone();
    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
    let shouldUpdateFetchers =
      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;

    return {
      matches,
      loaderData,
      errors,
      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),
    };
  }

  function getUpdatedActionData(
    pendingActionResult: PendingActionResult | undefined
  ): Record<string, RouteData> | null | undefined {
    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
      // This is cast to `any` currently because `RouteData`uses any and it
      // would be a breaking change to use any.
      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
      return {
        [pendingActionResult[0]]: pendingActionResult[1].data as any,
      };
    } else if (state.actionData) {
      if (Object.keys(state.actionData).length === 0) {
        return null;
      } else {
        return state.actionData;
      }
    }
  }

  function getUpdatedRevalidatingFetchers(
    revalidatingFetchers: RevalidatingFetcher[]
  ) {
    revalidatingFetchers.forEach((rf) => {
      let fetcher = state.fetchers.get(rf.key);
      let revalidatingFetcher = getLoadingFetcher(
        undefined,
        fetcher ? fetcher.data : undefined
      );
      state.fetchers.set(rf.key, revalidatingFetcher);
    });
    return new Map(state.fetchers);
  }

  // Trigger a fetcher load/submit for the given fetcher key
  function fetch(
    key: string,
    routeId: string,
    href: string | null,
    opts?: RouterFetchOptions
  ) {
    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."
      );
    }

    abortFetcher(key);

    let flushSync = (opts && opts.flushSync) === true;

    let routesToUse = inFlightDataRoutes || dataRoutes;
    let normalizedPath = normalizeTo(
      state.location,
      state.matches,
      basename,
      future.v7_prependBasename,
      href,
      future.v7_relativeSplatPath,
      routeId,
      opts?.relative
    );
    let matches = matchRoutes(routesToUse, normalizedPath, basename);

    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }

    if (!matches) {
      setFetcherError(
        key,
        routeId,
        getInternalRouterError(404, { pathname: normalizedPath }),
        { flushSync }
      );
      return;
    }

    let { path, submission, error } = normalizeNavigateOptions(
      future.v7_normalizeFormMethod,
      true,
      normalizedPath,
      opts
    );

    if (error) {
      setFetcherError(key, routeId, error, { flushSync });
      return;
    }

    let match = getTargetMatch(matches, path);

    let preventScrollReset = (opts && opts.preventScrollReset) === true;

    if (submission && isMutationMethod(submission.formMethod)) {
      handleFetcherAction(
        key,
        routeId,
        path,
        match,
        matches,
        fogOfWar.active,
        flushSync,
        preventScrollReset,
        submission
      );
      return;
    }

    // Store off the match so we can call it's shouldRevalidate on subsequent
    // revalidations
    fetchLoadMatches.set(key, { routeId, path });
    handleFetcherLoader(
      key,
      routeId,
      path,
      match,
      matches,
      fogOfWar.active,
      flushSync,
      preventScrollReset,
      submission
    );
  }

  // Call the action for the matched fetcher.submit(), and then handle redirects,
  // errors, and revalidation
  async function handleFetcherAction(
    key: string,
    routeId: string,
    path: string,
    match: AgnosticDataRouteMatch,
    requestMatches: AgnosticDataRouteMatch[],
    isFogOfWar: boolean,
    flushSync: boolean,
    preventScrollReset: boolean,
    submission: Submission
  ) {
    interruptActiveLoads();
    fetchLoadMatches.delete(key);

    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {
      if (!m.route.action && !m.route.lazy) {
        let error = getInternalRouterError(405, {
          method: submission.formMethod,
          pathname: path,
          routeId: routeId,
        });
        setFetcherError(key, routeId, error, { flushSync });
        return true;
      }
      return false;
    }

    if (!isFogOfWar && detectAndHandle405Error(match)) {
      return;
    }

    // Put this fetcher into it's submitting state
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
      flushSync,
    });

    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(
      init.history,
      path,
      abortController.signal,
      submission
    );

    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        requestMatches,
        new URL(fetchRequest.url).pathname,
        fetchRequest.signal,
        key
      );

      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, { flushSync });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(
          key,
          routeId,
          getInternalRouterError(404, { pathname: path }),
          { flushSync }
        );
        return;
      } else {
        requestMatches = discoverResult.matches;
        match = getTargetMatch(requestMatches, path);

        if (detectAndHandle405Error(match)) {
          return;
        }
      }
    }

    // Call the action for the fetcher
    fetchControllers.set(key, abortController);

    let originatingLoadId = incrementingLoadId;
    let actionResults = await callDataStrategy(
      "action",
      state,
      fetchRequest,
      [match],
      requestMatches,
      key
    );
    let actionResult = actionResults[match.route.id];

    if (fetchRequest.signal.aborted) {
      // We can delete this so long as we weren't aborted by our own fetcher
      // re-submit which would have put _new_ controller is in fetchControllers
      if (fetchControllers.get(key) === abortController) {
        fetchControllers.delete(key);
      }
      return;
    }

    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
    // or redirects processed for unmounted fetchers so we just revert them to
    // idle
    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      }
      // Let SuccessResult's fall through for revalidation
    } else {
      if (isRedirectResult(actionResult)) {
        fetchControllers.delete(key);
        if (pendingNavigationLoadId > originatingLoadId) {
          // A new navigation was kicked off after our action started, so that
          // should take precedence over this redirect navigation.  We already
          // set isRevalidationRequired so all loaders for the new route should
          // fire unless opted out via shouldRevalidate
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        } else {
          fetchRedirectIds.add(key);
          updateFetcherState(key, getLoadingFetcher(submission));
          return startRedirectNavigation(fetchRequest, actionResult, false, {
            fetcherSubmission: submission,
            preventScrollReset,
          });
        }
      }

      // Process any non-redirect errors thrown
      if (isErrorResult(actionResult)) {
        setFetcherError(key, routeId, actionResult.error);
        return;
      }
    }

    if (isDeferredResult(actionResult)) {
      throw getInternalRouterError(400, { type: "defer-action" });
    }

    // Start the data load for current matches, or the next location if we're
    // in the middle of a navigation
    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,
      future.v7_skipActionErrorRevalidation,
      isRevalidationRequired,
      cancelledDeferredRoutes,
      cancelledFetcherLoads,
      deletedFetchers,
      fetchLoadMatches,
      fetchRedirectIds,
      routesToUse,
      basename,
      [match.route.id, actionResult]
    );

    // Put all revalidating fetchers into the loading state, except for the
    // current fetcher which we want to keep in it's current loading state which
    // contains it's action submission info + action data
    revalidatingFetchers
      .filter((rf) => rf.key !== key)
      .forEach((rf) => {
        let staleKey = rf.key;
        let existingFetcher = state.fetchers.get(staleKey);
        let revalidatingFetcher = getLoadingFetcher(
          undefined,
          existingFetcher ? existingFetcher.data : undefined
        );
        state.fetchers.set(staleKey, revalidatingFetcher);
        abortFetcher(staleKey);
        if (rf.controller) {
          fetchControllers.set(staleKey, rf.controller);
        }
      });

    updateState({ fetchers: new Map(state.fetchers) });

    let abortPendingFetchRevalidations = () =>
      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));

    abortController.signal.addEventListener(
      "abort",
      abortPendingFetchRevalidations
    );

    let { loaderResults, fetcherResults } =
      await callLoadersAndMaybeResolveData(
        state,
        matches,
        matchesToLoad,
        revalidatingFetchers,
        revalidationRequest
      );

    if (abortController.signal.aborted) {
      return;
    }

    abortController.signal.removeEventListener(
      "abort",
      abortPendingFetchRevalidations
    );

    fetchReloadIds.delete(key);
    fetchControllers.delete(key);
    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));

    let redirect = findRedirect(loaderResults);
    if (redirect) {
      return startRedirectNavigation(
        revalidationRequest,
        redirect.result,
        false,
        { preventScrollReset }
      );
    }

    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      return startRedirectNavigation(
        revalidationRequest,
        redirect.result,
        false,
        { preventScrollReset }
      );
    }

    // Process and commit output from loaders
    let { loaderData, errors } = processLoaderData(
      state,
      matches,
      loaderResults,
      undefined,
      revalidatingFetchers,
      fetcherResults,
      activeDeferreds
    );

    // Since we let revalidations complete even if the submitting fetcher was
    // deleted, only put it back to idle if it hasn't been deleted
    if (state.fetchers.has(key)) {
      let doneFetcher = getDoneFetcher(actionResult.data);
      state.fetchers.set(key, doneFetcher);
    }

    abortStaleFetchLoads(loadId);

    // If we are currently in a navigation loading state and this fetcher is
    // more recent than the navigation, we want the newer data so abort the
    // navigation and complete it with the fetcher data
    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 {
      // otherwise just update with the fetcher data, preserving any existing
      // loaderData for loaders that did not need to reload.  We have to
      // manually merge here since we aren't going through completeNavigation
      updateState({
        errors,
        loaderData: mergeLoaderData(
          state.loaderData,
          loaderData,
          matches,
          errors
        ),
        fetchers: new Map(state.fetchers),
      });
      isRevalidationRequired = false;
    }
  }

  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  async function handleFetcherLoader(
    key: string,
    routeId: string,
    path: string,
    match: AgnosticDataRouteMatch,
    matches: AgnosticDataRouteMatch[],
    isFogOfWar: boolean,
    flushSync: boolean,
    preventScrollReset: boolean,
    submission?: Submission
  ) {
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(
      key,
      getLoadingFetcher(
        submission,
        existingFetcher ? existingFetcher.data : undefined
      ),
      { flushSync }
    );

    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(
      init.history,
      path,
      abortController.signal
    );

    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        matches,
        new URL(fetchRequest.url).pathname,
        fetchRequest.signal,
        key
      );

      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, { flushSync });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(
          key,
          routeId,
          getInternalRouterError(404, { pathname: path }),
          { flushSync }
        );
        return;
      } else {
        matches = discoverResult.matches;
        match = getTargetMatch(matches, path);
      }
    }

    // Call the loader for this fetcher route match
    fetchControllers.set(key, abortController);

    let originatingLoadId = incrementingLoadId;
    let results = await callDataStrategy(
      "loader",
      state,
      fetchRequest,
      [match],
      matches,
      key
    );
    let result = results[match.route.id];

    // Deferred isn't supported for fetcher loads, await everything and treat it
    // as a normal load.  resolveDeferredData will return undefined if this
    // fetcher gets aborted, so we just leave result untouched and short circuit
    // below if that happens
    if (isDeferredResult(result)) {
      result =
        (await resolveDeferredData(result, fetchRequest.signal, true)) ||
        result;
    }

    // We can delete this so long as we weren't aborted by our our own fetcher
    // re-load which would have put _new_ controller is in fetchControllers
    if (fetchControllers.get(key) === abortController) {
      fetchControllers.delete(key);
    }

    if (fetchRequest.signal.aborted) {
      return;
    }

    // We don't want errors bubbling up or redirects followed for unmounted
    // fetchers, so short circuit here if it was removed from the UI
    if (deletedFetchers.has(key)) {
      updateFetcherState(key, getDoneFetcher(undefined));
      return;
    }

    // If the loader threw a redirect Response, start a new REPLACE navigation
    if (isRedirectResult(result)) {
      if (pendingNavigationLoadId > originatingLoadId) {
        // A new navigation was kicked off after our loader started, so that
        // should take precedence over this redirect navigation
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      } else {
        fetchRedirectIds.add(key);
        await startRedirectNavigation(fetchRequest, result, false, {
          preventScrollReset,
        });
        return;
      }
    }

    // Process any non-redirect errors thrown
    if (isErrorResult(result)) {
      setFetcherError(key, routeId, result.error);
      return;
    }

    invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");

    // Put the fetcher back into an idle state
    updateFetcherState(key, getDoneFetcher(result.data));
  }

  /**
   * Utility function to handle redirects returned from an action or loader.
   * Normally, a redirect "replaces" the navigation that triggered it.  So, for
   * example:
   *
   *  - user is on /a
   *  - user clicks a link to /b
   *  - loader for /b redirects to /c
   *
   * In a non-JS app the browser would track the in-flight navigation to /b and
   * then replace it with /c when it encountered the redirect response.  In
   * the end it would only ever update the URL bar with /c.
   *
   * In client-side routing using pushState/replaceState, we aim to emulate
   * this behavior and we also do not update history until the end of the
   * navigation (including processed redirects).  This means that we never
   * actually touch history until we've processed redirects, so we just use
   * the history action from the original navigation (PUSH or REPLACE).
   */
  async function startRedirectNavigation(
    request: Request,
    redirect: RedirectResult,
    isNavigation: boolean,
    {
      submission,
      fetcherSubmission,
      preventScrollReset,
      replace,
    }: {
      submission?: Submission;
      fetcherSubmission?: Submission;
      preventScrollReset?: boolean;
      replace?: boolean;
    } = {}
  ) {
    if (redirect.response.headers.has("X-Remix-Revalidate")) {
      isRevalidationRequired = true;
    }

    let location = redirect.response.headers.get("Location");
    invariant(location, "Expected a Location header on the redirect Response");
    location = normalizeRedirectLocation(
      location,
      new URL(request.url),
      basename,
      init.history,
    );
    let redirectLocation = createLocation(state.location, location, {
      _isRedirect: true,
    });

    if (isBrowser) {
      let isDocumentReload = false;

      if (redirect.response.headers.has("X-Remix-Reload-Document")) {
        // Hard reload if the response contained X-Remix-Reload-Document
        isDocumentReload = true;
      } else if (ABSOLUTE_URL_REGEX.test(location)) {
        const url = init.history.createURL(location);
        isDocumentReload =
          // Hard reload if it's an absolute URL to a new origin
          url.origin !== routerWindow.location.origin ||
          // Hard reload if it's an absolute URL that does not match our basename
          stripBasename(url.pathname, basename) == null;
      }

      if (isDocumentReload) {
        if (replace) {
          routerWindow.location.replace(location);
        } else {
          routerWindow.location.assign(location);
        }
        return;
      }
    }

    // There's no need to abort on redirects, since we don't detect the
    // redirect until the action/loaders have settled
    pendingNavigationController = null;

    let redirectHistoryAction =
      replace === true || redirect.response.headers.has("X-Remix-Replace")
        ? HistoryAction.Replace
        : HistoryAction.Push;

    // Use the incoming submission if provided, fallback on the active one in
    // state.navigation
    let { formMethod, formAction, formEncType } = state.navigation;
    if (
      !submission &&
      !fetcherSubmission &&
      formMethod &&
      formAction &&
      formEncType
    ) {
      submission = getSubmissionFromNavigation(state.navigation);
    }

    // If this was a 307/308 submission we want to preserve the HTTP method and
    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
    // redirected location
    let activeSubmission = submission || fetcherSubmission;
    if (
      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&
      activeSubmission &&
      isMutationMethod(activeSubmission.formMethod)
    ) {
      await startNavigation(redirectHistoryAction, redirectLocation, {
        submission: {
          ...activeSubmission,
          formAction: location,
        },
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation
          ? pendingViewTransitionEnabled
          : undefined,
      });
    } else {
      // If we have a navigation submission, we will preserve it through the
      // redirect navigation
      let overrideNavigation = getLoadingNavigation(
        redirectLocation,
        submission
      );
      await startNavigation(redirectHistoryAction, redirectLocation, {
        overrideNavigation,
        // Send fetcher submissions through for shouldRevalidate
        fetcherSubmission,
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation
          ? pendingViewTransitionEnabled
          : undefined,
      });
    }
  }

  // Utility wrapper for calling dataStrategy client-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(
    type: "loader" | "action",
    state: RouterState,
    request: Request,
    matchesToLoad: AgnosticDataRouteMatch[],
    matches: AgnosticDataRouteMatch[],
    fetcherKey: string | null
  ): Promise<Record<string, DataResult>> {
    let results: Record<string, DataStrategyResult>;
    let dataResults: Record<string, DataResult> = {};
    try {
      results = await callDataStrategyImpl(
        dataStrategyImpl,
        type,
        state,
        request,
        matchesToLoad,
        matches,
        fetcherKey,
        manifest,
        mapRouteProperties
      );
    } catch (e) {
      // If the outer dataStrategy method throws, just return the error for all
      // matches - and it'll naturally bubble to the root
      matchesToLoad.forEach((m) => {
        dataResults[m.route.id] = {
          type: ResultType.error,
          error: e,
        };
      });
      return dataResults;
    }

    for (let [routeId, result] of Object.entries(results)) {
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result as Response;
        dataResults[routeId] = {
          type: ResultType.redirect,
          response: normalizeRelativeRoutingRedirectResponse(
            response,
            request,
            routeId,
            matches,
            basename,
            future.v7_relativeSplatPath
          ),
        };
      } else {
        dataResults[routeId] = await convertDataStrategyResultToDataResult(
          result
        );
      }
    }

    return dataResults;
  }

  async function callLoadersAndMaybeResolveData(
    state: RouterState,
    matches: AgnosticDataRouteMatch[],
    matchesToLoad: AgnosticDataRouteMatch[],
    fetchersToLoad: RevalidatingFetcher[],
    request: Request
  ) {
    let currentMatches = state.matches;

    // Kick off loaders and fetchers in parallel
    let loaderResultsPromise = callDataStrategy(
      "loader",
      state,
      request,
      matchesToLoad,
      matches,
      null
    );

    let fetcherResultsPromise = Promise.all(
      fetchersToLoad.map(async (f) => {
        if (f.matches && f.match && f.controller) {
          let results = await callDataStrategy(
            "loader",
            state,
            createClientSideRequest(init.history, f.path, f.controller.signal),
            [f.match],
            f.matches,
            f.key
          );
          let result = results[f.match.route.id];
          // Fetcher results are keyed by fetcher key from here on out, not routeId
          return { [f.key]: result };
        } else {
          return Promise.resolve({
            [f.key]: {
              type: ResultType.error,
              error: getInternalRouterError(404, {
                pathname: f.path,
              }),
            } as ErrorResult,
          });
        }
      })
    );

    let loaderResults = await loaderResultsPromise;
    let fetcherResults = (await fetcherResultsPromise).reduce(
      (acc, r) => Object.assign(acc, r),
      {}
    );

    await Promise.all([
      resolveNavigationDeferredResults(
        matches,
        loaderResults,
        request.signal,
        currentMatches,
        state.loaderData
      ),
      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),
    ]);

    return {
      loaderResults,
      fetcherResults,
    };
  }

  function interruptActiveLoads() {
    // Every interruption triggers a revalidation
    isRevalidationRequired = true;

    // Cancel pending route-level deferreds and mark cancelled routes for
    // revalidation
    cancelledDeferredRoutes.push(...cancelActiveDeferreds());

    // Abort in-flight fetcher loads
    fetchLoadMatches.forEach((_, key) => {
      if (fetchControllers.has(key)) {
        cancelledFetcherLoads.add(key);
      }
      abortFetcher(key);
    });
  }

  function updateFetcherState(
    key: string,
    fetcher: Fetcher,
    opts: { flushSync?: boolean } = {}
  ) {
    state.fetchers.set(key, fetcher);
    updateState(
      { fetchers: new Map(state.fetchers) },
      { flushSync: (opts && opts.flushSync) === true }
    );
  }

  function setFetcherError(
    key: string,
    routeId: string,
    error: any,
    opts: { flushSync?: boolean } = {}
  ) {
    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<TData = any>(key: string): Fetcher<TData> {
    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
    // If this fetcher was previously marked for deletion, unmark it since we
    // have a new instance
    if (deletedFetchers.has(key)) {
      deletedFetchers.delete(key);
    }
    return state.fetchers.get(key) || IDLE_FETCHER;
  }

  function deleteFetcher(key: string): void {
    let fetcher = state.fetchers.get(key);
    // Don't abort the controller if this is a deletion of a fetcher.submit()
    // in it's loading phase since - we don't want to abort the corresponding
    // revalidation and want them to complete and land
    if (
      fetchControllers.has(key) &&
      !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))
    ) {
      abortFetcher(key);
    }
    fetchLoadMatches.delete(key);
    fetchReloadIds.delete(key);
    fetchRedirectIds.delete(key);

    // If we opted into the flag we can clear this now since we're calling
    // deleteFetcher() at the end of updateState() and we've already handed the
    // deleted fetcher keys off to the data layer.
    // If not, we're eagerly calling deleteFetcher() and we need to keep this
    // Set populated until the next updateState call, and we'll clear
    // `deletedFetchers` then
    if (future.v7_fetcherPersist) {
      deletedFetchers.delete(key);
    }

    cancelledFetcherLoads.delete(key);
    state.fetchers.delete(key);
  }

  function deleteFetcherAndUpdateState(key: string): void {
    let count = (activeFetchers.get(key) || 0) - 1;
    if (count <= 0) {
      activeFetchers.delete(key);
      deletedFetchers.add(key);
      if (!future.v7_fetcherPersist) {
        deleteFetcher(key);
      }
    } else {
      activeFetchers.set(key, count);
    }

    updateState({ fetchers: new Map(state.fetchers) });
  }

  function abortFetcher(key: string) {
    let controller = fetchControllers.get(key);
    if (controller) {
      controller.abort();
      fetchControllers.delete(key);
    }
  }

  function markFetchersDone(keys: string[]) {
    for (let key of keys) {
      let fetcher = getFetcher(key);
      let doneFetcher = getDoneFetcher(fetcher.data);
      state.fetchers.set(key, doneFetcher);
    }
  }

  function markFetchRedirectsDone(): boolean {
    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: number): boolean {
    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: string, fn: BlockerFunction) {
    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;

    if (blockerFunctions.get(key) !== fn) {
      blockerFunctions.set(key, fn);
    }

    return blocker;
  }

  function deleteBlocker(key: string) {
    state.blockers.delete(key);
    blockerFunctions.delete(key);
  }

  // Utility function to update blockers, ensuring valid state transitions
  function updateBlocker(key: string, newBlocker: Blocker) {
    let blocker = state.blockers.get(key) || IDLE_BLOCKER;

    // Poor mans state machine :)
    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
    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({
    currentLocation,
    nextLocation,
    historyAction,
  }: {
    currentLocation: Location;
    nextLocation: Location;
    historyAction: HistoryAction;
  }): string | undefined {
    if (blockerFunctions.size === 0) {
      return;
    }

    // We ony support a single active blocker at the moment since we don't have
    // any compelling use cases for multi-blocker yet
    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") {
      // If the blocker is currently proceeding, we don't need to re-check
      // it and can let this navigation continue
      return;
    }

    // At this point, we know we're unblocked/blocked so we need to check the
    // user-provided blocker function
    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
      return blockerKey;
    }
  }

  function handleNavigational404(pathname: string) {
    let error = getInternalRouterError(404, { pathname });
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let { matches, route } = getShortCircuitMatches(routesToUse);

    // Cancel all pending deferred on 404s since we don't keep any routes
    cancelActiveDeferreds();

    return { notFoundMatches: matches, route, error };
  }

  function cancelActiveDeferreds(
    predicate?: (routeId: string) => boolean
  ): string[] {
    let cancelledRouteIds: string[] = [];
    activeDeferreds.forEach((dfd, routeId) => {
      if (!predicate || predicate(routeId)) {
        // Cancel the deferred - but do not remove from activeDeferreds here -
        // we rely on the subscribers to do that so our tests can assert proper
        // cleanup via _internalActiveDeferreds
        dfd.cancel();
        cancelledRouteIds.push(routeId);
        activeDeferreds.delete(routeId);
      }
    });
    return cancelledRouteIds;
  }

  // Opt in to capturing and reporting scroll positions during navigations,
  // used by the <ScrollRestoration> component
  function enableScrollRestoration(
    positions: Record<string, number>,
    getPosition: GetScrollPositionFunction,
    getKey?: GetScrollRestorationKeyFunction
  ) {
    savedScrollPositions = positions;
    getScrollPosition = getPosition;
    getScrollRestorationKey = getKey || null;

    // Perform initial hydration scroll restoration, since we miss the boat on
    // the initial updateState() because we've not yet rendered <ScrollRestoration/>
    // and therefore have no savedScrollPositions available
    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
      initialScrollRestored = true;
      let y = getSavedScrollPosition(state.location, state.matches);
      if (y != null) {
        updateState({ restoreScrollPosition: y });
      }
    }

    return () => {
      savedScrollPositions = null;
      getScrollPosition = null;
      getScrollRestorationKey = null;
    };
  }

  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {
    if (getScrollRestorationKey) {
      let key = getScrollRestorationKey(
        location,
        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
      );
      return key || location.key;
    }
    return location.key;
  }

  function saveScrollPosition(
    location: Location,
    matches: AgnosticDataRouteMatch[]
  ): void {
    if (savedScrollPositions && getScrollPosition) {
      let key = getScrollKey(location, matches);
      savedScrollPositions[key] = getScrollPosition();
    }
  }

  function getSavedScrollPosition(
    location: Location,
    matches: AgnosticDataRouteMatch[]
  ): number | null {
    if (savedScrollPositions) {
      let key = getScrollKey(location, matches);
      let y = savedScrollPositions[key];
      if (typeof y === "number") {
        return y;
      }
    }
    return null;
  }

  function checkFogOfWar(
    matches: AgnosticDataRouteMatch[] | null,
    routesToUse: AgnosticDataRouteObject[],
    pathname: string
  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {
    if (patchRoutesOnNavigationImpl) {
      if (!matches) {
        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(
          routesToUse,
          pathname,
          basename,
          true
        );

        return { active: true, matches: fogMatches || [] };
      } else {
        if (Object.keys(matches[0].params).length > 0) {
          // If we matched a dynamic param or a splat, it might only be because
          // we haven't yet discovered other routes that would match with a
          // higher score.  Call patchRoutesOnNavigation just to be sure
          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(
            routesToUse,
            pathname,
            basename,
            true
          );
          return { active: true, matches: partialMatches };
        }
      }
    }

    return { active: false, matches: null };
  }

  type DiscoverRoutesSuccessResult = {
    type: "success";
    matches: AgnosticDataRouteMatch[] | null;
  };
  type DiscoverRoutesErrorResult = {
    type: "error";
    error: any;
    partialMatches: AgnosticDataRouteMatch[];
  };
  type DiscoverRoutesAbortedResult = { type: "aborted" };
  type DiscoverRoutesResult =
    | DiscoverRoutesSuccessResult
    | DiscoverRoutesErrorResult
    | DiscoverRoutesAbortedResult;

  async function discoverRoutes(
    matches: AgnosticDataRouteMatch[],
    pathname: string,
    signal: AbortSignal,
    fetcherKey?: string
  ): Promise<DiscoverRoutesResult> {
    if (!patchRoutesOnNavigationImpl) {
      return { type: "success", matches };
    }

    let partialMatches: AgnosticDataRouteMatch[] | null = matches;
    while (true) {
      let isNonHMR = inFlightDataRoutes == null;
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let localManifest = manifest;
      try {
        await patchRoutesOnNavigationImpl({
          signal,
          path: pathname,
          matches: partialMatches,
          fetcherKey,
          patch: (routeId, children) => {
            if (signal.aborted) return;
            patchRoutesImpl(
              routeId,
              children,
              routesToUse,
              localManifest,
              mapRouteProperties
            );
          },
        });
      } catch (e) {
        return { type: "error", error: e, partialMatches };
      } finally {
        // If we are not in the middle of an HMR revalidation and we changed the
        // routes, provide a new identity so when we `updateState` at the end of
        // this navigation/fetch `router.routes` will be a new identity and
        // trigger a re-run of memoized `router.routes` dependencies.
        // HMR will already update the identity and reflow when it lands
        // `inFlightDataRoutes` in `completeNavigation`
        if (isNonHMR && !signal.aborted) {
          dataRoutes = [...dataRoutes];
        }
      }

      if (signal.aborted) {
        return { type: "aborted" };
      }

      let newMatches = matchRoutes(routesToUse, pathname, basename);
      if (newMatches) {
        return { type: "success", matches: newMatches };
      }

      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(
        routesToUse,
        pathname,
        basename,
        true
      );

      // Avoid loops if the second pass results in the same partial matches
      if (
        !newPartialMatches ||
        (partialMatches.length === newPartialMatches.length &&
          partialMatches.every(
            (m, i) => m.route.id === newPartialMatches![i].route.id
          ))
      ) {
        return { type: "success", matches: null };
      }

      partialMatches = newPartialMatches;
    }
  }

  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {
    manifest = {};
    inFlightDataRoutes = convertRoutesToDataRoutes(
      newRoutes,
      mapRouteProperties,
      undefined,
      manifest
    );
  }

  function patchRoutes(
    routeId: string | null,
    children: AgnosticRouteObject[]
  ): void {
    let isNonHMR = inFlightDataRoutes == null;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    patchRoutesImpl(
      routeId,
      children,
      routesToUse,
      manifest,
      mapRouteProperties
    );

    // If we are not in the middle of an HMR revalidation and we changed the
    // routes, provide a new identity and trigger a reflow via `updateState`
    // to re-run memoized `router.routes` dependencies.
    // HMR will already update the identity and reflow when it lands
    // `inFlightDataRoutes` in `completeNavigation`
    if (isNonHMR) {
      dataRoutes = [...dataRoutes];
      updateState({});
    }
  }

  router = {
    get basename() {
      return basename;
    },
    get future() {
      return future;
    },
    get state() {
      return state;
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return routerWindow;
    },
    initialize,
    subscribe,
    enableScrollRestoration,
    navigate,
    fetch,
    revalidate,
    // Passthrough to history-aware createHref used by useHref so we get proper
    // hash-aware URLs in DOM paths
    createHref: (to: To) => init.history.createHref(to),
    encodeLocation: (to: To) => init.history.encodeLocation(to),
    getFetcher,
    deleteFetcher: deleteFetcherAndUpdateState,
    dispose,
    getBlocker,
    deleteBlocker,
    patchRoutes,
    _internalFetchControllers: fetchControllers,
    _internalActiveDeferreds: activeDeferreds,
    // TODO: Remove setRoutes, it's temporary to avoid dealing with
    // updating the tree while validating the update algorithm.
    _internalSetRoutes,
  };

  return router;
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region createStaticHandler
////////////////////////////////////////////////////////////////////////////////

export const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");

/**
 * Future flags to toggle new feature behavior
 */
export interface StaticHandlerFutureConfig {
  v7_relativeSplatPath: boolean;
  v7_throwAbortReason: boolean;
}

export interface CreateStaticHandlerOptions {
  basename?: string;
  /**
   * @deprecated Use `mapRouteProperties` instead
   */
  detectErrorBoundary?: DetectErrorBoundaryFunction;
  mapRouteProperties?: MapRoutePropertiesFunction;
  future?: Partial<StaticHandlerFutureConfig>;
}

export function createStaticHandler(
  routes: AgnosticRouteObject[],
  opts?: CreateStaticHandlerOptions
): StaticHandler {
  invariant(
    routes.length > 0,
    "You must provide a non-empty routes array to createStaticHandler"
  );

  let manifest: RouteManifest = {};
  let basename = (opts ? opts.basename : null) || "/";
  let mapRouteProperties: MapRoutePropertiesFunction;
  if (opts?.mapRouteProperties) {
    mapRouteProperties = opts.mapRouteProperties;
  } else if (opts?.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = opts.detectErrorBoundary;
    mapRouteProperties = (route) => ({
      hasErrorBoundary: detectErrorBoundary(route),
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Config driven behavior flags
  let future: StaticHandlerFutureConfig = {
    v7_relativeSplatPath: false,
    v7_throwAbortReason: false,
    ...(opts ? opts.future : null),
  };

  let dataRoutes = convertRoutesToDataRoutes(
    routes,
    mapRouteProperties,
    undefined,
    manifest
  );

  /**
   * The query() method is intended for document requests, in which we want to
   * call an optional action and potentially multiple loaders for all nested
   * routes.  It returns a StaticHandlerContext object, which is very similar
   * to the router state (location, loaderData, actionData, errors, etc.) and
   * also adds SSR-specific information such as the statusCode and headers
   * from action/loaders Responses.
   *
   * It _should_ never throw and should report all errors through the
   * returned context.errors object, properly associating errors to their error
   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be
   * used to emulate React error boundaries during SSr by performing a second
   * pass only down to the boundaryId.
   *
   * The one exception where we do not return a StaticHandlerContext is when a
   * redirect response is returned or thrown from any action/loader.  We
   * propagate that out and return the raw Response so the HTTP server can
   * return it directly.
   *
   * - `opts.requestContext` is an optional server context that will be passed
   *   to actions/loaders in the `context` parameter
   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
   *   the bubbling of errors which allows single-fetch-type implementations
   *   where the client will handle the bubbling and we may need to return data
   *   for the handling route
   */
  async function query(
    request: Request,
    {
      requestContext,
      skipLoaderErrorBubbling,
      dataStrategy,
    }: {
      requestContext?: unknown;
      skipLoaderErrorBubbling?: boolean;
      dataStrategy?: DataStrategyFunction;
    } = {}
  ): Promise<StaticHandlerContext | Response> {
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename);

    // SSR supports HEAD requests while SPA doesn't
    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,
      dataStrategy || null,
      skipLoaderErrorBubbling === true,
      null
    );
    if (isResponse(result)) {
      return result;
    }

    // When returning StaticHandlerContext, we patch back in the location here
    // since we need it for React Context.  But this helps keep our submit and
    // loadRouteData operating on a Request instead of a Location
    return { location, basename, ...result };
  }

  /**
   * The queryRoute() method is intended for targeted route requests, either
   * for fetch ?_data requests or resource route requests.  In this case, we
   * are only ever calling a single action or loader, and we are returning the
   * returned value directly.  In most cases, this will be a Response returned
   * from the action/loader, but it may be a primitive or other value as well -
   * and in such cases the calling context should handle that accordingly.
   *
   * We do respect the throw/return differentiation, so if an action/loader
   * throws, then this method will throw the value.  This is important so we
   * can do proper boundary identification in Remix where a thrown Response
   * must go to the Catch Boundary but a returned Response is happy-path.
   *
   * One thing to note is that any Router-initiated Errors that make sense
   * to associate with a status code will be thrown as an ErrorResponse
   * instance which include the raw Error, such that the calling context can
   * serialize the error as they see fit while including the proper response
   * code.  Examples here are 404 and 405 errors that occur prior to reaching
   * any user-defined loaders.
   *
   * - `opts.routeId` allows you to specify the specific route handler to call.
   *   If not provided the handler will determine the proper route by matching
   *   against `request.url`
   * - `opts.requestContext` is an optional server context that will be passed
   *    to actions/loaders in the `context` parameter
   */
  async function queryRoute(
    request: Request,
    {
      routeId,
      requestContext,
      dataStrategy,
    }: {
      requestContext?: unknown;
      routeId?: string;
      dataStrategy?: DataStrategyFunction;
    } = {}
  ): Promise<any> {
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename);

    // SSR supports HEAD requests while SPA doesn't
    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) {
      // This should never hit I don't think?
      throw getInternalRouterError(404, { pathname: location.pathname });
    }

    let result = await queryImpl(
      request,
      location,
      matches,
      requestContext,
      dataStrategy || null,
      false,
      match
    );

    if (isResponse(result)) {
      return result;
    }

    let error = result.errors ? Object.values(result.errors)[0] : undefined;
    if (error !== undefined) {
      // If we got back result.errors, that means the loader/action threw
      // _something_ that wasn't a Response, but it's not guaranteed/required
      // to be an `instanceof Error` either, so we have to use throw here to
      // preserve the "error" state outside of queryImpl.
      throw error;
    }

    // Pick off the right state value to return
    if (result.actionData) {
      return Object.values(result.actionData)[0];
    }

    if (result.loaderData) {
      let data = Object.values(result.loaderData)[0];
      if (result.activeDeferreds?.[match.route.id]) {
        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
      }
      return data;
    }

    return undefined;
  }

  async function queryImpl(
    request: Request,
    location: Location,
    matches: AgnosticDataRouteMatch[],
    requestContext: unknown,
    dataStrategy: DataStrategyFunction | null,
    skipLoaderErrorBubbling: boolean,
    routeMatch: AgnosticDataRouteMatch | null
  ): Promise<Omit<StaticHandlerContext, "location" | "basename"> | Response> {
    invariant(
      request.signal,
      "query()/queryRoute() requests must contain an AbortController signal"
    );

    try {
      if (isMutationMethod(request.method.toLowerCase())) {
        let result = await submit(
          request,
          matches,
          routeMatch || getTargetMatch(matches, location),
          requestContext,
          dataStrategy,
          skipLoaderErrorBubbling,
          routeMatch != null
        );
        return result;
      }

      let result = await loadRouteData(
        request,
        matches,
        requestContext,
        dataStrategy,
        skipLoaderErrorBubbling,
        routeMatch
      );
      return isResponse(result)
        ? result
        : {
            ...result,
            actionData: null,
            actionHeaders: {},
          };
    } catch (e) {
      // If the user threw/returned a Response in callLoaderOrAction for a
      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
      // and then return or throw the raw Response here accordingly
      if (isDataStrategyResult(e) && isResponse(e.result)) {
        if (e.type === ResultType.error) {
          throw e.result;
        }
        return e.result;
      }
      // Redirects are always returned since they don't propagate to catch
      // boundaries
      if (isRedirectResponse(e)) {
        return e;
      }
      throw e;
    }
  }

  async function submit(
    request: Request,
    matches: AgnosticDataRouteMatch[],
    actionMatch: AgnosticDataRouteMatch,
    requestContext: unknown,
    dataStrategy: DataStrategyFunction | null,
    skipLoaderErrorBubbling: boolean,
    isRouteRequest: boolean
  ): Promise<Omit<StaticHandlerContext, "location" | "basename"> | Response> {
    let result: DataResult;

    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      let error = getInternalRouterError(405, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: actionMatch.route.id,
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error,
      };
    } else {
      let results = await callDataStrategy(
        "action",
        request,
        [actionMatch],
        matches,
        isRouteRequest,
        requestContext,
        dataStrategy
      );
      result = results[actionMatch.route.id];

      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future);
      }
    }

    if (isRedirectResult(result)) {
      // Uhhhh - this should never happen, we should always throw these from
      // callLoaderOrAction, but the type narrowing here keeps TS happy and we
      // can get back on the "throw all redirect responses" train here should
      // this ever happen :/
      throw new Response(null, {
        status: result.response.status,
        headers: {
          Location: result.response.headers.get("Location")!,
        },
      });
    }

    if (isDeferredResult(result)) {
      let error = getInternalRouterError(400, { type: "defer-action" });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error,
      };
    }

    if (isRouteRequest) {
      // Note: This should only be non-Response values if we get here, since
      // isRouteRequest should throw any Response received in callLoaderOrAction
      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,
      };
    }

    // Create a GET request for the loaders
    let loaderRequest = new Request(request.url, {
      headers: request.headers,
      redirect: request.redirect,
      signal: request.signal,
    });

    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = skipLoaderErrorBubbling
        ? actionMatch
        : findNearestBoundary(matches, actionMatch.route.id);

      let context = await loadRouteData(
        loaderRequest,
        matches,
        requestContext,
        dataStrategy,
        skipLoaderErrorBubbling,
        null,
        [boundaryMatch.route.id, result]
      );

      // action status codes take precedence over loader status codes
      return {
        ...context,
        statusCode: isRouteErrorResponse(result.error)
          ? result.error.status
          : result.statusCode != null
          ? result.statusCode
          : 500,
        actionData: null,
        actionHeaders: {
          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),
        },
      };
    }

    let context = await loadRouteData(
      loaderRequest,
      matches,
      requestContext,
      dataStrategy,
      skipLoaderErrorBubbling,
      null
    );

    return {
      ...context,
      actionData: {
        [actionMatch.route.id]: result.data,
      },
      // action status codes take precedence over loader status codes
      ...(result.statusCode ? { statusCode: result.statusCode } : {}),
      actionHeaders: result.headers
        ? { [actionMatch.route.id]: result.headers }
        : {},
    };
  }

  async function loadRouteData(
    request: Request,
    matches: AgnosticDataRouteMatch[],
    requestContext: unknown,
    dataStrategy: DataStrategyFunction | null,
    skipLoaderErrorBubbling: boolean,
    routeMatch: AgnosticDataRouteMatch | null,
    pendingActionResult?: PendingActionResult
  ): Promise<
    | Omit<
        StaticHandlerContext,
        "location" | "basename" | "actionData" | "actionHeaders"
      >
    | Response
  > {
    let isRouteRequest = routeMatch != null;

    // Short circuit if we have no loaders to run (queryRoute())
    if (
      isRouteRequest &&
      !routeMatch?.route.loader &&
      !routeMatch?.route.lazy
    ) {
      throw getInternalRouterError(400, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: routeMatch?.route.id,
      });
    }

    let requestMatches = routeMatch
      ? [routeMatch]
      : pendingActionResult && isErrorResult(pendingActionResult[1])
      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])
      : matches;
    let matchesToLoad = requestMatches.filter(
      (m) => m.route.loader || m.route.lazy
    );

    // Short circuit if we have no loaders to run (query())
    if (matchesToLoad.length === 0) {
      return {
        matches,
        // Add a null for all matched routes for proper revalidation on the client
        loaderData: matches.reduce(
          (acc, m) => Object.assign(acc, { [m.route.id]: null }),
          {}
        ),
        errors:
          pendingActionResult && isErrorResult(pendingActionResult[1])
            ? {
                [pendingActionResult[0]]: pendingActionResult[1].error,
              }
            : null,
        statusCode: 200,
        loaderHeaders: {},
        activeDeferreds: null,
      };
    }

    let results = await callDataStrategy(
      "loader",
      request,
      matchesToLoad,
      matches,
      isRouteRequest,
      requestContext,
      dataStrategy
    );

    if (request.signal.aborted) {
      throwStaticHandlerAbortedError(request, isRouteRequest, future);
    }

    // Process and commit output from loaders
    let activeDeferreds = new Map<string, DeferredData>();
    let context = processRouteLoaderData(
      matches,
      results,
      pendingActionResult,
      activeDeferreds,
      skipLoaderErrorBubbling
    );

    // Add a null for any non-loader matches for proper revalidation on the client
    let executedLoaders = new Set<string>(
      matchesToLoad.map((match) => match.route.id)
    );
    matches.forEach((match) => {
      if (!executedLoaders.has(match.route.id)) {
        context.loaderData[match.route.id] = null;
      }
    });

    return {
      ...context,
      matches,
      activeDeferreds:
        activeDeferreds.size > 0
          ? Object.fromEntries(activeDeferreds.entries())
          : null,
    };
  }

  // Utility wrapper for calling dataStrategy server-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(
    type: "loader" | "action",
    request: Request,
    matchesToLoad: AgnosticDataRouteMatch[],
    matches: AgnosticDataRouteMatch[],
    isRouteRequest: boolean,
    requestContext: unknown,
    dataStrategy: DataStrategyFunction | null
  ): Promise<Record<string, DataResult>> {
    let results = await callDataStrategyImpl(
      dataStrategy || defaultDataStrategy,
      type,
      null,
      request,
      matchesToLoad,
      matches,
      null,
      manifest,
      mapRouteProperties,
      requestContext
    );

    let dataResults: Record<string, DataResult> = {};
    await Promise.all(
      matches.map(async (match) => {
        if (!(match.route.id in results)) {
          return;
        }
        let result = results[match.route.id];
        if (isRedirectDataStrategyResultResult(result)) {
          let response = result.result as Response;
          // Throw redirects and let the server handle them with an HTTP redirect
          throw normalizeRelativeRoutingRedirectResponse(
            response,
            request,
            match.route.id,
            matches,
            basename,
            future.v7_relativeSplatPath
          );
        }
        if (isResponse(result.result) && isRouteRequest) {
          // For SSR single-route requests, we want to hand Responses back
          // directly without unwrapping
          throw result;
        }

        dataResults[match.route.id] =
          await convertDataStrategyResultToDataResult(result);
      })
    );
    return dataResults;
  }

  return {
    dataRoutes,
    query,
    queryRoute,
  };
}

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Helpers
////////////////////////////////////////////////////////////////////////////////

/**
 * Given an existing StaticHandlerContext and an error thrown at render time,
 * provide an updated StaticHandlerContext suitable for a second SSR render
 */
export function getStaticContextFromError(
  routes: AgnosticDataRouteObject[],
  context: StaticHandlerContext,
  error: any
) {
  let newContext: StaticHandlerContext = {
    ...context,
    statusCode: isRouteErrorResponse(error) ? error.status : 500,
    errors: {
      [context._deepestRenderedBoundaryId || routes[0].id]: error,
    },
  };
  return newContext;
}

function throwStaticHandlerAbortedError(
  request: Request,
  isRouteRequest: boolean,
  future: StaticHandlerFutureConfig
) {
  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
    throw request.signal.reason;
  }

  let method = isRouteRequest ? "queryRoute" : "query";
  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);
}

function isSubmissionNavigation(
  opts: BaseNavigateOrFetchOptions
): opts is SubmissionNavigateOptions {
  return (
    opts != null &&
    (("formData" in opts && opts.formData != null) ||
      ("body" in opts && opts.body !== undefined))
  );
}

function normalizeTo(
  location: Path,
  matches: AgnosticDataRouteMatch[],
  basename: string,
  prependBasename: boolean,
  to: To | null,
  v7_relativeSplatPath: boolean,
  fromRouteId?: string,
  relative?: RelativeRoutingType
) {
  let contextualMatches: AgnosticDataRouteMatch[];
  let activeRouteMatch: AgnosticDataRouteMatch | undefined;
  if (fromRouteId) {
    // Grab matches up to the calling route so our route-relative logic is
    // relative to the correct source route
    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];
  }

  // Resolve the relative path
  let path = resolveTo(
    to ? to : ".",
    getResolveToMatches(contextualMatches, v7_relativeSplatPath),
    stripBasename(location.pathname, basename) || location.pathname,
    relative === "path"
  );

  // When `to` is not specified we inherit search/hash from the current
  // location, unlike when to="." and we just inherit the path.
  // See https://github.com/remix-run/remix/issues/927
  if (to == null) {
    path.search = location.search;
    path.hash = location.hash;
  }

  // Account for `?index` params when routing to the current location
  if ((to == null || to === "" || to === ".") && activeRouteMatch) {
    let nakedIndex = hasNakedIndexQuery(path.search);
    if (activeRouteMatch.route.index && !nakedIndex) {
      // Add one when we're targeting an index route
      path.search = path.search
        ? path.search.replace(/^\?/, "?index&")
        : "?index";
    } else if (!activeRouteMatch.route.index && nakedIndex) {
      // Remove existing ones when we're not
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      params.delete("index");
      indexValues.filter((v) => v).forEach((v) => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? `?${qs}` : "";
    }
  }

  // If we're operating within a basename, prepend it to the pathname.  If
  // this is a root navigation, then just use the raw basename which allows
  // the basename to have full control over the presence of a trailing slash
  // on root actions
  if (prependBasename && basename !== "/") {
    path.pathname =
      path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }

  return createPath(path);
}

// Normalize navigation options by converting formMethod=GET formData objects to
// URLSearchParams so they behave identically to links with query params
function normalizeNavigateOptions(
  normalizeFormMethod: boolean,
  isFetcher: boolean,
  path: string,
  opts?: BaseNavigateOrFetchOptions
): {
  path: string;
  submission?: Submission;
  error?: ErrorResponseImpl;
} {
  // Return location verbatim on non-submission navigations
  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" }),
  });

  // Create a Submission on non-GET navigations
  let rawFormMethod = opts.formMethod || "get";
  let formMethod = normalizeFormMethod
    ? (rawFormMethod.toUpperCase() as V7_FormMethod)
    : (rawFormMethod.toLowerCase() as FormMethod);
  let formAction = stripHashFromPath(path);

  if (opts.body !== undefined) {
    if (opts.formEncType === "text/plain") {
      // text only support POST/PUT/PATCH/DELETE submissions
      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, [name, value]) => `${acc}${name}=${value}\n`,
              ""
            )
          : String(opts.body);

      return {
        path,
        submission: {
          formMethod,
          formAction,
          formEncType: opts.formEncType,
          formData: undefined,
          json: undefined,
          text,
        },
      };
    } else if (opts.formEncType === "application/json") {
      // json only supports POST/PUT/PATCH/DELETE submissions
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }

      try {
        let json =
          typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;

        return {
          path,
          submission: {
            formMethod,
            formAction,
            formEncType: opts.formEncType,
            formData: undefined,
            json,
            text: undefined,
          },
        };
      } catch (e) {
        return getInvalidBodyError();
      }
    }
  }

  invariant(
    typeof FormData === "function",
    "FormData is not available in this environment"
  );

  let searchParams: URLSearchParams;
  let formData: 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: Submission = {
    formMethod,
    formAction,
    formEncType:
      (opts && opts.formEncType) || "application/x-www-form-urlencoded",
    formData,
    json: undefined,
    text: undefined,
  };

  if (isMutationMethod(submission.formMethod)) {
    return { path, submission };
  }

  // Flatten submission onto URLSearchParams for GET submissions
  let parsedPath = parsePath(path);
  // On GET navigation submissions we can drop the ?index param from the
  // resulting location since all loaders will run.  But fetcher GET submissions
  // only run a single loader so we need to preserve any incoming ?index params
  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
    searchParams.append("index", "");
  }
  parsedPath.search = `?${searchParams}`;

  return { path: createPath(parsedPath), submission };
}

// Filter out all routes at/below any caught error as they aren't going to
// render so we don't need to load them
function getLoaderMatchesUntilBoundary(
  matches: AgnosticDataRouteMatch[],
  boundaryId: string,
  includeBoundary = false
) {
  let index = matches.findIndex((m) => m.route.id === boundaryId);
  if (index >= 0) {
    return matches.slice(0, includeBoundary ? index + 1 : index);
  }
  return matches;
}

function getMatchesToLoad(
  history: History,
  state: RouterState,
  matches: AgnosticDataRouteMatch[],
  submission: Submission | undefined,
  location: Location,
  initialHydration: boolean,
  skipActionErrorRevalidation: boolean,
  isRevalidationRequired: boolean,
  cancelledDeferredRoutes: string[],
  cancelledFetcherLoads: Set<string>,
  deletedFetchers: Set<string>,
  fetchLoadMatches: Map<string, FetchLoadMatch>,
  fetchRedirectIds: Set<string>,
  routesToUse: AgnosticDataRouteObject[],
  basename: string | undefined,
  pendingActionResult?: PendingActionResult
): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {
  let actionResult = pendingActionResult
    ? isErrorResult(pendingActionResult[1])
      ? pendingActionResult[1].error
      : pendingActionResult[1].data
    : undefined;
  let currentUrl = history.createURL(state.location);
  let nextUrl = history.createURL(location);

  // Pick navigation matches that are net-new or qualify for revalidation
  let boundaryMatches = matches;
  if (initialHydration && state.errors) {
    // On initial hydration, only consider matches up to _and including_ the boundary.
    // This is inclusive to handle cases where a server loader ran successfully,
    // a child server loader bubbled up to this route, but this route has
    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
    // we have a complete version of `loaderData`
    boundaryMatches = getLoaderMatchesUntilBoundary(
      matches,
      Object.keys(state.errors)[0],
      true
    );
  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
    // If an action threw an error, we call loaders up to, but not including the
    // boundary
    boundaryMatches = getLoaderMatchesUntilBoundary(
      matches,
      pendingActionResult[0]
    );
  }

  // Don't revalidate loaders by default after action 4xx/5xx responses
  // when the flag is enabled.  They can still opt-into revalidation via
  // `shouldRevalidate` via `actionResult`
  let actionStatus = pendingActionResult
    ? pendingActionResult[1].statusCode
    : undefined;
  let shouldSkipRevalidation =
    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;

  let navigationMatches = boundaryMatches.filter((match, index) => {
    let { route } = match;
    if (route.lazy) {
      // We haven't loaded this route yet so we don't know if it's got a loader!
      return true;
    }

    if (route.loader == null) {
      return false;
    }

    if (initialHydration) {
      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
    }

    // Always call the loader on new route instances and pending defer cancellations
    if (
      isNewLoader(state.loaderData, state.matches[index], match) ||
      cancelledDeferredRoutes.some((id) => id === match.route.id)
    ) {
      return true;
    }

    // This is the default implementation for when we revalidate.  If the route
    // provides it's own implementation, then we give them full control but
    // provide this value so they can leverage it if needed after they check
    // their own specific use cases
    let currentRouteMatch = state.matches[index];
    let nextRouteMatch = match;

    return shouldRevalidateLoader(match, {
      currentUrl,
      currentParams: currentRouteMatch.params,
      nextUrl,
      nextParams: nextRouteMatch.params,
      ...submission,
      actionResult,
      actionStatus,
      defaultShouldRevalidate: shouldSkipRevalidation
        ? false
        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
          isRevalidationRequired ||
          currentUrl.pathname + currentUrl.search ===
            nextUrl.pathname + nextUrl.search ||
          // Search params affect all loaders
          currentUrl.search !== nextUrl.search ||
          isNewRouteInstance(currentRouteMatch, nextRouteMatch),
    });
  });

  // Pick fetcher.loads that need to be revalidated
  let revalidatingFetchers: RevalidatingFetcher[] = [];
  fetchLoadMatches.forEach((f, key) => {
    // Don't revalidate:
    //  - on initial hydration (shouldn't be any fetchers then anyway)
    //  - if fetcher won't be present in the subsequent render
    //    - no longer matches the URL (v7_fetcherPersist=false)
    //    - was unmounted but persisted due to v7_fetcherPersist=true
    if (
      initialHydration ||
      !matches.some((m) => m.route.id === f.routeId) ||
      deletedFetchers.has(key)
    ) {
      return;
    }

    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);

    // If the fetcher path no longer matches, push it in with null matches so
    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is
    // currently only a use-case for Remix HMR where the route tree can change
    // at runtime and remove a route previously loaded via a fetcher
    if (!fetcherMatches) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: null,
        match: null,
        controller: null,
      });
      return;
    }

    // Revalidating fetchers are decoupled from the route matches since they
    // load from a static href.  They revalidate based on explicit revalidation
    // (submission, useRevalidator, or X-Remix-Revalidate)
    let fetcher = state.fetchers.get(key);
    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);

    let shouldRevalidate = false;
    if (fetchRedirectIds.has(key)) {
      // Never trigger a revalidation of an actively redirecting fetcher
      shouldRevalidate = false;
    } else if (cancelledFetcherLoads.has(key)) {
      // Always mark for revalidation if the fetcher was cancelled
      cancelledFetcherLoads.delete(key);
      shouldRevalidate = true;
    } else if (
      fetcher &&
      fetcher.state !== "idle" &&
      fetcher.data === undefined
    ) {
      // If the fetcher hasn't ever completed loading yet, then this isn't a
      // revalidation, it would just be a brand new load if an explicit
      // revalidation is required
      shouldRevalidate = isRevalidationRequired;
    } else {
      // Otherwise fall back on any user-defined shouldRevalidate, defaulting
      // to explicit revalidations only
      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {
        currentUrl,
        currentParams: state.matches[state.matches.length - 1].params,
        nextUrl,
        nextParams: matches[matches.length - 1].params,
        ...submission,
        actionResult,
        actionStatus,
        defaultShouldRevalidate: shouldSkipRevalidation
          ? false
          : isRevalidationRequired,
      });
    }

    if (shouldRevalidate) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: fetcherMatches,
        match: fetcherMatch,
        controller: new AbortController(),
      });
    }
  });

  return [navigationMatches, revalidatingFetchers];
}

function shouldLoadRouteOnHydration(
  route: AgnosticDataRouteObject,
  loaderData: RouteData | null | undefined,
  errors: RouteData | null | undefined
) {
  // We dunno if we have a loader - gotta find out!
  if (route.lazy) {
    return true;
  }

  // No loader, nothing to initialize
  if (!route.loader) {
    return false;
  }

  let hasData = loaderData != null && loaderData[route.id] !== undefined;
  let hasError = errors != null && errors[route.id] !== undefined;

  // Don't run if we error'd during SSR
  if (!hasData && hasError) {
    return false;
  }

  // Explicitly opting-in to running on hydration
  if (typeof route.loader === "function" && route.loader.hydrate === true) {
    return true;
  }

  // Otherwise, run if we're not yet initialized with anything
  return !hasData && !hasError;
}

function isNewLoader(
  currentLoaderData: RouteData,
  currentMatch: AgnosticDataRouteMatch,
  match: AgnosticDataRouteMatch
) {
  let isNew =
    // [a] -> [a, b]
    !currentMatch ||
    // [a, b] -> [a, c]
    match.route.id !== currentMatch.route.id;

  // Handle the case that we don't have data for a re-used route, potentially
  // from a prior error or from a cancelled pending deferred
  let isMissingData = currentLoaderData[match.route.id] === undefined;

  // Always load if this is a net-new route or we don't yet have data
  return isNew || isMissingData;
}

function isNewRouteInstance(
  currentMatch: AgnosticDataRouteMatch,
  match: AgnosticDataRouteMatch
) {
  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: AgnosticDataRouteMatch,
  arg: ShouldRevalidateFunctionArgs
) {
  if (loaderMatch.route.shouldRevalidate) {
    let routeChoice = loaderMatch.route.shouldRevalidate(arg);
    if (typeof routeChoice === "boolean") {
      return routeChoice;
    }
  }

  return arg.defaultShouldRevalidate;
}

function patchRoutesImpl(
  routeId: string | null,
  children: AgnosticRouteObject[],
  routesToUse: AgnosticDataRouteObject[],
  manifest: RouteManifest,
  mapRouteProperties: MapRoutePropertiesFunction
) {
  let childrenToPatch: AgnosticDataRouteObject[];
  if (routeId) {
    let route = manifest[routeId];
    invariant(
      route,
      `No route found to patch children into: routeId = ${routeId}`
    );
    if (!route.children) {
      route.children = [];
    }
    childrenToPatch = route.children;
  } else {
    childrenToPatch = routesToUse;
  }

  // Don't patch in routes we already know about so that `patch` is idempotent
  // to simplify user-land code. This is useful because we re-call the
  // `patchRoutesOnNavigation` function for matched routes with params.
  let uniqueChildren = children.filter(
    (newRoute) =>
      !childrenToPatch.some((existingRoute) =>
        isSameRoute(newRoute, existingRoute)
      )
  );

  let newRoutes = convertRoutesToDataRoutes(
    uniqueChildren,
    mapRouteProperties,
    [routeId || "_", "patch", String(childrenToPatch?.length || "0")],
    manifest
  );

  childrenToPatch.push(...newRoutes);
}

function isSameRoute(
  newRoute: AgnosticRouteObject,
  existingRoute: AgnosticRouteObject
): boolean {
  // Most optimal check is by id
  if (
    "id" in newRoute &&
    "id" in existingRoute &&
    newRoute.id === existingRoute.id
  ) {
    return true;
  }

  // Second is by pathing differences
  if (
    !(
      newRoute.index === existingRoute.index &&
      newRoute.path === existingRoute.path &&
      newRoute.caseSensitive === existingRoute.caseSensitive
    )
  ) {
    return false;
  }

  // Pathless layout routes are trickier since we need to check children.
  // If they have no children then they're the same as far as we can tell
  if (
    (!newRoute.children || newRoute.children.length === 0) &&
    (!existingRoute.children || existingRoute.children.length === 0)
  ) {
    return true;
  }

  // Otherwise, we look to see if every child in the new route is already
  // represented in the existing route's children
  return newRoute.children!.every((aChild, i) =>
    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))
  );
}

/**
 * Execute route.lazy() methods to lazily load route modules (loader, action,
 * shouldRevalidate) and update the routeManifest in place which shares objects
 * with dataRoutes so those get updated as well.
 */
async function loadLazyRouteModule(
  route: AgnosticDataRouteObject,
  mapRouteProperties: MapRoutePropertiesFunction,
  manifest: RouteManifest
) {
  if (!route.lazy) {
    return;
  }

  let lazyRoute = await route.lazy();

  // If the lazy route function was executed and removed by another parallel
  // call then we can return - first lazy() to finish wins because the return
  // value of lazy is expected to be static
  if (!route.lazy) {
    return;
  }

  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");

  // Update the route in place.  This should be safe because there's no way
  // we could yet be sitting on this route as we can't get there without
  // resolving lazy() first.
  //
  // This is different than the HMR "update" use-case where we may actively be
  // on the route being updated.  The main concern boils down to "does this
  // mutation affect any ongoing navigations or any current state.matches
  // values?".  If not, it should be safe to update in place.
  let routeUpdates: Record<string, any> = {};
  for (let lazyRouteProperty in lazyRoute) {
    let staticRouteValue =
      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];

    let isPropertyStaticallyDefined =
      staticRouteValue !== undefined &&
      // 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 as ImmutableRouteKey)
    ) {
      routeUpdates[lazyRouteProperty] =
        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];
    }
  }

  // Mutate the route with the provided updates.  Do this first so we pass
  // the updated version to mapRouteProperties
  Object.assign(routeToUpdate, routeUpdates);

  // Mutate the `hasErrorBoundary` property on the route based on the route
  // updates and remove the `lazy` function so we don't resolve the lazy
  // route again.
  Object.assign(routeToUpdate, {
    // To keep things framework agnostic, we use the provided
    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to
    // set the framework-aware properties (`element`/`hasErrorBoundary`) since
    // the logic will differ between frameworks.
    ...mapRouteProperties(routeToUpdate),
    lazy: undefined,
  });
}

// Default implementation of `dataStrategy` which fetches all loaders in parallel
async function defaultDataStrategy({
  matches,
}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {
  let matchesToLoad = matches.filter((m) => m.shouldLoad);
  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  return results.reduce(
    (acc, result, i) =>
      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),
    {}
  );
}

async function callDataStrategyImpl(
  dataStrategyImpl: DataStrategyFunction,
  type: "loader" | "action",
  state: RouterState | null,
  request: Request,
  matchesToLoad: AgnosticDataRouteMatch[],
  matches: AgnosticDataRouteMatch[],
  fetcherKey: string | null,
  manifest: RouteManifest,
  mapRouteProperties: MapRoutePropertiesFunction,
  requestContext?: unknown
): Promise<Record<string, DataStrategyResult>> {
  let loadRouteDefinitionsPromises = matches.map((m) =>
    m.route.lazy
      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)
      : undefined
  );

  let dsMatches = matches.map((match, i) => {
    let loadRoutePromise = loadRouteDefinitionsPromises[i];
    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);
    // `resolve` encapsulates route.lazy(), executing the loader/action,
    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users
    // can pass a callback to take fine-grained control over the execution
    // of the loader/action
    let resolve: DataStrategyMatch["resolve"] = async (handlerOverride) => {
      if (
        handlerOverride &&
        request.method === "GET" &&
        (match.route.lazy || match.route.loader)
      ) {
        shouldLoad = true;
      }
      return shouldLoad
        ? callLoaderOrAction(
            type,
            request,
            match,
            loadRoutePromise,
            handlerOverride,
            requestContext
          )
        : Promise.resolve({ type: ResultType.data, result: undefined });
    };

    return {
      ...match,
      shouldLoad,
      resolve,
    };
  });

  // Send all matches here to allow for a middleware-type implementation.
  // handler will be a no-op for unneeded routes and we filter those results
  // back out below.
  let results = await dataStrategyImpl({
    matches: dsMatches,
    request,
    params: matches[0].params,
    fetcherKey,
    context: requestContext,
  });

  // Wait for all routes to load here but 'swallow the error since we want
  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
  // called from `match.resolve()`
  try {
    await Promise.all(loadRouteDefinitionsPromises);
  } catch (e) {
    // No-op
  }

  return results;
}

// Default logic for calling a loader/action is the user has no specified a dataStrategy
async function callLoaderOrAction(
  type: "loader" | "action",
  request: Request,
  match: AgnosticDataRouteMatch,
  loadRoutePromise: Promise<void> | undefined,
  handlerOverride: Parameters<DataStrategyMatch["resolve"]>[0],
  staticContext?: unknown
): Promise<DataStrategyResult> {
  let result: DataStrategyResult;
  let onReject: (() => void) | undefined;

  let runHandler = (
    handler: AgnosticRouteObject["loader"] | AgnosticRouteObject["action"]
  ): Promise<DataStrategyResult> => {
    // Setup a promise we can race against so that abort signals short circuit
    let reject: () => void;
    // This will never resolve so safe to type it as Promise<DataStrategyResult> to
    // satisfy the function return value
    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);

    let actualHandler = (ctx?: unknown) => {
      if (typeof handler !== "function") {
        return Promise.reject(
          new Error(
            `You cannot call the handler for a route which defines a boolean ` +
              `"${type}" [routeId: ${match.route.id}]`
          )
        );
      }
      return handler(
        {
          request,
          params: match.params,
          context: staticContext,
        },
        ...(ctx !== undefined ? [ctx] : [])
      );
    };

    let handlerPromise: Promise<DataStrategyResult> = (async () => {
      try {
        let val = await (handlerOverride
          ? handlerOverride((ctx: unknown) => actualHandler(ctx))
          : actualHandler());
        return { type: "data", result: val };
      } catch (e) {
        return { type: "error", result: e };
      }
    })();

    return Promise.race([handlerPromise, abortPromise]);
  };

  try {
    let handler = match.route[type];

    // If we have a route.lazy promise, await that first
    if (loadRoutePromise) {
      if (handler) {
        // Run statically defined handler in parallel with lazy()
        let handlerError;
        let [value] = await Promise.all([
          // If the handler throws, don't let it immediately bubble out,
          // since we need to let the lazy() execution finish so we know if this
          // route has a boundary that can handle the error
          runHandler(handler).catch((e) => {
            handlerError = e;
          }),
          loadRoutePromise,
        ]);
        if (handlerError !== undefined) {
          throw handlerError;
        }
        result = value!;
      } else {
        // Load lazy route module, then run any returned handler
        await loadRoutePromise;

        handler = match.route[type];
        if (handler) {
          // Handler still runs even if we got interrupted to maintain consistency
          // with un-abortable behavior of handler execution on non-lazy or
          // previously-lazy-loaded routes
          result = await runHandler(handler);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match.route.id,
          });
        } else {
          // lazy() route has no loader to run.  Short circuit here so we don't
          // hit the invariant below that errors on returning undefined.
          return { type: ResultType.data, result: undefined };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname,
      });
    } else {
      result = await runHandler(handler);
    }

    invariant(
      result.result !== undefined,
      `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) {
    // We should already be catching and converting normal handler executions to
    // DataStrategyResults and returning them, so anything that throws here is an
    // unexpected error we still need to wrap
    return { type: ResultType.error, result: e };
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }

  return result;
}

async function convertDataStrategyResultToDataResult(
  dataStrategyResult: DataStrategyResult
): Promise<DataResult> {
  let { result, type } = dataStrategyResult;

  if (isResponse(result)) {
    let data: any;

    try {
      let contentType = result.headers.get("Content-Type");
      // Check between word boundaries instead of startsWith() due to the last
      // paragraph of https://httpwg.org/specs/rfc9110.html#field.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 (type === ResultType.error) {
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(result.status, result.statusText, data),
        statusCode: result.status,
        headers: result.headers,
      };
    }

    return {
      type: ResultType.data,
      data,
      statusCode: result.status,
      headers: result.headers,
    };
  }

  if (type === ResultType.error) {
    if (isDataWithResponseInit(result)) {
      if (result.data instanceof Error) {
        return {
          type: ResultType.error,
          error: result.data,
          statusCode: result.init?.status,
          headers: result.init?.headers
            ? new Headers(result.init.headers)
            : undefined,
        };
      }

      // Convert thrown data() to ErrorResponse instances
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(
          result.init?.status || 500,
          undefined,
          result.data
        ),
        statusCode: isRouteErrorResponse(result) ? result.status : undefined,
        headers: result.init?.headers
          ? new Headers(result.init.headers)
          : undefined,
      };
    }
    return {
      type: ResultType.error,
      error: result,
      statusCode: isRouteErrorResponse(result) ? result.status : undefined,
    };
  }

  if (isDeferredData(result)) {
    return {
      type: ResultType.deferred,
      deferredData: result,
      statusCode: result.init?.status,
      headers: result.init?.headers && new Headers(result.init.headers),
    };
  }

  if (isDataWithResponseInit(result)) {
    return {
      type: ResultType.data,
      data: result.data,
      statusCode: result.init?.status,
      headers: result.init?.headers
        ? new Headers(result.init.headers)
        : undefined,
    };
  }

  return { type: ResultType.data, data: result };
}

// Support relative routing in internal redirects
function normalizeRelativeRoutingRedirectResponse(
  response: Response,
  request: Request,
  routeId: string,
  matches: AgnosticDataRouteMatch[],
  basename: string,
  v7_relativeSplatPath: boolean
) {
  let location = response.headers.get("Location");
  invariant(
    location,
    "Redirects returned/thrown from loaders/actions must have a Location header"
  );

  if (!ABSOLUTE_URL_REGEX.test(location)) {
    let trimmedMatches = matches.slice(
      0,
      matches.findIndex((m) => m.route.id === routeId) + 1
    );
    location = normalizeTo(
      new URL(request.url),
      trimmedMatches,
      basename,
      true,
      location,
      v7_relativeSplatPath
    );
    response.headers.set("Location", location);
  }

  return response;
}

function normalizeRedirectLocation(
  location: string,
  currentUrl: URL,
  basename: string,
  historyInstance: History,
): string {
  // Match Chrome's behavior:
  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
  let invalidProtocols = [
    "about:",
    "blob:",
    "chrome:",
    "chrome-untrusted:",
    "content:",
    "data:",
    "devtools:",
    "file:",
    "filesystem:",
    // eslint-disable-next-line no-script-url
    "javascript:",
  ];

  if (ABSOLUTE_URL_REGEX.test(location)) {
    // Strip off the protocol+origin for same-origin + same-basename absolute redirects
    let normalizedLocation = location;
    let url = normalizedLocation.startsWith("//")
      ? new URL(currentUrl.protocol + normalizedLocation)
      : new URL(normalizedLocation);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
    let isSameBasename = stripBasename(url.pathname, basename) != null;
    if (url.origin === currentUrl.origin && isSameBasename) {
      return removeDoubleSlashes(url.pathname) + url.search + url.hash;
    }
  }

  try {
    let url = historyInstance.createURL(location);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
  } catch (e) {}

  return location;
}

// Utility method for creating the Request instances for loaders/actions during
// client-side navigations and fetches.  During SSR we will always have a
// Request instance from the static handler (query/queryRoute)
function createClientSideRequest(
  history: History,
  location: string | Location,
  signal: AbortSignal,
  submission?: Submission
): Request {
  let url = history.createURL(stripHashFromPath(location)).toString();
  let init: RequestInit = { signal };

  if (submission && isMutationMethod(submission.formMethod)) {
    let { formMethod, formEncType } = submission;
    // Didn't think we needed this but it turns out unlike other methods, patch
    // won't be properly normalized to uppercase and results in a 405 error.
    // See: https://fetch.spec.whatwg.org/#concept-method
    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") {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.text;
    } else if (
      formEncType === "application/x-www-form-urlencoded" &&
      submission.formData
    ) {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = convertFormDataToSearchParams(submission.formData);
    } else {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.formData;
    }
  }

  return new Request(url, init);
}

function convertFormDataToSearchParams(formData: FormData): URLSearchParams {
  let searchParams = new URLSearchParams();

  for (let [key, value] of formData.entries()) {
    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
    searchParams.append(key, typeof value === "string" ? value : value.name);
  }

  return searchParams;
}

function convertSearchParamsToFormData(
  searchParams: URLSearchParams
): FormData {
  let formData = new FormData();
  for (let [key, value] of searchParams.entries()) {
    formData.append(key, value);
  }
  return formData;
}

function processRouteLoaderData(
  matches: AgnosticDataRouteMatch[],
  results: Record<string, DataResult>,
  pendingActionResult: PendingActionResult | undefined,
  activeDeferreds: Map<string, DeferredData>,
  skipLoaderErrorBubbling: boolean
): {
  loaderData: RouterState["loaderData"];
  errors: RouterState["errors"] | null;
  statusCode: number;
  loaderHeaders: Record<string, Headers>;
} {
  // Fill in loaderData/errors from our loaders
  let loaderData: RouterState["loaderData"] = {};
  let errors: RouterState["errors"] | null = null;
  let statusCode: number | undefined;
  let foundError = false;
  let loaderHeaders: Record<string, Headers> = {};
  let pendingError =
    pendingActionResult && isErrorResult(pendingActionResult[1])
      ? pendingActionResult[1].error
      : undefined;

  // Process loader results into state.loaderData/state.errors
  matches.forEach((match) => {
    if (!(match.route.id in results)) {
      return;
    }
    let id = match.route.id;
    let result = results[id];
    invariant(
      !isRedirectResult(result),
      "Cannot handle redirect results in processLoaderData"
    );
    if (isErrorResult(result)) {
      let error = result.error;
      // If we have a pending action error, we report it at the highest-route
      // that throws a loader error, and then clear it out to indicate that
      // it was consumed
      if (pendingError !== undefined) {
        error = pendingError;
        pendingError = undefined;
      }

      errors = errors || {};

      if (skipLoaderErrorBubbling) {
        errors[id] = error;
      } else {
        // Look upwards from the matched route for the closest ancestor error
        // boundary, defaulting to the root match.  Prefer higher error values
        // if lower errors bubble to the same boundary
        let boundaryMatch = findNearestBoundary(matches, id);
        if (errors[boundaryMatch.route.id] == null) {
          errors[boundaryMatch.route.id] = error;
        }
      }

      // Clear our any prior loaderData for the throwing route
      loaderData[id] = undefined;

      // Once we find our first (highest) error, we set the status code and
      // prevent deeper status codes from overriding
      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;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (
          result.statusCode != null &&
          result.statusCode !== 200 &&
          !foundError
        ) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      } else {
        loaderData[id] = result.data;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (result.statusCode && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      }
    }
  });

  // If we didn't consume the pending action error (i.e., all loaders
  // resolved), then consume it here.  Also clear out any loaderData for the
  // throwing route
  if (pendingError !== undefined && pendingActionResult) {
    errors = { [pendingActionResult[0]]: pendingError };
    loaderData[pendingActionResult[0]] = undefined;
  }

  return {
    loaderData,
    errors,
    statusCode: statusCode || 200,
    loaderHeaders,
  };
}

function processLoaderData(
  state: RouterState,
  matches: AgnosticDataRouteMatch[],
  results: Record<string, DataResult>,
  pendingActionResult: PendingActionResult | undefined,
  revalidatingFetchers: RevalidatingFetcher[],
  fetcherResults: Record<string, DataResult>,
  activeDeferreds: Map<string, DeferredData>
): {
  loaderData: RouterState["loaderData"];
  errors?: RouterState["errors"];
} {
  let { loaderData, errors } = processRouteLoaderData(
    matches,
    results,
    pendingActionResult,
    activeDeferreds,
    false // This method is only called client side so we always want to bubble
  );

  // Process results from our revalidating fetchers
  revalidatingFetchers.forEach((rf) => {
    let { key, match, controller } = rf;
    let result = fetcherResults[key];
    invariant(result, "Did not find corresponding fetcher result");

    // Process fetcher non-redirect errors
    if (controller && controller.signal.aborted) {
      // Nothing to do for aborted fetchers
      return;
    } else if (isErrorResult(result)) {
      let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);
      if (!(errors && errors[boundaryMatch.route.id])) {
        errors = {
          ...errors,
          [boundaryMatch.route.id]: result.error,
        };
      }
      state.fetchers.delete(key);
    } else if (isRedirectResult(result)) {
      // Should never get here, redirects should get processed above, but we
      // keep this to type narrow to a success result in the else
      invariant(false, "Unhandled fetcher revalidation redirect");
    } else if (isDeferredResult(result)) {
      // Should never get here, deferred data should be awaited for fetchers
      // in resolveDeferredResults
      invariant(false, "Unhandled fetcher deferred data");
    } else {
      let doneFetcher = getDoneFetcher(result.data);
      state.fetchers.set(key, doneFetcher);
    }
  });

  return { loaderData, errors };
}

function mergeLoaderData(
  loaderData: RouteData,
  newLoaderData: RouteData,
  matches: AgnosticDataRouteMatch[],
  errors: RouteData | null | undefined
): RouteData {
  let mergedLoaderData = { ...newLoaderData };
  for (let match of matches) {
    let id = match.route.id;
    if (newLoaderData.hasOwnProperty(id)) {
      if (newLoaderData[id] !== undefined) {
        mergedLoaderData[id] = newLoaderData[id];
      } else {
        // No-op - this is so we ignore existing data if we have a key in the
        // incoming object with an undefined value, which is how we unset a prior
        // loaderData if we encounter a loader error
      }
    } else if (loaderData[id] !== undefined && match.route.loader) {
      // Preserve existing keys not included in newLoaderData and where a loader
      // wasn't removed by HMR
      mergedLoaderData[id] = loaderData[id];
    }

    if (errors && errors.hasOwnProperty(id)) {
      // Don't keep any loader data below the boundary
      break;
    }
  }
  return mergedLoaderData;
}

function getActionDataForCommit(
  pendingActionResult: PendingActionResult | undefined
) {
  if (!pendingActionResult) {
    return {};
  }
  return isErrorResult(pendingActionResult[1])
    ? {
        // Clear out prior actionData on errors
        actionData: {},
      }
    : {
        actionData: {
          [pendingActionResult[0]]: pendingActionResult[1].data,
        },
      };
}

// Find the nearest error boundary, looking upwards from the leaf route (or the
// route specified by routeId) for the closest ancestor error boundary,
// defaulting to the root match
function findNearestBoundary(
  matches: AgnosticDataRouteMatch[],
  routeId?: string
): AgnosticDataRouteMatch {
  let eligibleMatches = routeId
    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)
    : [...matches];
  return (
    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||
    matches[0]
  );
}

function getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {
  matches: AgnosticDataRouteMatch[];
  route: AgnosticDataRouteObject;
} {
  // Prefer a root layout route if present, otherwise shim in a route object
  let route =
    routes.length === 1
      ? routes[0]
      : routes.find((r) => r.index || !r.path || r.path === "/") || {
          id: `__shim-error-route__`,
        };

  return {
    matches: [
      {
        params: {},
        pathname: "",
        pathnameBase: "",
        route,
      },
    ],
    route,
  };
}

function getInternalRouterError(
  status: number,
  {
    pathname,
    routeId,
    method,
    type,
    message,
  }: {
    pathname?: string;
    routeId?: string;
    method?: string;
    type?: "defer-action" | "invalid-body";
    message?: string;
  } = {}
) {
  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
  );
}

// Find any returned redirect errors, starting from the lowest match
function findRedirect(
  results: Record<string, DataResult>
): { key: string; result: RedirectResult } | undefined {
  let entries = Object.entries(results);
  for (let i = entries.length - 1; i >= 0; i--) {
    let [key, result] = entries[i];
    if (isRedirectResult(result)) {
      return { key, result };
    }
  }
}

function stripHashFromPath(path: To) {
  let parsedPath = typeof path === "string" ? parsePath(path) : path;
  return createPath({ ...parsedPath, hash: "" });
}

function isHashChangeOnly(a: Location, b: Location): boolean {
  if (a.pathname !== b.pathname || a.search !== b.search) {
    return false;
  }

  if (a.hash === "") {
    // /page -> /page#hash
    return b.hash !== "";
  } else if (a.hash === b.hash) {
    // /page#hash -> /page#hash
    return true;
  } else if (b.hash !== "") {
    // /page#hash -> /page#other
    return true;
  }

  // If the hash is removed the browser will re-perform a request to the server
  // /page#hash -> /page
  return false;
}

function isPromise<T = unknown>(val: unknown): val is Promise<T> {
  return typeof val === "object" && val != null && "then" in val;
}

function isDataStrategyResult(result: unknown): result is DataStrategyResult {
  return (
    result != null &&
    typeof result === "object" &&
    "type" in result &&
    "result" in result &&
    (result.type === ResultType.data || result.type === ResultType.error)
  );
}

function isRedirectDataStrategyResultResult(result: DataStrategyResult) {
  return (
    isResponse(result.result) && redirectStatusCodes.has(result.result.status)
  );
}

function isDeferredResult(result: DataResult): result is DeferredResult {
  return result.type === ResultType.deferred;
}

function isErrorResult(result: DataResult): result is ErrorResult {
  return result.type === ResultType.error;
}

function isRedirectResult(result?: DataResult): result is RedirectResult {
  return (result && result.type) === ResultType.redirect;
}

export function isDataWithResponseInit(
  value: any
): value is DataWithResponseInit<unknown> {
  return (
    typeof value === "object" &&
    value != null &&
    "type" in value &&
    "data" in value &&
    "init" in value &&
    value.type === "DataWithResponseInit"
  );
}

export function isDeferredData(value: any): value is DeferredData {
  let deferred: DeferredData = 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: any): value is Response {
  return (
    value != null &&
    typeof value.status === "number" &&
    typeof value.statusText === "string" &&
    typeof value.headers === "object" &&
    typeof value.body !== "undefined"
  );
}

function isRedirectResponse(result: any): result is Response {
  if (!isResponse(result)) {
    return false;
  }

  let status = result.status;
  let location = result.headers.get("Location");
  return status >= 300 && status <= 399 && location != null;
}

function isValidMethod(method: string): method is FormMethod | V7_FormMethod {
  return validRequestMethods.has(method.toLowerCase() as FormMethod);
}

function isMutationMethod(
  method: string
): method is MutationFormMethod | V7_MutationFormMethod {
  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);
}

async function resolveNavigationDeferredResults(
  matches: (AgnosticDataRouteMatch | null)[],
  results: Record<string, DataResult>,
  signal: AbortSignal,
  currentMatches: AgnosticDataRouteMatch[],
  currentLoaderData: RouteData
) {
  let entries = Object.entries(results);
  for (let index = 0; index < entries.length; index++) {
    let [routeId, result] = entries[index];
    let match = matches.find((m) => m?.route.id === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    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]) !== undefined;

    if (isDeferredResult(result) && isRevalidatingLoader) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      await resolveDeferredData(result, signal, false).then((result) => {
        if (result) {
          results[routeId] = result;
        }
      });
    }
  }
}

async function resolveFetcherDeferredResults(
  matches: (AgnosticDataRouteMatch | null)[],
  results: Record<string, DataResult>,
  revalidatingFetchers: RevalidatingFetcher[]
) {
  for (let index = 0; index < revalidatingFetchers.length; index++) {
    let { key, routeId, controller } = revalidatingFetchers[index];
    let result = results[key];
    let match = matches.find((m) => m?.route.id === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    if (!match) {
      continue;
    }

    if (isDeferredResult(result)) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      invariant(
        controller,
        "Expected an AbortController for revalidating fetcher deferred result"
      );
      await resolveDeferredData(result, controller.signal, true).then(
        (result) => {
          if (result) {
            results[key] = result;
          }
        }
      );
    }
  }
}

async function resolveDeferredData(
  result: DeferredResult,
  signal: AbortSignal,
  unwrap = false
): Promise<SuccessResult | ErrorResult | undefined> {
  let aborted = await result.deferredData.resolveData(signal);
  if (aborted) {
    return;
  }

  if (unwrap) {
    try {
      return {
        type: ResultType.data,
        data: result.deferredData.unwrappedData,
      };
    } catch (e) {
      // Handle any TrackedPromise._error values encountered while unwrapping
      return {
        type: ResultType.error,
        error: e,
      };
    }
  }

  return {
    type: ResultType.data,
    data: result.deferredData.data,
  };
}

function hasNakedIndexQuery(search: string): boolean {
  return new URLSearchParams(search).getAll("index").some((v) => v === "");
}

function getTargetMatch(
  matches: AgnosticDataRouteMatch[],
  location: Location | string
) {
  let search =
    typeof location === "string" ? parsePath(location).search : location.search;
  if (
    matches[matches.length - 1].route.index &&
    hasNakedIndexQuery(search || "")
  ) {
    // Return the leaf index route when index is present
    return matches[matches.length - 1];
  }
  // Otherwise grab the deepest "path contributing" match (ignoring index and
  // pathless layout routes)
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}

function getSubmissionFromNavigation(
  navigation: Navigation
): Submission | undefined {
  let { formMethod, formAction, formEncType, text, formData, json } =
    navigation;
  if (!formMethod || !formAction || !formEncType) {
    return;
  }

  if (text != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json: undefined,
      text,
    };
  } else if (formData != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData,
      json: undefined,
      text: undefined,
    };
  } else if (json !== undefined) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json,
      text: undefined,
    };
  }
}

function getLoadingNavigation(
  location: Location,
  submission?: Submission
): NavigationStates["Loading"] {
  if (submission) {
    let navigation: NavigationStates["Loading"] = {
      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: NavigationStates["Loading"] = {
      state: "loading",
      location,
      formMethod: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
    };
    return navigation;
  }
}

function getSubmittingNavigation(
  location: Location,
  submission: Submission
): NavigationStates["Submitting"] {
  let navigation: NavigationStates["Submitting"] = {
    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?: Submission,
  data?: Fetcher["data"]
): FetcherStates["Loading"] {
  if (submission) {
    let fetcher: FetcherStates["Loading"] = {
      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: FetcherStates["Loading"] = {
      state: "loading",
      formMethod: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
      data,
    };
    return fetcher;
  }
}

function getSubmittingFetcher(
  submission: Submission,
  existingFetcher?: Fetcher
): FetcherStates["Submitting"] {
  let fetcher: FetcherStates["Submitting"] = {
    state: "submitting",
    formMethod: submission.formMethod,
    formAction: submission.formAction,
    formEncType: submission.formEncType,
    formData: submission.formData,
    json: submission.json,
    text: submission.text,
    data: existingFetcher ? existingFetcher.data : undefined,
  };
  return fetcher;
}

function getDoneFetcher(data: Fetcher["data"]): FetcherStates["Idle"] {
  let fetcher: FetcherStates["Idle"] = {
    state: "idle",
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined,
    data,
  };
  return fetcher;
}

function restoreAppliedTransitions(
  _window: Window,
  transitions: Map<string, Set<string>>
) {
  try {
    let sessionPositions = _window.sessionStorage.getItem(
      TRANSITIONS_STORAGE_KEY
    );
    if (sessionPositions) {
      let json = JSON.parse(sessionPositions);
      for (let [k, v] of Object.entries(json || {})) {
        if (v && Array.isArray(v)) {
          transitions.set(k, new Set(v || []));
        }
      }
    }
  } catch (e) {
    // no-op, use default empty object
  }
}

function persistAppliedTransitions(
  _window: Window,
  transitions: Map<string, Set<string>>
) {
  if (transitions.size > 0) {
    let json: Record<string, string[]> = {};
    for (let [k, v] of transitions) {
      json[k] = [...v];
    }
    try {
      _window.sessionStorage.setItem(
        TRANSITIONS_STORAGE_KEY,
        JSON.stringify(json)
      );
    } catch (error) {
      warning(
        false,
        `Failed to save applied view transitions in sessionStorage (${error}).`
      );
    }
  }
}
//#endregion
import type { Location, Path, To } from "./history";
import { invariant, parsePath, warning } from "./history";

/**
 * Map of routeId -> data returned from a loader/action/error
 */
export interface RouteData {
  [routeId: string]: any;
}

export enum ResultType {
  data = "data",
  deferred = "deferred",
  redirect = "redirect",
  error = "error",
}

/**
 * Successful result from a loader or action
 */
export interface SuccessResult {
  type: ResultType.data;
  data: unknown;
  statusCode?: number;
  headers?: Headers;
}

/**
 * Successful defer() result from a loader or action
 */
export interface DeferredResult {
  type: ResultType.deferred;
  deferredData: DeferredData;
  statusCode?: number;
  headers?: Headers;
}

/**
 * Redirect result from a loader or action
 */
export interface RedirectResult {
  type: ResultType.redirect;
  // We keep the raw Response for redirects so we can return it verbatim
  response: Response;
}

/**
 * Unsuccessful result from a loader or action
 */
export interface ErrorResult {
  type: ResultType.error;
  error: unknown;
  statusCode?: number;
  headers?: Headers;
}

/**
 * Result from a loader or action - potentially successful or unsuccessful
 */
export type DataResult =
  | SuccessResult
  | DeferredResult
  | RedirectResult
  | ErrorResult;

type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;

/**
 * Users can specify either lowercase or uppercase form methods on `<Form>`,
 * useSubmit(), `<fetcher.Form>`, etc.
 */
export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;

/**
 * Active navigation/fetcher form methods are exposed in lowercase on the
 * RouterState
 */
export type FormMethod = LowerCaseFormMethod;
export type MutationFormMethod = Exclude<FormMethod, "get">;

/**
 * In v7, active navigation/fetcher form methods are exposed in uppercase on the
 * RouterState.  This is to align with the normalization done via fetch().
 */
export type V7_FormMethod = UpperCaseFormMethod;
export type V7_MutationFormMethod = Exclude<V7_FormMethod, "GET">;

export type FormEncType =
  | "application/x-www-form-urlencoded"
  | "multipart/form-data"
  | "application/json"
  | "text/plain";

// Thanks https://github.com/sindresorhus/type-fest!
type JsonObject = { [Key in string]: JsonValue } & {
  [Key in string]?: JsonValue | undefined;
};
type JsonArray = JsonValue[] | readonly JsonValue[];
type JsonPrimitive = string | number | boolean | null;
type JsonValue = JsonPrimitive | JsonObject | JsonArray;

/**
 * @private
 * Internal interface to pass around for action submissions, not intended for
 * external consumption
 */
export type Submission =
  | {
      formMethod: FormMethod | V7_FormMethod;
      formAction: string;
      formEncType: FormEncType;
      formData: FormData;
      json: undefined;
      text: undefined;
    }
  | {
      formMethod: FormMethod | V7_FormMethod;
      formAction: string;
      formEncType: FormEncType;
      formData: undefined;
      json: JsonValue;
      text: undefined;
    }
  | {
      formMethod: FormMethod | V7_FormMethod;
      formAction: string;
      formEncType: FormEncType;
      formData: undefined;
      json: undefined;
      text: string;
    };

/**
 * @private
 * Arguments passed to route loader/action functions.  Same for now but we keep
 * this as a private implementation detail in case they diverge in the future.
 */
interface DataFunctionArgs<Context> {
  request: Request;
  params: Params;
  context?: Context;
}

// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
//   Also, make them a type alias instead of an interface

/**
 * Arguments passed to loader functions
 */
export interface LoaderFunctionArgs<Context = any>
  extends DataFunctionArgs<Context> {}

/**
 * Arguments passed to action functions
 */
export interface ActionFunctionArgs<Context = any>
  extends DataFunctionArgs<Context> {}

/**
 * Loaders and actions can return anything except `undefined` (`null` is a
 * valid return value if there is no data to return).  Responses are preferred
 * and will ease any future migration to Remix
 */
type DataFunctionValue = Response | NonNullable<unknown> | null;

type DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;

/**
 * Route loader function signature
 */
export type LoaderFunction<Context = any> = {
  (
    args: LoaderFunctionArgs<Context>,
    handlerCtx?: unknown
  ): DataFunctionReturnValue;
} & { hydrate?: boolean };

/**
 * Route action function signature
 */
export interface ActionFunction<Context = any> {
  (
    args: ActionFunctionArgs<Context>,
    handlerCtx?: unknown
  ): DataFunctionReturnValue;
}

/**
 * Arguments passed to shouldRevalidate function
 */
export interface ShouldRevalidateFunctionArgs {
  currentUrl: URL;
  currentParams: AgnosticDataRouteMatch["params"];
  nextUrl: URL;
  nextParams: AgnosticDataRouteMatch["params"];
  formMethod?: Submission["formMethod"];
  formAction?: Submission["formAction"];
  formEncType?: Submission["formEncType"];
  text?: Submission["text"];
  formData?: Submission["formData"];
  json?: Submission["json"];
  actionStatus?: number;
  actionResult?: any;
  defaultShouldRevalidate: boolean;
}

/**
 * Route shouldRevalidate function signature.  This runs after any submission
 * (navigation or fetcher), so we flatten the navigation/fetcher submission
 * onto the arguments.  It shouldn't matter whether it came from a navigation
 * or a fetcher, what really matters is the URLs and the formData since loaders
 * have to re-run based on the data models that were potentially mutated.
 */
export interface ShouldRevalidateFunction {
  (args: ShouldRevalidateFunctionArgs): boolean;
}

/**
 * Function provided by the framework-aware layers to set `hasErrorBoundary`
 * from the framework-aware `errorElement` prop
 *
 * @deprecated Use `mapRouteProperties` instead
 */
export interface DetectErrorBoundaryFunction {
  (route: AgnosticRouteObject): boolean;
}

export interface DataStrategyMatch
  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
  shouldLoad: boolean;
  resolve: (
    handlerOverride?: (
      handler: (ctx?: unknown) => DataFunctionReturnValue
    ) => DataFunctionReturnValue
  ) => Promise<DataStrategyResult>;
}

export interface DataStrategyFunctionArgs<Context = any>
  extends DataFunctionArgs<Context> {
  matches: DataStrategyMatch[];
  fetcherKey: string | null;
}

/**
 * Result from a loader or action called via dataStrategy
 */
export interface DataStrategyResult {
  type: "data" | "error";
  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit
}

export interface DataStrategyFunction {
  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;
}

export type AgnosticPatchRoutesOnNavigationFunctionArgs<
  O extends AgnosticRouteObject = AgnosticRouteObject,
  M extends AgnosticRouteMatch = AgnosticRouteMatch
> = {
  signal: AbortSignal;
  path: string;
  matches: M[];
  fetcherKey: string | undefined;
  patch: (routeId: string | null, children: O[]) => void;
};

export type AgnosticPatchRoutesOnNavigationFunction<
  O extends AgnosticRouteObject = AgnosticRouteObject,
  M extends AgnosticRouteMatch = AgnosticRouteMatch
> = (
  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>
) => void | Promise<void>;

/**
 * Function provided by the framework-aware layers to set any framework-specific
 * properties from framework-agnostic properties
 */
export interface MapRoutePropertiesFunction {
  (route: AgnosticRouteObject): {
    hasErrorBoundary: boolean;
  } & Record<string, any>;
}

/**
 * Keys we cannot change from within a lazy() function. We spread all other keys
 * onto the route. Either they're meaningful to the router, or they'll get
 * ignored.
 */
export type ImmutableRouteKey =
  | "lazy"
  | "caseSensitive"
  | "path"
  | "id"
  | "index"
  | "children";

export const immutableRouteKeys = new Set<ImmutableRouteKey>([
  "lazy",
  "caseSensitive",
  "path",
  "id",
  "index",
  "children",
]);

type RequireOne<T, Key = keyof T> = Exclude<
  {
    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;
  }[keyof T],
  undefined
>;

/**
 * lazy() function to load a route definition, which can add non-matching
 * related properties to a route
 */
export interface LazyRouteFunction<R extends AgnosticRouteObject> {
  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;
}

/**
 * Base RouteObject with common props shared by all types of routes
 */
type AgnosticBaseRouteObject = {
  caseSensitive?: boolean;
  path?: string;
  id?: string;
  loader?: LoaderFunction | boolean;
  action?: ActionFunction | boolean;
  hasErrorBoundary?: boolean;
  shouldRevalidate?: ShouldRevalidateFunction;
  handle?: any;
  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;
};

/**
 * Index routes must not have children
 */
export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
  children?: undefined;
  index: true;
};

/**
 * Non-index routes may have children, but cannot have index
 */
export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
  children?: AgnosticRouteObject[];
  index?: false;
};

/**
 * A route object represents a logical route, with (optionally) its child
 * routes organized in a tree-like structure.
 */
export type AgnosticRouteObject =
  | AgnosticIndexRouteObject
  | AgnosticNonIndexRouteObject;

export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
  id: string;
};

export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
  children?: AgnosticDataRouteObject[];
  id: string;
};

/**
 * A data route object, which is just a RouteObject with a required unique ID
 */
export type AgnosticDataRouteObject =
  | AgnosticDataIndexRouteObject
  | AgnosticDataNonIndexRouteObject;

export type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;

// Recursive helper for finding path parameters in the absence of wildcards
type _PathParam<Path extends string> =
  // split path into individual path segments
  Path extends `${infer L}/${infer R}`
    ? _PathParam<L> | _PathParam<R>
    : // find params after `:`
    Path extends `:${infer Param}`
    ? Param extends `${infer Optional}?`
      ? Optional
      : Param
    : // otherwise, there aren't any params present
      never;

/**
 * Examples:
 * "/a/b/*" -> "*"
 * ":a" -> "a"
 * "/a/:b" -> "b"
 * "/a/blahblahblah:b" -> "b"
 * "/:a/:b" -> "a" | "b"
 * "/:a/b/:c/*" -> "a" | "c" | "*"
 */
export type PathParam<Path extends string> =
  // check if path is just a wildcard
  Path extends "*" | "/*"
    ? "*"
    : // look for wildcard at the end of the path
    Path extends `${infer Rest}/*`
    ? "*" | _PathParam<Rest>
    : // look for params in the absence of wildcards
      _PathParam<Path>;

// Attempt to parse the given string segment. If it fails, then just return the
// plain string type as a default fallback. Otherwise, return the union of the
// parsed string literals that were referenced as dynamic segments in the route.
export type ParamParseKey<Segment extends string> =
  // if you could not find path params, fallback to `string`
  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;

/**
 * The parameters that were parsed from the URL path.
 */
export type Params<Key extends string = string> = {
  readonly [key in Key]: string | undefined;
};

/**
 * A RouteMatch contains info about how a route matched a URL.
 */
export interface AgnosticRouteMatch<
  ParamKey extends string = string,
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
> {
  /**
   * The names and values of dynamic parameters in the URL.
   */
  params: Params<ParamKey>;
  /**
   * The portion of the URL pathname that was matched.
   */
  pathname: string;
  /**
   * The portion of the URL pathname that was matched before child routes.
   */
  pathnameBase: string;
  /**
   * The route object that was used to match.
   */
  route: RouteObjectType;
}

export interface AgnosticDataRouteMatch
  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}

function isIndexRoute(
  route: AgnosticRouteObject
): route is AgnosticIndexRouteObject {
  return route.index === true;
}

// Walk the route tree generating unique IDs where necessary, so we are working
// solely with AgnosticDataRouteObject's within the Router
export function convertRoutesToDataRoutes(
  routes: AgnosticRouteObject[],
  mapRouteProperties: MapRoutePropertiesFunction,
  parentPath: string[] = [],
  manifest: RouteManifest = {}
): AgnosticDataRouteObject[] {
  return routes.map((route, index) => {
    let treePath = [...parentPath, String(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: AgnosticDataIndexRouteObject = {
        ...route,
        ...mapRouteProperties(route),
        id,
      };
      manifest[id] = indexRoute;
      return indexRoute;
    } else {
      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {
        ...route,
        ...mapRouteProperties(route),
        id,
        children: undefined,
      };
      manifest[id] = pathOrLayoutRoute;

      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(
          route.children,
          mapRouteProperties,
          treePath,
          manifest
        );
      }

      return pathOrLayoutRoute;
    }
  });
}

/**
 * Matches the given routes to a location and returns the match data.
 *
 * @see https://reactrouter.com/v6/utils/match-routes
 */
export function matchRoutes<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
>(
  routes: RouteObjectType[],
  locationArg: Partial<Location> | string,
  basename = "/"
): AgnosticRouteMatch<string, RouteObjectType>[] | null {
  return matchRoutesImpl(routes, locationArg, basename, false);
}

export function matchRoutesImpl<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
>(
  routes: RouteObjectType[],
  locationArg: Partial<Location> | string,
  basename: string,
  allowPartial: boolean
): AgnosticRouteMatch<string, RouteObjectType>[] | null {
  let location =
    typeof locationArg === "string" ? parsePath(locationArg) : locationArg;

  let pathname = stripBasename(location.pathname || "/", basename);

  if (pathname == null) {
    return null;
  }

  let branches = flattenRoutes(routes);
  rankRouteBranches(branches);

  let matches = null;
  let decoded = decodePath(pathname);
  for (let i = 0; matches == null && i < branches.length; ++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.
    matches = matchRouteBranch<string, RouteObjectType>(
      branches[i],
      decoded,
      allowPartial
    );
  }

  return matches;
}

export interface UIMatch<Data = unknown, Handle = unknown> {
  id: string;
  pathname: string;
  params: AgnosticRouteMatch["params"];
  data: Data;
  handle: Handle;
}

export function convertRouteMatchToUiMatch(
  match: AgnosticDataRouteMatch,
  loaderData: RouteData
): UIMatch {
  let { route, pathname, params } = match;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    handle: route.handle,
  };
}

interface RouteMeta<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
> {
  relativePath: string;
  caseSensitive: boolean;
  childrenIndex: number;
  route: RouteObjectType;
}

interface RouteBranch<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
> {
  path: string;
  score: number;
  routesMeta: RouteMeta<RouteObjectType>[];
}

function flattenRoutes<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
>(
  routes: RouteObjectType[],
  branches: RouteBranch<RouteObjectType>[] = [],
  parentsMeta: RouteMeta<RouteObjectType>[] = [],
  parentPath = ""
): RouteBranch<RouteObjectType>[] {
  let flattenRoute = (
    route: RouteObjectType,
    index: number,
    relativePath?: string
  ) => {
    let meta: RouteMeta<RouteObjectType> = {
      relativePath:
        relativePath === undefined ? 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);

    // Add the children before adding this route to the array, so we traverse the
    // route tree depth-first and child routes appear before their parents in
    // the "flattened" version.
    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);
    }

    // Routes without a path shouldn't ever match by themselves unless they are
    // index routes, so don't add them to the list of possible branches.
    if (route.path == null && !route.index) {
      return;
    }

    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta,
    });
  };
  routes.forEach((route, index) => {
    // coarse-grain check for optional params
    if (route.path === "" || !route.path?.includes("?")) {
      flattenRoute(route, index);
    } else {
      for (let exploded of explodeOptionalSegments(route.path)) {
        flattenRoute(route, index, exploded);
      }
    }
  });

  return branches;
}

/**
 * Computes all combinations of optional path segments for a given path,
 * excluding combinations that are ambiguous and of lower priority.
 *
 * For example, `/one/:two?/three/:four?/:five?` explodes to:
 * - `/one/three`
 * - `/one/:two/three`
 * - `/one/three/:four`
 * - `/one/three/:five`
 * - `/one/:two/three/:four`
 * - `/one/:two/three/:five`
 * - `/one/three/:four/:five`
 * - `/one/:two/three/:four/:five`
 */
function explodeOptionalSegments(path: string): string[] {
  let segments = path.split("/");
  if (segments.length === 0) return [];

  let [first, ...rest] = segments;

  // Optional path segments are denoted by a trailing `?`
  let isOptional = first.endsWith("?");
  // Compute the corresponding required segment: `foo?` -> `foo`
  let required = first.replace(/\?$/, "");

  if (rest.length === 0) {
    // Intepret empty string as omitting an optional segment
    // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
    return isOptional ? [required, ""] : [required];
  }

  let restExploded = explodeOptionalSegments(rest.join("/"));

  let result: string[] = [];

  // All child paths with the prefix.  Do this for all children before the
  // optional version for all children, so we get consistent ordering where the
  // parent optional aspect is preferred as required.  Otherwise, we can get
  // child sections interspersed where deeper optional segments are higher than
  // parent optional segments, where for example, /:two would explode _earlier_
  // then /:one.  By always including the parent as required _for all children_
  // first, we avoid this issue
  result.push(
    ...restExploded.map((subpath) =>
      subpath === "" ? required : [required, subpath].join("/")
    )
  );

  // Then, if this is an optional value, add all child versions without
  if (isOptional) {
    result.push(...restExploded);
  }

  // for absolute paths, ensure `/` instead of empty segment
  return result.map((exploded) =>
    path.startsWith("/") && exploded === "" ? "/" : exploded
  );
}

function rankRouteBranches(branches: RouteBranch[]): void {
  branches.sort((a, b) =>
    a.score !== b.score
      ? b.score - a.score // Higher score first
      : compareIndexes(
          a.routesMeta.map((meta) => meta.childrenIndex),
          b.routesMeta.map((meta) => meta.childrenIndex)
        )
  );
}

const paramRe = /^:[\w-]+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = (s: string) => s === "*";

function computeScore(path: string, index: boolean | undefined): number {
  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: number[], b: number[]): number {
  let siblings =
    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[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] - b[b.length - 1]
    : // Otherwise, it doesn't really make sense to rank non-siblings by index,
      // so they sort equally.
      0;
}

function matchRouteBranch<
  ParamKey extends string = string,
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
>(
  branch: RouteBranch<RouteObjectType>,
  pathname: string,
  allowPartial = false
): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {
  let { routesMeta } = branch;

  let matchedParams = {};
  let matchedPathname = "/";
  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];
  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
    );

    let route = meta.route;

    if (
      !match &&
      end &&
      allowPartial &&
      !routesMeta[routesMeta.length - 1].route.index
    ) {
      match = matchPath(
        {
          path: meta.relativePath,
          caseSensitive: meta.caseSensitive,
          end: false,
        },
        remainingPathname
      );
    }

    if (!match) {
      return null;
    }

    Object.assign(matchedParams, match.params);

    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams as Params<ParamKey>,
      pathname: joinPaths([matchedPathname, match.pathname]),
      pathnameBase: normalizePathname(
        joinPaths([matchedPathname, match.pathnameBase])
      ),
      route,
    });

    if (match.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
    }
  }

  return matches;
}

/**
 * Returns a path with params interpolated.
 *
 * @see https://reactrouter.com/v6/utils/generate-path
 */
export function generatePath<Path extends string>(
  originalPath: Path,
  params: {
    [key in PathParam<Path>]: string | null;
  } = {} as any
): string {
  let path: string = 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(/\*$/, "/*") as Path;
  }

  // ensure `/` is added at the beginning if the path is absolute
  const prefix = path.startsWith("/") ? "/" : "";

  const stringify = (p: any) =>
    p == null ? "" : typeof p === "string" ? p : String(p);

  const segments = path
    .split(/\/+/)
    .map((segment, index, array) => {
      const isLastSegment = index === array.length - 1;

      // only apply the splat if it's the last segment
      if (isLastSegment && segment === "*") {
        const star = "*" as PathParam<Path>;
        // Apply the splat
        return stringify(params[star]);
      }

      const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
      if (keyMatch) {
        const [, key, optional] = keyMatch;
        let param = params[key as PathParam<Path>];
        invariant(optional === "?" || param != null, `Missing ":${key}" param`);
        return stringify(param);
      }

      // Remove any optional markers from optional static segments
      return segment.replace(/\?$/g, "");
    })
    // Remove empty segments
    .filter((segment) => !!segment);

  return prefix + segments.join("/");
}

/**
 * A PathPattern is used to match on some portion of a URL pathname.
 */
export interface PathPattern<Path extends string = string> {
  /**
   * A string to match against a URL pathname. May contain `:id`-style segments
   * to indicate placeholders for dynamic parameters. May also end with `/*` to
   * indicate matching the rest of the URL pathname.
   */
  path: Path;
  /**
   * Should be `true` if the static portions of the `path` should be matched in
   * the same case.
   */
  caseSensitive?: boolean;
  /**
   * Should be `true` if this pattern should match the entire URL pathname.
   */
  end?: boolean;
}

/**
 * A PathMatch contains info about how a PathPattern matched on a URL pathname.
 */
export interface PathMatch<ParamKey extends string = string> {
  /**
   * The names and values of dynamic parameters in the URL.
   */
  params: Params<ParamKey>;
  /**
   * The portion of the URL pathname that was matched.
   */
  pathname: string;
  /**
   * The portion of the URL pathname that was matched before child routes.
   */
  pathnameBase: string;
  /**
   * The pattern that was used to match.
   */
  pattern: PathPattern;
}

type Mutable<T> = {
  -readonly [P in keyof T]: T[P];
};

/**
 * Performs pattern matching on a URL pathname and returns information about
 * the match.
 *
 * @see https://reactrouter.com/v6/utils/match-path
 */
export function matchPath<
  ParamKey extends ParamParseKey<Path>,
  Path extends string
>(
  pattern: PathPattern<Path> | Path,
  pathname: string
): PathMatch<ParamKey> | null {
  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: Params = compiledParams.reduce<Mutable<Params>>(
    (memo, { paramName, isOptional }, index) => {
      // We need to compute the pathnameBase here using the raw splat value
      // instead of using params["*"] later because it will be decoded then
      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] = undefined;
      } else {
        memo[paramName] = (value || "").replace(/%2F/g, "/");
      }
      return memo;
    },
    {}
  );

  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern,
  };
}

type CompiledPathParam = { paramName: string; isOptional?: boolean };

function compilePath(
  path: string,
  caseSensitive = false,
  end = true
): [RegExp, CompiledPathParam[]] {
  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: CompiledPathParam[] = [];
  let regexpSource =
    "^" +
    path
      .replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
      .replace(/^\/*/, "/") // Make sure it has a leading /
      .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
      .replace(
        /\/:([\w-]+)(\?)?/g,
        (_: string, paramName: string, isOptional) => {
          params.push({ paramName, isOptional: isOptional != null });
          return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
        }
      );

  if (path.endsWith("*")) {
    params.push({ paramName: "*" });
    regexpSource +=
      path === "*" || path === "/*"
        ? "(.*)$" // Already matched the initial /, just match the rest
        : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  } else if (end) {
    // When matching to the end, ignore trailing slashes
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    // If our path is non-empty and contains anything beyond an initial slash,
    // then we have _some_ form of path in our regex, so we should expect to
    // match only if we find the end of this path segment.  Look for an optional
    // non-captured trailing slash (to match a portion of the URL) or the end
    // of the path (if we've matched to the end).  We used to do this with a
    // word boundary but that gives false positives on routes like
    // /user-preferences since `-` counts as a word boundary.
    regexpSource += "(?:(?=\\/|$))";
  } else {
    // Nothing to match for "" or "/"
  }

  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");

  return [matcher, params];
}

export function decodePath(value: string) {
  try {
    return value
      .split("/")
      .map((v) => decodeURIComponent(v).replace(/\//g, "%2F"))
      .join("/");
  } catch (error) {
    warning(
      false,
      `The URL path "${value}" could not be decoded because it is is a ` +
        `malformed URL segment. This is probably due to a bad percent ` +
        `encoding (${error}).`
    );

    return value;
  }
}

/**
 * @private
 */
export function stripBasename(
  pathname: string,
  basename: string
): string | null {
  if (basename === "/") return pathname;

  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
    return null;
  }

  // We want to leave trailing slash behavior in the user's control, so if they
  // specify a basename with a trailing slash, we should support it
  let startIndex = basename.endsWith("/")
    ? basename.length - 1
    : basename.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    // pathname does not start with basename/
    return null;
  }

  return pathname.slice(startIndex) || "/";
}

const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
export const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);

/**
 * Returns a resolved path object relative to the given pathname.
 *
 * @see https://reactrouter.com/v6/utils/resolve-path
 */
export function resolvePath(to: To, fromPathname = "/"): Path {
  let {
    pathname: toPathname,
    search = "",
    hash = "",
  } = typeof to === "string" ? parsePath(to) : to;

  let pathname: string;
  if (toPathname) {
    toPathname = removeDoubleSlashes(toPathname);
    if (toPathname.startsWith("/")) {
      pathname = resolvePathname(toPathname.substring(1), "/");
    } else {
      pathname = resolvePathname(toPathname, fromPathname);
    }
  } else {
    pathname = fromPathname;
  }

  return {
    pathname,
    search: normalizeSearch(search),
    hash: normalizeHash(hash),
  };
}

function resolvePathname(relativePath: string, fromPathname: string): string {
  let segments = fromPathname.replace(/\/+$/, "").split("/");
  let relativeSegments = relativePath.split("/");

  relativeSegments.forEach((segment) => {
    if (segment === "..") {
      // Keep the root "" segment so the pathname starts at /
      if (segments.length > 1) segments.pop();
    } else if (segment !== ".") {
      segments.push(segment);
    }
  });

  return segments.length > 1 ? segments.join("/") : "/";
}

function getInvalidPathError(
  char: string,
  field: string,
  dest: string,
  path: Partial<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 <Link to="..."> and the router will parse it for you.`
  );
}

/**
 * @private
 *
 * When processing relative navigation we want to ignore ancestor routes that
 * do not contribute to the path, such that index/pathless layout routes don't
 * interfere.
 *
 * For example, when moving a route element into an index route and/or a
 * pathless layout route, relative link behavior contained within should stay
 * the same.  Both of the following examples should link back to the root:
 *
 *   <Route path="/">
 *     <Route path="accounts" element={<Link to=".."}>
 *   </Route>
 *
 *   <Route path="/">
 *     <Route path="accounts">
 *       <Route element={<AccountsLayout />}>       // <-- Does not contribute
 *         <Route index element={<Link to=".."} />  // <-- Does not contribute
 *       </Route
 *     </Route>
 *   </Route>
 */
export function getPathContributingMatches<
  T extends AgnosticRouteMatch = AgnosticRouteMatch
>(matches: T[]) {
  return matches.filter(
    (match, index) =>
      index === 0 || (match.route.path && match.route.path.length > 0)
  );
}

// Return the array of pathnames for the current route matches - used to
// generate the routePathnames input for resolveTo()
export function getResolveToMatches<
  T extends AgnosticRouteMatch = AgnosticRouteMatch
>(matches: T[], v7_relativeSplatPath: boolean) {
  let pathMatches = getPathContributingMatches(matches);

  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
  // match so we include splat values for "." links.  See:
  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
  if (v7_relativeSplatPath) {
    return pathMatches.map((match, idx) =>
      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
    );
  }

  return pathMatches.map((match) => match.pathnameBase);
}

/**
 * @private
 */
export function resolveTo(
  toArg: To,
  routePathnames: string[],
  locationPathname: string,
  isPathRelative = false
): Path {
  let to: Partial<Path>;
  if (typeof toArg === "string") {
    to = parsePath(toArg);
  } else {
    to = { ...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: string;

  // Routing is relative to the current pathname if explicitly requested.
  //
  // If a pathname is explicitly provided in `to`, it should be relative to the
  // route context. This is explained in `Note on `<Link to>` values` in our
  // migration guide from v5 as a means of disambiguation between `to` values
  // that begin with `/` and those that do not. However, this is problematic for
  // `to` values that do not provide a pathname. `to` can simply be a search or
  // hash string, in which case we should assume that the navigation is relative
  // to the current location's pathname and *not* the route pathname.
  if (toPathname == null) {
    from = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;

    // With relative="route" (the default), each leading .. segment means
    // "go up one route" instead of "go up one URL segment".  This is a key
    // difference from how <a href> works and a major reason we call this a
    // "to" value instead of a "href".
    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);

  // Ensure the pathname has a trailing slash if the original "to" had one
  let hasExplicitTrailingSlash =
    toPathname && toPathname !== "/" && toPathname.endsWith("/");
  // Or if this was a link to the current path which has a trailing slash
  let hasCurrentTrailingSlash =
    (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (
    !path.pathname.endsWith("/") &&
    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)
  ) {
    path.pathname += "/";
  }

  return path;
}

/**
 * @private
 */
export function getToPathname(to: To): string | undefined {
  // Empty strings should be treated the same as / paths
  return to === "" || (to as Path).pathname === ""
    ? "/"
    : typeof to === "string"
    ? parsePath(to).pathname
    : to.pathname;
}

export const removeDoubleSlashes = (path: string): string =>
  path.replace(/\/\/+/g, "/");

/**
 * @private
 */
export const joinPaths = (paths: string[]): string =>
  removeDoubleSlashes(paths.join("/"));

/**
 * @private
 */
export const normalizePathname = (pathname: string): string =>
  pathname.replace(/\/+$/, "").replace(/^\/*/, "/");

/**
 * @private
 */
export const normalizeSearch = (search: string): string =>
  !search || search === "?"
    ? ""
    : search.startsWith("?")
    ? search
    : "?" + search;

/**
 * @private
 */
export const normalizeHash = (hash: string): string =>
  !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;

export type JsonFunction = <Data>(
  data: Data,
  init?: number | ResponseInit
) => Response;

/**
 * This is a shortcut for creating `application/json` responses. Converts `data`
 * to JSON and sets the `Content-Type` header.
 *
 * @deprecated The `json` method is deprecated in favor of returning raw objects.
 * This method will be removed in v7.
 */
export const json: JsonFunction = (data, 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), {
    ...responseInit,
    headers,
  });
};

export class DataWithResponseInit<D> {
  type: string = "DataWithResponseInit";
  data: D;
  init: ResponseInit | null;

  constructor(data: D, init?: ResponseInit) {
    this.data = data;
    this.init = init || null;
  }
}

/**
 * Create "responses" that contain `status`/`headers` without forcing
 * serialization into an actual `Response` - used by Remix single fetch
 */
export function data<D>(data: D, init?: number | ResponseInit) {
  return new DataWithResponseInit(
    data,
    typeof init === "number" ? { status: init } : init
  );
}

export interface TrackedPromise extends Promise<any> {
  _tracked?: boolean;
  _data?: any;
  _error?: any;
}

export class AbortedDeferredError extends Error {}

export class DeferredData {
  private pendingKeysSet: Set<string> = new Set<string>();
  private controller: AbortController;
  private abortPromise: Promise<void>;
  private unlistenAbortSignal: () => void;
  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =
    new Set();
  data: Record<string, unknown>;
  init?: ResponseInit;
  deferredKeys: string[] = [];

  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {
    invariant(
      data && typeof data === "object" && !Array.isArray(data),
      "defer() only accepts plain objects"
    );

    // Set up an AbortController + Promise we can race against to exit early
    // cancellation
    let reject: (e: AbortedDeferredError) => void;
    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, [key, value]) =>
        Object.assign(acc, {
          [key]: this.trackPromise(key, value),
        }),
      {}
    );

    if (this.done) {
      // All incoming values were resolved
      this.unlistenAbortSignal();
    }

    this.init = responseInit;
  }

  private trackPromise(
    key: string,
    value: Promise<unknown> | unknown
  ): TrackedPromise | unknown {
    if (!(value instanceof Promise)) {
      return value;
    }

    this.deferredKeys.push(key);
    this.pendingKeysSet.add(key);

    // We store a little wrapper promise that will be extended with
    // _data/_error props upon resolve/reject
    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(
      (data) => this.onSettle(promise, key, undefined, data as unknown),
      (error) => this.onSettle(promise, key, error as unknown)
    );

    // Register rejection listeners to avoid uncaught promise rejections on
    // errors or aborted deferred values
    promise.catch(() => {});

    Object.defineProperty(promise, "_tracked", { get: () => true });
    return promise;
  }

  private onSettle(
    promise: TrackedPromise,
    key: string,
    error: unknown,
    data?: unknown
  ): unknown {
    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) {
      // Nothing left to abort!
      this.unlistenAbortSignal();
    }

    // If the promise was resolved/rejected with undefined, we'll throw an error as you
    // should always resolve with a value or null
    if (error === undefined && data === undefined) {
      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 === undefined) {
      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;
  }

  private emit(aborted: boolean, settledKey?: string) {
    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));
  }

  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {
    this.subscribers.add(fn);
    return () => this.subscribers.delete(fn);
  }

  cancel() {
    this.controller.abort();
    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
    this.emit(true);
  }

  async resolveData(signal: AbortSignal) {
    let aborted = false;
    if (!this.done) {
      let onAbort = () => this.cancel();
      signal.addEventListener("abort", onAbort);
      aborted = await new Promise((resolve) => {
        this.subscribe((aborted) => {
          signal.removeEventListener("abort", onAbort);
          if (aborted || this.done) {
            resolve(aborted);
          }
        });
      });
    }
    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, [key, value]) =>
        Object.assign(acc, {
          [key]: unwrapTrackedPromise(value),
        }),
      {}
    );
  }

  get pendingKeys() {
    return Array.from(this.pendingKeysSet);
  }
}

function isTrackedPromise(value: any): value is TrackedPromise {
  return (
    value instanceof Promise && (value as TrackedPromise)._tracked === true
  );
}

function unwrapTrackedPromise(value: any) {
  if (!isTrackedPromise(value)) {
    return value;
  }

  if (value._error) {
    throw value._error;
  }
  return value._data;
}

export type DeferFunction = (
  data: Record<string, unknown>,
  init?: number | ResponseInit
) => DeferredData;

/**
 * @deprecated The `defer` method is deprecated in favor of returning raw
 * objects. This method will be removed in v7.
 */
export const defer: DeferFunction = (data, init = {}) => {
  let responseInit = typeof init === "number" ? { status: init } : init;

  return new DeferredData(data, responseInit);
};

export type RedirectFunction = (
  url: string,
  init?: number | ResponseInit
) => Response;

/**
 * A redirect response. Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
export const redirect: RedirectFunction = (url, 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, {
    ...responseInit,
    headers,
  });
};

/**
 * A redirect response that will force a document reload to the new location.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
export const redirectDocument: RedirectFunction = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Reload-Document", "true");
  return response;
};

/**
 * A redirect response that will perform a `history.replaceState` instead of a
 * `history.pushState` for client-side navigation redirects.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
export const replace: RedirectFunction = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Replace", "true");
  return response;
};

export type ErrorResponse = {
  status: number;
  statusText: string;
  data: any;
};

/**
 * @private
 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
 *
 * We don't export the class for public use since it's an implementation
 * detail, but we export the interface above so folks can build their own
 * abstractions around instances via isRouteErrorResponse()
 */
export class ErrorResponseImpl implements ErrorResponse {
  status: number;
  statusText: string;
  data: any;
  private error?: Error;
  private internal: boolean;

  constructor(
    status: number,
    statusText: string | undefined,
    data: any,
    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;
    }
  }
}

/**
 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
 * Response thrown from an action/loader
 */
export function isRouteErrorResponse(error: any): error is ErrorResponse {
  return (
    error != null &&
    typeof error.status === "number" &&
    typeof error.statusText === "string" &&
    typeof error.internal === "boolean" &&
    "data" in error
  );
}
/**
 * @remix-run/router v1.23.4
 *
 * 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
 */
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}

////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////

/**
 * Actions represent the type of change to a location value.
 */
let Action = /*#__PURE__*/function (Action) {
  /**
   * A POP indicates a change to an arbitrary index in the history stack, such
   * as a back or forward navigation. It does not describe the direction of the
   * navigation, only that the current index changed.
   *
   * Note: This is the default action for newly created history objects.
   */
  Action["Pop"] = "POP";
  /**
   * A PUSH indicates a new entry being added to the history stack, such as when
   * a link is clicked and a new page loads. When this happens, all subsequent
   * entries in the stack are lost.
   */
  Action["Push"] = "PUSH";
  /**
   * A REPLACE indicates the entry at the current index in the history stack
   * being replaced by a new one.
   */
  Action["Replace"] = "REPLACE";
  return Action;
}({});

/**
 * The pathname, search, and hash values of a URL.
 */

// TODO: (v7) Change the Location generic default from `any` to `unknown` and
// remove Remix `useLocation` wrapper.

/**
 * An entry in a history stack. A location contains information about the
 * URL path, as well as possibly some arbitrary state and a key.
 */

/**
 * A change to the current location.
 */

/**
 * A function that receives notifications about location changes.
 */

/**
 * Describes a location that is the destination of some navigation, either via
 * `history.push` or `history.replace`. This may be either a URL or the pieces
 * of a URL path.
 */

/**
 * A history is an interface to the navigation stack. The history serves as the
 * source of truth for the current location, as well as provides a set of
 * methods that may be used to change it.
 *
 * It is similar to the DOM's `window.history` object, but with a smaller, more
 * focused API.
 */

const PopStateEventType = "popstate";
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Memory History
////////////////////////////////////////////////////////////////////////////////

/**
 * A user-supplied object that describes a location. Used when providing
 * entries to `createMemoryHistory` via its `initialEntries` option.
 */

/**
 * A memory history stores locations in memory. This is useful in stateful
 * environments where there is no web browser, such as node tests or React
 * Native.
 */

/**
 * Memory history stores the current location in memory. It is designed for use
 * in stateful non-browser environments like tests and React Native.
 */
function createMemoryHistory(options) {
  if (options === void 0) {
    options = {};
  }
  let {
    initialEntries = ["/"],
    initialIndex,
    v5Compat = false
  } = options;
  let entries; // Declare so we can access from createMemoryLocation
  entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
  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;
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Browser History
////////////////////////////////////////////////////////////////////////////////

/**
 * A browser history stores the current location in regular URLs in a web
 * browser environment. This is the standard for most web apps and provides the
 * cleanest URLs the browser's address bar.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
 */

/**
 * Browser history stores the location in regular URLs. This is the standard for
 * most web apps, but it requires some configuration on the server to ensure you
 * serve the same app at multiple URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
 */
function createBrowserHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createBrowserLocation(window, globalHistory) {
    let {
      pathname,
      search,
      hash
    } = window.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(window, to) {
    return typeof to === "string" ? to : createPath(to);
  }
  return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Hash History
////////////////////////////////////////////////////////////////////////////////

/**
 * A hash history stores the current location in the fragment identifier portion
 * of the URL in a web browser environment.
 *
 * This is ideal for apps that do not control the server for some reason
 * (because the fragment identifier is never sent to the server), including some
 * shared hosting environments that do not provide fine-grained controls over
 * which pages are served at which URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
 */

/**
 * Hash history stores the location in window.location.hash. This makes it ideal
 * for situations where you don't want to send the location to the server for
 * some reason, either because you do cannot configure it or the URL space is
 * reserved for something else.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
 */
function createHashHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createHashLocation(window, globalHistory) {
    let {
      pathname = "/",
      search = "",
      hash = ""
    } = parsePath(window.location.hash.substr(1));

    // Hash URL should always have a leading / just like window.location.pathname
    // does, so if an app ends up at a route like /#something then we add a
    // leading slash so all of our path-matching behaves the same as if it would
    // in a browser router.  This is particularly important when there exists a
    // root splat route (<Route path="*">) since that matches internally against
    // "/*" and we'd expect /#something to 404 in a hash router app.
    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(window, to) {
    let base = window.document.querySelector("base");
    let href = "";
    if (base && base.getAttribute("href")) {
      let url = window.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);
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region UTILS
////////////////////////////////////////////////////////////////////////////////

/**
 * @private
 */

function invariant(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}
function warning(cond, message) {
  if (!cond) {
    // eslint-disable-next-line no-console
    if (typeof console !== "undefined") console.warn(message);
    try {
      // Welcome to debugging history!
      //
      // This error is thrown as a convenience, so you can more easily
      // find the source for a warning that appears in the console by
      // enabling "pause on exceptions" in your JavaScript debugger.
      throw new Error(message);
      // eslint-disable-next-line no-empty
    } catch (e) {}
  }
}
function createKey() {
  return Math.random().toString(36).substr(2, 8);
}

/**
 * For browser-based histories, we combine the state and key into an object
 */
function getHistoryState(location, index) {
  return {
    usr: location.state,
    key: location.key,
    idx: index
  };
}

/**
 * Creates a Location object with a unique key from the given Path
 */
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;
}

/**
 * Creates a string URL path from the given pathname, search, and hash components.
 */
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;
}

/**
 * Parses a string URL path into its separate pathname, search, and hash components.
 */
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 = document.defaultView,
    v5Compat = false
  } = options;
  let globalHistory = window.history;
  let action = Action.Pop;
  let listener = null;
  let index = getIndex();
  // Index should only be null when we initialize. If not, it's because the
  // user called history.pushState or history.replaceState directly, in which
  // case we should log a warning as it will result in bugs.
  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...catch because iOS limits us to 100 pushState calls :/
    try {
      globalHistory.pushState(historyState, "", url);
    } catch (error) {
      // If the exception is because `state` can't be serialized, let that throw
      // outwards just like a replace call would so the dev knows the cause
      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
      if (error instanceof DOMException && error.name === "DataCloneError") {
        throw error;
      }
      // They are going to lose state here, but there is no real
      // way to warn them about it since the page will refresh...
      window.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) {
    // window.location.origin is "null" (the literal string value) in Firefox
    // under certain conditions, notably when serving from a local HTML file
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
    let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
    let href = typeof to === "string" ? to : createPath(to);
    // Treating this as a full URL will strip any trailing spaces so we need to
    // pre-encode them since they might be part of a matching splat param from
    // an ancestor route
    href = href.replace(/ $/, "%20");
    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(window, globalHistory);
    },
    listen(fn) {
      if (listener) {
        throw new Error("A history only accepts one active listener");
      }
      window.addEventListener(PopStateEventType, handlePop);
      listener = fn;
      return () => {
        window.removeEventListener(PopStateEventType, handlePop);
        listener = null;
      };
    },
    createHref(to) {
      return createHref(window, to);
    },
    createURL,
    encodeLocation(to) {
      // Encode a Location the same way window.location would
      let url = createURL(to);
      return {
        pathname: url.pathname,
        search: url.search,
        hash: url.hash
      };
    },
    push,
    replace,
    go(n) {
      return globalHistory.go(n);
    }
  };
  return history;
}

//#endregion

/**
 * Map of routeId -> data returned from a loader/action/error
 */

let ResultType = /*#__PURE__*/function (ResultType) {
  ResultType["data"] = "data";
  ResultType["deferred"] = "deferred";
  ResultType["redirect"] = "redirect";
  ResultType["error"] = "error";
  return ResultType;
}({});

/**
 * Successful result from a loader or action
 */

/**
 * Successful defer() result from a loader or action
 */

/**
 * Redirect result from a loader or action
 */

/**
 * Unsuccessful result from a loader or action
 */

/**
 * Result from a loader or action - potentially successful or unsuccessful
 */

/**
 * Users can specify either lowercase or uppercase form methods on `<Form>`,
 * useSubmit(), `<fetcher.Form>`, etc.
 */

/**
 * Active navigation/fetcher form methods are exposed in lowercase on the
 * RouterState
 */

/**
 * In v7, active navigation/fetcher form methods are exposed in uppercase on the
 * RouterState.  This is to align with the normalization done via fetch().
 */

// Thanks https://github.com/sindresorhus/type-fest!

/**
 * @private
 * Internal interface to pass around for action submissions, not intended for
 * external consumption
 */

/**
 * @private
 * Arguments passed to route loader/action functions.  Same for now but we keep
 * this as a private implementation detail in case they diverge in the future.
 */

// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
//   Also, make them a type alias instead of an interface

/**
 * Arguments passed to loader functions
 */

/**
 * Arguments passed to action functions
 */

/**
 * Loaders and actions can return anything except `undefined` (`null` is a
 * valid return value if there is no data to return).  Responses are preferred
 * and will ease any future migration to Remix
 */

/**
 * Route loader function signature
 */

/**
 * Route action function signature
 */

/**
 * Arguments passed to shouldRevalidate function
 */

/**
 * Route shouldRevalidate function signature.  This runs after any submission
 * (navigation or fetcher), so we flatten the navigation/fetcher submission
 * onto the arguments.  It shouldn't matter whether it came from a navigation
 * or a fetcher, what really matters is the URLs and the formData since loaders
 * have to re-run based on the data models that were potentially mutated.
 */

/**
 * Function provided by the framework-aware layers to set `hasErrorBoundary`
 * from the framework-aware `errorElement` prop
 *
 * @deprecated Use `mapRouteProperties` instead
 */

/**
 * Result from a loader or action called via dataStrategy
 */

/**
 * Function provided by the framework-aware layers to set any framework-specific
 * properties from framework-agnostic properties
 */

/**
 * Keys we cannot change from within a lazy() function. We spread all other keys
 * onto the route. Either they're meaningful to the router, or they'll get
 * ignored.
 */

const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);

/**
 * lazy() function to load a route definition, which can add non-matching
 * related properties to a route
 */

/**
 * Base RouteObject with common props shared by all types of routes
 */

/**
 * Index routes must not have children
 */

/**
 * Non-index routes may have children, but cannot have index
 */

/**
 * A route object represents a logical route, with (optionally) its child
 * routes organized in a tree-like structure.
 */

/**
 * A data route object, which is just a RouteObject with a required unique ID
 */

// Recursive helper for finding path parameters in the absence of wildcards

/**
 * Examples:
 * "/a/b/*" -> "*"
 * ":a" -> "a"
 * "/a/:b" -> "b"
 * "/a/blahblahblah:b" -> "b"
 * "/:a/:b" -> "a" | "b"
 * "/:a/b/:c/*" -> "a" | "c" | "*"
 */

// Attempt to parse the given string segment. If it fails, then just return the
// plain string type as a default fallback. Otherwise, return the union of the
// parsed string literals that were referenced as dynamic segments in the route.

/**
 * The parameters that were parsed from the URL path.
 */

/**
 * A RouteMatch contains info about how a route matched a URL.
 */

function isIndexRoute(route) {
  return route.index === true;
}

// Walk the route tree generating unique IDs where necessary, so we are working
// solely with AgnosticDataRouteObject's within the Router
function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  if (manifest === void 0) {
    manifest = {};
  }
  return routes.map((route, index) => {
    let treePath = [...parentPath, String(index)];
    let id = typeof route.id === "string" ? route.id : treePath.join("-");
    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: undefined
      });
      manifest[id] = pathOrLayoutRoute;
      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
      }
      return pathOrLayoutRoute;
    }
  });
}

/**
 * Matches the given routes to a location and returns the match data.
 *
 * @see https://reactrouter.com/v6/utils/match-routes
 */
function matchRoutes(routes, locationArg, basename) {
  if (basename === void 0) {
    basename = "/";
  }
  return matchRoutesImpl(routes, locationArg, basename, false);
}
function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  let pathname = stripBasename(location.pathname || "/", basename);
  if (pathname == null) {
    return null;
  }
  let branches = flattenRoutes(routes);
  rankRouteBranches(branches);
  let matches = null;
  let decoded = decodePath(pathname);
  for (let i = 0; matches == null && i < branches.length; ++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.
    matches = matchRouteBranch(branches[i], decoded, allowPartial);
  }
  return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
  let {
    route,
    pathname,
    params
  } = match;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    handle: route.handle
  };
}
function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  if (branches === void 0) {
    branches = [];
  }
  if (parentsMeta === void 0) {
    parentsMeta = [];
  }
  if (parentPath === void 0) {
    parentPath = "";
  }
  let flattenRoute = (route, index, relativePath) => {
    let meta = {
      relativePath: relativePath === undefined ? 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);

    // Add the children before adding this route to the array, so we traverse the
    // route tree depth-first and child routes appear before their parents in
    // the "flattened" version.
    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);
    }

    // Routes without a path shouldn't ever match by themselves unless they are
    // index routes, so don't add them to the list of possible branches.
    if (route.path == null && !route.index) {
      return;
    }
    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta
    });
  };
  routes.forEach((route, index) => {
    var _route$path;
    // coarse-grain check for optional params
    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;
}

/**
 * Computes all combinations of optional path segments for a given path,
 * excluding combinations that are ambiguous and of lower priority.
 *
 * For example, `/one/:two?/three/:four?/:five?` explodes to:
 * - `/one/three`
 * - `/one/:two/three`
 * - `/one/three/:four`
 * - `/one/three/:five`
 * - `/one/:two/three/:four`
 * - `/one/:two/three/:five`
 * - `/one/three/:four/:five`
 * - `/one/:two/three/:four/:five`
 */
function explodeOptionalSegments(path) {
  let segments = path.split("/");
  if (segments.length === 0) return [];
  let [first, ...rest] = segments;

  // Optional path segments are denoted by a trailing `?`
  let isOptional = first.endsWith("?");
  // Compute the corresponding required segment: `foo?` -> `foo`
  let required = first.replace(/\?$/, "");
  if (rest.length === 0) {
    // Intepret empty string as omitting an optional segment
    // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
    return isOptional ? [required, ""] : [required];
  }
  let restExploded = explodeOptionalSegments(rest.join("/"));
  let result = [];

  // All child paths with the prefix.  Do this for all children before the
  // optional version for all children, so we get consistent ordering where the
  // parent optional aspect is preferred as required.  Otherwise, we can get
  // child sections interspersed where deeper optional segments are higher than
  // parent optional segments, where for example, /:two would explode _earlier_
  // then /:one.  By always including the parent as required _for all children_
  // first, we avoid this issue
  result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));

  // Then, if this is an optional value, add all child versions without
  if (isOptional) {
    result.push(...restExploded);
  }

  // for absolute paths, ensure `/` instead of empty segment
  return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
  branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
  : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
}
const paramRe = /^:[\w-]+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = s => s === "*";
function computeScore(path, index) {
  let segments = path.split("/");
  let initialScore = segments.length;
  if (segments.some(isSplat)) {
    initialScore += splatPenalty;
  }
  if (index) {
    initialScore += indexRouteValue;
  }
  return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
  let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[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] - b[b.length - 1] :
  // Otherwise, it doesn't really make sense to rank non-siblings by index,
  // so they sort equally.
  0;
}
function matchRouteBranch(branch, pathname, allowPartial) {
  if (allowPartial === void 0) {
    allowPartial = false;
  }
  let {
    routesMeta
  } = branch;
  let matchedParams = {};
  let matchedPathname = "/";
  let matches = [];
  for (let 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);
    let route = meta.route;
    if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
      match = matchPath({
        path: meta.relativePath,
        caseSensitive: meta.caseSensitive,
        end: false
      }, remainingPathname);
    }
    if (!match) {
      return null;
    }
    Object.assign(matchedParams, match.params);
    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams,
      pathname: joinPaths([matchedPathname, match.pathname]),
      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
      route
    });
    if (match.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
    }
  }
  return matches;
}

/**
 * Returns a path with params interpolated.
 *
 * @see https://reactrouter.com/v6/utils/generate-path
 */
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(/\*$/, "/*");
  }

  // ensure `/` is added at the beginning if the path is absolute
  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;

    // only apply the splat if it's the last segment
    if (isLastSegment && segment === "*") {
      const star = "*";
      // Apply the splat
      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);
    }

    // Remove any optional markers from optional static segments
    return segment.replace(/\?$/g, "");
  })
  // Remove empty segments
  .filter(segment => !!segment);
  return prefix + segments.join("/");
}

/**
 * A PathPattern is used to match on some portion of a URL pathname.
 */

/**
 * A PathMatch contains info about how a PathPattern matched on a URL pathname.
 */

/**
 * Performs pattern matching on a URL pathname and returns information about
 * the match.
 *
 * @see https://reactrouter.com/v6/utils/match-path
 */
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;
    // We need to compute the pathnameBase here using the raw splat value
    // instead of using params["*"] later because it will be decoded then
    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] = undefined;
    } else {
      memo[paramName] = (value || "").replace(/%2F/g, "/");
    }
    return memo;
  }, {});
  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern
  };
}
function compilePath(path, caseSensitive, end) {
  if (caseSensitive === void 0) {
    caseSensitive = false;
  }
  if (end === void 0) {
    end = true;
  }
  warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
  let params = [];
  let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
  .replace(/^\/*/, "/") // Make sure it has a leading /
  .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
  .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
    params.push({
      paramName,
      isOptional: isOptional != null
    });
    return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  });
  if (path.endsWith("*")) {
    params.push({
      paramName: "*"
    });
    regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
    : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  } else if (end) {
    // When matching to the end, ignore trailing slashes
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    // If our path is non-empty and contains anything beyond an initial slash,
    // then we have _some_ form of path in our regex, so we should expect to
    // match only if we find the end of this path segment.  Look for an optional
    // non-captured trailing slash (to match a portion of the URL) or the end
    // of the path (if we've matched to the end).  We used to do this with a
    // word boundary but that gives false positives on routes like
    // /user-preferences since `-` counts as a word boundary.
    regexpSource += "(?:(?=\\/|$))";
  } else ;
  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
  return [matcher, params];
}
function decodePath(value) {
  try {
    return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  } catch (error) {
    warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
    return value;
  }
}

/**
 * @private
 */
function stripBasename(pathname, basename) {
  if (basename === "/") return pathname;
  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
    return null;
  }

  // We want to leave trailing slash behavior in the user's control, so if they
  // specify a basename with a trailing slash, we should support it
  let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    // pathname does not start with basename/
    return null;
  }
  return pathname.slice(startIndex) || "/";
}

/**
 * Returns a resolved path object relative to the given pathname.
 *
 * @see https://reactrouter.com/v6/utils/resolve-path
 */
function resolvePath(to, fromPathname) {
  if (fromPathname === void 0) {
    fromPathname = "/";
  }
  let {
    pathname: toPathname,
    search = "",
    hash = ""
  } = typeof to === "string" ? parsePath(to) : to;
  let pathname;
  if (toPathname) {
    toPathname = removeDoubleSlashes(toPathname);
    if (toPathname.startsWith("/")) {
      pathname = resolvePathname(toPathname.substring(1), "/");
    } else {
      pathname = resolvePathname(toPathname, fromPathname);
    }
  } else {
    pathname = 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 === "..") {
      // Keep the root "" segment so the pathname starts at /
      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 <Link to=\"...\"> and the router will parse it for you.";
}

/**
 * @private
 *
 * When processing relative navigation we want to ignore ancestor routes that
 * do not contribute to the path, such that index/pathless layout routes don't
 * interfere.
 *
 * For example, when moving a route element into an index route and/or a
 * pathless layout route, relative link behavior contained within should stay
 * the same.  Both of the following examples should link back to the root:
 *
 *   <Route path="/">
 *     <Route path="accounts" element={<Link to=".."}>
 *   </Route>
 *
 *   <Route path="/">
 *     <Route path="accounts">
 *       <Route element={<AccountsLayout />}>       // <-- Does not contribute
 *         <Route index element={<Link to=".."} />  // <-- Does not contribute
 *       </Route
 *     </Route>
 *   </Route>
 */
function getPathContributingMatches(matches) {
  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}

// Return the array of pathnames for the current route matches - used to
// generate the routePathnames input for resolveTo()
function getResolveToMatches(matches, v7_relativeSplatPath) {
  let pathMatches = getPathContributingMatches(matches);

  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
  // match so we include splat values for "." links.  See:
  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
  if (v7_relativeSplatPath) {
    return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
  }
  return pathMatches.map(match => match.pathnameBase);
}

/**
 * @private
 */
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;

  // Routing is relative to the current pathname if explicitly requested.
  //
  // If a pathname is explicitly provided in `to`, it should be relative to the
  // route context. This is explained in `Note on `<Link to>` values` in our
  // migration guide from v5 as a means of disambiguation between `to` values
  // that begin with `/` and those that do not. However, this is problematic for
  // `to` values that do not provide a pathname. `to` can simply be a search or
  // hash string, in which case we should assume that the navigation is relative
  // to the current location's pathname and *not* the route pathname.
  if (toPathname == null) {
    from = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;

    // With relative="route" (the default), each leading .. segment means
    // "go up one route" instead of "go up one URL segment".  This is a key
    // difference from how <a href> works and a major reason we call this a
    // "to" value instead of a "href".
    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);

  // Ensure the pathname has a trailing slash if the original "to" had one
  let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  // Or if this was a link to the current path which has a trailing slash
  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
    path.pathname += "/";
  }
  return path;
}

/**
 * @private
 */
function getToPathname(to) {
  // Empty strings should be treated the same as / paths
  return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
}
const removeDoubleSlashes = path => path.replace(/\/\/+/g, "/");

/**
 * @private
 */
const joinPaths = paths => removeDoubleSlashes(paths.join("/"));

/**
 * @private
 */
const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");

/**
 * @private
 */
const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;

/**
 * @private
 */
const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
/**
 * This is a shortcut for creating `application/json` responses. Converts `data`
 * to JSON and sets the `Content-Type` header.
 *
 * @deprecated The `json` method is deprecated in favor of returning raw objects.
 * This method will be removed in v7.
 */
const json = function json(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
  }));
};
class DataWithResponseInit {
  constructor(data, init) {
    this.type = "DataWithResponseInit";
    this.data = data;
    this.init = init || null;
  }
}

/**
 * Create "responses" that contain `status`/`headers` without forcing
 * serialization into an actual `Response` - used by Remix single fetch
 */
function data(data, init) {
  return new DataWithResponseInit(data, typeof init === "number" ? {
    status: init
  } : init);
}
class AbortedDeferredError extends Error {}
class DeferredData {
  constructor(data, responseInit) {
    this.pendingKeysSet = new Set();
    this.subscribers = new Set();
    this.deferredKeys = [];
    invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");

    // Set up an AbortController + Promise we can race against to exit early
    // cancellation
    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) {
      // All incoming values were resolved
      this.unlistenAbortSignal();
    }
    this.init = responseInit;
  }
  trackPromise(key, value) {
    if (!(value instanceof Promise)) {
      return value;
    }
    this.deferredKeys.push(key);
    this.pendingKeysSet.add(key);

    // We store a little wrapper promise that will be extended with
    // _data/_error props upon resolve/reject
    let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));

    // Register rejection listeners to avoid uncaught promise rejections on
    // errors or aborted deferred values
    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) {
      // Nothing left to abort!
      this.unlistenAbortSignal();
    }

    // If the promise was resolved/rejected with undefined, we'll throw an error as you
    // should always resolve with a value or null
    if (error === undefined && data === undefined) {
      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 === undefined) {
      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, k) => this.pendingKeysSet.delete(k));
    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(aborted => {
          signal.removeEventListener("abort", onAbort);
          if (aborted || this.done) {
            resolve(aborted);
          }
        });
      });
    }
    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);
  }
}
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;
}
/**
 * @deprecated The `defer` method is deprecated in favor of returning raw
 * objects. This method will be removed in v7.
 */
const defer = function defer(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  return new DeferredData(data, responseInit);
};
/**
 * A redirect response. Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirect = function redirect(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
  }));
};

/**
 * A redirect response that will force a document reload to the new location.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirectDocument = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Reload-Document", "true");
  return response;
};

/**
 * A redirect response that will perform a `history.replaceState` instead of a
 * `history.pushState` for client-side navigation redirects.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const replace = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Replace", "true");
  return response;
};
/**
 * @private
 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
 *
 * We don't export the class for public use since it's an implementation
 * detail, but we export the interface above so folks can build their own
 * abstractions around instances via isRouteErrorResponse()
 */
class ErrorResponseImpl {
  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;
    }
  }
}

/**
 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
 * Response thrown from an action/loader
 */
function isRouteErrorResponse(error) {
  return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}

////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////

/**
 * A Router instance manages all navigation and data loading/mutations
 */

/**
 * State maintained internally by the router.  During a navigation, all states
 * reflect the the "old" location unless otherwise noted.
 */

/**
 * Data that can be passed into hydrate a Router from SSR
 */

/**
 * Future flags to toggle new feature behavior
 */

/**
 * Initialization options for createRouter
 */

/**
 * State returned from a server-side query() call
 */

/**
 * A StaticHandler instance manages a singular SSR navigation/fetch event
 */

/**
 * Subscriber function signature for changes to router state
 */

/**
 * Function signature for determining the key to be used in scroll restoration
 * for a given location
 */

/**
 * Function signature for determining the current scroll position
 */

// Allowed for any navigation or fetch

// Only allowed for navigations

// Only allowed for submission navigations

/**
 * Options for a navigate() call for a normal (non-submission) navigation
 */

/**
 * Options for a navigate() call for a submission navigation
 */

/**
 * Options to pass to navigate() for a navigation
 */

/**
 * Options for a fetch() load
 */

/**
 * Options for a fetch() submission
 */

/**
 * Options to pass to fetch()
 */

/**
 * Potential states for state.navigation
 */

/**
 * Potential states for fetchers
 */

/**
 * Cached info for active fetcher.load() instances so they can participate
 * in revalidation
 */

/**
 * Identified fetcher.load() calls that need to be revalidated
 */

const validMutationMethodsArr = ["post", "put", "patch", "delete"];
const validMutationMethods = new Set(validMutationMethodsArr);
const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
const validRequestMethods = new Set(validRequestMethodsArr);
const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
const redirectPreserveMethodStatusCodes = new Set([307, 308]);
const IDLE_NAVIGATION = {
  state: "idle",
  location: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_FETCHER = {
  state: "idle",
  data: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_BLOCKER = {
  state: "unblocked",
  proceed: undefined,
  reset: undefined,
  location: undefined
};
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const defaultMapRouteProperties = route => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////

/**
 * Create a router and listen to history POP navigations
 */
function createRouter(init) {
  const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
  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) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = init.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }

  // Routes keyed by ID
  let manifest = {};
  // Routes in tree format for matching
  let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
  let inFlightDataRoutes;
  let basename = init.basename || "/";
  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;

  // Config driven behavior flags
  let future = _extends({
    v7_fetcherPersist: false,
    v7_normalizeFormMethod: false,
    v7_partialHydration: false,
    v7_prependBasename: false,
    v7_relativeSplatPath: false,
    v7_skipActionErrorRevalidation: false
  }, init.future);
  // Cleanup function for history
  let unlistenHistory = null;
  // Externally-provided functions to call on all state changes
  let subscribers = new Set();
  // Externally-provided object to hold scroll restoration locations during routing
  let savedScrollPositions = null;
  // Externally-provided function to get scroll restoration keys
  let getScrollRestorationKey = null;
  // Externally-provided function to get current scroll position
  let getScrollPosition = null;
  // One-time flag to control the initial hydration scroll restoration.  Because
  // we don't get the saved positions from <ScrollRestoration /> until _after_
  // the initial render, we need to manually trigger a separate updateState to
  // send along the restoreScrollPosition
  // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  // SSR did the initial scroll restoration.
  let initialScrollRestored = init.hydrationData != null;
  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  let initialMatchesIsFOW = false;
  let initialErrors = null;
  if (initialMatches == null && !patchRoutesOnNavigationImpl) {
    // If we do not match a user-provided-route, fall back to the root
    // to allow the error boundary to take over
    let error = getInternalRouterError(404, {
      pathname: init.history.location.pathname
    });
    let {
      matches,
      route
    } = getShortCircuitMatches(dataRoutes);
    initialMatches = matches;
    initialErrors = {
      [route.id]: error
    };
  }

  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
  // our initial match is a splat route, clear them out so we run through lazy
  // discovery on hydration in case there's a more accurate lazy route match.
  // In SSR apps (with `hydrationData`), we expect that the server will send
  // up the proper matched routes so we don't want to run lazy discovery on
  // initial hydration and want to hydrate into the splat route.
  if (initialMatches && !init.hydrationData) {
    let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
    if (fogOfWar.active) {
      initialMatches = null;
    }
  }
  let initialized;
  if (!initialMatches) {
    initialized = false;
    initialMatches = [];

    // If partial hydration and fog of war is enabled, we will be running
    // `patchRoutesOnNavigation` during hydration so include any partial matches as
    // the initial matches so we can properly render `HydrateFallback`'s
    if (future.v7_partialHydration) {
      let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
      if (fogOfWar.active && fogOfWar.matches) {
        initialMatchesIsFOW = true;
        initialMatches = fogOfWar.matches;
      }
    }
  } else if (initialMatches.some(m => m.route.lazy)) {
    // All initialMatches need to be loaded before we're ready.  If we have lazy
    // functions around still then we'll need to run them in initialize()
    initialized = false;
  } else if (!initialMatches.some(m => m.route.loader)) {
    // If we've got no loaders to run, then we're good to go
    initialized = true;
  } else if (future.v7_partialHydration) {
    // If partial hydration is enabled, we're initialized so long as we were
    // provided with hydrationData for every route with a loader, and no loaders
    // were marked for explicit hydration
    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
    let errors = init.hydrationData ? init.hydrationData.errors : null;
    // If errors exist, don't consider routes below the boundary
    if (errors) {
      let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
      initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
    } else {
      initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
    }
  } else {
    // Without partial hydration - we're initialized if we were provided any
    // hydrationData - which is expected to be complete
    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: new Map(),
    blockers: new Map()
  };

  // -- Stateful internal variables to manage navigations --
  // Current navigation in progress (to be committed in completeNavigation)
  let pendingAction = Action.Pop;

  // Should the current navigation prevent the scroll reset if scroll cannot
  // be restored?
  let pendingPreventScrollReset = false;

  // AbortController for the active navigation
  let pendingNavigationController;

  // Should the current navigation enable document.startViewTransition?
  let pendingViewTransitionEnabled = false;

  // Store applied view transitions so we can apply them on POP
  let appliedViewTransitions = new Map();

  // Cleanup function for persisting applied transitions to sessionStorage
  let removePageHideEventListener = null;

  // We use this to avoid touching history in completeNavigation if a
  // revalidation is entirely uninterrupted
  let isUninterruptedRevalidation = false;

  // Use this internal flag to force revalidation of all loaders:
  //  - submissions (completed or interrupted)
  //  - useRevalidator()
  //  - X-Remix-Revalidate (from redirect)
  let isRevalidationRequired = false;

  // Use this internal array to capture routes that require revalidation due
  // to a cancelled deferred on action submission
  let cancelledDeferredRoutes = [];

  // Use this internal array to capture fetcher loads that were cancelled by an
  // action navigation and require revalidation
  let cancelledFetcherLoads = new Set();

  // AbortControllers for any in-flight fetchers
  let fetchControllers = new Map();

  // Track loads based on the order in which they started
  let incrementingLoadId = 0;

  // Track the outstanding pending navigation data load to be compared against
  // the globally incrementing load when a fetcher load lands after a completed
  // navigation
  let pendingNavigationLoadId = -1;

  // Fetchers that triggered data reloads as a result of their actions
  let fetchReloadIds = new Map();

  // Fetchers that triggered redirect navigations
  let fetchRedirectIds = new Set();

  // Most recent href/match for fetcher.load calls for fetchers
  let fetchLoadMatches = new Map();

  // Ref-count mounted fetchers so we know when it's ok to clean them up
  let activeFetchers = new Map();

  // Fetchers that have requested a delete when using v7_fetcherPersist,
  // they'll be officially removed after they return to idle
  let deletedFetchers = new Set();

  // Store DeferredData instances for active route matches.  When a
  // route loader returns defer() we stick one in here.  Then, when a nested
  // promise resolves we update loaderData.  If a new navigation starts we
  // cancel active deferreds for eliminated routes.
  let activeDeferreds = new Map();

  // Store blocker functions in a separate Map outside of router state since
  // we don't need to update UI state if they change
  let blockerFunctions = new Map();

  // Flag to ignore the next history update, so we can revert the URL change on
  // a POP navigation that was blocked by the user without touching router state
  let unblockBlockerHistoryUpdate = undefined;

  // Initialize the router, all side effects should be kicked off from here.
  // Implemented as a Fluent API for ease of:
  //   let router = createRouter(init).initialize();
  function initialize() {
    // If history informs us of a POP navigation, start the navigation but do not update
    // state.  We'll update our own state once the navigation completes
    unlistenHistory = init.history.listen(_ref => {
      let {
        action: historyAction,
        location,
        delta
      } = _ref;
      // Ignore this event if it was just us resetting the URL from a
      // blocked POP navigation
      if (unblockBlockerHistoryUpdate) {
        unblockBlockerHistoryUpdate();
        unblockBlockerHistoryUpdate = undefined;
        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) {
        // Restore the URL to match the current UI, but don't update router state
        let nextHistoryUpdatePromise = new Promise(resolve => {
          unblockBlockerHistoryUpdate = resolve;
        });
        init.history.go(delta * -1);

        // Put the blocker into a blocked state
        updateBlocker(blockerKey, {
          state: "blocked",
          location,
          proceed() {
            updateBlocker(blockerKey, {
              state: "proceeding",
              proceed: undefined,
              reset: undefined,
              location
            });
            // Re-do the same POP navigation we just blocked, after the url
            // restoration is also complete.  See:
            // https://github.com/remix-run/react-router/issues/11613
            nextHistoryUpdatePromise.then(() => init.history.go(delta));
          },
          reset() {
            let blockers = new Map(state.blockers);
            blockers.set(blockerKey, IDLE_BLOCKER);
            updateState({
              blockers
            });
          }
        });
        return;
      }
      return startNavigation(historyAction, location);
    });
    if (isBrowser) {
      // FIXME: This feels gross.  How can we cleanup the lines between
      // scrollRestoration/appliedTransitions persistance?
      restoreAppliedTransitions(routerWindow, appliedViewTransitions);
      let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
      routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
      removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
    }

    // Kick off initial data load if needed.  Use Pop to avoid modifying history
    // Note we don't do any handling of lazy here.  For SPA's it'll get handled
    // in the normal navigation flow.  For SSR it's expected that lazy modules are
    // resolved prior to router creation since we can't go into a fallbackElement
    // UI for SSR'd apps
    if (!state.initialized) {
      startNavigation(Action.Pop, state.location, {
        initialHydration: true
      });
    }
    return router;
  }

  // Clean up a router and it's side effects
  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));
  }

  // Subscribe to state updates for the router
  function subscribe(fn) {
    subscribers.add(fn);
    return () => subscribers.delete(fn);
  }

  // Update our state and notify the calling context of the change
  function updateState(newState, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state = _extends({}, state, newState);

    // Prep fetcher cleanup so we can tell the UI which fetcher data entries
    // can be removed
    let completedFetchers = [];
    let deletedFetchersKeys = [];
    if (future.v7_fetcherPersist) {
      state.fetchers.forEach((fetcher, key) => {
        if (fetcher.state === "idle") {
          if (deletedFetchers.has(key)) {
            // Unmounted from the UI and can be totally removed
            deletedFetchersKeys.push(key);
          } else {
            // Returned to idle but still mounted in the UI, so semi-remains for
            // revalidations and such
            completedFetchers.push(key);
          }
        }
      });
    }

    // Remove any lingering deleted fetchers that have already been removed
    // from state.fetchers
    deletedFetchers.forEach(key => {
      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
        deletedFetchersKeys.push(key);
      }
    });

    // Iterate over a local copy so that if flushSync is used and we end up
    // removing and adding a new subscriber due to the useCallback dependencies,
    // we don't get ourselves into a loop calling the new subscriber immediately
    [...subscribers].forEach(subscriber => subscriber(state, {
      deletedFetchers: deletedFetchersKeys,
      viewTransitionOpts: opts.viewTransitionOpts,
      flushSync: opts.flushSync === true
    }));

    // Remove idle fetchers from state since we only care about in-flight fetchers.
    if (future.v7_fetcherPersist) {
      completedFetchers.forEach(key => state.fetchers.delete(key));
      deletedFetchersKeys.forEach(key => deleteFetcher(key));
    } else {
      // We already called deleteFetcher() on these, can remove them from this
      // Set now that we've handed the keys off to the data layer
      deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));
    }
  }

  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  // and setting state.[historyAction/location/matches] to the new route.
  // - Location is a required param
  // - Navigation will always be set to IDLE_NAVIGATION
  // - Can pass any other state in newState
  function completeNavigation(location, newState, _temp) {
    var _location$state, _location$state2;
    let {
      flushSync
    } = _temp === void 0 ? {} : _temp;
    // Deduce if we're in a loading/actionReload state:
    // - We have committed actionData in the store
    // - The current navigation was a mutation submission
    // - We're past the submitting state and into the loading state
    // - The location being loaded is not the result of a redirect
    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 {
        // Empty actionData -> clear prior actionData due to an action error
        actionData = null;
      }
    } else if (isActionReload) {
      // Keep the current data if we're wrapping up the action reload
      actionData = state.actionData;
    } else {
      // Clear actionData on any other completed navigations
      actionData = null;
    }

    // Always preserve any existing loaderData from re-used routes
    let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;

    // On a successful navigation we can assume we got through all blockers
    // so we can start fresh
    let blockers = state.blockers;
    if (blockers.size > 0) {
      blockers = new Map(blockers);
      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
    }

    // Always respect the user flag.  Otherwise don't reset on mutation
    // submission navigations unless they redirect
    let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;

    // Commit any in-flight routes at the end of the HMR revalidation "navigation"
    if (inFlightDataRoutes) {
      dataRoutes = inFlightDataRoutes;
      inFlightDataRoutes = undefined;
    }
    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;

    // On POP, enable transitions if they were enabled on the original navigation
    if (pendingAction === Action.Pop) {
      // Forward takes precedence so they behave like the original navigation
      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)) {
        // If we don't have a previous forward nav, assume we're popping back to
        // the new location and enable if that location previously enabled
        viewTransitionOpts = {
          currentLocation: location,
          nextLocation: state.location
        };
      }
    } else if (pendingViewTransitionEnabled) {
      // Store the applied transition on PUSH/REPLACE
      let toPaths = appliedViewTransitions.get(state.location.pathname);
      if (toPaths) {
        toPaths.add(location.pathname);
      } else {
        toPaths = new Set([location.pathname]);
        appliedViewTransitions.set(state.location.pathname, toPaths);
      }
      viewTransitionOpts = {
        currentLocation: state.location,
        nextLocation: location
      };
    }
    updateState(_extends({}, newState, {
      // matches, errors, fetchers go through as-is
      actionData,
      loaderData,
      historyAction: pendingAction,
      location,
      initialized: true,
      navigation: IDLE_NAVIGATION,
      revalidation: "idle",
      restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
      preventScrollReset,
      blockers
    }), {
      viewTransitionOpts,
      flushSync: flushSync === true
    });

    // Reset stateful navigation vars
    pendingAction = Action.Pop;
    pendingPreventScrollReset = false;
    pendingViewTransitionEnabled = false;
    isUninterruptedRevalidation = false;
    isRevalidationRequired = false;
    cancelledDeferredRoutes = [];
  }

  // Trigger a navigation event, which can either be a numerical POP or a PUSH
  // replace with an optional submission
  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);

    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
    // URL from window.location, so we need to encode it here so the behavior
    // remains the same as POP and non-data-router usages.  new URL() does all
    // the same encoding we'd get from a history.pushState/window.location read
    // without having to touch history
    nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
    let userReplace = opts && opts.replace != null ? opts.replace : undefined;
    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) {
      // By default on submissions to the current location we REPLACE so that
      // users don't have to double-click the back button to get to the prior
      // location.  If the user redirects to a different location from the
      // action/loader this will be ignored and the redirect will be a PUSH
      historyAction = Action.Replace;
    }
    let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
    let flushSync = (opts && opts.flushSync) === true;
    let blockerKey = shouldBlockNavigation({
      currentLocation,
      nextLocation,
      historyAction
    });
    if (blockerKey) {
      // Put the blocker into a blocked state
      updateBlocker(blockerKey, {
        state: "blocked",
        location: nextLocation,
        proceed() {
          updateBlocker(blockerKey, {
            state: "proceeding",
            proceed: undefined,
            reset: undefined,
            location: nextLocation
          });
          // Send the same navigation through
          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.viewTransition,
      flushSync
    });
  }

  // Revalidate all current loaders.  If a navigation is in progress or if this
  // is interrupted by a navigation, allow this to "succeed" by calling all
  // loaders during the next loader round
  function revalidate() {
    interruptActiveLoads();
    updateState({
      revalidation: "loading"
    });

    // If we're currently submitting an action, we don't need to start a new
    // navigation, we'll just let the follow up loader execution call all loaders
    if (state.navigation.state === "submitting") {
      return;
    }

    // If we're currently in an idle state, start a new navigation for the current
    // action/location and mark it as uninterrupted, which will skip the history
    // update in completeNavigation
    if (state.navigation.state === "idle") {
      startNavigation(state.historyAction, state.location, {
        startUninterruptedRevalidation: true
      });
      return;
    }

    // Otherwise, if we're currently in a loading state, just start a new
    // navigation to the navigation.location but do not trigger an uninterrupted
    // revalidation so that history correctly updates once the navigation completes
    startNavigation(pendingAction || state.historyAction, state.navigation.location, {
      overrideNavigation: state.navigation,
      // Proxy through any rending view transition
      enableViewTransition: pendingViewTransitionEnabled === true
    });
  }

  // Start a navigation to the given action/location.  Can optionally provide a
  // overrideNavigation which will override the normalLoad in the case of a redirect
  // navigation
  async function startNavigation(historyAction, location, opts) {
    // Abort any in-progress navigations and start a new one. Unset any ongoing
    // uninterrupted revalidations unless told otherwise, since we want this
    // new navigation to update history normally
    pendingNavigationController && pendingNavigationController.abort();
    pendingNavigationController = null;
    pendingAction = historyAction;
    isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;

    // Save the current scroll position every time we start a new navigation,
    // and track whether we should reset scroll on completion
    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 = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?
    // `matchRoutes()` has already been called if we're in here via `router.initialize()`
    state.matches : matchRoutes(routesToUse, location, basename);
    let flushSync = (opts && opts.flushSync) === true;

    // Short circuit if it's only a hash change and not a revalidation or
    // mutation submission.
    //
    // Ignore on initial page loads because since the initial hydration will always
    // be "same hash".  For example, on /page#hash and submit a <Form method="post">
    // which will default to a navigation to /page
    if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
      completeNavigation(location, {
        matches
      }, {
        flushSync
      });
      return;
    }
    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }

    // Short circuit with a 404 on the root error boundary if we match nothing
    if (!matches) {
      let {
        error,
        notFoundMatches,
        route
      } = handleNavigational404(location.pathname);
      completeNavigation(location, {
        matches: notFoundMatches,
        loaderData: {},
        errors: {
          [route.id]: error
        }
      }, {
        flushSync
      });
      return;
    }

    // Create a controller/Request for this navigation
    pendingNavigationController = new AbortController();
    let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
    let pendingActionResult;
    if (opts && opts.pendingError) {
      // If we have a pendingError, it means the user attempted a GET submission
      // with binary FormData so assign here and skip to handleLoaders.  That
      // way we handle calling loaders above the boundary etc.  It's not really
      // different from an actionError in that sense.
      pendingActionResult = [findNearestBoundary(matches).route.id, {
        type: ResultType.error,
        error: opts.pendingError
      }];
    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
      // Call action if we received an action submission
      let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
        replace: opts.replace,
        flushSync
      });
      if (actionResult.shortCircuited) {
        return;
      }

      // If we received a 404 from handleAction, it's because we couldn't lazily
      // discover the destination route so we don't want to call loaders
      if (actionResult.pendingActionResult) {
        let [routeId, result] = actionResult.pendingActionResult;
        if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
          pendingNavigationController = null;
          completeNavigation(location, {
            matches: actionResult.matches,
            loaderData: {},
            errors: {
              [routeId]: result.error
            }
          });
          return;
        }
      }
      matches = actionResult.matches || matches;
      pendingActionResult = actionResult.pendingActionResult;
      loadingNavigation = getLoadingNavigation(location, opts.submission);
      flushSync = false;
      // No need to do fog of war matching again on loader execution
      fogOfWar.active = false;

      // Create a GET request for the loaders
      request = createClientSideRequest(init.history, request.url, request.signal);
    }

    // Call loaders
    let {
      shortCircuited,
      matches: updatedMatches,
      loaderData,
      errors
    } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
    if (shortCircuited) {
      return;
    }

    // Clean up now that the action/loaders have completed.  Don't clean up if
    // we short circuited because pendingNavigationController will have already
    // been assigned to a new controller for the next navigation
    pendingNavigationController = null;
    completeNavigation(location, _extends({
      matches: updatedMatches || matches
    }, getActionDataForCommit(pendingActionResult), {
      loaderData,
      errors
    }));
  }

  // Call the action matched by the leaf route for this navigation and handle
  // redirects/errors
  async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
    if (opts === void 0) {
      opts = {};
    }
    interruptActiveLoads();

    // Put us in a submitting state
    let navigation = getSubmittingNavigation(location, submission);
    updateState({
      navigation
    }, {
      flushSync: opts.flushSync === true
    });
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
      if (discoverResult.type === "aborted") {
        return {
          shortCircuited: true
        };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          pendingActionResult: [boundaryId, {
            type: ResultType.error,
            error: discoverResult.error
          }]
        };
      } else if (!discoverResult.matches) {
        let {
          notFoundMatches,
          error,
          route
        } = handleNavigational404(location.pathname);
        return {
          matches: notFoundMatches,
          pendingActionResult: [route.id, {
            type: ResultType.error,
            error
          }]
        };
      } else {
        matches = discoverResult.matches;
      }
    }

    // Call our action and get the result
    let result;
    let actionMatch = getTargetMatch(matches, location);
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      result = {
        type: ResultType.error,
        error: getInternalRouterError(405, {
          method: request.method,
          pathname: location.pathname,
          routeId: actionMatch.route.id
        })
      };
    } else {
      let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
      result = results[actionMatch.route.id];
      if (request.signal.aborted) {
        return {
          shortCircuited: true
        };
      }
    }
    if (isRedirectResult(result)) {
      let replace;
      if (opts && opts.replace != null) {
        replace = opts.replace;
      } else {
        // If the user didn't explicity indicate replace behavior, replace if
        // we redirected to the exact same location we're currently at to avoid
        // double back-buttons
        let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
        replace = location === state.location.pathname + state.location.search;
      }
      await startRedirectNavigation(request, result, true, {
        submission,
        replace
      });
      return {
        shortCircuited: true
      };
    }
    if (isDeferredResult(result)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);

      // By default, all submissions to the current location are REPLACE
      // navigations, but if the action threw an error that'll be rendered in
      // an errorElement, we fall back to PUSH so that the user can use the
      // back button to get back to the pre-submission form location to try
      // again
      if ((opts && opts.replace) !== true) {
        pendingAction = Action.Push;
      }
      return {
        matches,
        pendingActionResult: [boundaryMatch.route.id, result]
      };
    }
    return {
      matches,
      pendingActionResult: [actionMatch.route.id, result]
    };
  }

  // Call all applicable loaders for the given matches, handling redirects,
  // errors, etc.
  async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
    // Figure out the right navigation we want to use for data loading
    let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);

    // If this was a redirect from an action we don't have a "submission" but
    // we have it on the loading navigation so use that if available
    let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);

    // If this is an uninterrupted revalidation, we remain in our current idle
    // state.  If not, we need to switch to our loading state and load data,
    // preserving any new action data or existing action data (in the case of
    // a revalidation interrupting an actionReload)
    // If we have partialHydration enabled, then don't update the state for the
    // initial data load since it's not a "navigation"
    let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);

    // When fog of war is enabled, we enter our `loading` state earlier so we
    // can discover new routes during the `loading` state.  We skip this if
    // we've already run actions since we would have done our matching already.
    // If the children() function threw then, we want to proceed with the
    // partial matches it discovered.
    if (isFogOfWar) {
      if (shouldUpdateNavigationState) {
        let actionData = getUpdatedActionData(pendingActionResult);
        updateState(_extends({
          navigation: loadingNavigation
        }, actionData !== undefined ? {
          actionData
        } : {}), {
          flushSync
        });
      }
      let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
      if (discoverResult.type === "aborted") {
        return {
          shortCircuited: true
        };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          loaderData: {},
          errors: {
            [boundaryId]: discoverResult.error
          }
        };
      } else if (!discoverResult.matches) {
        let {
          error,
          notFoundMatches,
          route
        } = handleNavigational404(location.pathname);
        return {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error
          }
        };
      } else {
        matches = discoverResult.matches;
      }
    }
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);

    // Cancel pending deferreds for no-longer-matched routes or routes we're
    // about to reload.  Note that if this is an action reload we would have
    // already cancelled all pending deferreds so this would be a no-op
    cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
    pendingNavigationLoadId = ++incrementingLoadId;

    // Short circuit if we have no loaders to run
    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
      let updatedFetchers = markFetchRedirectsDone();
      completeNavigation(location, _extends({
        matches,
        loaderData: {},
        // Commit pending error if we're short circuiting
        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
          [pendingActionResult[0]]: pendingActionResult[1].error
        } : null
      }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
        fetchers: new Map(state.fetchers)
      } : {}), {
        flushSync
      });
      return {
        shortCircuited: true
      };
    }
    if (shouldUpdateNavigationState) {
      let updates = {};
      if (!isFogOfWar) {
        // Only update navigation/actionNData if we didn't already do it above
        updates.navigation = loadingNavigation;
        let actionData = getUpdatedActionData(pendingActionResult);
        if (actionData !== undefined) {
          updates.actionData = actionData;
        }
      }
      if (revalidatingFetchers.length > 0) {
        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
      }
      updateState(updates, {
        flushSync
      });
    }
    revalidatingFetchers.forEach(rf => {
      abortFetcher(rf.key);
      if (rf.controller) {
        // Fetchers use an independent AbortController so that aborting a fetcher
        // (via deleteFetcher) does not abort the triggering navigation that
        // triggered the revalidation
        fetchControllers.set(rf.key, rf.controller);
      }
    });

    // Proxy navigation abort through to revalidation fetchers
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
    if (pendingNavigationController) {
      pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    }
    let {
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
    if (request.signal.aborted) {
      return {
        shortCircuited: true
      };
    }

    // Clean up _after_ loaders have completed.  Don't clean up if we short
    // circuited because fetchControllers would have been aborted and
    // reassigned to new controllers for the next navigation
    if (pendingNavigationController) {
      pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    }
    revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));

    // If any loaders returned a redirect Response, start a new REPLACE navigation
    let redirect = findRedirect(loaderResults);
    if (redirect) {
      await startRedirectNavigation(request, redirect.result, true, {
        replace
      });
      return {
        shortCircuited: true
      };
    }
    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      await startRedirectNavigation(request, redirect.result, true, {
        replace
      });
      return {
        shortCircuited: true
      };
    }

    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);

    // Wire up subscribers to update loaderData as promises settle
    activeDeferreds.forEach((deferredData, routeId) => {
      deferredData.subscribe(aborted => {
        // Note: No need to updateState here since the TrackedPromise on
        // loaderData is stable across resolve/reject
        // Remove this instance if we were aborted or if promises have settled
        if (aborted || deferredData.done) {
          activeDeferreds.delete(routeId);
        }
      });
    });

    // Preserve SSR errors during partial hydration
    if (future.v7_partialHydration && initialHydration && state.errors) {
      errors = _extends({}, state.errors, errors);
    }
    let updatedFetchers = markFetchRedirectsDone();
    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
    let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
    return _extends({
      matches,
      loaderData,
      errors
    }, shouldUpdateFetchers ? {
      fetchers: new Map(state.fetchers)
    } : {});
  }
  function getUpdatedActionData(pendingActionResult) {
    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
      // This is cast to `any` currently because `RouteData`uses any and it
      // would be a breaking change to use any.
      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
      return {
        [pendingActionResult[0]]: pendingActionResult[1].data
      };
    } else if (state.actionData) {
      if (Object.keys(state.actionData).length === 0) {
        return null;
      } else {
        return state.actionData;
      }
    }
  }
  function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
    revalidatingFetchers.forEach(rf => {
      let fetcher = state.fetchers.get(rf.key);
      let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
      state.fetchers.set(rf.key, revalidatingFetcher);
    });
    return new Map(state.fetchers);
  }

  // Trigger a fetcher load/submit for the given fetcher key
  function fetch(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.");
    }
    abortFetcher(key);
    let flushSync = (opts && opts.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);
    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }
    if (!matches) {
      setFetcherError(key, routeId, getInternalRouterError(404, {
        pathname: normalizedPath
      }), {
        flushSync
      });
      return;
    }
    let {
      path,
      submission,
      error
    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
    if (error) {
      setFetcherError(key, routeId, error, {
        flushSync
      });
      return;
    }
    let match = getTargetMatch(matches, path);
    let preventScrollReset = (opts && opts.preventScrollReset) === true;
    if (submission && isMutationMethod(submission.formMethod)) {
      handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
      return;
    }

    // Store off the match so we can call it's shouldRevalidate on subsequent
    // revalidations
    fetchLoadMatches.set(key, {
      routeId,
      path
    });
    handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  }

  // Call the action for the matched fetcher.submit(), and then handle redirects,
  // errors, and revalidation
  async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
    interruptActiveLoads();
    fetchLoadMatches.delete(key);
    function detectAndHandle405Error(m) {
      if (!m.route.action && !m.route.lazy) {
        let error = getInternalRouterError(405, {
          method: submission.formMethod,
          pathname: path,
          routeId: routeId
        });
        setFetcherError(key, routeId, error, {
          flushSync
        });
        return true;
      }
      return false;
    }
    if (!isFogOfWar && detectAndHandle405Error(match)) {
      return;
    }

    // Put this fetcher into it's submitting state
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
      flushSync
    });
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, {
          flushSync
        });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(key, routeId, getInternalRouterError(404, {
          pathname: path
        }), {
          flushSync
        });
        return;
      } else {
        requestMatches = discoverResult.matches;
        match = getTargetMatch(requestMatches, path);
        if (detectAndHandle405Error(match)) {
          return;
        }
      }
    }

    // Call the action for the fetcher
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
    let actionResult = actionResults[match.route.id];
    if (fetchRequest.signal.aborted) {
      // We can delete this so long as we weren't aborted by our own fetcher
      // re-submit which would have put _new_ controller is in fetchControllers
      if (fetchControllers.get(key) === abortController) {
        fetchControllers.delete(key);
      }
      return;
    }

    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
    // or redirects processed for unmounted fetchers so we just revert them to
    // idle
    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      }
      // Let SuccessResult's fall through for revalidation
    } else {
      if (isRedirectResult(actionResult)) {
        fetchControllers.delete(key);
        if (pendingNavigationLoadId > originatingLoadId) {
          // A new navigation was kicked off after our action started, so that
          // should take precedence over this redirect navigation.  We already
          // set isRevalidationRequired so all loaders for the new route should
          // fire unless opted out via shouldRevalidate
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        } else {
          fetchRedirectIds.add(key);
          updateFetcherState(key, getLoadingFetcher(submission));
          return startRedirectNavigation(fetchRequest, actionResult, false, {
            fetcherSubmission: submission,
            preventScrollReset
          });
        }
      }

      // Process any non-redirect errors thrown
      if (isErrorResult(actionResult)) {
        setFetcherError(key, routeId, actionResult.error);
        return;
      }
    }
    if (isDeferredResult(actionResult)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }

    // Start the data load for current matches, or the next location if we're
    // in the middle of a navigation
    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, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);

    // Put all revalidating fetchers into the loading state, except for the
    // current fetcher which we want to keep in it's current loading state which
    // contains it's action submission info + action data
    revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
      let staleKey = rf.key;
      let existingFetcher = state.fetchers.get(staleKey);
      let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
      state.fetchers.set(staleKey, revalidatingFetcher);
      abortFetcher(staleKey);
      if (rf.controller) {
        fetchControllers.set(staleKey, rf.controller);
      }
    });
    updateState({
      fetchers: new Map(state.fetchers)
    });
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
    abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    let {
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
    if (abortController.signal.aborted) {
      return;
    }
    abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    fetchReloadIds.delete(key);
    fetchControllers.delete(key);
    revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
    let redirect = findRedirect(loaderResults);
    if (redirect) {
      return startRedirectNavigation(revalidationRequest, redirect.result, false, {
        preventScrollReset
      });
    }
    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      return startRedirectNavigation(revalidationRequest, redirect.result, false, {
        preventScrollReset
      });
    }

    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);

    // Since we let revalidations complete even if the submitting fetcher was
    // deleted, only put it back to idle if it hasn't been deleted
    if (state.fetchers.has(key)) {
      let doneFetcher = getDoneFetcher(actionResult.data);
      state.fetchers.set(key, doneFetcher);
    }
    abortStaleFetchLoads(loadId);

    // If we are currently in a navigation loading state and this fetcher is
    // more recent than the navigation, we want the newer data so abort the
    // navigation and complete it with the fetcher data
    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 {
      // otherwise just update with the fetcher data, preserving any existing
      // loaderData for loaders that did not need to reload.  We have to
      // manually merge here since we aren't going through completeNavigation
      updateState({
        errors,
        loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
        fetchers: new Map(state.fetchers)
      });
      isRevalidationRequired = false;
    }
  }

  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
      flushSync
    });
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, {
          flushSync
        });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(key, routeId, getInternalRouterError(404, {
          pathname: path
        }), {
          flushSync
        });
        return;
      } else {
        matches = discoverResult.matches;
        match = getTargetMatch(matches, path);
      }
    }

    // Call the loader for this fetcher route match
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
    let result = results[match.route.id];

    // Deferred isn't supported for fetcher loads, await everything and treat it
    // as a normal load.  resolveDeferredData will return undefined if this
    // fetcher gets aborted, so we just leave result untouched and short circuit
    // below if that happens
    if (isDeferredResult(result)) {
      result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
    }

    // We can delete this so long as we weren't aborted by our our own fetcher
    // re-load which would have put _new_ controller is in fetchControllers
    if (fetchControllers.get(key) === abortController) {
      fetchControllers.delete(key);
    }
    if (fetchRequest.signal.aborted) {
      return;
    }

    // We don't want errors bubbling up or redirects followed for unmounted
    // fetchers, so short circuit here if it was removed from the UI
    if (deletedFetchers.has(key)) {
      updateFetcherState(key, getDoneFetcher(undefined));
      return;
    }

    // If the loader threw a redirect Response, start a new REPLACE navigation
    if (isRedirectResult(result)) {
      if (pendingNavigationLoadId > originatingLoadId) {
        // A new navigation was kicked off after our loader started, so that
        // should take precedence over this redirect navigation
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      } else {
        fetchRedirectIds.add(key);
        await startRedirectNavigation(fetchRequest, result, false, {
          preventScrollReset
        });
        return;
      }
    }

    // Process any non-redirect errors thrown
    if (isErrorResult(result)) {
      setFetcherError(key, routeId, result.error);
      return;
    }
    invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");

    // Put the fetcher back into an idle state
    updateFetcherState(key, getDoneFetcher(result.data));
  }

  /**
   * Utility function to handle redirects returned from an action or loader.
   * Normally, a redirect "replaces" the navigation that triggered it.  So, for
   * example:
   *
   *  - user is on /a
   *  - user clicks a link to /b
   *  - loader for /b redirects to /c
   *
   * In a non-JS app the browser would track the in-flight navigation to /b and
   * then replace it with /c when it encountered the redirect response.  In
   * the end it would only ever update the URL bar with /c.
   *
   * In client-side routing using pushState/replaceState, we aim to emulate
   * this behavior and we also do not update history until the end of the
   * navigation (including processed redirects).  This means that we never
   * actually touch history until we've processed redirects, so we just use
   * the history action from the original navigation (PUSH or REPLACE).
   */
  async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
    let {
      submission,
      fetcherSubmission,
      preventScrollReset,
      replace
    } = _temp2 === void 0 ? {} : _temp2;
    if (redirect.response.headers.has("X-Remix-Revalidate")) {
      isRevalidationRequired = true;
    }
    let location = redirect.response.headers.get("Location");
    invariant(location, "Expected a Location header on the redirect Response");
    location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
    let redirectLocation = createLocation(state.location, location, {
      _isRedirect: true
    });
    if (isBrowser) {
      let isDocumentReload = false;
      if (redirect.response.headers.has("X-Remix-Reload-Document")) {
        // Hard reload if the response contained X-Remix-Reload-Document
        isDocumentReload = true;
      } else if (ABSOLUTE_URL_REGEX.test(location)) {
        const url = init.history.createURL(location);
        isDocumentReload =
        // Hard reload if it's an absolute URL to a new origin
        url.origin !== routerWindow.location.origin ||
        // Hard reload if it's an absolute URL that does not match our basename
        stripBasename(url.pathname, basename) == null;
      }
      if (isDocumentReload) {
        if (replace) {
          routerWindow.location.replace(location);
        } else {
          routerWindow.location.assign(location);
        }
        return;
      }
    }

    // There's no need to abort on redirects, since we don't detect the
    // redirect until the action/loaders have settled
    pendingNavigationController = null;
    let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;

    // Use the incoming submission if provided, fallback on the active one in
    // state.navigation
    let {
      formMethod,
      formAction,
      formEncType
    } = state.navigation;
    if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
      submission = getSubmissionFromNavigation(state.navigation);
    }

    // If this was a 307/308 submission we want to preserve the HTTP method and
    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
    // redirected location
    let activeSubmission = submission || fetcherSubmission;
    if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
      await startNavigation(redirectHistoryAction, redirectLocation, {
        submission: _extends({}, activeSubmission, {
          formAction: location
        }),
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
      });
    } else {
      // If we have a navigation submission, we will preserve it through the
      // redirect navigation
      let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
      await startNavigation(redirectHistoryAction, redirectLocation, {
        overrideNavigation,
        // Send fetcher submissions through for shouldRevalidate
        fetcherSubmission,
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
      });
    }
  }

  // Utility wrapper for calling dataStrategy client-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
    let results;
    let dataResults = {};
    try {
      results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
    } catch (e) {
      // If the outer dataStrategy method throws, just return the error for all
      // matches - and it'll naturally bubble to the root
      matchesToLoad.forEach(m => {
        dataResults[m.route.id] = {
          type: ResultType.error,
          error: e
        };
      });
      return dataResults;
    }
    for (let [routeId, result] of Object.entries(results)) {
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result;
        dataResults[routeId] = {
          type: ResultType.redirect,
          response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
        };
      } else {
        dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
      }
    }
    return dataResults;
  }
  async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
    let currentMatches = state.matches;

    // Kick off loaders and fetchers in parallel
    let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
    let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
      if (f.matches && f.match && f.controller) {
        let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
        let result = results[f.match.route.id];
        // Fetcher results are keyed by fetcher key from here on out, not routeId
        return {
          [f.key]: result
        };
      } else {
        return Promise.resolve({
          [f.key]: {
            type: ResultType.error,
            error: getInternalRouterError(404, {
              pathname: f.path
            })
          }
        });
      }
    }));
    let loaderResults = await loaderResultsPromise;
    let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
    await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
    return {
      loaderResults,
      fetcherResults
    };
  }
  function interruptActiveLoads() {
    // Every interruption triggers a revalidation
    isRevalidationRequired = true;

    // Cancel pending route-level deferreds and mark cancelled routes for
    // revalidation
    cancelledDeferredRoutes.push(...cancelActiveDeferreds());

    // Abort in-flight fetcher loads
    fetchLoadMatches.forEach((_, key) => {
      if (fetchControllers.has(key)) {
        cancelledFetcherLoads.add(key);
      }
      abortFetcher(key);
    });
  }
  function updateFetcherState(key, fetcher, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state.fetchers.set(key, fetcher);
    updateState({
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function setFetcherError(key, routeId, error, opts) {
    if (opts === void 0) {
      opts = {};
    }
    let boundaryMatch = findNearestBoundary(state.matches, routeId);
    deleteFetcher(key);
    updateState({
      errors: {
        [boundaryMatch.route.id]: error
      },
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function getFetcher(key) {
    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
    // If this fetcher was previously marked for deletion, unmark it since we
    // have a new instance
    if (deletedFetchers.has(key)) {
      deletedFetchers.delete(key);
    }
    return state.fetchers.get(key) || IDLE_FETCHER;
  }
  function deleteFetcher(key) {
    let fetcher = state.fetchers.get(key);
    // Don't abort the controller if this is a deletion of a fetcher.submit()
    // in it's loading phase since - we don't want to abort the corresponding
    // revalidation and want them to complete and land
    if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
      abortFetcher(key);
    }
    fetchLoadMatches.delete(key);
    fetchReloadIds.delete(key);
    fetchRedirectIds.delete(key);

    // If we opted into the flag we can clear this now since we're calling
    // deleteFetcher() at the end of updateState() and we've already handed the
    // deleted fetcher keys off to the data layer.
    // If not, we're eagerly calling deleteFetcher() and we need to keep this
    // Set populated until the next updateState call, and we'll clear
    // `deletedFetchers` then
    if (future.v7_fetcherPersist) {
      deletedFetchers.delete(key);
    }
    cancelledFetcherLoads.delete(key);
    state.fetchers.delete(key);
  }
  function deleteFetcherAndUpdateState(key) {
    let count = (activeFetchers.get(key) || 0) - 1;
    if (count <= 0) {
      activeFetchers.delete(key);
      deletedFetchers.add(key);
      if (!future.v7_fetcherPersist) {
        deleteFetcher(key);
      }
    } else {
      activeFetchers.set(key, count);
    }
    updateState({
      fetchers: new Map(state.fetchers)
    });
  }
  function abortFetcher(key) {
    let controller = fetchControllers.get(key);
    if (controller) {
      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);
  }

  // Utility function to update blockers, ensuring valid state transitions
  function updateBlocker(key, newBlocker) {
    let blocker = state.blockers.get(key) || IDLE_BLOCKER;

    // Poor mans state machine :)
    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
    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;
    }

    // We ony support a single active blocker at the moment since we don't have
    // any compelling use cases for multi-blocker yet
    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") {
      // If the blocker is currently proceeding, we don't need to re-check
      // it and can let this navigation continue
      return;
    }

    // At this point, we know we're unblocked/blocked so we need to check the
    // user-provided blocker function
    if (blockerFunction({
      currentLocation,
      nextLocation,
      historyAction
    })) {
      return blockerKey;
    }
  }
  function handleNavigational404(pathname) {
    let error = getInternalRouterError(404, {
      pathname
    });
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let {
      matches,
      route
    } = getShortCircuitMatches(routesToUse);

    // Cancel all pending deferred on 404s since we don't keep any routes
    cancelActiveDeferreds();
    return {
      notFoundMatches: matches,
      route,
      error
    };
  }
  function cancelActiveDeferreds(predicate) {
    let cancelledRouteIds = [];
    activeDeferreds.forEach((dfd, routeId) => {
      if (!predicate || predicate(routeId)) {
        // Cancel the deferred - but do not remove from activeDeferreds here -
        // we rely on the subscribers to do that so our tests can assert proper
        // cleanup via _internalActiveDeferreds
        dfd.cancel();
        cancelledRouteIds.push(routeId);
        activeDeferreds.delete(routeId);
      }
    });
    return cancelledRouteIds;
  }

  // Opt in to capturing and reporting scroll positions during navigations,
  // used by the <ScrollRestoration> component
  function enableScrollRestoration(positions, getPosition, getKey) {
    savedScrollPositions = positions;
    getScrollPosition = getPosition;
    getScrollRestorationKey = getKey || null;

    // Perform initial hydration scroll restoration, since we miss the boat on
    // the initial updateState() because we've not yet rendered <ScrollRestoration/>
    // and therefore have no savedScrollPositions available
    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
      initialScrollRestored = true;
      let y = getSavedScrollPosition(state.location, state.matches);
      if (y != null) {
        updateState({
          restoreScrollPosition: y
        });
      }
    }
    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 y = savedScrollPositions[key];
      if (typeof y === "number") {
        return y;
      }
    }
    return null;
  }
  function checkFogOfWar(matches, routesToUse, pathname) {
    if (patchRoutesOnNavigationImpl) {
      if (!matches) {
        let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
        return {
          active: true,
          matches: fogMatches || []
        };
      } else {
        if (Object.keys(matches[0].params).length > 0) {
          // If we matched a dynamic param or a splat, it might only be because
          // we haven't yet discovered other routes that would match with a
          // higher score.  Call patchRoutesOnNavigation just to be sure
          let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
          return {
            active: true,
            matches: partialMatches
          };
        }
      }
    }
    return {
      active: false,
      matches: null
    };
  }
  async function discoverRoutes(matches, pathname, signal, fetcherKey) {
    if (!patchRoutesOnNavigationImpl) {
      return {
        type: "success",
        matches
      };
    }
    let partialMatches = matches;
    while (true) {
      let isNonHMR = inFlightDataRoutes == null;
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let localManifest = manifest;
      try {
        await patchRoutesOnNavigationImpl({
          signal,
          path: pathname,
          matches: partialMatches,
          fetcherKey,
          patch: (routeId, children) => {
            if (signal.aborted) return;
            patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
          }
        });
      } catch (e) {
        return {
          type: "error",
          error: e,
          partialMatches
        };
      } finally {
        // If we are not in the middle of an HMR revalidation and we changed the
        // routes, provide a new identity so when we `updateState` at the end of
        // this navigation/fetch `router.routes` will be a new identity and
        // trigger a re-run of memoized `router.routes` dependencies.
        // HMR will already update the identity and reflow when it lands
        // `inFlightDataRoutes` in `completeNavigation`
        if (isNonHMR && !signal.aborted) {
          dataRoutes = [...dataRoutes];
        }
      }
      if (signal.aborted) {
        return {
          type: "aborted"
        };
      }
      let newMatches = matchRoutes(routesToUse, pathname, basename);
      if (newMatches) {
        return {
          type: "success",
          matches: newMatches
        };
      }
      let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);

      // Avoid loops if the second pass results in the same partial matches
      if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
        return {
          type: "success",
          matches: null
        };
      }
      partialMatches = newPartialMatches;
    }
  }
  function _internalSetRoutes(newRoutes) {
    manifest = {};
    inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
  }
  function patchRoutes(routeId, children) {
    let isNonHMR = inFlightDataRoutes == null;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);

    // If we are not in the middle of an HMR revalidation and we changed the
    // routes, provide a new identity and trigger a reflow via `updateState`
    // to re-run memoized `router.routes` dependencies.
    // HMR will already update the identity and reflow when it lands
    // `inFlightDataRoutes` in `completeNavigation`
    if (isNonHMR) {
      dataRoutes = [...dataRoutes];
      updateState({});
    }
  }
  router = {
    get basename() {
      return basename;
    },
    get future() {
      return future;
    },
    get state() {
      return state;
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return routerWindow;
    },
    initialize,
    subscribe,
    enableScrollRestoration,
    navigate,
    fetch,
    revalidate,
    // Passthrough to history-aware createHref used by useHref so we get proper
    // hash-aware URLs in DOM paths
    createHref: to => init.history.createHref(to),
    encodeLocation: to => init.history.encodeLocation(to),
    getFetcher,
    deleteFetcher: deleteFetcherAndUpdateState,
    dispose,
    getBlocker,
    deleteBlocker,
    patchRoutes,
    _internalFetchControllers: fetchControllers,
    _internalActiveDeferreds: activeDeferreds,
    // TODO: Remove setRoutes, it's temporary to avoid dealing with
    // updating the tree while validating the update algorithm.
    _internalSetRoutes
  };
  return router;
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region createStaticHandler
////////////////////////////////////////////////////////////////////////////////

const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");

/**
 * Future flags to toggle new feature behavior
 */

function createStaticHandler(routes, opts) {
  invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  let manifest = {};
  let basename = (opts ? opts.basename : null) || "/";
  let mapRouteProperties;
  if (opts != null && opts.mapRouteProperties) {
    mapRouteProperties = opts.mapRouteProperties;
  } else if (opts != null && opts.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = opts.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Config driven behavior flags
  let future = _extends({
    v7_relativeSplatPath: false,
    v7_throwAbortReason: false
  }, opts ? opts.future : null);
  let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);

  /**
   * The query() method is intended for document requests, in which we want to
   * call an optional action and potentially multiple loaders for all nested
   * routes.  It returns a StaticHandlerContext object, which is very similar
   * to the router state (location, loaderData, actionData, errors, etc.) and
   * also adds SSR-specific information such as the statusCode and headers
   * from action/loaders Responses.
   *
   * It _should_ never throw and should report all errors through the
   * returned context.errors object, properly associating errors to their error
   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be
   * used to emulate React error boundaries during SSr by performing a second
   * pass only down to the boundaryId.
   *
   * The one exception where we do not return a StaticHandlerContext is when a
   * redirect response is returned or thrown from any action/loader.  We
   * propagate that out and return the raw Response so the HTTP server can
   * return it directly.
   *
   * - `opts.requestContext` is an optional server context that will be passed
   *   to actions/loaders in the `context` parameter
   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
   *   the bubbling of errors which allows single-fetch-type implementations
   *   where the client will handle the bubbling and we may need to return data
   *   for the handling route
   */
  async function query(request, _temp3) {
    let {
      requestContext,
      skipLoaderErrorBubbling,
      dataStrategy
    } = _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);

    // SSR supports HEAD requests while SPA doesn't
    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, dataStrategy || null, skipLoaderErrorBubbling === true, null);
    if (isResponse(result)) {
      return result;
    }

    // When returning StaticHandlerContext, we patch back in the location here
    // since we need it for React Context.  But this helps keep our submit and
    // loadRouteData operating on a Request instead of a Location
    return _extends({
      location,
      basename
    }, result);
  }

  /**
   * The queryRoute() method is intended for targeted route requests, either
   * for fetch ?_data requests or resource route requests.  In this case, we
   * are only ever calling a single action or loader, and we are returning the
   * returned value directly.  In most cases, this will be a Response returned
   * from the action/loader, but it may be a primitive or other value as well -
   * and in such cases the calling context should handle that accordingly.
   *
   * We do respect the throw/return differentiation, so if an action/loader
   * throws, then this method will throw the value.  This is important so we
   * can do proper boundary identification in Remix where a thrown Response
   * must go to the Catch Boundary but a returned Response is happy-path.
   *
   * One thing to note is that any Router-initiated Errors that make sense
   * to associate with a status code will be thrown as an ErrorResponse
   * instance which include the raw Error, such that the calling context can
   * serialize the error as they see fit while including the proper response
   * code.  Examples here are 404 and 405 errors that occur prior to reaching
   * any user-defined loaders.
   *
   * - `opts.routeId` allows you to specify the specific route handler to call.
   *   If not provided the handler will determine the proper route by matching
   *   against `request.url`
   * - `opts.requestContext` is an optional server context that will be passed
   *    to actions/loaders in the `context` parameter
   */
  async function queryRoute(request, _temp4) {
    let {
      routeId,
      requestContext,
      dataStrategy
    } = _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);

    // SSR supports HEAD requests while SPA doesn't
    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) {
      // This should never hit I don't think?
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
    if (isResponse(result)) {
      return result;
    }
    let error = result.errors ? Object.values(result.errors)[0] : undefined;
    if (error !== undefined) {
      // If we got back result.errors, that means the loader/action threw
      // _something_ that wasn't a Response, but it's not guaranteed/required
      // to be an `instanceof Error` either, so we have to use throw here to
      // preserve the "error" state outside of queryImpl.
      throw error;
    }

    // Pick off the right state value to return
    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 undefined;
  }
  async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
    invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
    try {
      if (isMutationMethod(request.method.toLowerCase())) {
        let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
        return result;
      }
      let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
      return isResponse(result) ? result : _extends({}, result, {
        actionData: null,
        actionHeaders: {}
      });
    } catch (e) {
      // If the user threw/returned a Response in callLoaderOrAction for a
      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
      // and then return or throw the raw Response here accordingly
      if (isDataStrategyResult(e) && isResponse(e.result)) {
        if (e.type === ResultType.error) {
          throw e.result;
        }
        return e.result;
      }
      // Redirects are always returned since they don't propagate to catch
      // boundaries
      if (isRedirectResponse(e)) {
        return e;
      }
      throw e;
    }
  }
  async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
    let result;
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      let error = getInternalRouterError(405, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: actionMatch.route.id
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    } else {
      let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
      result = results[actionMatch.route.id];
      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future);
      }
    }
    if (isRedirectResult(result)) {
      // Uhhhh - this should never happen, we should always throw these from
      // callLoaderOrAction, but the type narrowing here keeps TS happy and we
      // can get back on the "throw all redirect responses" train here should
      // this ever happen :/
      throw new Response(null, {
        status: result.response.status,
        headers: {
          Location: result.response.headers.get("Location")
        }
      });
    }
    if (isDeferredResult(result)) {
      let error = getInternalRouterError(400, {
        type: "defer-action"
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    }
    if (isRouteRequest) {
      // Note: This should only be non-Response values if we get here, since
      // isRouteRequest should throw any Response received in callLoaderOrAction
      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
      };
    }

    // Create a GET request for the loaders
    let loaderRequest = new Request(request.url, {
      headers: request.headers,
      redirect: request.redirect,
      signal: request.signal
    });
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
      let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);

      // action status codes take precedence over loader status codes
      return _extends({}, context, {
        statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
        actionData: null,
        actionHeaders: _extends({}, result.headers ? {
          [actionMatch.route.id]: result.headers
        } : {})
      });
    }
    let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
    return _extends({}, context, {
      actionData: {
        [actionMatch.route.id]: result.data
      }
    }, result.statusCode ? {
      statusCode: result.statusCode
    } : {}, {
      actionHeaders: result.headers ? {
        [actionMatch.route.id]: result.headers
      } : {}
    });
  }
  async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
    let isRouteRequest = routeMatch != null;

    // Short circuit if we have no loaders to run (queryRoute())
    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
      throw getInternalRouterError(400, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: routeMatch == null ? void 0 : routeMatch.route.id
      });
    }
    let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
    let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);

    // Short circuit if we have no loaders to run (query())
    if (matchesToLoad.length === 0) {
      return {
        matches,
        // Add a null for all matched routes for proper revalidation on the client
        loaderData: matches.reduce((acc, m) => Object.assign(acc, {
          [m.route.id]: null
        }), {}),
        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
          [pendingActionResult[0]]: pendingActionResult[1].error
        } : null,
        statusCode: 200,
        loaderHeaders: {},
        activeDeferreds: null
      };
    }
    let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
    if (request.signal.aborted) {
      throwStaticHandlerAbortedError(request, isRouteRequest, future);
    }

    // Process and commit output from loaders
    let activeDeferreds = new Map();
    let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);

    // Add a null for any non-loader matches for proper revalidation on the client
    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
    });
  }

  // Utility wrapper for calling dataStrategy server-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
    let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
    let dataResults = {};
    await Promise.all(matches.map(async match => {
      if (!(match.route.id in results)) {
        return;
      }
      let result = results[match.route.id];
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result;
        // Throw redirects and let the server handle them with an HTTP redirect
        throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
      }
      if (isResponse(result.result) && isRouteRequest) {
        // For SSR single-route requests, we want to hand Responses back
        // directly without unwrapping
        throw result;
      }
      dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
    }));
    return dataResults;
  }
  return {
    dataRoutes,
    query,
    queryRoute
  };
}

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Helpers
////////////////////////////////////////////////////////////////////////////////

/**
 * Given an existing StaticHandlerContext and an error thrown at render time,
 * provide an updated StaticHandlerContext suitable for a second SSR render
 */
function getStaticContextFromError(routes, context, error) {
  let newContext = _extends({}, context, {
    statusCode: isRouteErrorResponse(error) ? error.status : 500,
    errors: {
      [context._deepestRenderedBoundaryId || routes[0].id]: error
    }
  });
  return newContext;
}
function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
    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 !== undefined);
}
function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  let contextualMatches;
  let activeRouteMatch;
  if (fromRouteId) {
    // Grab matches up to the calling route so our route-relative logic is
    // relative to the correct source route
    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];
  }

  // Resolve the relative path
  let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");

  // When `to` is not specified we inherit search/hash from the current
  // location, unlike when to="." and we just inherit the path.
  // See https://github.com/remix-run/remix/issues/927
  if (to == null) {
    path.search = location.search;
    path.hash = location.hash;
  }

  // Account for `?index` params when routing to the current location
  if ((to == null || to === "" || to === ".") && activeRouteMatch) {
    let nakedIndex = hasNakedIndexQuery(path.search);
    if (activeRouteMatch.route.index && !nakedIndex) {
      // Add one when we're targeting an index route
      path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
    } else if (!activeRouteMatch.route.index && nakedIndex) {
      // Remove existing ones when we're not
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      params.delete("index");
      indexValues.filter(v => v).forEach(v => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? "?" + qs : "";
    }
  }

  // If we're operating within a basename, prepend it to the pathname.  If
  // this is a root navigation, then just use the raw basename which allows
  // the basename to have full control over the presence of a trailing slash
  // on root actions
  if (prependBasename && basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}

// Normalize navigation options by converting formMethod=GET formData objects to
// URLSearchParams so they behave identically to links with query params
function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  // Return location verbatim on non-submission navigations
  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"
    })
  });

  // Create a Submission on non-GET navigations
  let rawFormMethod = opts.formMethod || "get";
  let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  let formAction = stripHashFromPath(path);
  if (opts.body !== undefined) {
    if (opts.formEncType === "text/plain") {
      // text only support POST/PUT/PATCH/DELETE submissions
      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: undefined,
          json: undefined,
          text
        }
      };
    } else if (opts.formEncType === "application/json") {
      // json only supports POST/PUT/PATCH/DELETE submissions
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      try {
        let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
        return {
          path,
          submission: {
            formMethod,
            formAction,
            formEncType: opts.formEncType,
            formData: undefined,
            json,
            text: undefined
          }
        };
      } 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: undefined,
    text: undefined
  };
  if (isMutationMethod(submission.formMethod)) {
    return {
      path,
      submission
    };
  }

  // Flatten submission onto URLSearchParams for GET submissions
  let parsedPath = parsePath(path);
  // On GET navigation submissions we can drop the ?index param from the
  // resulting location since all loaders will run.  But fetcher GET submissions
  // only run a single loader so we need to preserve any incoming ?index params
  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
    searchParams.append("index", "");
  }
  parsedPath.search = "?" + searchParams;
  return {
    path: createPath(parsedPath),
    submission
  };
}

// Filter out all routes at/below any caught error as they aren't going to
// render so we don't need to load them
function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
  if (includeBoundary === void 0) {
    includeBoundary = false;
  }
  let index = matches.findIndex(m => m.route.id === boundaryId);
  if (index >= 0) {
    return matches.slice(0, includeBoundary ? index + 1 : index);
  }
  return matches;
}
function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
  let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
  let currentUrl = history.createURL(state.location);
  let nextUrl = history.createURL(location);

  // Pick navigation matches that are net-new or qualify for revalidation
  let boundaryMatches = matches;
  if (initialHydration && state.errors) {
    // On initial hydration, only consider matches up to _and including_ the boundary.
    // This is inclusive to handle cases where a server loader ran successfully,
    // a child server loader bubbled up to this route, but this route has
    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
    // we have a complete version of `loaderData`
    boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
    // If an action threw an error, we call loaders up to, but not including the
    // boundary
    boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
  }

  // Don't revalidate loaders by default after action 4xx/5xx responses
  // when the flag is enabled.  They can still opt-into revalidation via
  // `shouldRevalidate` via `actionResult`
  let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
  let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
  let navigationMatches = boundaryMatches.filter((match, index) => {
    let {
      route
    } = match;
    if (route.lazy) {
      // We haven't loaded this route yet so we don't know if it's got a loader!
      return true;
    }
    if (route.loader == null) {
      return false;
    }
    if (initialHydration) {
      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
    }

    // Always call the loader on new route instances and pending defer cancellations
    if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
      return true;
    }

    // This is the default implementation for when we revalidate.  If the route
    // provides it's own implementation, then we give them full control but
    // provide this value so they can leverage it if needed after they check
    // their own specific use cases
    let currentRouteMatch = state.matches[index];
    let nextRouteMatch = match;
    return shouldRevalidateLoader(match, _extends({
      currentUrl,
      currentParams: currentRouteMatch.params,
      nextUrl,
      nextParams: nextRouteMatch.params
    }, submission, {
      actionResult,
      actionStatus,
      defaultShouldRevalidate: shouldSkipRevalidation ? false :
      // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
      isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
      // Search params affect all loaders
      currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
    }));
  });

  // Pick fetcher.loads that need to be revalidated
  let revalidatingFetchers = [];
  fetchLoadMatches.forEach((f, key) => {
    // Don't revalidate:
    //  - on initial hydration (shouldn't be any fetchers then anyway)
    //  - if fetcher won't be present in the subsequent render
    //    - no longer matches the URL (v7_fetcherPersist=false)
    //    - was unmounted but persisted due to v7_fetcherPersist=true
    if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
      return;
    }
    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);

    // If the fetcher path no longer matches, push it in with null matches so
    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is
    // currently only a use-case for Remix HMR where the route tree can change
    // at runtime and remove a route previously loaded via a fetcher
    if (!fetcherMatches) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: null,
        match: null,
        controller: null
      });
      return;
    }

    // Revalidating fetchers are decoupled from the route matches since they
    // load from a static href.  They revalidate based on explicit revalidation
    // (submission, useRevalidator, or X-Remix-Revalidate)
    let fetcher = state.fetchers.get(key);
    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
    let shouldRevalidate = false;
    if (fetchRedirectIds.has(key)) {
      // Never trigger a revalidation of an actively redirecting fetcher
      shouldRevalidate = false;
    } else if (cancelledFetcherLoads.has(key)) {
      // Always mark for revalidation if the fetcher was cancelled
      cancelledFetcherLoads.delete(key);
      shouldRevalidate = true;
    } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
      // If the fetcher hasn't ever completed loading yet, then this isn't a
      // revalidation, it would just be a brand new load if an explicit
      // revalidation is required
      shouldRevalidate = isRevalidationRequired;
    } else {
      // Otherwise fall back on any user-defined shouldRevalidate, defaulting
      // to explicit revalidations only
      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
        currentUrl,
        currentParams: state.matches[state.matches.length - 1].params,
        nextUrl,
        nextParams: matches[matches.length - 1].params
      }, submission, {
        actionResult,
        actionStatus,
        defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
      }));
    }
    if (shouldRevalidate) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: fetcherMatches,
        match: fetcherMatch,
        controller: new AbortController()
      });
    }
  });
  return [navigationMatches, revalidatingFetchers];
}
function shouldLoadRouteOnHydration(route, loaderData, errors) {
  // We dunno if we have a loader - gotta find out!
  if (route.lazy) {
    return true;
  }

  // No loader, nothing to initialize
  if (!route.loader) {
    return false;
  }
  let hasData = loaderData != null && loaderData[route.id] !== undefined;
  let hasError = errors != null && errors[route.id] !== undefined;

  // Don't run if we error'd during SSR
  if (!hasData && hasError) {
    return false;
  }

  // Explicitly opting-in to running on hydration
  if (typeof route.loader === "function" && route.loader.hydrate === true) {
    return true;
  }

  // Otherwise, run if we're not yet initialized with anything
  return !hasData && !hasError;
}
function isNewLoader(currentLoaderData, currentMatch, match) {
  let isNew =
  // [a] -> [a, b]
  !currentMatch ||
  // [a, b] -> [a, c]
  match.route.id !== currentMatch.route.id;

  // Handle the case that we don't have data for a re-used route, potentially
  // from a prior error or from a cancelled pending deferred
  let isMissingData = currentLoaderData[match.route.id] === undefined;

  // Always load if this is a net-new route or we don't yet have data
  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;
}
function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
  var _childrenToPatch;
  let childrenToPatch;
  if (routeId) {
    let route = manifest[routeId];
    invariant(route, "No route found to patch children into: routeId = " + routeId);
    if (!route.children) {
      route.children = [];
    }
    childrenToPatch = route.children;
  } else {
    childrenToPatch = routesToUse;
  }

  // Don't patch in routes we already know about so that `patch` is idempotent
  // to simplify user-land code. This is useful because we re-call the
  // `patchRoutesOnNavigation` function for matched routes with params.
  let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
  let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
  childrenToPatch.push(...newRoutes);
}
function isSameRoute(newRoute, existingRoute) {
  // Most optimal check is by id
  if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
    return true;
  }

  // Second is by pathing differences
  if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
    return false;
  }

  // Pathless layout routes are trickier since we need to check children.
  // If they have no children then they're the same as far as we can tell
  if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
    return true;
  }

  // Otherwise, we look to see if every child in the new route is already
  // represented in the existing route's children
  return newRoute.children.every((aChild, i) => {
    var _existingRoute$childr;
    return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
  });
}

/**
 * Execute route.lazy() methods to lazily load route modules (loader, action,
 * shouldRevalidate) and update the routeManifest in place which shares objects
 * with dataRoutes so those get updated as well.
 */
async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
  if (!route.lazy) {
    return;
  }
  let lazyRoute = await route.lazy();

  // If the lazy route function was executed and removed by another parallel
  // call then we can return - first lazy() to finish wins because the return
  // value of lazy is expected to be static
  if (!route.lazy) {
    return;
  }
  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");

  // Update the route in place.  This should be safe because there's no way
  // we could yet be sitting on this route as we can't get there without
  // resolving lazy() first.
  //
  // This is different than the HMR "update" use-case where we may actively be
  // on the route being updated.  The main concern boils down to "does this
  // mutation affect any ongoing navigations or any current state.matches
  // values?".  If not, it should be safe to update in place.
  let routeUpdates = {};
  for (let lazyRouteProperty in lazyRoute) {
    let staticRouteValue = routeToUpdate[lazyRouteProperty];
    let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
    // 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];
    }
  }

  // Mutate the route with the provided updates.  Do this first so we pass
  // the updated version to mapRouteProperties
  Object.assign(routeToUpdate, routeUpdates);

  // Mutate the `hasErrorBoundary` property on the route based on the route
  // updates and remove the `lazy` function so we don't resolve the lazy
  // route again.
  Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
    lazy: undefined
  }));
}

// Default implementation of `dataStrategy` which fetches all loaders in parallel
async function defaultDataStrategy(_ref4) {
  let {
    matches
  } = _ref4;
  let matchesToLoad = matches.filter(m => m.shouldLoad);
  let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
  return results.reduce((acc, result, i) => Object.assign(acc, {
    [matchesToLoad[i].route.id]: result
  }), {});
}
async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
  let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
  let dsMatches = matches.map((match, i) => {
    let loadRoutePromise = loadRouteDefinitionsPromises[i];
    let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
    // `resolve` encapsulates route.lazy(), executing the loader/action,
    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users
    // can pass a callback to take fine-grained control over the execution
    // of the loader/action
    let resolve = async handlerOverride => {
      if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
        shouldLoad = true;
      }
      return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
        type: ResultType.data,
        result: undefined
      });
    };
    return _extends({}, match, {
      shouldLoad,
      resolve
    });
  });

  // Send all matches here to allow for a middleware-type implementation.
  // handler will be a no-op for unneeded routes and we filter those results
  // back out below.
  let results = await dataStrategyImpl({
    matches: dsMatches,
    request,
    params: matches[0].params,
    fetcherKey,
    context: requestContext
  });

  // Wait for all routes to load here but 'swallow the error since we want
  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
  // called from `match.resolve()`
  try {
    await Promise.all(loadRouteDefinitionsPromises);
  } catch (e) {
    // No-op
  }
  return results;
}

// Default logic for calling a loader/action is the user has no specified a dataStrategy
async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
  let result;
  let onReject;
  let runHandler = handler => {
    // Setup a promise we can race against so that abort signals short circuit
    let reject;
    // This will never resolve so safe to type it as Promise<DataStrategyResult> to
    // satisfy the function return value
    let abortPromise = new Promise((_, r) => reject = r);
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);
    let actualHandler = ctx => {
      if (typeof handler !== "function") {
        return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
      }
      return handler({
        request,
        params: match.params,
        context: staticContext
      }, ...(ctx !== undefined ? [ctx] : []));
    };
    let handlerPromise = (async () => {
      try {
        let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
        return {
          type: "data",
          result: val
        };
      } catch (e) {
        return {
          type: "error",
          result: e
        };
      }
    })();
    return Promise.race([handlerPromise, abortPromise]);
  };
  try {
    let handler = match.route[type];

    // If we have a route.lazy promise, await that first
    if (loadRoutePromise) {
      if (handler) {
        // Run statically defined handler in parallel with lazy()
        let handlerError;
        let [value] = await Promise.all([
        // If the handler throws, don't let it immediately bubble out,
        // since we need to let the lazy() execution finish so we know if this
        // route has a boundary that can handle the error
        runHandler(handler).catch(e => {
          handlerError = e;
        }), loadRoutePromise]);
        if (handlerError !== undefined) {
          throw handlerError;
        }
        result = value;
      } else {
        // Load lazy route module, then run any returned handler
        await loadRoutePromise;
        handler = match.route[type];
        if (handler) {
          // Handler still runs even if we got interrupted to maintain consistency
          // with un-abortable behavior of handler execution on non-lazy or
          // previously-lazy-loaded routes
          result = await runHandler(handler);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match.route.id
          });
        } else {
          // lazy() route has no loader to run.  Short circuit here so we don't
          // hit the invariant below that errors on returning undefined.
          return {
            type: ResultType.data,
            result: undefined
          };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname
      });
    } else {
      result = await runHandler(handler);
    }
    invariant(result.result !== undefined, "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) {
    // We should already be catching and converting normal handler executions to
    // DataStrategyResults and returning them, so anything that throws here is an
    // unexpected error we still need to wrap
    return {
      type: ResultType.error,
      result: e
    };
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }
  return result;
}
async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  let {
    result,
    type
  } = dataStrategyResult;
  if (isResponse(result)) {
    let data;
    try {
      let contentType = result.headers.get("Content-Type");
      // Check between word boundaries instead of startsWith() due to the last
      // paragraph of https://httpwg.org/specs/rfc9110.html#field.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 (type === ResultType.error) {
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(result.status, result.statusText, data),
        statusCode: result.status,
        headers: result.headers
      };
    }
    return {
      type: ResultType.data,
      data,
      statusCode: result.status,
      headers: result.headers
    };
  }
  if (type === ResultType.error) {
    if (isDataWithResponseInit(result)) {
      var _result$init3, _result$init4;
      if (result.data instanceof Error) {
        var _result$init, _result$init2;
        return {
          type: ResultType.error,
          error: result.data,
          statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
          headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined
        };
      }

      // Convert thrown data() to ErrorResponse instances
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),
        statusCode: isRouteErrorResponse(result) ? result.status : undefined,
        headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined
      };
    }
    return {
      type: ResultType.error,
      error: result,
      statusCode: isRouteErrorResponse(result) ? result.status : undefined
    };
  }
  if (isDeferredData(result)) {
    var _result$init5, _result$init6;
    return {
      type: ResultType.deferred,
      deferredData: result,
      statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
      headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
    };
  }
  if (isDataWithResponseInit(result)) {
    var _result$init7, _result$init8;
    return {
      type: ResultType.data,
      data: result.data,
      statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
      headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined
    };
  }
  return {
    type: ResultType.data,
    data: result
  };
}

// Support relative routing in internal redirects
function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
  let location = response.headers.get("Location");
  invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  if (!ABSOLUTE_URL_REGEX.test(location)) {
    let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
    location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
    response.headers.set("Location", location);
  }
  return response;
}
function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
  // Match Chrome's behavior:
  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
  let invalidProtocols = ["about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:",
  // eslint-disable-next-line no-script-url
  "javascript:"];
  if (ABSOLUTE_URL_REGEX.test(location)) {
    // Strip off the protocol+origin for same-origin + same-basename absolute redirects
    let normalizedLocation = location;
    let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
    let isSameBasename = stripBasename(url.pathname, basename) != null;
    if (url.origin === currentUrl.origin && isSameBasename) {
      return removeDoubleSlashes(url.pathname) + url.search + url.hash;
    }
  }
  try {
    let url = historyInstance.createURL(location);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
  } catch (e) {}
  return location;
}

// Utility method for creating the Request instances for loaders/actions during
// client-side navigations and fetches.  During SSR we will always have a
// Request instance from the static handler (query/queryRoute)
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;
    // Didn't think we needed this but it turns out unlike other methods, patch
    // won't be properly normalized to uppercase and results in a 405 error.
    // See: https://fetch.spec.whatwg.org/#concept-method
    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") {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.text;
    } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = convertFormDataToSearchParams(submission.formData);
    } else {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.formData;
    }
  }
  return new Request(url, init);
}
function convertFormDataToSearchParams(formData) {
  let searchParams = new URLSearchParams();
  for (let [key, value] of formData.entries()) {
    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
    searchParams.append(key, typeof value === "string" ? value : value.name);
  }
  return searchParams;
}
function convertSearchParamsToFormData(searchParams) {
  let formData = new FormData();
  for (let [key, value] of searchParams.entries()) {
    formData.append(key, value);
  }
  return formData;
}
function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
  // Fill in loaderData/errors from our loaders
  let loaderData = {};
  let errors = null;
  let statusCode;
  let foundError = false;
  let loaderHeaders = {};
  let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;

  // Process loader results into state.loaderData/state.errors
  matches.forEach(match => {
    if (!(match.route.id in results)) {
      return;
    }
    let id = match.route.id;
    let result = results[id];
    invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
    if (isErrorResult(result)) {
      let error = result.error;
      // If we have a pending action error, we report it at the highest-route
      // that throws a loader error, and then clear it out to indicate that
      // it was consumed
      if (pendingError !== undefined) {
        error = pendingError;
        pendingError = undefined;
      }
      errors = errors || {};
      if (skipLoaderErrorBubbling) {
        errors[id] = error;
      } else {
        // Look upwards from the matched route for the closest ancestor error
        // boundary, defaulting to the root match.  Prefer higher error values
        // if lower errors bubble to the same boundary
        let boundaryMatch = findNearestBoundary(matches, id);
        if (errors[boundaryMatch.route.id] == null) {
          errors[boundaryMatch.route.id] = error;
        }
      }

      // Clear our any prior loaderData for the throwing route
      loaderData[id] = undefined;

      // Once we find our first (highest) error, we set the status code and
      // prevent deeper status codes from overriding
      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;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      } else {
        loaderData[id] = result.data;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (result.statusCode && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      }
    }
  });

  // If we didn't consume the pending action error (i.e., all loaders
  // resolved), then consume it here.  Also clear out any loaderData for the
  // throwing route
  if (pendingError !== undefined && pendingActionResult) {
    errors = {
      [pendingActionResult[0]]: pendingError
    };
    loaderData[pendingActionResult[0]] = undefined;
  }
  return {
    loaderData,
    errors,
    statusCode: statusCode || 200,
    loaderHeaders
  };
}
function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
  let {
    loaderData,
    errors
  } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
  );

  // Process results from our revalidating fetchers
  revalidatingFetchers.forEach(rf => {
    let {
      key,
      match,
      controller
    } = rf;
    let result = fetcherResults[key];
    invariant(result, "Did not find corresponding fetcher result");

    // Process fetcher non-redirect errors
    if (controller && controller.signal.aborted) {
      // Nothing to do for aborted fetchers
      return;
    } 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)) {
      // Should never get here, redirects should get processed above, but we
      // keep this to type narrow to a success result in the else
      invariant(false, "Unhandled fetcher revalidation redirect");
    } else if (isDeferredResult(result)) {
      // Should never get here, deferred data should be awaited for fetchers
      // in resolveDeferredResults
      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] !== undefined) {
        mergedLoaderData[id] = newLoaderData[id];
      }
    } else if (loaderData[id] !== undefined && match.route.loader) {
      // Preserve existing keys not included in newLoaderData and where a loader
      // wasn't removed by HMR
      mergedLoaderData[id] = loaderData[id];
    }
    if (errors && errors.hasOwnProperty(id)) {
      // Don't keep any loader data below the boundary
      break;
    }
  }
  return mergedLoaderData;
}
function getActionDataForCommit(pendingActionResult) {
  if (!pendingActionResult) {
    return {};
  }
  return isErrorResult(pendingActionResult[1]) ? {
    // Clear out prior actionData on errors
    actionData: {}
  } : {
    actionData: {
      [pendingActionResult[0]]: pendingActionResult[1].data
    }
  };
}

// Find the nearest error boundary, looking upwards from the leaf route (or the
// route specified by routeId) for the closest ancestor error boundary,
// defaulting to the root match
function findNearestBoundary(matches, routeId) {
  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
  return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
}
function getShortCircuitMatches(routes) {
  // Prefer a root layout route if present, otherwise shim in a route object
  let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
    id: "__shim-error-route__"
  };
  return {
    matches: [{
      params: {},
      pathname: "",
      pathnameBase: "",
      route
    }],
    route
  };
}
function getInternalRouterError(status, _temp5) {
  let {
    pathname,
    routeId,
    method,
    type,
    message
  } = _temp5 === void 0 ? {} : _temp5;
  let statusText = "Unknown Server Error";
  let errorMessage = "Unknown @remix-run/router error";
  if (status === 400) {
    statusText = "Bad Request";
    if (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);
}

// Find any returned redirect errors, starting from the lowest match
function findRedirect(results) {
  let entries = Object.entries(results);
  for (let i = entries.length - 1; i >= 0; i--) {
    let [key, result] = entries[i];
    if (isRedirectResult(result)) {
      return {
        key,
        result
      };
    }
  }
}
function stripHashFromPath(path) {
  let parsedPath = typeof path === "string" ? parsePath(path) : path;
  return createPath(_extends({}, parsedPath, {
    hash: ""
  }));
}
function isHashChangeOnly(a, b) {
  if (a.pathname !== b.pathname || a.search !== b.search) {
    return false;
  }
  if (a.hash === "") {
    // /page -> /page#hash
    return b.hash !== "";
  } else if (a.hash === b.hash) {
    // /page#hash -> /page#hash
    return true;
  } else if (b.hash !== "") {
    // /page#hash -> /page#other
    return true;
  }

  // If the hash is removed the browser will re-perform a request to the server
  // /page#hash -> /page
  return false;
}
function isDataStrategyResult(result) {
  return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
}
function isRedirectDataStrategyResultResult(result) {
  return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
}
function isDeferredResult(result) {
  return result.type === ResultType.deferred;
}
function isErrorResult(result) {
  return result.type === ResultType.error;
}
function isRedirectResult(result) {
  return (result && result.type) === ResultType.redirect;
}
function isDataWithResponseInit(value) {
  return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
}
function isDeferredData(value) {
  let deferred = value;
  return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
}
function isResponse(value) {
  return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
}
function isRedirectResponse(result) {
  if (!isResponse(result)) {
    return false;
  }
  let status = result.status;
  let location = result.headers.get("Location");
  return status >= 300 && status <= 399 && location != null;
}
function isValidMethod(method) {
  return validRequestMethods.has(method.toLowerCase());
}
function isMutationMethod(method) {
  return validMutationMethods.has(method.toLowerCase());
}
async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
  let entries = Object.entries(results);
  for (let index = 0; index < entries.length; index++) {
    let [routeId, result] = entries[index];
    let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    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]) !== undefined;
    if (isDeferredResult(result) && isRevalidatingLoader) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      await resolveDeferredData(result, signal, false).then(result => {
        if (result) {
          results[routeId] = result;
        }
      });
    }
  }
}
async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
  for (let index = 0; index < revalidatingFetchers.length; index++) {
    let {
      key,
      routeId,
      controller
    } = revalidatingFetchers[index];
    let result = results[key];
    let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    if (!match) {
      continue;
    }
    if (isDeferredResult(result)) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
      await resolveDeferredData(result, controller.signal, true).then(result => {
        if (result) {
          results[key] = result;
        }
      });
    }
  }
}
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) {
      // Handle any TrackedPromise._error values encountered while unwrapping
      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 the leaf index route when index is present
    return matches[matches.length - 1];
  }
  // Otherwise grab the deepest "path contributing" match (ignoring index and
  // pathless layout routes)
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}
function getSubmissionFromNavigation(navigation) {
  let {
    formMethod,
    formAction,
    formEncType,
    text,
    formData,
    json
  } = navigation;
  if (!formMethod || !formAction || !formEncType) {
    return;
  }
  if (text != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json: undefined,
      text
    };
  } else if (formData != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData,
      json: undefined,
      text: undefined
    };
  } else if (json !== undefined) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json,
      text: undefined
    };
  }
}
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: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined
    };
    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: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
      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 : undefined
  };
  return fetcher;
}
function getDoneFetcher(data) {
  let fetcher = {
    state: "idle",
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined,
    data
  };
  return fetcher;
}
function restoreAppliedTransitions(_window, transitions) {
  try {
    let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
    if (sessionPositions) {
      let json = JSON.parse(sessionPositions);
      for (let [k, v] of Object.entries(json || {})) {
        if (v && Array.isArray(v)) {
          transitions.set(k, new Set(v || []));
        }
      }
    }
  } catch (e) {
    // no-op, use default empty object
  }
}
function persistAppliedTransitions(_window, transitions) {
  if (transitions.size > 0) {
    let json = {};
    for (let [k, v] of transitions) {
      json[k] = [...v];
    }
    try {
      _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
    } catch (error) {
      warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
    }
  }
}
//#endregion

exports.AbortedDeferredError = AbortedDeferredError;
exports.Action = Action;
exports.IDLE_BLOCKER = IDLE_BLOCKER;
exports.IDLE_FETCHER = IDLE_FETCHER;
exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
exports.UNSAFE_DeferredData = DeferredData;
exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl;
exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch;
exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
exports.UNSAFE_decodePath = decodePath;
exports.UNSAFE_getResolveToMatches = getResolveToMatches;
exports.UNSAFE_invariant = invariant;
exports.UNSAFE_warning = warning;
exports.createBrowserHistory = createBrowserHistory;
exports.createHashHistory = createHashHistory;
exports.createMemoryHistory = createMemoryHistory;
exports.createPath = createPath;
exports.createRouter = createRouter;
exports.createStaticHandler = createStaticHandler;
exports.data = data;
exports.defer = defer;
exports.generatePath = generatePath;
exports.getStaticContextFromError = getStaticContextFromError;
exports.getToPathname = getToPathname;
exports.isDataWithResponseInit = isDataWithResponseInit;
exports.isDeferredData = isDeferredData;
exports.isRouteErrorResponse = isRouteErrorResponse;
exports.joinPaths = joinPaths;
exports.json = json;
exports.matchPath = matchPath;
exports.matchRoutes = matchRoutes;
exports.normalizePathname = normalizePathname;
exports.parsePath = parsePath;
exports.redirect = redirect;
exports.redirectDocument = redirectDocument;
exports.replace = replace;
exports.resolvePath = resolvePath;
exports.resolveTo = resolveTo;
exports.stripBasename = stripBasename;
//# sourceMappingURL=router.cjs.js.map
{"version":3,"file":"router.cjs.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n\n  /**\n   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n  idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 1 });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nexport function warning(cond: any, message: string) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience, so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\n  };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n  current: string | Location,\n  to: To,\n  state: any = null,\n  key?: string\n): Readonly<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): URL {\n    // window.location.origin is \"null\" (the literal string value) in Firefox\n    // under certain conditions, notably when serving from a local HTML file\n    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n    let base =\n      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\n    invariant(\n      base,\n      `No window.location.(origin|href) available to create URL for href: ${href}`\n    );\n    return new URL(href, base);\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n  [routeId: string]: any;\n}\n\nexport enum ResultType {\n  data = \"data\",\n  deferred = \"deferred\",\n  redirect = \"redirect\",\n  error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n  type: ResultType.data;\n  data: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n  type: ResultType.deferred;\n  deferredData: DeferredData;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n  | SuccessResult\n  | DeferredResult\n  | RedirectResult\n  | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\n    };\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n  currentUrl: URL;\n  currentParams: AgnosticDataRouteMatch[\"params\"];\n  nextUrl: URL;\n  nextParams: AgnosticDataRouteMatch[\"params\"];\n  formMethod?: Submission[\"formMethod\"];\n  formAction?: Submission[\"formAction\"];\n  formEncType?: Submission[\"formEncType\"];\n  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature.  This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments.  It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n  (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => DataFunctionReturnValue\n  ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n  fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n  signal: AbortSignal;\n  path: string;\n  matches: M[];\n  fetcherKey: string | undefined;\n  patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param extends `${infer Optional}?`\n      ? Optional\n      : Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\" | \"/*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if you could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(index)];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(\n      route.index !== true || !route.children,\n      `Cannot specify children on an index route`\n    );\n    invariant(\n      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\n\n      return pathOrLayoutRoute;\n    }\n  });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  let decoded = decodePath(pathname);\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array, so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children, so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explode _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string,\n  allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\n\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams as Params<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, compiledParams] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let params: CompiledPathParam[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex, so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\n  } catch (error) {\n    warning(\n      false,\n      `The URL path \"${value}\" could not be decoded because it is is a ` +\n        `malformed URL segment. This is probably due to a bad percent ` +\n        `encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n  pathname: string,\n  basename: string\n): string | null {\n  if (basename === \"/\") return pathname;\n\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  }\n\n  // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n  let startIndex = basename.endsWith(\"/\")\n    ? basename.length - 1\n    : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n\n  return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\",\n  } = typeof to === \"string\" ? parsePath(to) : to;\n\n  let pathname: string;\n  if (toPathname) {\n    toPathname = removeDoubleSlashes(toPathname);\n    if (toPathname.startsWith(\"/\")) {\n      pathname = resolvePathname(toPathname.substring(1), \"/\");\n    } else {\n      pathname = resolvePathname(toPathname, fromPathname);\n    }\n  } else {\n    pathname = fromPathname;\n  }\n\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash),\n  };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\n\n  relativeSegments.forEach((segment) => {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n  toArg: To,\n  routePathnames: string[],\n  locationPathname: string,\n  isPathRelative = false\n): Path {\n  let to: Partial<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || (to as Path).pathname === \"\"\n    ? \"/\"\n    : typeof to === \"string\"\n    ? parsePath(to).pathname\n    : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n  path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n  removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n  data: Data,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  let headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n\n  return new Response(JSON.stringify(data), {\n    ...responseInit,\n    headers,\n  });\n};\n\nexport class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\n  );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n    invariant(\n      data && typeof data === \"object\" && !Array.isArray(data),\n      \"defer() only accepts plain objects\"\n    );\n\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject: (e: AbortedDeferredError) => void;\n    this.abortPromise = new Promise((_, r) => (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =>\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =>\n      this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n\n    this.data = Object.entries(data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: this.trackPromise(key, value),\n        }),\n      {}\n    );\n\n    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.add(key);\n\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n      (data) => this.onSettle(promise, key, undefined, data as unknown),\n      (error) => this.onSettle(promise, key, error as unknown)\n    );\n\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () => true });\n    return promise;\n  }\n\n  private onSettle(\n    promise: TrackedPromise,\n    key: string,\n    error: unknown,\n    data?: unknown\n  ): unknown {\n    if (\n      this.controller.signal.aborted &&\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      return Promise.reject(error);\n    }\n\n    this.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(true);\n  }\n\n  async resolveData(signal: AbortSignal) {\n    let aborted = false;\n    if (!this.done) {\n      let onAbort = () => this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) => {\n        this.subscribe((aborted) => {\n          signal.removeEventListener(\"abort\", onAbort);\n          if (aborted || this.done) {\n            resolve(aborted);\n          }\n        });\n      });\n    }\n    return aborted;\n  }\n\n  get done() {\n    return this.pendingKeysSet.size === 0;\n  }\n\n  get unwrappedData() {\n    invariant(\n      this.data !== null && this.done,\n      \"Can only unwrap data on initialized and settled deferreds\"\n    );\n\n    return Object.entries(this.data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: unwrapTrackedPromise(value),\n        }),\n      {}\n    );\n  }\n\n  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\n  }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n  return (\n    value instanceof Promise && (value as TrackedPromise)._tracked === true\n  );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\n\nexport type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n  url: string,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = { status: responseInit };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n\n  return new Response(null, {\n    ...responseInit,\n    headers,\n  });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private internal: boolean;\n\n  constructor(\n    status: number,\n    statusText: string | undefined,\n    data: any,\n    internal = false\n  ) {\n    this.status = status;\n    this.statusText = statusText || \"\";\n    this.internal = internal;\n    if (data instanceof Error) {\n      this.data = data.toString();\n      this.error = data;\n    } else {\n      this.data = data;\n    }\n  }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  DataStrategyResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnNavigationFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  removeDoubleSlashes,\n  resolveTo,\n  stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the basename for the router\n   */\n  get basename(): RouterInit[\"basename\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the future config for the router\n   */\n  get future(): FutureConfig;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the current state of the router\n   */\n  get state(): RouterState;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the routes for this router instance\n   */\n  get routes(): AgnosticDataRouteObject[];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Initialize the router, including adding history listeners and kicking off\n   * initial data fetches.  Returns a function to cleanup listeners and abort\n   * any in-progress loads\n   */\n  initialize(): Router;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Subscribe to router.state updates\n   *\n   * @param fn function to call with the new state\n   */\n  subscribe(fn: RouterSubscriber): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Enable scroll restoration behavior in the router\n   *\n   * @param savedScrollPositions Object that will manage positions, in case\n   *                             it's being restored from sessionStorage\n   * @param getScrollPosition    Function to get the active Y scroll position\n   * @param getKey               Function to get the key to use for restoration\n   */\n  enableScrollRestoration(\n    savedScrollPositions: Record<string, number>,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Navigate forward/backward in the history stack\n   * @param to Delta to move in the history stack\n   */\n  navigate(to: number): Promise<void>;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a fetcher load/submission\n   *\n   * @param key     Fetcher key\n   * @param routeId Route that owns the fetcher\n   * @param href    href to fetch\n   * @param opts    Fetcher options, (method, submission, etc.)\n   */\n  fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a revalidation of all current route loaders and fetcher loads\n   */\n  revalidate(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to create an href for the given location\n   * @param location\n   */\n  createHref(location: Location | URL): string;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to URL encode a destination path according to the internal\n   * history implementation\n   * @param to\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get/create a fetcher for the given key\n   * @param key\n   */\n  getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete the fetcher for a given key\n   * @param key\n   */\n  deleteFetcher(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Cleanup listeners and abort any in-progress loads\n   */\n  dispose(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal fetch AbortControllers accessed by unit tests\n   */\n  _internalFetchControllers: Map<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router.  During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n  /**\n   * The action of the most recent navigation\n   */\n  historyAction: HistoryAction;\n\n  /**\n   * The current location reflected by the router\n   */\n  location: Location;\n\n  /**\n   * The current set of route matches\n   */\n  matches: AgnosticDataRouteMatch[];\n\n  /**\n   * Tracks whether we've completed our initial data load\n   */\n  initialized: boolean;\n\n  /**\n   * Current scroll position we should start at for a new view\n   *  - number -> scroll position to restore to\n   *  - false -> do not restore scroll at all (used during submissions)\n   *  - null -> don't have a saved position, scroll to hash or top of page\n   */\n  restoreScrollPosition: number | false | null;\n\n  /**\n   * Indicate whether this navigation should skip resetting the scroll position\n   * if we are unable to restore the scroll position\n   */\n  preventScrollReset: boolean;\n\n  /**\n   * Tracks the state of the current navigation\n   */\n  navigation: Navigation;\n\n  /**\n   * Tracks any in-progress revalidations\n   */\n  revalidation: RevalidationState;\n\n  /**\n   * Data from the loaders for the current matches\n   */\n  loaderData: RouteData;\n\n  /**\n   * Data from the action for the current matches\n   */\n  actionData: RouteData | null;\n\n  /**\n   * Errors caught from loaders for the current matches\n   */\n  errors: RouteData | null;\n\n  /**\n   * Map of current fetchers\n   */\n  fetchers: Map<string, Fetcher>;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  activeDeferreds: Record<string, DeferredData> | null;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      viewTransitionOpts?: ViewTransitionOpts;\n      flushSync: boolean;\n    }\n  ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n  (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n  Idle: {\n    state: \"idle\";\n    location: undefined;\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\n  };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n  Idle: {\n    state: \"idle\";\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n  /**\n   * startNavigation does not need to complete the navigation because we\n   * redirected or got interrupted\n   */\n  shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * loaderData returned from the current set of loaders\n   */\n  loaderData?: RouterState[\"loaderData\"];\n  /**\n   * errors thrown from the current set of loaders\n   */\n  errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n  \"post\",\n  \"put\",\n  \"patch\",\n  \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\n  // Cleanup function for history\n  let unlistenHistory: (() => void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialMatchesIsFOW = false;\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    let error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname,\n    });\n    let { matches, route } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = { [route.id]: error };\n  }\n\n  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnNavigation` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatchesIsFOW = true;\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n      );\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\n\n  let router: Router;\n  let state: RouterState = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n    errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n    fetchers: new Map(),\n    blockers: new Map(),\n  };\n\n  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction: HistoryAction = HistoryAction.Pop;\n\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\n  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes: string[] = [];\n\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\n  // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n  let activeDeferreds = new Map<string, DeferredData>();\n\n  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n  // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(\n      ({ action: historyAction, location, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (unblockBlockerHistoryUpdate) {\n          unblockBlockerHistoryUpdate();\n          unblockBlockerHistoryUpdate = undefined;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n            unblockBlockerHistoryUpdate = resolve;\n          });\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked, after the url\n              // restoration is also complete.  See:\n              // https://github.com/remix-run/react-router/issues/11613\n              nextHistoryUpdatePromise.then(() => init.history.go(delta));\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\n    }\n\n    return router;\n  }\n\n  // Clean up a router and it's side effects\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Remove any lingering deleted fetchers that have already been removed\n    // from state.fetchers\n    deletedFetchers.forEach((key) => {\n      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n        deletedFetchersKeys.push(key);\n      }\n    });\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        viewTransitionOpts: opts.viewTransitionOpts,\n        flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    } else {\n      // We already called deleteFetcher() on these, can remove them from this\n      // Set now that we've handed the keys off to the data layer\n      deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n    }\n  }\n\n  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n  function completeNavigation(\n    location: Location,\n    newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n    { flushSync }: { flushSync?: boolean } = {}\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\n    }\n\n    if (isUninterruptedRevalidation) {\n      // If this was an uninterrupted revalidation then do not touch history\n    } else if (pendingAction === HistoryAction.Pop) {\n      // Do nothing for POP - URL has already been updated\n    } else if (pendingAction === HistoryAction.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === HistoryAction.Replace) {\n      init.history.replace(location, location.state);\n    }\n\n    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\n        ...newState, // matches, errors, fetchers go through as-is\n        actionData,\n        loaderData,\n        historyAction: pendingAction,\n        location,\n        initialized: true,\n        navigation: IDLE_NAVIGATION,\n        revalidation: \"idle\",\n        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n  }\n\n  // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  async function navigate(\n    to: number | To | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n    // URL from window.location, so we need to encode it here so the behavior\n    // remains the same as POP and non-data-router usages.  new URL() does all\n    // the same encoding we'd get from a history.pushState/window.location read\n    // without having to touch history\n    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\n    };\n\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n    let historyAction = HistoryAction.Push;\n\n    if (userReplace === true) {\n      historyAction = HistoryAction.Replace;\n    } else if (userReplace === false) {\n      // no-op\n    } else if (\n      submission != null &&\n      isMutationMethod(submission.formMethod) &&\n      submission.formAction === state.location.pathname + state.location.search\n    ) {\n      // By default on submissions to the current location we REPLACE so that\n      // users don't have to double-click the back button to get to the prior\n      // location.  If the user redirects to a different location from the\n      // action/loader this will be ignored and the redirect will be a PUSH\n      historyAction = HistoryAction.Replace;\n    }\n\n    let preventScrollReset =\n      opts && \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.viewTransition,\n      flushSync,\n    });\n  }\n\n  // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({ revalidation: \"loading\" });\n\n    // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n    if (state.navigation.state === \"submitting\") {\n      return;\n    }\n\n    // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true,\n      });\n      return;\n    }\n\n    // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n    startNavigation(\n      pendingAction || state.historyAction,\n      state.navigation.location,\n      {\n        overrideNavigation: state.navigation,\n        // Proxy through any rending view transition\n        enableViewTransition: pendingViewTransitionEnabled === true,\n      }\n    );\n  }\n\n  // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  async function startNavigation(\n    historyAction: HistoryAction,\n    location: Location,\n    opts?: {\n      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: boolean;\n    }\n  ): Promise<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches =\n      opts?.initialHydration &&\n      state.matches &&\n      state.matches.length > 0 &&\n      !initialMatchesIsFOW\n        ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n          state.matches\n        : matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial hydration will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      matches &&\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: opts.pendingError },\n      ];\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\n    );\n\n    if (shortCircuited) {\n      return;\n    }\n\n    // Clean up now that the action/loaders have completed.  Don't clean up if\n    // we short circuited because pendingNavigationController will have already\n    // been assigned to a new controller for the next navigation\n    pendingNavigationController = null;\n\n    completeNavigation(location, {\n      matches: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\n      loaderData,\n      errors,\n    });\n  }\n\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(\n    request: Request,\n    location: Location,\n    submission: Submission,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error: discoverResult.error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    // Call our action and get the result\n    let result: DataResult;\n    let actionMatch = getTargetMatch(matches, location);\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      result = {\n        type: ResultType.error,\n        error: getInternalRouterError(405, {\n          method: request.method,\n          pathname: location.pathname,\n          routeId: actionMatch.route.id,\n        }),\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        state,\n        request,\n        [actionMatch],\n        matches,\n        null\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        return { shortCircuited: true };\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      let replace: boolean;\n      if (opts && opts.replace != null) {\n        replace = opts.replace;\n      } else {\n        // If the user didn't explicity indicate replace behavior, replace if\n        // we redirected to the exact same location we're currently at to avoid\n        // double back-buttons\n        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename,\n          init.history,\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, true, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\n    };\n  }\n\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\n\n    // If this is an uninterrupted revalidation, we remain in our current idle\n    // state.  If not, we need to switch to our loading state and load data,\n    // preserving any new action data or existing action data (in the case of\n    // a revalidation interrupting an actionReload)\n    // If we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: discoverResult.error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\n    );\n\n    // Cancel pending deferreds for no-longer-matched routes or routes we're\n    // about to reload.  Note that if this is an action reload we would have\n    // already cancelled all pending deferreds so this would be a no-op\n    cancelActiveDeferreds(\n      (routeId) =>\n        !(matches && matches.some((m) => m.route.id === routeId)) ||\n        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n    );\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      abortFetcher(rf.key);\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        request\n      );\n\n    if (request.signal.aborted) {\n      return { shortCircuited: true };\n    }\n\n    // Clean up _after_ loaders have completed.  Don't clean up if we short\n    // circuited because fetchControllers would have been aborted and\n    // reassigned to new controllers for the next navigation\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      pendingActionResult,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Wire up subscribers to update loaderData as promises settle\n    activeDeferreds.forEach((deferredData, routeId) => {\n      deferredData.subscribe((aborted) => {\n        // Note: No need to updateState here since the TrackedPromise on\n        // loaderData is stable across resolve/reject\n        // Remove this instance if we were aborted or if promises have settled\n        if (aborted || deferredData.done) {\n          activeDeferreds.delete(routeId);\n        }\n      });\n    });\n\n    // Preserve SSR errors during partial hydration\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      errors = { ...state.errors, ...errors };\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\n  }\n\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ) {\n    if (isServer) {\n      throw new Error(\n        \"router.fetch() was called during the server render, but it shouldn't be. \" +\n          \"You are likely calling a useFetcher() method in the body of your component. \" +\n          \"Try moving it to a useEffect or a callback.\"\n      );\n    }\n\n    abortFetcher(key);\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        preventScrollReset,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      preventScrollReset,\n      submission\n    );\n  }\n\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    requestMatches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      state,\n      fetchRequest,\n      [match],\n      requestMatches,\n      key\n    );\n    let actionResult = actionResults[match.route.id];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by our own fetcher\n      // re-submit which would have put _new_ controller is in fetchControllers\n      if (fetchControllers.get(key) === abortController) {\n        fetchControllers.delete(key);\n      }\n      return;\n    }\n\n    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, false, {\n            fetcherSubmission: submission,\n            preventScrollReset,\n          });\n        }\n      }\n\n      // Process any non-redirect errors thrown\n      if (isErrorResult(actionResult)) {\n        setFetcherError(key, routeId, actionResult.error);\n        return;\n      }\n    }\n\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(\n      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, basename)\n        : state.matches;\n\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n\n    let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\n    );\n\n    // Put all revalidating fetchers into the loading state, except for the\n    // current fetcher which we want to keep in it's current loading state which\n    // contains it's action submission info + action data\n    revalidatingFetchers\n      .filter((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        abortFetcher(staleKey);\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    abortStaleFetchLoads(loadId);\n\n    // If we are currently in a navigation loading state and this fetcher is\n    // more recent than the navigation, we want the newer data so abort the\n    // navigation and complete it with the fetcher data\n    if (\n      state.navigation.state === \"loading\" &&\n      loadId > pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\n\n      completeNavigation(state.navigation.location, {\n        matches,\n        loaderData,\n        errors,\n        fetchers: new Map(state.fetchers),\n      });\n    } else {\n      // otherwise just update with the fetcher data, preserving any existing\n      // loaderData for loaders that did not need to reload.  We have to\n      // manually merge here since we aren't going through completeNavigation\n      updateState({\n        errors,\n        loaderData: mergeLoaderData(\n          state.loaderData,\n          loaderData,\n          matches,\n          errors\n        ),\n        fetchers: new Map(state.fetchers),\n      });\n      isRevalidationRequired = false;\n    }\n  }\n\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      state,\n      fetchRequest,\n      [match],\n      matches,\n      key\n    );\n    let result = results[match.route.id];\n\n    // Deferred isn't supported for fetcher loads, await everything and treat it\n    // as a normal load.  resolveDeferredData will return undefined if this\n    // fetcher gets aborted, so we just leave result untouched and short circuit\n    // below if that happens\n    if (isDeferredResult(result)) {\n      result =\n        (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n        result;\n    }\n\n    // We can delete this so long as we weren't aborted by our our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n\n    if (fetchRequest.signal.aborted) {\n      return;\n    }\n\n    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result, false, {\n          preventScrollReset,\n        });\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\n  }\n\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  async function startRedirectNavigation(\n    request: Request,\n    redirect: RedirectResult,\n    isNavigation: boolean,\n    {\n      submission,\n      fetcherSubmission,\n      preventScrollReset,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename,\n      init.history,\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(location);\n        }\n        return;\n      }\n    }\n\n    // There's no need to abort on redirects, since we don't detect the\n    // redirect until the action/loaders have settled\n    pendingNavigationController = null;\n\n    let redirectHistoryAction =\n      replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\n    }\n\n    // If this was a 307/308 submission we want to preserve the HTTP method and\n    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n    // redirected location\n    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    state: RouterState,\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    fetcherKey: string | null\n  ): Promise<Record<string, DataResult>> {\n    let results: Record<string, DataStrategyResult>;\n    let dataResults: Record<string, DataResult> = {};\n    try {\n      results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        state,\n        request,\n        matchesToLoad,\n        matches,\n        fetcherKey,\n        manifest,\n        mapRouteProperties\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      matchesToLoad.forEach((m) => {\n        dataResults[m.route.id] = {\n          type: ResultType.error,\n          error: e,\n        };\n      });\n      return dataResults;\n    }\n\n    for (let [routeId, result] of Object.entries(results)) {\n      if (isRedirectDataStrategyResultResult(result)) {\n        let response = result.result as Response;\n        dataResults[routeId] = {\n          type: ResultType.redirect,\n          response: normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            routeId,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          ),\n        };\n      } else {\n        dataResults[routeId] = await convertDataStrategyResultToDataResult(\n          result\n        );\n      }\n    }\n\n    return dataResults;\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    state: RouterState,\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    let currentMatches = state.matches;\n\n    // Kick off loaders and fetchers in parallel\n    let loaderResultsPromise = callDataStrategy(\n      \"loader\",\n      state,\n      request,\n      matchesToLoad,\n      matches,\n      null\n    );\n\n    let fetcherResultsPromise = Promise.all(\n      fetchersToLoad.map(async (f) => {\n        if (f.matches && f.match && f.controller) {\n          let results = await callDataStrategy(\n            \"loader\",\n            state,\n            createClientSideRequest(init.history, f.path, f.controller.signal),\n            [f.match],\n            f.matches,\n            f.key\n          );\n          let result = results[f.match.route.id];\n          // Fetcher results are keyed by fetcher key from here on out, not routeId\n          return { [f.key]: result };\n        } else {\n          return Promise.resolve({\n            [f.key]: {\n              type: ResultType.error,\n              error: getInternalRouterError(404, {\n                pathname: f.path,\n              }),\n            } as ErrorResult,\n          });\n        }\n      })\n    );\n\n    let loaderResults = await loaderResultsPromise;\n    let fetcherResults = (await fetcherResultsPromise).reduce(\n      (acc, r) => Object.assign(acc, r),\n      {}\n    );\n\n    await Promise.all([\n      resolveNavigationDeferredResults(\n        matches,\n        loaderResults,\n        request.signal,\n        currentMatches,\n        state.loaderData\n      ),\n      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\n  }\n\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n    // Abort in-flight fetcher loads\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.add(key);\n      }\n      abortFetcher(key);\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n    // If this fetcher was previously marked for deletion, unmark it since we\n    // have a new instance\n    if (deletedFetchers.has(key)) {\n      deletedFetchers.delete(key);\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n\n    // If we opted into the flag we can clear this now since we're calling\n    // deleteFetcher() at the end of updateState() and we've already handed the\n    // deleted fetcher keys off to the data layer.\n    // If not, we're eagerly calling deleteFetcher() and we need to keep this\n    // Set populated until the next updateState call, and we'll clear\n    // `deletedFetchers` then\n    if (future.v7_fetcherPersist) {\n      deletedFetchers.delete(key);\n    }\n\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    let count = (activeFetchers.get(key) || 0) - 1;\n    if (count <= 0) {\n      activeFetchers.delete(key);\n      deletedFetchers.add(key);\n      if (!future.v7_fetcherPersist) {\n        deleteFetcher(key);\n      }\n    } else {\n      activeFetchers.set(key, count);\n    }\n\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    if (controller) {\n      controller.abort();\n      fetchControllers.delete(key);\n    }\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\n    for (let key of fetchRedirectIds) {\n      let fetcher = state.fetchers.get(key);\n      invariant(fetcher, `Expected fetcher: ${key}`);\n      if (fetcher.state === \"loading\") {\n        fetchRedirectIds.delete(key);\n        doneKeys.push(key);\n        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\n  }\n\n  function abortStaleFetchLoads(landedId: number): boolean {\n    let yeetedKeys = [];\n    for (let [key, id] of fetchReloadIds) {\n      if (id < landedId) {\n        let fetcher = state.fetchers.get(key);\n        invariant(fetcher, `Expected fetcher: ${key}`);\n        if (fetcher.state === \"loading\") {\n          abortFetcher(key);\n          fetchReloadIds.delete(key);\n          yeetedKeys.push(key);\n        }\n      }\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n\n  function getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\n  }\n\n  function cancelActiveDeferreds(\n    predicate?: (routeId: string) => boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) => {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  }\n\n  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnNavigationImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        if (Object.keys(matches[0].params).length > 0) {\n          // If we matched a dynamic param or a splat, it might only be because\n          // we haven't yet discovered other routes that would match with a\n          // higher score.  Call patchRoutesOnNavigation just to be sure\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal,\n    fetcherKey?: string\n  ): Promise<DiscoverRoutesResult> {\n    if (!patchRoutesOnNavigationImpl) {\n      return { type: \"success\", matches };\n    }\n\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      let localManifest = manifest;\n      try {\n        await patchRoutesOnNavigationImpl({\n          signal,\n          path: pathname,\n          matches: partialMatches,\n          fetcherKey,\n          patch: (routeId, children) => {\n            if (signal.aborted) return;\n            patchRoutesImpl(\n              routeId,\n              children,\n              routesToUse,\n              localManifest,\n              mapRouteProperties\n            );\n          },\n        });\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR && !signal.aborted) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      if (newMatches) {\n        return { type: \"success\", matches: newMatches };\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // Avoid loops if the second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        (partialMatches.length === newPartialMatches.length &&\n          partialMatches.every(\n            (m, i) => m.route.id === newPartialMatches![i].route.id\n          ))\n      ) {\n        return { type: \"success\", matches: null };\n      }\n\n      partialMatches = newPartialMatches;\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\n    },\n    initialize,\n    subscribe,\n    enableScrollRestoration,\n    navigate,\n    fetch,\n    revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: (to: To) => init.history.createHref(to),\n    encodeLocation: (to: To) => init.history.encodeLocation(to),\n    getFetcher,\n    deleteFetcher: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   *\n   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\n    if (isResponse(result)) {\n      return result;\n    }\n\n    // When returning StaticHandlerContext, we patch back in the location here\n    // since we need it for React Context.  But this helps keep our submit and\n    // loadRouteData operating on a Request instead of a Location\n    return { location, basename, ...result };\n  }\n\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   *\n   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      false,\n      match\n    );\n\n    if (isResponse(result)) {\n      return result;\n    }\n\n    let error = result.errors ? Object.values(result.errors)[0] : undefined;\n    if (error !== undefined) {\n      // If we got back result.errors, that means the loader/action threw\n      // _something_ that wasn't a Response, but it's not guaranteed/required\n      // to be an `instanceof Error` either, so we have to use throw here to\n      // preserve the \"error\" state outside of queryImpl.\n      throw error;\n    }\n\n    // Pick off the right state value to return\n    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(\n          request,\n          matches,\n          routeMatch || getTargetMatch(matches, location),\n          requestContext,\n          dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        routeMatch\n      );\n      return isResponse(result)\n        ? result\n        : {\n            ...result,\n            actionData: null,\n            actionHeaders: {},\n          };\n    } catch (e) {\n      // If the user threw/returned a Response in callLoaderOrAction for a\n      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isDataStrategyResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\n      }\n      // Redirects are always returned since they don't propagate to catch\n      // boundaries\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n\n  async function submit(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    actionMatch: AgnosticDataRouteMatch,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        dataStrategy\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      // Uhhhh - this should never happen, we should always throw these from\n      // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n      // can get back on the \"throw all redirect responses\" train here should\n      // this ever happen :/\n      throw new Response(null, {\n        status: result.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    // Create a GET request for the loaders\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal,\n    });\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\n      );\n\n      // action status codes take precedence over loader status codes\n      return {\n        ...context,\n        statusCode: isRouteErrorResponse(result.error)\n          ? result.error.status\n          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\n  ): Promise<\n    | Omit<\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      >\n    | Response\n  > {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch?.route.id,\n      });\n    }\n\n    let requestMatches = routeMatch\n      ? [routeMatch]\n      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\n\n    // Short circuit if we have no loaders to run (query())\n    if (matchesToLoad.length === 0) {\n      return {\n        matches,\n        // Add a null for all matched routes for proper revalidation on the client\n        loaderData: matches.reduce(\n          (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null\n  ): Promise<Record<string, DataResult>> {\n    let results = await callDataStrategyImpl(\n      dataStrategy || defaultDataStrategy,\n      type,\n      null,\n      request,\n      matchesToLoad,\n      matches,\n      null,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    let dataResults: Record<string, DataResult> = {};\n    await Promise.all(\n      matches.map(async (match) => {\n        if (!(match.route.id in results)) {\n          return;\n        }\n        let result = results[match.route.id];\n        if (isRedirectDataStrategyResultResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            match.route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        dataResults[match.route.id] =\n          await convertDataStrategyResultToDataResult(result);\n      })\n    );\n    return dataResults;\n  }\n\n  return {\n    dataRoutes,\n    query,\n    queryRoute,\n  };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n  routes: AgnosticDataRouteObject[],\n  context: StaticHandlerContext,\n  error: any\n) {\n  let newContext: StaticHandlerContext = {\n    ...context,\n    statusCode: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Account for `?index` params when routing to the current location\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index && !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index&\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index && nakedIndex) {\n      // Remove existing ones when we're not\n      let params = new URLSearchParams(path.search);\n      let indexValues = params.getAll(\"index\");\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\n} {\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return { path };\n  }\n\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n  matches: AgnosticDataRouteMatch[],\n  boundaryId: string,\n  includeBoundary = false\n) {\n  let index = matches.findIndex((m) => m.route.id === boundaryId);\n  if (index >= 0) {\n    return matches.slice(0, includeBoundary ? index + 1 : index);\n  }\n  return matches;\n}\n\nfunction getMatchesToLoad(\n  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  initialHydration: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryMatches = matches;\n  if (initialHydration && state.errors) {\n    // On initial hydration, only consider matches up to _and including_ the boundary.\n    // This is inclusive to handle cases where a server loader ran successfully,\n    // a child server loader bubbled up to this route, but this route has\n    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n    // we have a complete version of `loaderData`\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      Object.keys(state.errors)[0],\n      true\n    );\n  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n    // If an action threw an error, we call loaders up to, but not including the\n    // boundary\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      pendingActionResult[0]\n    );\n  }\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (initialHydration) {\n      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for when we revalidate.  If the route\n    // provides it's own implementation, then we give them full control but\n    // provide this value so they can leverage it if needed after they check\n    // their own specific use cases\n    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial hydration (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      initialHydration ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\n      });\n    }\n  });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n  route: AgnosticDataRouteObject,\n  loaderData: RouteData | null | undefined,\n  errors: RouteData | null | undefined\n) {\n  // We dunno if we have a loader - gotta find out!\n  if (route.lazy) {\n    return true;\n  }\n\n  // No loader, nothing to initialize\n  if (!route.loader) {\n    return false;\n  }\n\n  let hasData = loaderData != null && loaderData[route.id] !== undefined;\n  let hasError = errors != null && errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData && hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -> [a, b]\n    !currentMatch ||\n    // [a, b] -> [a, c]\n    match.route.id !== currentMatch.route.id;\n\n  // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n  let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    (currentPath != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  let childrenToPatch: AgnosticDataRouteObject[];\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    if (!route.children) {\n      route.children = [];\n    }\n    childrenToPatch = route.children;\n  } else {\n    childrenToPatch = routesToUse;\n  }\n\n  // Don't patch in routes we already know about so that `patch` is idempotent\n  // to simplify user-land code. This is useful because we re-call the\n  // `patchRoutesOnNavigation` function for matched routes with params.\n  let uniqueChildren = children.filter(\n    (newRoute) =>\n      !childrenToPatch.some((existingRoute) =>\n        isSameRoute(newRoute, existingRoute)\n      )\n  );\n\n  let newRoutes = convertRoutesToDataRoutes(\n    uniqueChildren,\n    mapRouteProperties,\n    [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n    manifest\n  );\n\n  childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n  newRoute: AgnosticRouteObject,\n  existingRoute: AgnosticRouteObject\n): boolean {\n  // Most optimal check is by id\n  if (\n    \"id\" in newRoute &&\n    \"id\" in existingRoute &&\n    newRoute.id === existingRoute.id\n  ) {\n    return true;\n  }\n\n  // Second is by pathing differences\n  if (\n    !(\n      newRoute.index === existingRoute.index &&\n      newRoute.path === existingRoute.path &&\n      newRoute.caseSensitive === existingRoute.caseSensitive\n    )\n  ) {\n    return false;\n  }\n\n  // Pathless layout routes are trickier since we need to check children.\n  // If they have no children then they're the same as far as we can tell\n  if (\n    (!newRoute.children || newRoute.children.length === 0) &&\n    (!existingRoute.children || existingRoute.children.length === 0)\n  ) {\n    return true;\n  }\n\n  // Otherwise, we look to see if every child in the new route is already\n  // represented in the existing route's children\n  return newRoute.children!.every((aChild, i) =>\n    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n  );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n  matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n  let matchesToLoad = matches.filter((m) => m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n  return results.reduce(\n    (acc, result, i) =>\n      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n    {}\n  );\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  state: RouterState | null,\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  fetcherKey: string | null,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n  let loadRouteDefinitionsPromises = matches.map((m) =>\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) => {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n    // `resolve` encapsulates route.lazy(), executing the loader/action,\n    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users\n    // can pass a callback to take fine-grained control over the execution\n    // of the loader/action\n    let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n      if (\n        handlerOverride &&\n        request.method === \"GET\" &&\n        (match.route.lazy || match.route.loader)\n      ) {\n        shouldLoad = true;\n      }\n      return shouldLoad\n        ? callLoaderOrAction(\n            type,\n            request,\n            match,\n            loadRoutePromise,\n            handlerOverride,\n            requestContext\n          )\n        : Promise.resolve({ type: ResultType.data, result: undefined });\n    };\n\n    return {\n      ...match,\n      shouldLoad,\n      resolve,\n    };\n  });\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: dsMatches,\n    request,\n    params: matches[0].params,\n    fetcherKey,\n    context: requestContext,\n  });\n\n  // Wait for all routes to load here but 'swallow the error since we want\n  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n  // called from `match.resolve()`\n  try {\n    await Promise.all(loadRouteDefinitionsPromises);\n  } catch (e) {\n    // No-op\n  }\n\n  return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  loadRoutePromise: Promise<void> | undefined,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<DataStrategyResult> {\n  let result: DataStrategyResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<DataStrategyResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<DataStrategyResult> = (async () => {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n          : actualHandler());\n        return { type: \"data\", result: val };\n      } catch (e) {\n        return { type: \"error\", result: e };\n      }\n    })();\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    // If we have a route.lazy promise, await that first\n    if (loadRoutePromise) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadRoutePromise,\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadRoutePromise;\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.result !== undefined,\n      `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n        `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n        `function. Please return a value or \\`null\\`.`\n    );\n  } catch (e) {\n    // We should already be catching and converting normal handler executions to\n    // DataStrategyResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n  dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n  let { result, type } = dataStrategyResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\n      let contentType = result.headers.get(\"Content-Type\");\n      // Check between word boundaries instead of startsWith() due to the last\n      // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n      if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\n        headers: result.headers,\n      };\n    }\n\n    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers,\n    };\n  }\n\n  if (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n          headers: result.init?.headers\n            ? new Headers(result.init.headers)\n            : undefined,\n        };\n      }\n\n      // Convert thrown data() to ErrorResponse instances\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(\n          result.init?.status || 500,\n          undefined,\n          result.data\n        ),\n        statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n        headers: result.init?.headers\n          ? new Headers(result.init.headers)\n          : undefined,\n      };\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string,\n  historyInstance: History,\n): string {\n  // Match Chrome's behavior:\n  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n  let invalidProtocols = [\n    \"about:\",\n    \"blob:\",\n    \"chrome:\",\n    \"chrome-untrusted:\",\n    \"content:\",\n    \"data:\",\n    \"devtools:\",\n    \"file:\",\n    \"filesystem:\",\n    // eslint-disable-next-line no-script-url\n    \"javascript:\",\n  ];\n\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n    }\n  }\n\n  try {\n    let url = historyInstance.createURL(location);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n  } catch (e) {}\n\n  return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\n  return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n  let searchParams = new URLSearchParams();\n\n  for (let [key, value] of formData.entries()) {\n    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) => {\n    if (!(match.route.id in results)) {\n      return;\n    }\n    let id = match.route.id;\n    let result = results[id];\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\n      let error = result.error;\n      // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n      if (pendingError !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\n      }\n\n      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\n\n      // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (\n          result.statusCode != null &&\n          result.statusCode !== 200 &&\n          !foundError\n        ) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      } else {\n        loaderData[id] = result.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      }\n    }\n  });\n\n  // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n  if (pendingError !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[0]] = undefined;\n  }\n\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders,\n  };\n}\n\nfunction processLoaderData(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record<string, DataResult>,\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    results,\n    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  revalidatingFetchers.forEach((rf) => {\n    let { key, match, controller } = rf;\n    let result = fetcherResults[key];\n    invariant(result, \"Did not find corresponding fetcher result\");\n\n    // Process fetcher non-redirect errors\n    if (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      return;\n    } else if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = {\n          ...errors,\n          [boundaryMatch.route.id]: result.error,\n        };\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      invariant(false, \"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  });\n\n  return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n  loaderData: RouteData,\n  newLoaderData: RouteData,\n  matches: AgnosticDataRouteMatch[],\n  errors: RouteData | null | undefined\n): RouteData {\n  let mergedLoaderData = { ...newLoaderData };\n  for (let match of matches) {\n    let id = match.route.id;\n    if (newLoaderData.hasOwnProperty(id)) {\n      if (newLoaderData[id] !== undefined) {\n        mergedLoaderData[id] = newLoaderData[id];\n      } else {\n        // No-op - this is so we ignore existing data if we have a key in the\n        // incoming object with an undefined value, which is how we unset a prior\n        // loaderData if we encounter a loader error\n      }\n    } else if (loaderData[id] !== undefined && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\n      mergedLoaderData[id] = loaderData[id];\n    }\n\n    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n  matches: AgnosticDataRouteMatch[],\n  routeId?: string\n): AgnosticDataRouteMatch {\n  let eligibleMatches = routeId\n    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n    matches[0]\n  );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n  matches: AgnosticDataRouteMatch[];\n  route: AgnosticDataRouteObject;\n} {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route =\n    routes.length === 1\n      ? routes[0]\n      : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n          id: `__shim-error-route__`,\n        };\n\n  return {\n    matches: [\n      {\n        params: {},\n        pathname: \"\",\n        pathnameBase: \"\",\n        route,\n      },\n    ],\n    route,\n  };\n}\n\nfunction getInternalRouterError(\n  status: number,\n  {\n    pathname,\n    routeId,\n    method,\n    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\";\n    message?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = `No route matches URL \"${pathname}\"`;\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n        `did not provide an \\`action\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (method) {\n      errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n    }\n  }\n\n  return new ErrorResponseImpl(\n    status || 500,\n    statusText,\n    new Error(errorMessage),\n    true\n  );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n  results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i >= 0; i--) {\n    let [key, result] = entries[i];\n    if (isRedirectResult(result)) {\n      return { key, result };\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n  );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n  return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n  return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n  return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null &&\n    typeof value.status === \"number\" &&\n    typeof value.statusText === \"string\" &&\n    typeof value.headers === \"object\" &&\n    typeof value.body !== \"undefined\"\n  );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n  if (!isResponse(result)) {\n    return false;\n  }\n\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index < entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    let currentMatch = currentMatches.find(\n      (m) => m.route.id === match!.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null &&\n      !isNewRouteInstance(currentMatch, match) &&\n      (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) && isRevalidatingLoader) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      await resolveDeferredData(result, signal, false).then((result) => {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    if (isDeferredResult(result)) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      invariant(\n        controller,\n        \"Expected an AbortController for revalidating fetcher deferred result\"\n      );\n      await resolveDeferredData(result, controller.signal, true).then(\n        (result) => {\n          if (result) {\n            results[key] = result;\n          }\n        }\n      );\n    }\n  }\n}\n\nasync function resolveDeferredData(\n  result: DeferredResult,\n  signal: AbortSignal,\n  unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\n  }\n\n  if (unwrap) {\n    try {\n      return {\n        type: ResultType.data,\n        data: result.deferredData.unwrappedData,\n      };\n    } catch (e) {\n      // Handle any TrackedPromise._error values encountered while unwrapping\n      return {\n        type: ResultType.error,\n        error: e,\n      };\n    }\n  }\n\n  return {\n    type: ResultType.data,\n    data: result.deferredData.data,\n  };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n  return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n  matches: AgnosticDataRouteMatch[],\n  location: Location | string\n) {\n  let search =\n    typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (\n    matches[matches.length - 1].route.index &&\n    hasNakedIndexQuery(search || \"\")\n  ) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  }\n  // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;AACA;AACA;AACYA,IAAAA,MAAM,0BAANA,MAAM,EAAA;AAChB;AACF;AACA;AACA;AACA;AACA;AACA;EAPYA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;AAUhB;AACF;AACA;AACA;AACA;EAdYA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;AAiBhB;AACF;AACA;AACA;EApBYA,MAAM,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;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}/**
 * @remix-run/router v1.23.4
 *
 * 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
 */
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}

////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////
/**
 * Actions represent the type of change to a location value.
 */
var Action;
(function (Action) {
  /**
   * A POP indicates a change to an arbitrary index in the history stack, such
   * as a back or forward navigation. It does not describe the direction of the
   * navigation, only that the current index changed.
   *
   * Note: This is the default action for newly created history objects.
   */
  Action["Pop"] = "POP";
  /**
   * A PUSH indicates a new entry being added to the history stack, such as when
   * a link is clicked and a new page loads. When this happens, all subsequent
   * entries in the stack are lost.
   */
  Action["Push"] = "PUSH";
  /**
   * A REPLACE indicates the entry at the current index in the history stack
   * being replaced by a new one.
   */
  Action["Replace"] = "REPLACE";
})(Action || (Action = {}));
const PopStateEventType = "popstate";
/**
 * Memory history stores the current location in memory. It is designed for use
 * in stateful non-browser environments like tests and React Native.
 */
function createMemoryHistory(options) {
  if (options === void 0) {
    options = {};
  }
  let {
    initialEntries = ["/"],
    initialIndex,
    v5Compat = false
  } = options;
  let entries; // Declare so we can access from createMemoryLocation
  entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
  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;
}
/**
 * Browser history stores the location in regular URLs. This is the standard for
 * most web apps, but it requires some configuration on the server to ensure you
 * serve the same app at multiple URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
 */
function createBrowserHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createBrowserLocation(window, globalHistory) {
    let {
      pathname,
      search,
      hash
    } = window.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(window, to) {
    return typeof to === "string" ? to : createPath(to);
  }
  return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
/**
 * Hash history stores the location in window.location.hash. This makes it ideal
 * for situations where you don't want to send the location to the server for
 * some reason, either because you do cannot configure it or the URL space is
 * reserved for something else.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
 */
function createHashHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createHashLocation(window, globalHistory) {
    let {
      pathname = "/",
      search = "",
      hash = ""
    } = parsePath(window.location.hash.substr(1));
    // Hash URL should always have a leading / just like window.location.pathname
    // does, so if an app ends up at a route like /#something then we add a
    // leading slash so all of our path-matching behaves the same as if it would
    // in a browser router.  This is particularly important when there exists a
    // root splat route (<Route path="*">) since that matches internally against
    // "/*" and we'd expect /#something to 404 in a hash router app.
    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(window, to) {
    let base = window.document.querySelector("base");
    let href = "";
    if (base && base.getAttribute("href")) {
      let url = window.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) {
    // eslint-disable-next-line no-console
    if (typeof console !== "undefined") console.warn(message);
    try {
      // Welcome to debugging history!
      //
      // This error is thrown as a convenience, so you can more easily
      // find the source for a warning that appears in the console by
      // enabling "pause on exceptions" in your JavaScript debugger.
      throw new Error(message);
      // eslint-disable-next-line no-empty
    } catch (e) {}
  }
}
function createKey() {
  return Math.random().toString(36).substr(2, 8);
}
/**
 * For browser-based histories, we combine the state and key into an object
 */
function getHistoryState(location, index) {
  return {
    usr: location.state,
    key: location.key,
    idx: index
  };
}
/**
 * Creates a Location object with a unique key from the given Path
 */
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;
}
/**
 * Creates a string URL path from the given pathname, search, and hash components.
 */
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;
}
/**
 * Parses a string URL path into its separate pathname, search, and hash components.
 */
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 = document.defaultView,
    v5Compat = false
  } = options;
  let globalHistory = window.history;
  let action = Action.Pop;
  let listener = null;
  let index = getIndex();
  // Index should only be null when we initialize. If not, it's because the
  // user called history.pushState or history.replaceState directly, in which
  // case we should log a warning as it will result in bugs.
  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...catch because iOS limits us to 100 pushState calls :/
    try {
      globalHistory.pushState(historyState, "", url);
    } catch (error) {
      // If the exception is because `state` can't be serialized, let that throw
      // outwards just like a replace call would so the dev knows the cause
      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
      if (error instanceof DOMException && error.name === "DataCloneError") {
        throw error;
      }
      // They are going to lose state here, but there is no real
      // way to warn them about it since the page will refresh...
      window.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) {
    // window.location.origin is "null" (the literal string value) in Firefox
    // under certain conditions, notably when serving from a local HTML file
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
    let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
    let href = typeof to === "string" ? to : createPath(to);
    // Treating this as a full URL will strip any trailing spaces so we need to
    // pre-encode them since they might be part of a matching splat param from
    // an ancestor route
    href = href.replace(/ $/, "%20");
    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(window, globalHistory);
    },
    listen(fn) {
      if (listener) {
        throw new Error("A history only accepts one active listener");
      }
      window.addEventListener(PopStateEventType, handlePop);
      listener = fn;
      return () => {
        window.removeEventListener(PopStateEventType, handlePop);
        listener = null;
      };
    },
    createHref(to) {
      return createHref(window, to);
    },
    createURL,
    encodeLocation(to) {
      // Encode a Location the same way window.location would
      let url = createURL(to);
      return {
        pathname: url.pathname,
        search: url.search,
        hash: url.hash
      };
    },
    push,
    replace,
    go(n) {
      return globalHistory.go(n);
    }
  };
  return history;
}
//#endregion

var ResultType;
(function (ResultType) {
  ResultType["data"] = "data";
  ResultType["deferred"] = "deferred";
  ResultType["redirect"] = "redirect";
  ResultType["error"] = "error";
})(ResultType || (ResultType = {}));
const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
function isIndexRoute(route) {
  return route.index === true;
}
// Walk the route tree generating unique IDs where necessary, so we are working
// solely with AgnosticDataRouteObject's within the Router
function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  if (manifest === void 0) {
    manifest = {};
  }
  return routes.map((route, index) => {
    let treePath = [...parentPath, String(index)];
    let id = typeof route.id === "string" ? route.id : treePath.join("-");
    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: undefined
      });
      manifest[id] = pathOrLayoutRoute;
      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
      }
      return pathOrLayoutRoute;
    }
  });
}
/**
 * Matches the given routes to a location and returns the match data.
 *
 * @see https://reactrouter.com/v6/utils/match-routes
 */
function matchRoutes(routes, locationArg, basename) {
  if (basename === void 0) {
    basename = "/";
  }
  return matchRoutesImpl(routes, locationArg, basename, false);
}
function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  let pathname = stripBasename(location.pathname || "/", basename);
  if (pathname == null) {
    return null;
  }
  let branches = flattenRoutes(routes);
  rankRouteBranches(branches);
  let matches = null;
  let decoded = decodePath(pathname);
  for (let i = 0; matches == null && i < branches.length; ++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.
    matches = matchRouteBranch(branches[i], decoded, allowPartial);
  }
  return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
  let {
    route,
    pathname,
    params
  } = match;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    handle: route.handle
  };
}
function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  if (branches === void 0) {
    branches = [];
  }
  if (parentsMeta === void 0) {
    parentsMeta = [];
  }
  if (parentPath === void 0) {
    parentPath = "";
  }
  let flattenRoute = (route, index, relativePath) => {
    let meta = {
      relativePath: relativePath === undefined ? 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);
    // Add the children before adding this route to the array, so we traverse the
    // route tree depth-first and child routes appear before their parents in
    // the "flattened" version.
    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);
    }
    // Routes without a path shouldn't ever match by themselves unless they are
    // index routes, so don't add them to the list of possible branches.
    if (route.path == null && !route.index) {
      return;
    }
    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta
    });
  };
  routes.forEach((route, index) => {
    var _route$path;
    // coarse-grain check for optional params
    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;
}
/**
 * Computes all combinations of optional path segments for a given path,
 * excluding combinations that are ambiguous and of lower priority.
 *
 * For example, `/one/:two?/three/:four?/:five?` explodes to:
 * - `/one/three`
 * - `/one/:two/three`
 * - `/one/three/:four`
 * - `/one/three/:five`
 * - `/one/:two/three/:four`
 * - `/one/:two/three/:five`
 * - `/one/three/:four/:five`
 * - `/one/:two/three/:four/:five`
 */
function explodeOptionalSegments(path) {
  let segments = path.split("/");
  if (segments.length === 0) return [];
  let [first, ...rest] = segments;
  // Optional path segments are denoted by a trailing `?`
  let isOptional = first.endsWith("?");
  // Compute the corresponding required segment: `foo?` -> `foo`
  let required = first.replace(/\?$/, "");
  if (rest.length === 0) {
    // Intepret empty string as omitting an optional segment
    // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
    return isOptional ? [required, ""] : [required];
  }
  let restExploded = explodeOptionalSegments(rest.join("/"));
  let result = [];
  // All child paths with the prefix.  Do this for all children before the
  // optional version for all children, so we get consistent ordering where the
  // parent optional aspect is preferred as required.  Otherwise, we can get
  // child sections interspersed where deeper optional segments are higher than
  // parent optional segments, where for example, /:two would explode _earlier_
  // then /:one.  By always including the parent as required _for all children_
  // first, we avoid this issue
  result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
  // Then, if this is an optional value, add all child versions without
  if (isOptional) {
    result.push(...restExploded);
  }
  // for absolute paths, ensure `/` instead of empty segment
  return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
  branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
  : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
}
const paramRe = /^:[\w-]+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = s => s === "*";
function computeScore(path, index) {
  let segments = path.split("/");
  let initialScore = segments.length;
  if (segments.some(isSplat)) {
    initialScore += splatPenalty;
  }
  if (index) {
    initialScore += indexRouteValue;
  }
  return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
  let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[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] - b[b.length - 1] :
  // Otherwise, it doesn't really make sense to rank non-siblings by index,
  // so they sort equally.
  0;
}
function matchRouteBranch(branch, pathname, allowPartial) {
  if (allowPartial === void 0) {
    allowPartial = false;
  }
  let {
    routesMeta
  } = branch;
  let matchedParams = {};
  let matchedPathname = "/";
  let matches = [];
  for (let 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);
    let route = meta.route;
    if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
      match = matchPath({
        path: meta.relativePath,
        caseSensitive: meta.caseSensitive,
        end: false
      }, remainingPathname);
    }
    if (!match) {
      return null;
    }
    Object.assign(matchedParams, match.params);
    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams,
      pathname: joinPaths([matchedPathname, match.pathname]),
      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
      route
    });
    if (match.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
    }
  }
  return matches;
}
/**
 * Returns a path with params interpolated.
 *
 * @see https://reactrouter.com/v6/utils/generate-path
 */
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(/\*$/, "/*");
  }
  // ensure `/` is added at the beginning if the path is absolute
  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;
    // only apply the splat if it's the last segment
    if (isLastSegment && segment === "*") {
      const star = "*";
      // Apply the splat
      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);
    }
    // Remove any optional markers from optional static segments
    return segment.replace(/\?$/g, "");
  })
  // Remove empty segments
  .filter(segment => !!segment);
  return prefix + segments.join("/");
}
/**
 * Performs pattern matching on a URL pathname and returns information about
 * the match.
 *
 * @see https://reactrouter.com/v6/utils/match-path
 */
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;
    // We need to compute the pathnameBase here using the raw splat value
    // instead of using params["*"] later because it will be decoded then
    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] = undefined;
    } else {
      memo[paramName] = (value || "").replace(/%2F/g, "/");
    }
    return memo;
  }, {});
  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern
  };
}
function compilePath(path, caseSensitive, end) {
  if (caseSensitive === void 0) {
    caseSensitive = false;
  }
  if (end === void 0) {
    end = true;
  }
  warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
  let params = [];
  let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
  .replace(/^\/*/, "/") // Make sure it has a leading /
  .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
  .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
    params.push({
      paramName,
      isOptional: isOptional != null
    });
    return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  });
  if (path.endsWith("*")) {
    params.push({
      paramName: "*"
    });
    regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
    : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  } else if (end) {
    // When matching to the end, ignore trailing slashes
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    // If our path is non-empty and contains anything beyond an initial slash,
    // then we have _some_ form of path in our regex, so we should expect to
    // match only if we find the end of this path segment.  Look for an optional
    // non-captured trailing slash (to match a portion of the URL) or the end
    // of the path (if we've matched to the end).  We used to do this with a
    // word boundary but that gives false positives on routes like
    // /user-preferences since `-` counts as a word boundary.
    regexpSource += "(?:(?=\\/|$))";
  } else ;
  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
  return [matcher, params];
}
function decodePath(value) {
  try {
    return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  } catch (error) {
    warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
    return value;
  }
}
/**
 * @private
 */
function stripBasename(pathname, basename) {
  if (basename === "/") return pathname;
  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
    return null;
  }
  // We want to leave trailing slash behavior in the user's control, so if they
  // specify a basename with a trailing slash, we should support it
  let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    // pathname does not start with basename/
    return null;
  }
  return pathname.slice(startIndex) || "/";
}
/**
 * Returns a resolved path object relative to the given pathname.
 *
 * @see https://reactrouter.com/v6/utils/resolve-path
 */
function resolvePath(to, fromPathname) {
  if (fromPathname === void 0) {
    fromPathname = "/";
  }
  let {
    pathname: toPathname,
    search = "",
    hash = ""
  } = typeof to === "string" ? parsePath(to) : to;
  let pathname;
  if (toPathname) {
    toPathname = removeDoubleSlashes(toPathname);
    if (toPathname.startsWith("/")) {
      pathname = resolvePathname(toPathname.substring(1), "/");
    } else {
      pathname = resolvePathname(toPathname, fromPathname);
    }
  } else {
    pathname = 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 === "..") {
      // Keep the root "" segment so the pathname starts at /
      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 <Link to=\"...\"> and the router will parse it for you.";
}
/**
 * @private
 *
 * When processing relative navigation we want to ignore ancestor routes that
 * do not contribute to the path, such that index/pathless layout routes don't
 * interfere.
 *
 * For example, when moving a route element into an index route and/or a
 * pathless layout route, relative link behavior contained within should stay
 * the same.  Both of the following examples should link back to the root:
 *
 *   <Route path="/">
 *     <Route path="accounts" element={<Link to=".."}>
 *   </Route>
 *
 *   <Route path="/">
 *     <Route path="accounts">
 *       <Route element={<AccountsLayout />}>       // <-- Does not contribute
 *         <Route index element={<Link to=".."} />  // <-- Does not contribute
 *       </Route
 *     </Route>
 *   </Route>
 */
function getPathContributingMatches(matches) {
  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}
// Return the array of pathnames for the current route matches - used to
// generate the routePathnames input for resolveTo()
function getResolveToMatches(matches, v7_relativeSplatPath) {
  let pathMatches = getPathContributingMatches(matches);
  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
  // match so we include splat values for "." links.  See:
  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
  if (v7_relativeSplatPath) {
    return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
  }
  return pathMatches.map(match => match.pathnameBase);
}
/**
 * @private
 */
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;
  // Routing is relative to the current pathname if explicitly requested.
  //
  // If a pathname is explicitly provided in `to`, it should be relative to the
  // route context. This is explained in `Note on `<Link to>` values` in our
  // migration guide from v5 as a means of disambiguation between `to` values
  // that begin with `/` and those that do not. However, this is problematic for
  // `to` values that do not provide a pathname. `to` can simply be a search or
  // hash string, in which case we should assume that the navigation is relative
  // to the current location's pathname and *not* the route pathname.
  if (toPathname == null) {
    from = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;
    // With relative="route" (the default), each leading .. segment means
    // "go up one route" instead of "go up one URL segment".  This is a key
    // difference from how <a href> works and a major reason we call this a
    // "to" value instead of a "href".
    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);
  // Ensure the pathname has a trailing slash if the original "to" had one
  let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  // Or if this was a link to the current path which has a trailing slash
  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
    path.pathname += "/";
  }
  return path;
}
/**
 * @private
 */
function getToPathname(to) {
  // Empty strings should be treated the same as / paths
  return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
}
const removeDoubleSlashes = path => path.replace(/\/\/+/g, "/");
/**
 * @private
 */
const joinPaths = paths => removeDoubleSlashes(paths.join("/"));
/**
 * @private
 */
const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
/**
 * @private
 */
const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
/**
 * @private
 */
const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
/**
 * This is a shortcut for creating `application/json` responses. Converts `data`
 * to JSON and sets the `Content-Type` header.
 *
 * @deprecated The `json` method is deprecated in favor of returning raw objects.
 * This method will be removed in v7.
 */
const json = function json(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
  }));
};
class DataWithResponseInit {
  constructor(data, init) {
    this.type = "DataWithResponseInit";
    this.data = data;
    this.init = init || null;
  }
}
/**
 * Create "responses" that contain `status`/`headers` without forcing
 * serialization into an actual `Response` - used by Remix single fetch
 */
function data(data, init) {
  return new DataWithResponseInit(data, typeof init === "number" ? {
    status: init
  } : init);
}
class AbortedDeferredError extends Error {}
class DeferredData {
  constructor(data, responseInit) {
    this.pendingKeysSet = new Set();
    this.subscribers = new Set();
    this.deferredKeys = [];
    invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
    // Set up an AbortController + Promise we can race against to exit early
    // cancellation
    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) {
      // All incoming values were resolved
      this.unlistenAbortSignal();
    }
    this.init = responseInit;
  }
  trackPromise(key, value) {
    if (!(value instanceof Promise)) {
      return value;
    }
    this.deferredKeys.push(key);
    this.pendingKeysSet.add(key);
    // We store a little wrapper promise that will be extended with
    // _data/_error props upon resolve/reject
    let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));
    // Register rejection listeners to avoid uncaught promise rejections on
    // errors or aborted deferred values
    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) {
      // Nothing left to abort!
      this.unlistenAbortSignal();
    }
    // If the promise was resolved/rejected with undefined, we'll throw an error as you
    // should always resolve with a value or null
    if (error === undefined && data === undefined) {
      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 === undefined) {
      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, k) => this.pendingKeysSet.delete(k));
    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(aborted => {
          signal.removeEventListener("abort", onAbort);
          if (aborted || this.done) {
            resolve(aborted);
          }
        });
      });
    }
    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);
  }
}
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;
}
/**
 * @deprecated The `defer` method is deprecated in favor of returning raw
 * objects. This method will be removed in v7.
 */
const defer = function defer(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  return new DeferredData(data, responseInit);
};
/**
 * A redirect response. Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirect = function redirect(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
  }));
};
/**
 * A redirect response that will force a document reload to the new location.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirectDocument = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Reload-Document", "true");
  return response;
};
/**
 * A redirect response that will perform a `history.replaceState` instead of a
 * `history.pushState` for client-side navigation redirects.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const replace = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Replace", "true");
  return response;
};
/**
 * @private
 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
 *
 * We don't export the class for public use since it's an implementation
 * detail, but we export the interface above so folks can build their own
 * abstractions around instances via isRouteErrorResponse()
 */
class ErrorResponseImpl {
  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;
    }
  }
}
/**
 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
 * Response thrown from an action/loader
 */
function isRouteErrorResponse(error) {
  return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}

const validMutationMethodsArr = ["post", "put", "patch", "delete"];
const validMutationMethods = new Set(validMutationMethodsArr);
const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
const validRequestMethods = new Set(validRequestMethodsArr);
const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
const redirectPreserveMethodStatusCodes = new Set([307, 308]);
const IDLE_NAVIGATION = {
  state: "idle",
  location: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_FETCHER = {
  state: "idle",
  data: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_BLOCKER = {
  state: "unblocked",
  proceed: undefined,
  reset: undefined,
  location: undefined
};
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const defaultMapRouteProperties = route => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////
/**
 * Create a router and listen to history POP navigations
 */
function createRouter(init) {
  const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
  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) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = init.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Routes keyed by ID
  let manifest = {};
  // Routes in tree format for matching
  let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
  let inFlightDataRoutes;
  let basename = init.basename || "/";
  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
  // Config driven behavior flags
  let future = _extends({
    v7_fetcherPersist: false,
    v7_normalizeFormMethod: false,
    v7_partialHydration: false,
    v7_prependBasename: false,
    v7_relativeSplatPath: false,
    v7_skipActionErrorRevalidation: false
  }, init.future);
  // Cleanup function for history
  let unlistenHistory = null;
  // Externally-provided functions to call on all state changes
  let subscribers = new Set();
  // Externally-provided object to hold scroll restoration locations during routing
  let savedScrollPositions = null;
  // Externally-provided function to get scroll restoration keys
  let getScrollRestorationKey = null;
  // Externally-provided function to get current scroll position
  let getScrollPosition = null;
  // One-time flag to control the initial hydration scroll restoration.  Because
  // we don't get the saved positions from <ScrollRestoration /> until _after_
  // the initial render, we need to manually trigger a separate updateState to
  // send along the restoreScrollPosition
  // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  // SSR did the initial scroll restoration.
  let initialScrollRestored = init.hydrationData != null;
  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  let initialMatchesIsFOW = false;
  let initialErrors = null;
  if (initialMatches == null && !patchRoutesOnNavigationImpl) {
    // If we do not match a user-provided-route, fall back to the root
    // to allow the error boundary to take over
    let error = getInternalRouterError(404, {
      pathname: init.history.location.pathname
    });
    let {
      matches,
      route
    } = getShortCircuitMatches(dataRoutes);
    initialMatches = matches;
    initialErrors = {
      [route.id]: error
    };
  }
  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
  // our initial match is a splat route, clear them out so we run through lazy
  // discovery on hydration in case there's a more accurate lazy route match.
  // In SSR apps (with `hydrationData`), we expect that the server will send
  // up the proper matched routes so we don't want to run lazy discovery on
  // initial hydration and want to hydrate into the splat route.
  if (initialMatches && !init.hydrationData) {
    let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
    if (fogOfWar.active) {
      initialMatches = null;
    }
  }
  let initialized;
  if (!initialMatches) {
    initialized = false;
    initialMatches = [];
    // If partial hydration and fog of war is enabled, we will be running
    // `patchRoutesOnNavigation` during hydration so include any partial matches as
    // the initial matches so we can properly render `HydrateFallback`'s
    if (future.v7_partialHydration) {
      let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
      if (fogOfWar.active && fogOfWar.matches) {
        initialMatchesIsFOW = true;
        initialMatches = fogOfWar.matches;
      }
    }
  } else if (initialMatches.some(m => m.route.lazy)) {
    // All initialMatches need to be loaded before we're ready.  If we have lazy
    // functions around still then we'll need to run them in initialize()
    initialized = false;
  } else if (!initialMatches.some(m => m.route.loader)) {
    // If we've got no loaders to run, then we're good to go
    initialized = true;
  } else if (future.v7_partialHydration) {
    // If partial hydration is enabled, we're initialized so long as we were
    // provided with hydrationData for every route with a loader, and no loaders
    // were marked for explicit hydration
    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
    let errors = init.hydrationData ? init.hydrationData.errors : null;
    // If errors exist, don't consider routes below the boundary
    if (errors) {
      let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
      initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
    } else {
      initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
    }
  } else {
    // Without partial hydration - we're initialized if we were provided any
    // hydrationData - which is expected to be complete
    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: new Map(),
    blockers: new Map()
  };
  // -- Stateful internal variables to manage navigations --
  // Current navigation in progress (to be committed in completeNavigation)
  let pendingAction = Action.Pop;
  // Should the current navigation prevent the scroll reset if scroll cannot
  // be restored?
  let pendingPreventScrollReset = false;
  // AbortController for the active navigation
  let pendingNavigationController;
  // Should the current navigation enable document.startViewTransition?
  let pendingViewTransitionEnabled = false;
  // Store applied view transitions so we can apply them on POP
  let appliedViewTransitions = new Map();
  // Cleanup function for persisting applied transitions to sessionStorage
  let removePageHideEventListener = null;
  // We use this to avoid touching history in completeNavigation if a
  // revalidation is entirely uninterrupted
  let isUninterruptedRevalidation = false;
  // Use this internal flag to force revalidation of all loaders:
  //  - submissions (completed or interrupted)
  //  - useRevalidator()
  //  - X-Remix-Revalidate (from redirect)
  let isRevalidationRequired = false;
  // Use this internal array to capture routes that require revalidation due
  // to a cancelled deferred on action submission
  let cancelledDeferredRoutes = [];
  // Use this internal array to capture fetcher loads that were cancelled by an
  // action navigation and require revalidation
  let cancelledFetcherLoads = new Set();
  // AbortControllers for any in-flight fetchers
  let fetchControllers = new Map();
  // Track loads based on the order in which they started
  let incrementingLoadId = 0;
  // Track the outstanding pending navigation data load to be compared against
  // the globally incrementing load when a fetcher load lands after a completed
  // navigation
  let pendingNavigationLoadId = -1;
  // Fetchers that triggered data reloads as a result of their actions
  let fetchReloadIds = new Map();
  // Fetchers that triggered redirect navigations
  let fetchRedirectIds = new Set();
  // Most recent href/match for fetcher.load calls for fetchers
  let fetchLoadMatches = new Map();
  // Ref-count mounted fetchers so we know when it's ok to clean them up
  let activeFetchers = new Map();
  // Fetchers that have requested a delete when using v7_fetcherPersist,
  // they'll be officially removed after they return to idle
  let deletedFetchers = new Set();
  // Store DeferredData instances for active route matches.  When a
  // route loader returns defer() we stick one in here.  Then, when a nested
  // promise resolves we update loaderData.  If a new navigation starts we
  // cancel active deferreds for eliminated routes.
  let activeDeferreds = new Map();
  // Store blocker functions in a separate Map outside of router state since
  // we don't need to update UI state if they change
  let blockerFunctions = new Map();
  // Flag to ignore the next history update, so we can revert the URL change on
  // a POP navigation that was blocked by the user without touching router state
  let unblockBlockerHistoryUpdate = undefined;
  // Initialize the router, all side effects should be kicked off from here.
  // Implemented as a Fluent API for ease of:
  //   let router = createRouter(init).initialize();
  function initialize() {
    // If history informs us of a POP navigation, start the navigation but do not update
    // state.  We'll update our own state once the navigation completes
    unlistenHistory = init.history.listen(_ref => {
      let {
        action: historyAction,
        location,
        delta
      } = _ref;
      // Ignore this event if it was just us resetting the URL from a
      // blocked POP navigation
      if (unblockBlockerHistoryUpdate) {
        unblockBlockerHistoryUpdate();
        unblockBlockerHistoryUpdate = undefined;
        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) {
        // Restore the URL to match the current UI, but don't update router state
        let nextHistoryUpdatePromise = new Promise(resolve => {
          unblockBlockerHistoryUpdate = resolve;
        });
        init.history.go(delta * -1);
        // Put the blocker into a blocked state
        updateBlocker(blockerKey, {
          state: "blocked",
          location,
          proceed() {
            updateBlocker(blockerKey, {
              state: "proceeding",
              proceed: undefined,
              reset: undefined,
              location
            });
            // Re-do the same POP navigation we just blocked, after the url
            // restoration is also complete.  See:
            // https://github.com/remix-run/react-router/issues/11613
            nextHistoryUpdatePromise.then(() => init.history.go(delta));
          },
          reset() {
            let blockers = new Map(state.blockers);
            blockers.set(blockerKey, IDLE_BLOCKER);
            updateState({
              blockers
            });
          }
        });
        return;
      }
      return startNavigation(historyAction, location);
    });
    if (isBrowser) {
      // FIXME: This feels gross.  How can we cleanup the lines between
      // scrollRestoration/appliedTransitions persistance?
      restoreAppliedTransitions(routerWindow, appliedViewTransitions);
      let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
      routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
      removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
    }
    // Kick off initial data load if needed.  Use Pop to avoid modifying history
    // Note we don't do any handling of lazy here.  For SPA's it'll get handled
    // in the normal navigation flow.  For SSR it's expected that lazy modules are
    // resolved prior to router creation since we can't go into a fallbackElement
    // UI for SSR'd apps
    if (!state.initialized) {
      startNavigation(Action.Pop, state.location, {
        initialHydration: true
      });
    }
    return router;
  }
  // Clean up a router and it's side effects
  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));
  }
  // Subscribe to state updates for the router
  function subscribe(fn) {
    subscribers.add(fn);
    return () => subscribers.delete(fn);
  }
  // Update our state and notify the calling context of the change
  function updateState(newState, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state = _extends({}, state, newState);
    // Prep fetcher cleanup so we can tell the UI which fetcher data entries
    // can be removed
    let completedFetchers = [];
    let deletedFetchersKeys = [];
    if (future.v7_fetcherPersist) {
      state.fetchers.forEach((fetcher, key) => {
        if (fetcher.state === "idle") {
          if (deletedFetchers.has(key)) {
            // Unmounted from the UI and can be totally removed
            deletedFetchersKeys.push(key);
          } else {
            // Returned to idle but still mounted in the UI, so semi-remains for
            // revalidations and such
            completedFetchers.push(key);
          }
        }
      });
    }
    // Remove any lingering deleted fetchers that have already been removed
    // from state.fetchers
    deletedFetchers.forEach(key => {
      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
        deletedFetchersKeys.push(key);
      }
    });
    // Iterate over a local copy so that if flushSync is used and we end up
    // removing and adding a new subscriber due to the useCallback dependencies,
    // we don't get ourselves into a loop calling the new subscriber immediately
    [...subscribers].forEach(subscriber => subscriber(state, {
      deletedFetchers: deletedFetchersKeys,
      viewTransitionOpts: opts.viewTransitionOpts,
      flushSync: opts.flushSync === true
    }));
    // Remove idle fetchers from state since we only care about in-flight fetchers.
    if (future.v7_fetcherPersist) {
      completedFetchers.forEach(key => state.fetchers.delete(key));
      deletedFetchersKeys.forEach(key => deleteFetcher(key));
    } else {
      // We already called deleteFetcher() on these, can remove them from this
      // Set now that we've handed the keys off to the data layer
      deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));
    }
  }
  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  // and setting state.[historyAction/location/matches] to the new route.
  // - Location is a required param
  // - Navigation will always be set to IDLE_NAVIGATION
  // - Can pass any other state in newState
  function completeNavigation(location, newState, _temp) {
    var _location$state, _location$state2;
    let {
      flushSync
    } = _temp === void 0 ? {} : _temp;
    // Deduce if we're in a loading/actionReload state:
    // - We have committed actionData in the store
    // - The current navigation was a mutation submission
    // - We're past the submitting state and into the loading state
    // - The location being loaded is not the result of a redirect
    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 {
        // Empty actionData -> clear prior actionData due to an action error
        actionData = null;
      }
    } else if (isActionReload) {
      // Keep the current data if we're wrapping up the action reload
      actionData = state.actionData;
    } else {
      // Clear actionData on any other completed navigations
      actionData = null;
    }
    // Always preserve any existing loaderData from re-used routes
    let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
    // On a successful navigation we can assume we got through all blockers
    // so we can start fresh
    let blockers = state.blockers;
    if (blockers.size > 0) {
      blockers = new Map(blockers);
      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
    }
    // Always respect the user flag.  Otherwise don't reset on mutation
    // submission navigations unless they redirect
    let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
    // Commit any in-flight routes at the end of the HMR revalidation "navigation"
    if (inFlightDataRoutes) {
      dataRoutes = inFlightDataRoutes;
      inFlightDataRoutes = undefined;
    }
    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;
    // On POP, enable transitions if they were enabled on the original navigation
    if (pendingAction === Action.Pop) {
      // Forward takes precedence so they behave like the original navigation
      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)) {
        // If we don't have a previous forward nav, assume we're popping back to
        // the new location and enable if that location previously enabled
        viewTransitionOpts = {
          currentLocation: location,
          nextLocation: state.location
        };
      }
    } else if (pendingViewTransitionEnabled) {
      // Store the applied transition on PUSH/REPLACE
      let toPaths = appliedViewTransitions.get(state.location.pathname);
      if (toPaths) {
        toPaths.add(location.pathname);
      } else {
        toPaths = 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
    });
    // Reset stateful navigation vars
    pendingAction = Action.Pop;
    pendingPreventScrollReset = false;
    pendingViewTransitionEnabled = false;
    isUninterruptedRevalidation = false;
    isRevalidationRequired = false;
    cancelledDeferredRoutes = [];
  }
  // Trigger a navigation event, which can either be a numerical POP or a PUSH
  // replace with an optional submission
  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);
    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
    // URL from window.location, so we need to encode it here so the behavior
    // remains the same as POP and non-data-router usages.  new URL() does all
    // the same encoding we'd get from a history.pushState/window.location read
    // without having to touch history
    nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
    let userReplace = opts && opts.replace != null ? opts.replace : undefined;
    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) {
      // By default on submissions to the current location we REPLACE so that
      // users don't have to double-click the back button to get to the prior
      // location.  If the user redirects to a different location from the
      // action/loader this will be ignored and the redirect will be a PUSH
      historyAction = Action.Replace;
    }
    let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
    let flushSync = (opts && opts.flushSync) === true;
    let blockerKey = shouldBlockNavigation({
      currentLocation,
      nextLocation,
      historyAction
    });
    if (blockerKey) {
      // Put the blocker into a blocked state
      updateBlocker(blockerKey, {
        state: "blocked",
        location: nextLocation,
        proceed() {
          updateBlocker(blockerKey, {
            state: "proceeding",
            proceed: undefined,
            reset: undefined,
            location: nextLocation
          });
          // Send the same navigation through
          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.viewTransition,
      flushSync
    });
  }
  // Revalidate all current loaders.  If a navigation is in progress or if this
  // is interrupted by a navigation, allow this to "succeed" by calling all
  // loaders during the next loader round
  function revalidate() {
    interruptActiveLoads();
    updateState({
      revalidation: "loading"
    });
    // If we're currently submitting an action, we don't need to start a new
    // navigation, we'll just let the follow up loader execution call all loaders
    if (state.navigation.state === "submitting") {
      return;
    }
    // If we're currently in an idle state, start a new navigation for the current
    // action/location and mark it as uninterrupted, which will skip the history
    // update in completeNavigation
    if (state.navigation.state === "idle") {
      startNavigation(state.historyAction, state.location, {
        startUninterruptedRevalidation: true
      });
      return;
    }
    // Otherwise, if we're currently in a loading state, just start a new
    // navigation to the navigation.location but do not trigger an uninterrupted
    // revalidation so that history correctly updates once the navigation completes
    startNavigation(pendingAction || state.historyAction, state.navigation.location, {
      overrideNavigation: state.navigation,
      // Proxy through any rending view transition
      enableViewTransition: pendingViewTransitionEnabled === true
    });
  }
  // Start a navigation to the given action/location.  Can optionally provide a
  // overrideNavigation which will override the normalLoad in the case of a redirect
  // navigation
  async function startNavigation(historyAction, location, opts) {
    // Abort any in-progress navigations and start a new one. Unset any ongoing
    // uninterrupted revalidations unless told otherwise, since we want this
    // new navigation to update history normally
    pendingNavigationController && pendingNavigationController.abort();
    pendingNavigationController = null;
    pendingAction = historyAction;
    isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
    // Save the current scroll position every time we start a new navigation,
    // and track whether we should reset scroll on completion
    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 = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?
    // `matchRoutes()` has already been called if we're in here via `router.initialize()`
    state.matches : matchRoutes(routesToUse, location, basename);
    let flushSync = (opts && opts.flushSync) === true;
    // Short circuit if it's only a hash change and not a revalidation or
    // mutation submission.
    //
    // Ignore on initial page loads because since the initial hydration will always
    // be "same hash".  For example, on /page#hash and submit a <Form method="post">
    // which will default to a navigation to /page
    if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
      completeNavigation(location, {
        matches
      }, {
        flushSync
      });
      return;
    }
    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }
    // Short circuit with a 404 on the root error boundary if we match nothing
    if (!matches) {
      let {
        error,
        notFoundMatches,
        route
      } = handleNavigational404(location.pathname);
      completeNavigation(location, {
        matches: notFoundMatches,
        loaderData: {},
        errors: {
          [route.id]: error
        }
      }, {
        flushSync
      });
      return;
    }
    // Create a controller/Request for this navigation
    pendingNavigationController = new AbortController();
    let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
    let pendingActionResult;
    if (opts && opts.pendingError) {
      // If we have a pendingError, it means the user attempted a GET submission
      // with binary FormData so assign here and skip to handleLoaders.  That
      // way we handle calling loaders above the boundary etc.  It's not really
      // different from an actionError in that sense.
      pendingActionResult = [findNearestBoundary(matches).route.id, {
        type: ResultType.error,
        error: opts.pendingError
      }];
    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
      // Call action if we received an action submission
      let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
        replace: opts.replace,
        flushSync
      });
      if (actionResult.shortCircuited) {
        return;
      }
      // If we received a 404 from handleAction, it's because we couldn't lazily
      // discover the destination route so we don't want to call loaders
      if (actionResult.pendingActionResult) {
        let [routeId, result] = actionResult.pendingActionResult;
        if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
          pendingNavigationController = null;
          completeNavigation(location, {
            matches: actionResult.matches,
            loaderData: {},
            errors: {
              [routeId]: result.error
            }
          });
          return;
        }
      }
      matches = actionResult.matches || matches;
      pendingActionResult = actionResult.pendingActionResult;
      loadingNavigation = getLoadingNavigation(location, opts.submission);
      flushSync = false;
      // No need to do fog of war matching again on loader execution
      fogOfWar.active = false;
      // Create a GET request for the loaders
      request = createClientSideRequest(init.history, request.url, request.signal);
    }
    // Call loaders
    let {
      shortCircuited,
      matches: updatedMatches,
      loaderData,
      errors
    } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
    if (shortCircuited) {
      return;
    }
    // Clean up now that the action/loaders have completed.  Don't clean up if
    // we short circuited because pendingNavigationController will have already
    // been assigned to a new controller for the next navigation
    pendingNavigationController = null;
    completeNavigation(location, _extends({
      matches: updatedMatches || matches
    }, getActionDataForCommit(pendingActionResult), {
      loaderData,
      errors
    }));
  }
  // Call the action matched by the leaf route for this navigation and handle
  // redirects/errors
  async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
    if (opts === void 0) {
      opts = {};
    }
    interruptActiveLoads();
    // Put us in a submitting state
    let navigation = getSubmittingNavigation(location, submission);
    updateState({
      navigation
    }, {
      flushSync: opts.flushSync === true
    });
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
      if (discoverResult.type === "aborted") {
        return {
          shortCircuited: true
        };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          pendingActionResult: [boundaryId, {
            type: ResultType.error,
            error: discoverResult.error
          }]
        };
      } else if (!discoverResult.matches) {
        let {
          notFoundMatches,
          error,
          route
        } = handleNavigational404(location.pathname);
        return {
          matches: notFoundMatches,
          pendingActionResult: [route.id, {
            type: ResultType.error,
            error
          }]
        };
      } else {
        matches = discoverResult.matches;
      }
    }
    // Call our action and get the result
    let result;
    let actionMatch = getTargetMatch(matches, location);
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      result = {
        type: ResultType.error,
        error: getInternalRouterError(405, {
          method: request.method,
          pathname: location.pathname,
          routeId: actionMatch.route.id
        })
      };
    } else {
      let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
      result = results[actionMatch.route.id];
      if (request.signal.aborted) {
        return {
          shortCircuited: true
        };
      }
    }
    if (isRedirectResult(result)) {
      let replace;
      if (opts && opts.replace != null) {
        replace = opts.replace;
      } else {
        // If the user didn't explicity indicate replace behavior, replace if
        // we redirected to the exact same location we're currently at to avoid
        // double back-buttons
        let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
        replace = location === state.location.pathname + state.location.search;
      }
      await startRedirectNavigation(request, result, true, {
        submission,
        replace
      });
      return {
        shortCircuited: true
      };
    }
    if (isDeferredResult(result)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
      // By default, all submissions to the current location are REPLACE
      // navigations, but if the action threw an error that'll be rendered in
      // an errorElement, we fall back to PUSH so that the user can use the
      // back button to get back to the pre-submission form location to try
      // again
      if ((opts && opts.replace) !== true) {
        pendingAction = Action.Push;
      }
      return {
        matches,
        pendingActionResult: [boundaryMatch.route.id, result]
      };
    }
    return {
      matches,
      pendingActionResult: [actionMatch.route.id, result]
    };
  }
  // Call all applicable loaders for the given matches, handling redirects,
  // errors, etc.
  async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
    // Figure out the right navigation we want to use for data loading
    let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
    // If this was a redirect from an action we don't have a "submission" but
    // we have it on the loading navigation so use that if available
    let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
    // If this is an uninterrupted revalidation, we remain in our current idle
    // state.  If not, we need to switch to our loading state and load data,
    // preserving any new action data or existing action data (in the case of
    // a revalidation interrupting an actionReload)
    // If we have partialHydration enabled, then don't update the state for the
    // initial data load since it's not a "navigation"
    let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);
    // When fog of war is enabled, we enter our `loading` state earlier so we
    // can discover new routes during the `loading` state.  We skip this if
    // we've already run actions since we would have done our matching already.
    // If the children() function threw then, we want to proceed with the
    // partial matches it discovered.
    if (isFogOfWar) {
      if (shouldUpdateNavigationState) {
        let actionData = getUpdatedActionData(pendingActionResult);
        updateState(_extends({
          navigation: loadingNavigation
        }, actionData !== undefined ? {
          actionData
        } : {}), {
          flushSync
        });
      }
      let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
      if (discoverResult.type === "aborted") {
        return {
          shortCircuited: true
        };
      } else if (discoverResult.type === "error") {
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          loaderData: {},
          errors: {
            [boundaryId]: discoverResult.error
          }
        };
      } else if (!discoverResult.matches) {
        let {
          error,
          notFoundMatches,
          route
        } = handleNavigational404(location.pathname);
        return {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error
          }
        };
      } else {
        matches = discoverResult.matches;
      }
    }
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);
    // Cancel pending deferreds for no-longer-matched routes or routes we're
    // about to reload.  Note that if this is an action reload we would have
    // already cancelled all pending deferreds so this would be a no-op
    cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
    pendingNavigationLoadId = ++incrementingLoadId;
    // Short circuit if we have no loaders to run
    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
      let updatedFetchers = markFetchRedirectsDone();
      completeNavigation(location, _extends({
        matches,
        loaderData: {},
        // Commit pending error if we're short circuiting
        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
          [pendingActionResult[0]]: pendingActionResult[1].error
        } : null
      }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
        fetchers: new Map(state.fetchers)
      } : {}), {
        flushSync
      });
      return {
        shortCircuited: true
      };
    }
    if (shouldUpdateNavigationState) {
      let updates = {};
      if (!isFogOfWar) {
        // Only update navigation/actionNData if we didn't already do it above
        updates.navigation = loadingNavigation;
        let actionData = getUpdatedActionData(pendingActionResult);
        if (actionData !== undefined) {
          updates.actionData = actionData;
        }
      }
      if (revalidatingFetchers.length > 0) {
        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
      }
      updateState(updates, {
        flushSync
      });
    }
    revalidatingFetchers.forEach(rf => {
      abortFetcher(rf.key);
      if (rf.controller) {
        // Fetchers use an independent AbortController so that aborting a fetcher
        // (via deleteFetcher) does not abort the triggering navigation that
        // triggered the revalidation
        fetchControllers.set(rf.key, rf.controller);
      }
    });
    // Proxy navigation abort through to revalidation fetchers
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
    if (pendingNavigationController) {
      pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    }
    let {
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
    if (request.signal.aborted) {
      return {
        shortCircuited: true
      };
    }
    // Clean up _after_ loaders have completed.  Don't clean up if we short
    // circuited because fetchControllers would have been aborted and
    // reassigned to new controllers for the next navigation
    if (pendingNavigationController) {
      pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    }
    revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));
    // If any loaders returned a redirect Response, start a new REPLACE navigation
    let redirect = findRedirect(loaderResults);
    if (redirect) {
      await startRedirectNavigation(request, redirect.result, true, {
        replace
      });
      return {
        shortCircuited: true
      };
    }
    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      await startRedirectNavigation(request, redirect.result, true, {
        replace
      });
      return {
        shortCircuited: true
      };
    }
    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);
    // Wire up subscribers to update loaderData as promises settle
    activeDeferreds.forEach((deferredData, routeId) => {
      deferredData.subscribe(aborted => {
        // Note: No need to updateState here since the TrackedPromise on
        // loaderData is stable across resolve/reject
        // Remove this instance if we were aborted or if promises have settled
        if (aborted || deferredData.done) {
          activeDeferreds.delete(routeId);
        }
      });
    });
    // Preserve SSR errors during partial hydration
    if (future.v7_partialHydration && initialHydration && state.errors) {
      errors = _extends({}, state.errors, errors);
    }
    let updatedFetchers = markFetchRedirectsDone();
    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
    let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
    return _extends({
      matches,
      loaderData,
      errors
    }, shouldUpdateFetchers ? {
      fetchers: new Map(state.fetchers)
    } : {});
  }
  function getUpdatedActionData(pendingActionResult) {
    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
      // This is cast to `any` currently because `RouteData`uses any and it
      // would be a breaking change to use any.
      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
      return {
        [pendingActionResult[0]]: pendingActionResult[1].data
      };
    } else if (state.actionData) {
      if (Object.keys(state.actionData).length === 0) {
        return null;
      } else {
        return state.actionData;
      }
    }
  }
  function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
    revalidatingFetchers.forEach(rf => {
      let fetcher = state.fetchers.get(rf.key);
      let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
      state.fetchers.set(rf.key, revalidatingFetcher);
    });
    return new Map(state.fetchers);
  }
  // Trigger a fetcher load/submit for the given fetcher key
  function fetch(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.");
    }
    abortFetcher(key);
    let flushSync = (opts && opts.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);
    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }
    if (!matches) {
      setFetcherError(key, routeId, getInternalRouterError(404, {
        pathname: normalizedPath
      }), {
        flushSync
      });
      return;
    }
    let {
      path,
      submission,
      error
    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
    if (error) {
      setFetcherError(key, routeId, error, {
        flushSync
      });
      return;
    }
    let match = getTargetMatch(matches, path);
    let preventScrollReset = (opts && opts.preventScrollReset) === true;
    if (submission && isMutationMethod(submission.formMethod)) {
      handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
      return;
    }
    // Store off the match so we can call it's shouldRevalidate on subsequent
    // revalidations
    fetchLoadMatches.set(key, {
      routeId,
      path
    });
    handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  }
  // Call the action for the matched fetcher.submit(), and then handle redirects,
  // errors, and revalidation
  async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
    interruptActiveLoads();
    fetchLoadMatches.delete(key);
    function detectAndHandle405Error(m) {
      if (!m.route.action && !m.route.lazy) {
        let error = getInternalRouterError(405, {
          method: submission.formMethod,
          pathname: path,
          routeId: routeId
        });
        setFetcherError(key, routeId, error, {
          flushSync
        });
        return true;
      }
      return false;
    }
    if (!isFogOfWar && detectAndHandle405Error(match)) {
      return;
    }
    // Put this fetcher into it's submitting state
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
      flushSync
    });
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, {
          flushSync
        });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(key, routeId, getInternalRouterError(404, {
          pathname: path
        }), {
          flushSync
        });
        return;
      } else {
        requestMatches = discoverResult.matches;
        match = getTargetMatch(requestMatches, path);
        if (detectAndHandle405Error(match)) {
          return;
        }
      }
    }
    // Call the action for the fetcher
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
    let actionResult = actionResults[match.route.id];
    if (fetchRequest.signal.aborted) {
      // We can delete this so long as we weren't aborted by our own fetcher
      // re-submit which would have put _new_ controller is in fetchControllers
      if (fetchControllers.get(key) === abortController) {
        fetchControllers.delete(key);
      }
      return;
    }
    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
    // or redirects processed for unmounted fetchers so we just revert them to
    // idle
    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      }
      // Let SuccessResult's fall through for revalidation
    } else {
      if (isRedirectResult(actionResult)) {
        fetchControllers.delete(key);
        if (pendingNavigationLoadId > originatingLoadId) {
          // A new navigation was kicked off after our action started, so that
          // should take precedence over this redirect navigation.  We already
          // set isRevalidationRequired so all loaders for the new route should
          // fire unless opted out via shouldRevalidate
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        } else {
          fetchRedirectIds.add(key);
          updateFetcherState(key, getLoadingFetcher(submission));
          return startRedirectNavigation(fetchRequest, actionResult, false, {
            fetcherSubmission: submission,
            preventScrollReset
          });
        }
      }
      // Process any non-redirect errors thrown
      if (isErrorResult(actionResult)) {
        setFetcherError(key, routeId, actionResult.error);
        return;
      }
    }
    if (isDeferredResult(actionResult)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }
    // Start the data load for current matches, or the next location if we're
    // in the middle of a navigation
    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, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);
    // Put all revalidating fetchers into the loading state, except for the
    // current fetcher which we want to keep in it's current loading state which
    // contains it's action submission info + action data
    revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
      let staleKey = rf.key;
      let existingFetcher = state.fetchers.get(staleKey);
      let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
      state.fetchers.set(staleKey, revalidatingFetcher);
      abortFetcher(staleKey);
      if (rf.controller) {
        fetchControllers.set(staleKey, rf.controller);
      }
    });
    updateState({
      fetchers: new Map(state.fetchers)
    });
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
    abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    let {
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
    if (abortController.signal.aborted) {
      return;
    }
    abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    fetchReloadIds.delete(key);
    fetchControllers.delete(key);
    revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
    let redirect = findRedirect(loaderResults);
    if (redirect) {
      return startRedirectNavigation(revalidationRequest, redirect.result, false, {
        preventScrollReset
      });
    }
    redirect = findRedirect(fetcherResults);
    if (redirect) {
      // If this redirect came from a fetcher make sure we mark it in
      // fetchRedirectIds so it doesn't get revalidated on the next set of
      // loader executions
      fetchRedirectIds.add(redirect.key);
      return startRedirectNavigation(revalidationRequest, redirect.result, false, {
        preventScrollReset
      });
    }
    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
    // Since we let revalidations complete even if the submitting fetcher was
    // deleted, only put it back to idle if it hasn't been deleted
    if (state.fetchers.has(key)) {
      let doneFetcher = getDoneFetcher(actionResult.data);
      state.fetchers.set(key, doneFetcher);
    }
    abortStaleFetchLoads(loadId);
    // If we are currently in a navigation loading state and this fetcher is
    // more recent than the navigation, we want the newer data so abort the
    // navigation and complete it with the fetcher data
    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 {
      // otherwise just update with the fetcher data, preserving any existing
      // loaderData for loaders that did not need to reload.  We have to
      // manually merge here since we aren't going through completeNavigation
      updateState({
        errors,
        loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
        fetchers: new Map(state.fetchers)
      });
      isRevalidationRequired = false;
    }
  }
  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
      flushSync
    });
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key, routeId, discoverResult.error, {
          flushSync
        });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(key, routeId, getInternalRouterError(404, {
          pathname: path
        }), {
          flushSync
        });
        return;
      } else {
        matches = discoverResult.matches;
        match = getTargetMatch(matches, path);
      }
    }
    // Call the loader for this fetcher route match
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
    let result = results[match.route.id];
    // Deferred isn't supported for fetcher loads, await everything and treat it
    // as a normal load.  resolveDeferredData will return undefined if this
    // fetcher gets aborted, so we just leave result untouched and short circuit
    // below if that happens
    if (isDeferredResult(result)) {
      result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
    }
    // We can delete this so long as we weren't aborted by our our own fetcher
    // re-load which would have put _new_ controller is in fetchControllers
    if (fetchControllers.get(key) === abortController) {
      fetchControllers.delete(key);
    }
    if (fetchRequest.signal.aborted) {
      return;
    }
    // We don't want errors bubbling up or redirects followed for unmounted
    // fetchers, so short circuit here if it was removed from the UI
    if (deletedFetchers.has(key)) {
      updateFetcherState(key, getDoneFetcher(undefined));
      return;
    }
    // If the loader threw a redirect Response, start a new REPLACE navigation
    if (isRedirectResult(result)) {
      if (pendingNavigationLoadId > originatingLoadId) {
        // A new navigation was kicked off after our loader started, so that
        // should take precedence over this redirect navigation
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      } else {
        fetchRedirectIds.add(key);
        await startRedirectNavigation(fetchRequest, result, false, {
          preventScrollReset
        });
        return;
      }
    }
    // Process any non-redirect errors thrown
    if (isErrorResult(result)) {
      setFetcherError(key, routeId, result.error);
      return;
    }
    invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
    // Put the fetcher back into an idle state
    updateFetcherState(key, getDoneFetcher(result.data));
  }
  /**
   * Utility function to handle redirects returned from an action or loader.
   * Normally, a redirect "replaces" the navigation that triggered it.  So, for
   * example:
   *
   *  - user is on /a
   *  - user clicks a link to /b
   *  - loader for /b redirects to /c
   *
   * In a non-JS app the browser would track the in-flight navigation to /b and
   * then replace it with /c when it encountered the redirect response.  In
   * the end it would only ever update the URL bar with /c.
   *
   * In client-side routing using pushState/replaceState, we aim to emulate
   * this behavior and we also do not update history until the end of the
   * navigation (including processed redirects).  This means that we never
   * actually touch history until we've processed redirects, so we just use
   * the history action from the original navigation (PUSH or REPLACE).
   */
  async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
    let {
      submission,
      fetcherSubmission,
      preventScrollReset,
      replace
    } = _temp2 === void 0 ? {} : _temp2;
    if (redirect.response.headers.has("X-Remix-Revalidate")) {
      isRevalidationRequired = true;
    }
    let location = redirect.response.headers.get("Location");
    invariant(location, "Expected a Location header on the redirect Response");
    location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
    let redirectLocation = createLocation(state.location, location, {
      _isRedirect: true
    });
    if (isBrowser) {
      let isDocumentReload = false;
      if (redirect.response.headers.has("X-Remix-Reload-Document")) {
        // Hard reload if the response contained X-Remix-Reload-Document
        isDocumentReload = true;
      } else if (ABSOLUTE_URL_REGEX.test(location)) {
        const url = init.history.createURL(location);
        isDocumentReload =
        // Hard reload if it's an absolute URL to a new origin
        url.origin !== routerWindow.location.origin ||
        // Hard reload if it's an absolute URL that does not match our basename
        stripBasename(url.pathname, basename) == null;
      }
      if (isDocumentReload) {
        if (replace) {
          routerWindow.location.replace(location);
        } else {
          routerWindow.location.assign(location);
        }
        return;
      }
    }
    // There's no need to abort on redirects, since we don't detect the
    // redirect until the action/loaders have settled
    pendingNavigationController = null;
    let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;
    // Use the incoming submission if provided, fallback on the active one in
    // state.navigation
    let {
      formMethod,
      formAction,
      formEncType
    } = state.navigation;
    if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
      submission = getSubmissionFromNavigation(state.navigation);
    }
    // If this was a 307/308 submission we want to preserve the HTTP method and
    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
    // redirected location
    let activeSubmission = submission || fetcherSubmission;
    if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
      await startNavigation(redirectHistoryAction, redirectLocation, {
        submission: _extends({}, activeSubmission, {
          formAction: location
        }),
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
      });
    } else {
      // If we have a navigation submission, we will preserve it through the
      // redirect navigation
      let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
      await startNavigation(redirectHistoryAction, redirectLocation, {
        overrideNavigation,
        // Send fetcher submissions through for shouldRevalidate
        fetcherSubmission,
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
      });
    }
  }
  // Utility wrapper for calling dataStrategy client-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
    let results;
    let dataResults = {};
    try {
      results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
    } catch (e) {
      // If the outer dataStrategy method throws, just return the error for all
      // matches - and it'll naturally bubble to the root
      matchesToLoad.forEach(m => {
        dataResults[m.route.id] = {
          type: ResultType.error,
          error: e
        };
      });
      return dataResults;
    }
    for (let [routeId, result] of Object.entries(results)) {
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result;
        dataResults[routeId] = {
          type: ResultType.redirect,
          response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
        };
      } else {
        dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
      }
    }
    return dataResults;
  }
  async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
    let currentMatches = state.matches;
    // Kick off loaders and fetchers in parallel
    let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
    let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
      if (f.matches && f.match && f.controller) {
        let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
        let result = results[f.match.route.id];
        // Fetcher results are keyed by fetcher key from here on out, not routeId
        return {
          [f.key]: result
        };
      } else {
        return Promise.resolve({
          [f.key]: {
            type: ResultType.error,
            error: getInternalRouterError(404, {
              pathname: f.path
            })
          }
        });
      }
    }));
    let loaderResults = await loaderResultsPromise;
    let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
    await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
    return {
      loaderResults,
      fetcherResults
    };
  }
  function interruptActiveLoads() {
    // Every interruption triggers a revalidation
    isRevalidationRequired = true;
    // Cancel pending route-level deferreds and mark cancelled routes for
    // revalidation
    cancelledDeferredRoutes.push(...cancelActiveDeferreds());
    // Abort in-flight fetcher loads
    fetchLoadMatches.forEach((_, key) => {
      if (fetchControllers.has(key)) {
        cancelledFetcherLoads.add(key);
      }
      abortFetcher(key);
    });
  }
  function updateFetcherState(key, fetcher, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state.fetchers.set(key, fetcher);
    updateState({
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function setFetcherError(key, routeId, error, opts) {
    if (opts === void 0) {
      opts = {};
    }
    let boundaryMatch = findNearestBoundary(state.matches, routeId);
    deleteFetcher(key);
    updateState({
      errors: {
        [boundaryMatch.route.id]: error
      },
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function getFetcher(key) {
    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
    // If this fetcher was previously marked for deletion, unmark it since we
    // have a new instance
    if (deletedFetchers.has(key)) {
      deletedFetchers.delete(key);
    }
    return state.fetchers.get(key) || IDLE_FETCHER;
  }
  function deleteFetcher(key) {
    let fetcher = state.fetchers.get(key);
    // Don't abort the controller if this is a deletion of a fetcher.submit()
    // in it's loading phase since - we don't want to abort the corresponding
    // revalidation and want them to complete and land
    if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
      abortFetcher(key);
    }
    fetchLoadMatches.delete(key);
    fetchReloadIds.delete(key);
    fetchRedirectIds.delete(key);
    // If we opted into the flag we can clear this now since we're calling
    // deleteFetcher() at the end of updateState() and we've already handed the
    // deleted fetcher keys off to the data layer.
    // If not, we're eagerly calling deleteFetcher() and we need to keep this
    // Set populated until the next updateState call, and we'll clear
    // `deletedFetchers` then
    if (future.v7_fetcherPersist) {
      deletedFetchers.delete(key);
    }
    cancelledFetcherLoads.delete(key);
    state.fetchers.delete(key);
  }
  function deleteFetcherAndUpdateState(key) {
    let count = (activeFetchers.get(key) || 0) - 1;
    if (count <= 0) {
      activeFetchers.delete(key);
      deletedFetchers.add(key);
      if (!future.v7_fetcherPersist) {
        deleteFetcher(key);
      }
    } else {
      activeFetchers.set(key, count);
    }
    updateState({
      fetchers: new Map(state.fetchers)
    });
  }
  function abortFetcher(key) {
    let controller = fetchControllers.get(key);
    if (controller) {
      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);
  }
  // Utility function to update blockers, ensuring valid state transitions
  function updateBlocker(key, newBlocker) {
    let blocker = state.blockers.get(key) || IDLE_BLOCKER;
    // Poor mans state machine :)
    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
    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;
    }
    // We ony support a single active blocker at the moment since we don't have
    // any compelling use cases for multi-blocker yet
    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") {
      // If the blocker is currently proceeding, we don't need to re-check
      // it and can let this navigation continue
      return;
    }
    // At this point, we know we're unblocked/blocked so we need to check the
    // user-provided blocker function
    if (blockerFunction({
      currentLocation,
      nextLocation,
      historyAction
    })) {
      return blockerKey;
    }
  }
  function handleNavigational404(pathname) {
    let error = getInternalRouterError(404, {
      pathname
    });
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let {
      matches,
      route
    } = getShortCircuitMatches(routesToUse);
    // Cancel all pending deferred on 404s since we don't keep any routes
    cancelActiveDeferreds();
    return {
      notFoundMatches: matches,
      route,
      error
    };
  }
  function cancelActiveDeferreds(predicate) {
    let cancelledRouteIds = [];
    activeDeferreds.forEach((dfd, routeId) => {
      if (!predicate || predicate(routeId)) {
        // Cancel the deferred - but do not remove from activeDeferreds here -
        // we rely on the subscribers to do that so our tests can assert proper
        // cleanup via _internalActiveDeferreds
        dfd.cancel();
        cancelledRouteIds.push(routeId);
        activeDeferreds.delete(routeId);
      }
    });
    return cancelledRouteIds;
  }
  // Opt in to capturing and reporting scroll positions during navigations,
  // used by the <ScrollRestoration> component
  function enableScrollRestoration(positions, getPosition, getKey) {
    savedScrollPositions = positions;
    getScrollPosition = getPosition;
    getScrollRestorationKey = getKey || null;
    // Perform initial hydration scroll restoration, since we miss the boat on
    // the initial updateState() because we've not yet rendered <ScrollRestoration/>
    // and therefore have no savedScrollPositions available
    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
      initialScrollRestored = true;
      let y = getSavedScrollPosition(state.location, state.matches);
      if (y != null) {
        updateState({
          restoreScrollPosition: y
        });
      }
    }
    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 y = savedScrollPositions[key];
      if (typeof y === "number") {
        return y;
      }
    }
    return null;
  }
  function checkFogOfWar(matches, routesToUse, pathname) {
    if (patchRoutesOnNavigationImpl) {
      if (!matches) {
        let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
        return {
          active: true,
          matches: fogMatches || []
        };
      } else {
        if (Object.keys(matches[0].params).length > 0) {
          // If we matched a dynamic param or a splat, it might only be because
          // we haven't yet discovered other routes that would match with a
          // higher score.  Call patchRoutesOnNavigation just to be sure
          let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
          return {
            active: true,
            matches: partialMatches
          };
        }
      }
    }
    return {
      active: false,
      matches: null
    };
  }
  async function discoverRoutes(matches, pathname, signal, fetcherKey) {
    if (!patchRoutesOnNavigationImpl) {
      return {
        type: "success",
        matches
      };
    }
    let partialMatches = matches;
    while (true) {
      let isNonHMR = inFlightDataRoutes == null;
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let localManifest = manifest;
      try {
        await patchRoutesOnNavigationImpl({
          signal,
          path: pathname,
          matches: partialMatches,
          fetcherKey,
          patch: (routeId, children) => {
            if (signal.aborted) return;
            patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
          }
        });
      } catch (e) {
        return {
          type: "error",
          error: e,
          partialMatches
        };
      } finally {
        // If we are not in the middle of an HMR revalidation and we changed the
        // routes, provide a new identity so when we `updateState` at the end of
        // this navigation/fetch `router.routes` will be a new identity and
        // trigger a re-run of memoized `router.routes` dependencies.
        // HMR will already update the identity and reflow when it lands
        // `inFlightDataRoutes` in `completeNavigation`
        if (isNonHMR && !signal.aborted) {
          dataRoutes = [...dataRoutes];
        }
      }
      if (signal.aborted) {
        return {
          type: "aborted"
        };
      }
      let newMatches = matchRoutes(routesToUse, pathname, basename);
      if (newMatches) {
        return {
          type: "success",
          matches: newMatches
        };
      }
      let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
      // Avoid loops if the second pass results in the same partial matches
      if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
        return {
          type: "success",
          matches: null
        };
      }
      partialMatches = newPartialMatches;
    }
  }
  function _internalSetRoutes(newRoutes) {
    manifest = {};
    inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
  }
  function patchRoutes(routeId, children) {
    let isNonHMR = inFlightDataRoutes == null;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);
    // If we are not in the middle of an HMR revalidation and we changed the
    // routes, provide a new identity and trigger a reflow via `updateState`
    // to re-run memoized `router.routes` dependencies.
    // HMR will already update the identity and reflow when it lands
    // `inFlightDataRoutes` in `completeNavigation`
    if (isNonHMR) {
      dataRoutes = [...dataRoutes];
      updateState({});
    }
  }
  router = {
    get basename() {
      return basename;
    },
    get future() {
      return future;
    },
    get state() {
      return state;
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return routerWindow;
    },
    initialize,
    subscribe,
    enableScrollRestoration,
    navigate,
    fetch,
    revalidate,
    // Passthrough to history-aware createHref used by useHref so we get proper
    // hash-aware URLs in DOM paths
    createHref: to => init.history.createHref(to),
    encodeLocation: to => init.history.encodeLocation(to),
    getFetcher,
    deleteFetcher: deleteFetcherAndUpdateState,
    dispose,
    getBlocker,
    deleteBlocker,
    patchRoutes,
    _internalFetchControllers: fetchControllers,
    _internalActiveDeferreds: activeDeferreds,
    // TODO: Remove setRoutes, it's temporary to avoid dealing with
    // updating the tree while validating the update algorithm.
    _internalSetRoutes
  };
  return router;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createStaticHandler
////////////////////////////////////////////////////////////////////////////////
const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
function createStaticHandler(routes, opts) {
  invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  let manifest = {};
  let basename = (opts ? opts.basename : null) || "/";
  let mapRouteProperties;
  if (opts != null && opts.mapRouteProperties) {
    mapRouteProperties = opts.mapRouteProperties;
  } else if (opts != null && opts.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = opts.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Config driven behavior flags
  let future = _extends({
    v7_relativeSplatPath: false,
    v7_throwAbortReason: false
  }, opts ? opts.future : null);
  let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);
  /**
   * The query() method is intended for document requests, in which we want to
   * call an optional action and potentially multiple loaders for all nested
   * routes.  It returns a StaticHandlerContext object, which is very similar
   * to the router state (location, loaderData, actionData, errors, etc.) and
   * also adds SSR-specific information such as the statusCode and headers
   * from action/loaders Responses.
   *
   * It _should_ never throw and should report all errors through the
   * returned context.errors object, properly associating errors to their error
   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be
   * used to emulate React error boundaries during SSr by performing a second
   * pass only down to the boundaryId.
   *
   * The one exception where we do not return a StaticHandlerContext is when a
   * redirect response is returned or thrown from any action/loader.  We
   * propagate that out and return the raw Response so the HTTP server can
   * return it directly.
   *
   * - `opts.requestContext` is an optional server context that will be passed
   *   to actions/loaders in the `context` parameter
   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
   *   the bubbling of errors which allows single-fetch-type implementations
   *   where the client will handle the bubbling and we may need to return data
   *   for the handling route
   */
  async function query(request, _temp3) {
    let {
      requestContext,
      skipLoaderErrorBubbling,
      dataStrategy
    } = _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);
    // SSR supports HEAD requests while SPA doesn't
    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, dataStrategy || null, skipLoaderErrorBubbling === true, null);
    if (isResponse(result)) {
      return result;
    }
    // When returning StaticHandlerContext, we patch back in the location here
    // since we need it for React Context.  But this helps keep our submit and
    // loadRouteData operating on a Request instead of a Location
    return _extends({
      location,
      basename
    }, result);
  }
  /**
   * The queryRoute() method is intended for targeted route requests, either
   * for fetch ?_data requests or resource route requests.  In this case, we
   * are only ever calling a single action or loader, and we are returning the
   * returned value directly.  In most cases, this will be a Response returned
   * from the action/loader, but it may be a primitive or other value as well -
   * and in such cases the calling context should handle that accordingly.
   *
   * We do respect the throw/return differentiation, so if an action/loader
   * throws, then this method will throw the value.  This is important so we
   * can do proper boundary identification in Remix where a thrown Response
   * must go to the Catch Boundary but a returned Response is happy-path.
   *
   * One thing to note is that any Router-initiated Errors that make sense
   * to associate with a status code will be thrown as an ErrorResponse
   * instance which include the raw Error, such that the calling context can
   * serialize the error as they see fit while including the proper response
   * code.  Examples here are 404 and 405 errors that occur prior to reaching
   * any user-defined loaders.
   *
   * - `opts.routeId` allows you to specify the specific route handler to call.
   *   If not provided the handler will determine the proper route by matching
   *   against `request.url`
   * - `opts.requestContext` is an optional server context that will be passed
   *    to actions/loaders in the `context` parameter
   */
  async function queryRoute(request, _temp4) {
    let {
      routeId,
      requestContext,
      dataStrategy
    } = _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);
    // SSR supports HEAD requests while SPA doesn't
    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) {
      // This should never hit I don't think?
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
    if (isResponse(result)) {
      return result;
    }
    let error = result.errors ? Object.values(result.errors)[0] : undefined;
    if (error !== undefined) {
      // If we got back result.errors, that means the loader/action threw
      // _something_ that wasn't a Response, but it's not guaranteed/required
      // to be an `instanceof Error` either, so we have to use throw here to
      // preserve the "error" state outside of queryImpl.
      throw error;
    }
    // Pick off the right state value to return
    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 undefined;
  }
  async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
    invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
    try {
      if (isMutationMethod(request.method.toLowerCase())) {
        let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
        return result;
      }
      let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
      return isResponse(result) ? result : _extends({}, result, {
        actionData: null,
        actionHeaders: {}
      });
    } catch (e) {
      // If the user threw/returned a Response in callLoaderOrAction for a
      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
      // and then return or throw the raw Response here accordingly
      if (isDataStrategyResult(e) && isResponse(e.result)) {
        if (e.type === ResultType.error) {
          throw e.result;
        }
        return e.result;
      }
      // Redirects are always returned since they don't propagate to catch
      // boundaries
      if (isRedirectResponse(e)) {
        return e;
      }
      throw e;
    }
  }
  async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
    let result;
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      let error = getInternalRouterError(405, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: actionMatch.route.id
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    } else {
      let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
      result = results[actionMatch.route.id];
      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future);
      }
    }
    if (isRedirectResult(result)) {
      // Uhhhh - this should never happen, we should always throw these from
      // callLoaderOrAction, but the type narrowing here keeps TS happy and we
      // can get back on the "throw all redirect responses" train here should
      // this ever happen :/
      throw new Response(null, {
        status: result.response.status,
        headers: {
          Location: result.response.headers.get("Location")
        }
      });
    }
    if (isDeferredResult(result)) {
      let error = getInternalRouterError(400, {
        type: "defer-action"
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    }
    if (isRouteRequest) {
      // Note: This should only be non-Response values if we get here, since
      // isRouteRequest should throw any Response received in callLoaderOrAction
      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
      };
    }
    // Create a GET request for the loaders
    let loaderRequest = new Request(request.url, {
      headers: request.headers,
      redirect: request.redirect,
      signal: request.signal
    });
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
      let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);
      // action status codes take precedence over loader status codes
      return _extends({}, context, {
        statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
        actionData: null,
        actionHeaders: _extends({}, result.headers ? {
          [actionMatch.route.id]: result.headers
        } : {})
      });
    }
    let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
    return _extends({}, context, {
      actionData: {
        [actionMatch.route.id]: result.data
      }
    }, result.statusCode ? {
      statusCode: result.statusCode
    } : {}, {
      actionHeaders: result.headers ? {
        [actionMatch.route.id]: result.headers
      } : {}
    });
  }
  async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
    let isRouteRequest = routeMatch != null;
    // Short circuit if we have no loaders to run (queryRoute())
    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
      throw getInternalRouterError(400, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: routeMatch == null ? void 0 : routeMatch.route.id
      });
    }
    let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
    let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);
    // Short circuit if we have no loaders to run (query())
    if (matchesToLoad.length === 0) {
      return {
        matches,
        // Add a null for all matched routes for proper revalidation on the client
        loaderData: matches.reduce((acc, m) => Object.assign(acc, {
          [m.route.id]: null
        }), {}),
        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
          [pendingActionResult[0]]: pendingActionResult[1].error
        } : null,
        statusCode: 200,
        loaderHeaders: {},
        activeDeferreds: null
      };
    }
    let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
    if (request.signal.aborted) {
      throwStaticHandlerAbortedError(request, isRouteRequest, future);
    }
    // Process and commit output from loaders
    let activeDeferreds = new Map();
    let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);
    // Add a null for any non-loader matches for proper revalidation on the client
    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
    });
  }
  // Utility wrapper for calling dataStrategy server-side without having to
  // pass around the manifest, mapRouteProperties, etc.
  async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
    let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
    let dataResults = {};
    await Promise.all(matches.map(async match => {
      if (!(match.route.id in results)) {
        return;
      }
      let result = results[match.route.id];
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result;
        // Throw redirects and let the server handle them with an HTTP redirect
        throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
      }
      if (isResponse(result.result) && isRouteRequest) {
        // For SSR single-route requests, we want to hand Responses back
        // directly without unwrapping
        throw result;
      }
      dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
    }));
    return dataResults;
  }
  return {
    dataRoutes,
    query,
    queryRoute
  };
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Helpers
////////////////////////////////////////////////////////////////////////////////
/**
 * Given an existing StaticHandlerContext and an error thrown at render time,
 * provide an updated StaticHandlerContext suitable for a second SSR render
 */
function getStaticContextFromError(routes, context, error) {
  let newContext = _extends({}, context, {
    statusCode: isRouteErrorResponse(error) ? error.status : 500,
    errors: {
      [context._deepestRenderedBoundaryId || routes[0].id]: error
    }
  });
  return newContext;
}
function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
    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 !== undefined);
}
function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  let contextualMatches;
  let activeRouteMatch;
  if (fromRouteId) {
    // Grab matches up to the calling route so our route-relative logic is
    // relative to the correct source route
    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];
  }
  // Resolve the relative path
  let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
  // When `to` is not specified we inherit search/hash from the current
  // location, unlike when to="." and we just inherit the path.
  // See https://github.com/remix-run/remix/issues/927
  if (to == null) {
    path.search = location.search;
    path.hash = location.hash;
  }
  // Account for `?index` params when routing to the current location
  if ((to == null || to === "" || to === ".") && activeRouteMatch) {
    let nakedIndex = hasNakedIndexQuery(path.search);
    if (activeRouteMatch.route.index && !nakedIndex) {
      // Add one when we're targeting an index route
      path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
    } else if (!activeRouteMatch.route.index && nakedIndex) {
      // Remove existing ones when we're not
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      params.delete("index");
      indexValues.filter(v => v).forEach(v => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? "?" + qs : "";
    }
  }
  // If we're operating within a basename, prepend it to the pathname.  If
  // this is a root navigation, then just use the raw basename which allows
  // the basename to have full control over the presence of a trailing slash
  // on root actions
  if (prependBasename && basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}
// Normalize navigation options by converting formMethod=GET formData objects to
// URLSearchParams so they behave identically to links with query params
function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  // Return location verbatim on non-submission navigations
  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"
    })
  });
  // Create a Submission on non-GET navigations
  let rawFormMethod = opts.formMethod || "get";
  let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  let formAction = stripHashFromPath(path);
  if (opts.body !== undefined) {
    if (opts.formEncType === "text/plain") {
      // text only support POST/PUT/PATCH/DELETE submissions
      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: undefined,
          json: undefined,
          text
        }
      };
    } else if (opts.formEncType === "application/json") {
      // json only supports POST/PUT/PATCH/DELETE submissions
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      try {
        let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
        return {
          path,
          submission: {
            formMethod,
            formAction,
            formEncType: opts.formEncType,
            formData: undefined,
            json,
            text: undefined
          }
        };
      } 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: undefined,
    text: undefined
  };
  if (isMutationMethod(submission.formMethod)) {
    return {
      path,
      submission
    };
  }
  // Flatten submission onto URLSearchParams for GET submissions
  let parsedPath = parsePath(path);
  // On GET navigation submissions we can drop the ?index param from the
  // resulting location since all loaders will run.  But fetcher GET submissions
  // only run a single loader so we need to preserve any incoming ?index params
  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
    searchParams.append("index", "");
  }
  parsedPath.search = "?" + searchParams;
  return {
    path: createPath(parsedPath),
    submission
  };
}
// Filter out all routes at/below any caught error as they aren't going to
// render so we don't need to load them
function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
  if (includeBoundary === void 0) {
    includeBoundary = false;
  }
  let index = matches.findIndex(m => m.route.id === boundaryId);
  if (index >= 0) {
    return matches.slice(0, includeBoundary ? index + 1 : index);
  }
  return matches;
}
function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
  let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
  let currentUrl = history.createURL(state.location);
  let nextUrl = history.createURL(location);
  // Pick navigation matches that are net-new or qualify for revalidation
  let boundaryMatches = matches;
  if (initialHydration && state.errors) {
    // On initial hydration, only consider matches up to _and including_ the boundary.
    // This is inclusive to handle cases where a server loader ran successfully,
    // a child server loader bubbled up to this route, but this route has
    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
    // we have a complete version of `loaderData`
    boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
    // If an action threw an error, we call loaders up to, but not including the
    // boundary
    boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
  }
  // Don't revalidate loaders by default after action 4xx/5xx responses
  // when the flag is enabled.  They can still opt-into revalidation via
  // `shouldRevalidate` via `actionResult`
  let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
  let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
  let navigationMatches = boundaryMatches.filter((match, index) => {
    let {
      route
    } = match;
    if (route.lazy) {
      // We haven't loaded this route yet so we don't know if it's got a loader!
      return true;
    }
    if (route.loader == null) {
      return false;
    }
    if (initialHydration) {
      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
    }
    // Always call the loader on new route instances and pending defer cancellations
    if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
      return true;
    }
    // This is the default implementation for when we revalidate.  If the route
    // provides it's own implementation, then we give them full control but
    // provide this value so they can leverage it if needed after they check
    // their own specific use cases
    let currentRouteMatch = state.matches[index];
    let nextRouteMatch = match;
    return shouldRevalidateLoader(match, _extends({
      currentUrl,
      currentParams: currentRouteMatch.params,
      nextUrl,
      nextParams: nextRouteMatch.params
    }, submission, {
      actionResult,
      actionStatus,
      defaultShouldRevalidate: shouldSkipRevalidation ? false :
      // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
      isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
      // Search params affect all loaders
      currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
    }));
  });
  // Pick fetcher.loads that need to be revalidated
  let revalidatingFetchers = [];
  fetchLoadMatches.forEach((f, key) => {
    // Don't revalidate:
    //  - on initial hydration (shouldn't be any fetchers then anyway)
    //  - if fetcher won't be present in the subsequent render
    //    - no longer matches the URL (v7_fetcherPersist=false)
    //    - was unmounted but persisted due to v7_fetcherPersist=true
    if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
      return;
    }
    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
    // If the fetcher path no longer matches, push it in with null matches so
    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is
    // currently only a use-case for Remix HMR where the route tree can change
    // at runtime and remove a route previously loaded via a fetcher
    if (!fetcherMatches) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: null,
        match: null,
        controller: null
      });
      return;
    }
    // Revalidating fetchers are decoupled from the route matches since they
    // load from a static href.  They revalidate based on explicit revalidation
    // (submission, useRevalidator, or X-Remix-Revalidate)
    let fetcher = state.fetchers.get(key);
    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
    let shouldRevalidate = false;
    if (fetchRedirectIds.has(key)) {
      // Never trigger a revalidation of an actively redirecting fetcher
      shouldRevalidate = false;
    } else if (cancelledFetcherLoads.has(key)) {
      // Always mark for revalidation if the fetcher was cancelled
      cancelledFetcherLoads.delete(key);
      shouldRevalidate = true;
    } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
      // If the fetcher hasn't ever completed loading yet, then this isn't a
      // revalidation, it would just be a brand new load if an explicit
      // revalidation is required
      shouldRevalidate = isRevalidationRequired;
    } else {
      // Otherwise fall back on any user-defined shouldRevalidate, defaulting
      // to explicit revalidations only
      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
        currentUrl,
        currentParams: state.matches[state.matches.length - 1].params,
        nextUrl,
        nextParams: matches[matches.length - 1].params
      }, submission, {
        actionResult,
        actionStatus,
        defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
      }));
    }
    if (shouldRevalidate) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: fetcherMatches,
        match: fetcherMatch,
        controller: new AbortController()
      });
    }
  });
  return [navigationMatches, revalidatingFetchers];
}
function shouldLoadRouteOnHydration(route, loaderData, errors) {
  // We dunno if we have a loader - gotta find out!
  if (route.lazy) {
    return true;
  }
  // No loader, nothing to initialize
  if (!route.loader) {
    return false;
  }
  let hasData = loaderData != null && loaderData[route.id] !== undefined;
  let hasError = errors != null && errors[route.id] !== undefined;
  // Don't run if we error'd during SSR
  if (!hasData && hasError) {
    return false;
  }
  // Explicitly opting-in to running on hydration
  if (typeof route.loader === "function" && route.loader.hydrate === true) {
    return true;
  }
  // Otherwise, run if we're not yet initialized with anything
  return !hasData && !hasError;
}
function isNewLoader(currentLoaderData, currentMatch, match) {
  let isNew =
  // [a] -> [a, b]
  !currentMatch ||
  // [a, b] -> [a, c]
  match.route.id !== currentMatch.route.id;
  // Handle the case that we don't have data for a re-used route, potentially
  // from a prior error or from a cancelled pending deferred
  let isMissingData = currentLoaderData[match.route.id] === undefined;
  // Always load if this is a net-new route or we don't yet have data
  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;
}
function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
  var _childrenToPatch;
  let childrenToPatch;
  if (routeId) {
    let route = manifest[routeId];
    invariant(route, "No route found to patch children into: routeId = " + routeId);
    if (!route.children) {
      route.children = [];
    }
    childrenToPatch = route.children;
  } else {
    childrenToPatch = routesToUse;
  }
  // Don't patch in routes we already know about so that `patch` is idempotent
  // to simplify user-land code. This is useful because we re-call the
  // `patchRoutesOnNavigation` function for matched routes with params.
  let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
  let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
  childrenToPatch.push(...newRoutes);
}
function isSameRoute(newRoute, existingRoute) {
  // Most optimal check is by id
  if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
    return true;
  }
  // Second is by pathing differences
  if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
    return false;
  }
  // Pathless layout routes are trickier since we need to check children.
  // If they have no children then they're the same as far as we can tell
  if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
    return true;
  }
  // Otherwise, we look to see if every child in the new route is already
  // represented in the existing route's children
  return newRoute.children.every((aChild, i) => {
    var _existingRoute$childr;
    return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
  });
}
/**
 * Execute route.lazy() methods to lazily load route modules (loader, action,
 * shouldRevalidate) and update the routeManifest in place which shares objects
 * with dataRoutes so those get updated as well.
 */
async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
  if (!route.lazy) {
    return;
  }
  let lazyRoute = await route.lazy();
  // If the lazy route function was executed and removed by another parallel
  // call then we can return - first lazy() to finish wins because the return
  // value of lazy is expected to be static
  if (!route.lazy) {
    return;
  }
  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");
  // Update the route in place.  This should be safe because there's no way
  // we could yet be sitting on this route as we can't get there without
  // resolving lazy() first.
  //
  // This is different than the HMR "update" use-case where we may actively be
  // on the route being updated.  The main concern boils down to "does this
  // mutation affect any ongoing navigations or any current state.matches
  // values?".  If not, it should be safe to update in place.
  let routeUpdates = {};
  for (let lazyRouteProperty in lazyRoute) {
    let staticRouteValue = routeToUpdate[lazyRouteProperty];
    let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
    // 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];
    }
  }
  // Mutate the route with the provided updates.  Do this first so we pass
  // the updated version to mapRouteProperties
  Object.assign(routeToUpdate, routeUpdates);
  // Mutate the `hasErrorBoundary` property on the route based on the route
  // updates and remove the `lazy` function so we don't resolve the lazy
  // route again.
  Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
    lazy: undefined
  }));
}
// Default implementation of `dataStrategy` which fetches all loaders in parallel
async function defaultDataStrategy(_ref4) {
  let {
    matches
  } = _ref4;
  let matchesToLoad = matches.filter(m => m.shouldLoad);
  let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
  return results.reduce((acc, result, i) => Object.assign(acc, {
    [matchesToLoad[i].route.id]: result
  }), {});
}
async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
  let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
  let dsMatches = matches.map((match, i) => {
    let loadRoutePromise = loadRouteDefinitionsPromises[i];
    let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
    // `resolve` encapsulates route.lazy(), executing the loader/action,
    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users
    // can pass a callback to take fine-grained control over the execution
    // of the loader/action
    let resolve = async handlerOverride => {
      if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
        shouldLoad = true;
      }
      return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
        type: ResultType.data,
        result: undefined
      });
    };
    return _extends({}, match, {
      shouldLoad,
      resolve
    });
  });
  // Send all matches here to allow for a middleware-type implementation.
  // handler will be a no-op for unneeded routes and we filter those results
  // back out below.
  let results = await dataStrategyImpl({
    matches: dsMatches,
    request,
    params: matches[0].params,
    fetcherKey,
    context: requestContext
  });
  // Wait for all routes to load here but 'swallow the error since we want
  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
  // called from `match.resolve()`
  try {
    await Promise.all(loadRouteDefinitionsPromises);
  } catch (e) {
    // No-op
  }
  return results;
}
// Default logic for calling a loader/action is the user has no specified a dataStrategy
async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
  let result;
  let onReject;
  let runHandler = handler => {
    // Setup a promise we can race against so that abort signals short circuit
    let reject;
    // This will never resolve so safe to type it as Promise<DataStrategyResult> to
    // satisfy the function return value
    let abortPromise = new Promise((_, r) => reject = r);
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);
    let actualHandler = ctx => {
      if (typeof handler !== "function") {
        return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
      }
      return handler({
        request,
        params: match.params,
        context: staticContext
      }, ...(ctx !== undefined ? [ctx] : []));
    };
    let handlerPromise = (async () => {
      try {
        let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
        return {
          type: "data",
          result: val
        };
      } catch (e) {
        return {
          type: "error",
          result: e
        };
      }
    })();
    return Promise.race([handlerPromise, abortPromise]);
  };
  try {
    let handler = match.route[type];
    // If we have a route.lazy promise, await that first
    if (loadRoutePromise) {
      if (handler) {
        // Run statically defined handler in parallel with lazy()
        let handlerError;
        let [value] = await Promise.all([
        // If the handler throws, don't let it immediately bubble out,
        // since we need to let the lazy() execution finish so we know if this
        // route has a boundary that can handle the error
        runHandler(handler).catch(e => {
          handlerError = e;
        }), loadRoutePromise]);
        if (handlerError !== undefined) {
          throw handlerError;
        }
        result = value;
      } else {
        // Load lazy route module, then run any returned handler
        await loadRoutePromise;
        handler = match.route[type];
        if (handler) {
          // Handler still runs even if we got interrupted to maintain consistency
          // with un-abortable behavior of handler execution on non-lazy or
          // previously-lazy-loaded routes
          result = await runHandler(handler);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match.route.id
          });
        } else {
          // lazy() route has no loader to run.  Short circuit here so we don't
          // hit the invariant below that errors on returning undefined.
          return {
            type: ResultType.data,
            result: undefined
          };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname
      });
    } else {
      result = await runHandler(handler);
    }
    invariant(result.result !== undefined, "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) {
    // We should already be catching and converting normal handler executions to
    // DataStrategyResults and returning them, so anything that throws here is an
    // unexpected error we still need to wrap
    return {
      type: ResultType.error,
      result: e
    };
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }
  return result;
}
async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  let {
    result,
    type
  } = dataStrategyResult;
  if (isResponse(result)) {
    let data;
    try {
      let contentType = result.headers.get("Content-Type");
      // Check between word boundaries instead of startsWith() due to the last
      // paragraph of https://httpwg.org/specs/rfc9110.html#field.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 (type === ResultType.error) {
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(result.status, result.statusText, data),
        statusCode: result.status,
        headers: result.headers
      };
    }
    return {
      type: ResultType.data,
      data,
      statusCode: result.status,
      headers: result.headers
    };
  }
  if (type === ResultType.error) {
    if (isDataWithResponseInit(result)) {
      var _result$init3, _result$init4;
      if (result.data instanceof Error) {
        var _result$init, _result$init2;
        return {
          type: ResultType.error,
          error: result.data,
          statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
          headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined
        };
      }
      // Convert thrown data() to ErrorResponse instances
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),
        statusCode: isRouteErrorResponse(result) ? result.status : undefined,
        headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined
      };
    }
    return {
      type: ResultType.error,
      error: result,
      statusCode: isRouteErrorResponse(result) ? result.status : undefined
    };
  }
  if (isDeferredData(result)) {
    var _result$init5, _result$init6;
    return {
      type: ResultType.deferred,
      deferredData: result,
      statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
      headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
    };
  }
  if (isDataWithResponseInit(result)) {
    var _result$init7, _result$init8;
    return {
      type: ResultType.data,
      data: result.data,
      statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
      headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined
    };
  }
  return {
    type: ResultType.data,
    data: result
  };
}
// Support relative routing in internal redirects
function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
  let location = response.headers.get("Location");
  invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  if (!ABSOLUTE_URL_REGEX.test(location)) {
    let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
    location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
    response.headers.set("Location", location);
  }
  return response;
}
function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
  // Match Chrome's behavior:
  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
  let invalidProtocols = ["about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:",
  // eslint-disable-next-line no-script-url
  "javascript:"];
  if (ABSOLUTE_URL_REGEX.test(location)) {
    // Strip off the protocol+origin for same-origin + same-basename absolute redirects
    let normalizedLocation = location;
    let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
    let isSameBasename = stripBasename(url.pathname, basename) != null;
    if (url.origin === currentUrl.origin && isSameBasename) {
      return removeDoubleSlashes(url.pathname) + url.search + url.hash;
    }
  }
  try {
    let url = historyInstance.createURL(location);
    if (invalidProtocols.includes(url.protocol)) {
      throw new Error("Invalid redirect location");
    }
  } catch (e) {}
  return location;
}
// Utility method for creating the Request instances for loaders/actions during
// client-side navigations and fetches.  During SSR we will always have a
// Request instance from the static handler (query/queryRoute)
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;
    // Didn't think we needed this but it turns out unlike other methods, patch
    // won't be properly normalized to uppercase and results in a 405 error.
    // See: https://fetch.spec.whatwg.org/#concept-method
    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") {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.text;
    } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = convertFormDataToSearchParams(submission.formData);
    } else {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.formData;
    }
  }
  return new Request(url, init);
}
function convertFormDataToSearchParams(formData) {
  let searchParams = new URLSearchParams();
  for (let [key, value] of formData.entries()) {
    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
    searchParams.append(key, typeof value === "string" ? value : value.name);
  }
  return searchParams;
}
function convertSearchParamsToFormData(searchParams) {
  let formData = new FormData();
  for (let [key, value] of searchParams.entries()) {
    formData.append(key, value);
  }
  return formData;
}
function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
  // Fill in loaderData/errors from our loaders
  let loaderData = {};
  let errors = null;
  let statusCode;
  let foundError = false;
  let loaderHeaders = {};
  let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;
  // Process loader results into state.loaderData/state.errors
  matches.forEach(match => {
    if (!(match.route.id in results)) {
      return;
    }
    let id = match.route.id;
    let result = results[id];
    invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
    if (isErrorResult(result)) {
      let error = result.error;
      // If we have a pending action error, we report it at the highest-route
      // that throws a loader error, and then clear it out to indicate that
      // it was consumed
      if (pendingError !== undefined) {
        error = pendingError;
        pendingError = undefined;
      }
      errors = errors || {};
      if (skipLoaderErrorBubbling) {
        errors[id] = error;
      } else {
        // Look upwards from the matched route for the closest ancestor error
        // boundary, defaulting to the root match.  Prefer higher error values
        // if lower errors bubble to the same boundary
        let boundaryMatch = findNearestBoundary(matches, id);
        if (errors[boundaryMatch.route.id] == null) {
          errors[boundaryMatch.route.id] = error;
        }
      }
      // Clear our any prior loaderData for the throwing route
      loaderData[id] = undefined;
      // Once we find our first (highest) error, we set the status code and
      // prevent deeper status codes from overriding
      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;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      } else {
        loaderData[id] = result.data;
        // Error status codes always override success status codes, but if all
        // loaders are successful we take the deepest status code.
        if (result.statusCode && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      }
    }
  });
  // If we didn't consume the pending action error (i.e., all loaders
  // resolved), then consume it here.  Also clear out any loaderData for the
  // throwing route
  if (pendingError !== undefined && pendingActionResult) {
    errors = {
      [pendingActionResult[0]]: pendingError
    };
    loaderData[pendingActionResult[0]] = undefined;
  }
  return {
    loaderData,
    errors,
    statusCode: statusCode || 200,
    loaderHeaders
  };
}
function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
  let {
    loaderData,
    errors
  } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
  );
  // Process results from our revalidating fetchers
  revalidatingFetchers.forEach(rf => {
    let {
      key,
      match,
      controller
    } = rf;
    let result = fetcherResults[key];
    invariant(result, "Did not find corresponding fetcher result");
    // Process fetcher non-redirect errors
    if (controller && controller.signal.aborted) {
      // Nothing to do for aborted fetchers
      return;
    } 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)) {
      // Should never get here, redirects should get processed above, but we
      // keep this to type narrow to a success result in the else
      invariant(false, "Unhandled fetcher revalidation redirect");
    } else if (isDeferredResult(result)) {
      // Should never get here, deferred data should be awaited for fetchers
      // in resolveDeferredResults
      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] !== undefined) {
        mergedLoaderData[id] = newLoaderData[id];
      }
    } else if (loaderData[id] !== undefined && match.route.loader) {
      // Preserve existing keys not included in newLoaderData and where a loader
      // wasn't removed by HMR
      mergedLoaderData[id] = loaderData[id];
    }
    if (errors && errors.hasOwnProperty(id)) {
      // Don't keep any loader data below the boundary
      break;
    }
  }
  return mergedLoaderData;
}
function getActionDataForCommit(pendingActionResult) {
  if (!pendingActionResult) {
    return {};
  }
  return isErrorResult(pendingActionResult[1]) ? {
    // Clear out prior actionData on errors
    actionData: {}
  } : {
    actionData: {
      [pendingActionResult[0]]: pendingActionResult[1].data
    }
  };
}
// Find the nearest error boundary, looking upwards from the leaf route (or the
// route specified by routeId) for the closest ancestor error boundary,
// defaulting to the root match
function findNearestBoundary(matches, routeId) {
  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
  return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
}
function getShortCircuitMatches(routes) {
  // Prefer a root layout route if present, otherwise shim in a route object
  let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
    id: "__shim-error-route__"
  };
  return {
    matches: [{
      params: {},
      pathname: "",
      pathnameBase: "",
      route
    }],
    route
  };
}
function getInternalRouterError(status, _temp5) {
  let {
    pathname,
    routeId,
    method,
    type,
    message
  } = _temp5 === void 0 ? {} : _temp5;
  let statusText = "Unknown Server Error";
  let errorMessage = "Unknown @remix-run/router error";
  if (status === 400) {
    statusText = "Bad Request";
    if (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);
}
// Find any returned redirect errors, starting from the lowest match
function findRedirect(results) {
  let entries = Object.entries(results);
  for (let i = entries.length - 1; i >= 0; i--) {
    let [key, result] = entries[i];
    if (isRedirectResult(result)) {
      return {
        key,
        result
      };
    }
  }
}
function stripHashFromPath(path) {
  let parsedPath = typeof path === "string" ? parsePath(path) : path;
  return createPath(_extends({}, parsedPath, {
    hash: ""
  }));
}
function isHashChangeOnly(a, b) {
  if (a.pathname !== b.pathname || a.search !== b.search) {
    return false;
  }
  if (a.hash === "") {
    // /page -> /page#hash
    return b.hash !== "";
  } else if (a.hash === b.hash) {
    // /page#hash -> /page#hash
    return true;
  } else if (b.hash !== "") {
    // /page#hash -> /page#other
    return true;
  }
  // If the hash is removed the browser will re-perform a request to the server
  // /page#hash -> /page
  return false;
}
function isDataStrategyResult(result) {
  return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
}
function isRedirectDataStrategyResultResult(result) {
  return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
}
function isDeferredResult(result) {
  return result.type === ResultType.deferred;
}
function isErrorResult(result) {
  return result.type === ResultType.error;
}
function isRedirectResult(result) {
  return (result && result.type) === ResultType.redirect;
}
function isDataWithResponseInit(value) {
  return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
}
function isDeferredData(value) {
  let deferred = value;
  return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
}
function isResponse(value) {
  return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
}
function isRedirectResponse(result) {
  if (!isResponse(result)) {
    return false;
  }
  let status = result.status;
  let location = result.headers.get("Location");
  return status >= 300 && status <= 399 && location != null;
}
function isValidMethod(method) {
  return validRequestMethods.has(method.toLowerCase());
}
function isMutationMethod(method) {
  return validMutationMethods.has(method.toLowerCase());
}
async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
  let entries = Object.entries(results);
  for (let index = 0; index < entries.length; index++) {
    let [routeId, result] = entries[index];
    let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    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]) !== undefined;
    if (isDeferredResult(result) && isRevalidatingLoader) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      await resolveDeferredData(result, signal, false).then(result => {
        if (result) {
          results[routeId] = result;
        }
      });
    }
  }
}
async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
  for (let index = 0; index < revalidatingFetchers.length; index++) {
    let {
      key,
      routeId,
      controller
    } = revalidatingFetchers[index];
    let result = results[key];
    let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    if (!match) {
      continue;
    }
    if (isDeferredResult(result)) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
      await resolveDeferredData(result, controller.signal, true).then(result => {
        if (result) {
          results[key] = result;
        }
      });
    }
  }
}
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) {
      // Handle any TrackedPromise._error values encountered while unwrapping
      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 the leaf index route when index is present
    return matches[matches.length - 1];
  }
  // Otherwise grab the deepest "path contributing" match (ignoring index and
  // pathless layout routes)
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}
function getSubmissionFromNavigation(navigation) {
  let {
    formMethod,
    formAction,
    formEncType,
    text,
    formData,
    json
  } = navigation;
  if (!formMethod || !formAction || !formEncType) {
    return;
  }
  if (text != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json: undefined,
      text
    };
  } else if (formData != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData,
      json: undefined,
      text: undefined
    };
  } else if (json !== undefined) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json,
      text: undefined
    };
  }
}
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: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined
    };
    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: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
      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 : undefined
  };
  return fetcher;
}
function getDoneFetcher(data) {
  let fetcher = {
    state: "idle",
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined,
    data
  };
  return fetcher;
}
function restoreAppliedTransitions(_window, transitions) {
  try {
    let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
    if (sessionPositions) {
      let json = JSON.parse(sessionPositions);
      for (let [k, v] of Object.entries(json || {})) {
        if (v && Array.isArray(v)) {
          transitions.set(k, new Set(v || []));
        }
      }
    }
  } catch (e) {
    // no-op, use default empty object
  }
}
function persistAppliedTransitions(_window, transitions) {
  if (transitions.size > 0) {
    let json = {};
    for (let [k, v] of transitions) {
      json[k] = [...v];
    }
    try {
      _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
    } catch (error) {
      warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
    }
  }
}
//#endregion

export { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, decodePath as UNSAFE_decodePath, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, data, defer, generatePath, getStaticContextFromError, getToPathname, isDataWithResponseInit, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, replace, resolvePath, resolveTo, stripBasename };
//# sourceMappingURL=router.js.map
{"version":3,"file":"router.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n\n  /**\n   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n  idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 1 });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nexport function warning(cond: any, message: string) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience, so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\n  };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n  current: string | Location,\n  to: To,\n  state: any = null,\n  key?: string\n): Readonly<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): URL {\n    // window.location.origin is \"null\" (the literal string value) in Firefox\n    // under certain conditions, notably when serving from a local HTML file\n    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n    let base =\n      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\n    invariant(\n      base,\n      `No window.location.(origin|href) available to create URL for href: ${href}`\n    );\n    return new URL(href, base);\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n  [routeId: string]: any;\n}\n\nexport enum ResultType {\n  data = \"data\",\n  deferred = \"deferred\",\n  redirect = \"redirect\",\n  error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n  type: ResultType.data;\n  data: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n  type: ResultType.deferred;\n  deferredData: DeferredData;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n  | SuccessResult\n  | DeferredResult\n  | RedirectResult\n  | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\n    };\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n  currentUrl: URL;\n  currentParams: AgnosticDataRouteMatch[\"params\"];\n  nextUrl: URL;\n  nextParams: AgnosticDataRouteMatch[\"params\"];\n  formMethod?: Submission[\"formMethod\"];\n  formAction?: Submission[\"formAction\"];\n  formEncType?: Submission[\"formEncType\"];\n  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature.  This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments.  It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n  (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => DataFunctionReturnValue\n  ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n  fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n  signal: AbortSignal;\n  path: string;\n  matches: M[];\n  fetcherKey: string | undefined;\n  patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param extends `${infer Optional}?`\n      ? Optional\n      : Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\" | \"/*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if you could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(index)];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(\n      route.index !== true || !route.children,\n      `Cannot specify children on an index route`\n    );\n    invariant(\n      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\n\n      return pathOrLayoutRoute;\n    }\n  });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  let decoded = decodePath(pathname);\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array, so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children, so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explode _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string,\n  allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\n\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams as Params<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, compiledParams] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let params: CompiledPathParam[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex, so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\n  } catch (error) {\n    warning(\n      false,\n      `The URL path \"${value}\" could not be decoded because it is is a ` +\n        `malformed URL segment. This is probably due to a bad percent ` +\n        `encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n  pathname: string,\n  basename: string\n): string | null {\n  if (basename === \"/\") return pathname;\n\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  }\n\n  // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n  let startIndex = basename.endsWith(\"/\")\n    ? basename.length - 1\n    : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n\n  return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\",\n  } = typeof to === \"string\" ? parsePath(to) : to;\n\n  let pathname: string;\n  if (toPathname) {\n    toPathname = removeDoubleSlashes(toPathname);\n    if (toPathname.startsWith(\"/\")) {\n      pathname = resolvePathname(toPathname.substring(1), \"/\");\n    } else {\n      pathname = resolvePathname(toPathname, fromPathname);\n    }\n  } else {\n    pathname = fromPathname;\n  }\n\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash),\n  };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\n\n  relativeSegments.forEach((segment) => {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n  toArg: To,\n  routePathnames: string[],\n  locationPathname: string,\n  isPathRelative = false\n): Path {\n  let to: Partial<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || (to as Path).pathname === \"\"\n    ? \"/\"\n    : typeof to === \"string\"\n    ? parsePath(to).pathname\n    : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n  path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n  removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n  data: Data,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  let headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n\n  return new Response(JSON.stringify(data), {\n    ...responseInit,\n    headers,\n  });\n};\n\nexport class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\n  );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n    invariant(\n      data && typeof data === \"object\" && !Array.isArray(data),\n      \"defer() only accepts plain objects\"\n    );\n\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject: (e: AbortedDeferredError) => void;\n    this.abortPromise = new Promise((_, r) => (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =>\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =>\n      this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n\n    this.data = Object.entries(data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: this.trackPromise(key, value),\n        }),\n      {}\n    );\n\n    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.add(key);\n\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n      (data) => this.onSettle(promise, key, undefined, data as unknown),\n      (error) => this.onSettle(promise, key, error as unknown)\n    );\n\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () => true });\n    return promise;\n  }\n\n  private onSettle(\n    promise: TrackedPromise,\n    key: string,\n    error: unknown,\n    data?: unknown\n  ): unknown {\n    if (\n      this.controller.signal.aborted &&\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      return Promise.reject(error);\n    }\n\n    this.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(true);\n  }\n\n  async resolveData(signal: AbortSignal) {\n    let aborted = false;\n    if (!this.done) {\n      let onAbort = () => this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) => {\n        this.subscribe((aborted) => {\n          signal.removeEventListener(\"abort\", onAbort);\n          if (aborted || this.done) {\n            resolve(aborted);\n          }\n        });\n      });\n    }\n    return aborted;\n  }\n\n  get done() {\n    return this.pendingKeysSet.size === 0;\n  }\n\n  get unwrappedData() {\n    invariant(\n      this.data !== null && this.done,\n      \"Can only unwrap data on initialized and settled deferreds\"\n    );\n\n    return Object.entries(this.data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: unwrapTrackedPromise(value),\n        }),\n      {}\n    );\n  }\n\n  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\n  }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n  return (\n    value instanceof Promise && (value as TrackedPromise)._tracked === true\n  );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\n\nexport type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n  url: string,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = { status: responseInit };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n\n  return new Response(null, {\n    ...responseInit,\n    headers,\n  });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private internal: boolean;\n\n  constructor(\n    status: number,\n    statusText: string | undefined,\n    data: any,\n    internal = false\n  ) {\n    this.status = status;\n    this.statusText = statusText || \"\";\n    this.internal = internal;\n    if (data instanceof Error) {\n      this.data = data.toString();\n      this.error = data;\n    } else {\n      this.data = data;\n    }\n  }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  DataStrategyResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnNavigationFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  removeDoubleSlashes,\n  resolveTo,\n  stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the basename for the router\n   */\n  get basename(): RouterInit[\"basename\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the future config for the router\n   */\n  get future(): FutureConfig;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the current state of the router\n   */\n  get state(): RouterState;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the routes for this router instance\n   */\n  get routes(): AgnosticDataRouteObject[];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Initialize the router, including adding history listeners and kicking off\n   * initial data fetches.  Returns a function to cleanup listeners and abort\n   * any in-progress loads\n   */\n  initialize(): Router;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Subscribe to router.state updates\n   *\n   * @param fn function to call with the new state\n   */\n  subscribe(fn: RouterSubscriber): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Enable scroll restoration behavior in the router\n   *\n   * @param savedScrollPositions Object that will manage positions, in case\n   *                             it's being restored from sessionStorage\n   * @param getScrollPosition    Function to get the active Y scroll position\n   * @param getKey               Function to get the key to use for restoration\n   */\n  enableScrollRestoration(\n    savedScrollPositions: Record<string, number>,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Navigate forward/backward in the history stack\n   * @param to Delta to move in the history stack\n   */\n  navigate(to: number): Promise<void>;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a fetcher load/submission\n   *\n   * @param key     Fetcher key\n   * @param routeId Route that owns the fetcher\n   * @param href    href to fetch\n   * @param opts    Fetcher options, (method, submission, etc.)\n   */\n  fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a revalidation of all current route loaders and fetcher loads\n   */\n  revalidate(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to create an href for the given location\n   * @param location\n   */\n  createHref(location: Location | URL): string;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to URL encode a destination path according to the internal\n   * history implementation\n   * @param to\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get/create a fetcher for the given key\n   * @param key\n   */\n  getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete the fetcher for a given key\n   * @param key\n   */\n  deleteFetcher(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Cleanup listeners and abort any in-progress loads\n   */\n  dispose(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal fetch AbortControllers accessed by unit tests\n   */\n  _internalFetchControllers: Map<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router.  During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n  /**\n   * The action of the most recent navigation\n   */\n  historyAction: HistoryAction;\n\n  /**\n   * The current location reflected by the router\n   */\n  location: Location;\n\n  /**\n   * The current set of route matches\n   */\n  matches: AgnosticDataRouteMatch[];\n\n  /**\n   * Tracks whether we've completed our initial data load\n   */\n  initialized: boolean;\n\n  /**\n   * Current scroll position we should start at for a new view\n   *  - number -> scroll position to restore to\n   *  - false -> do not restore scroll at all (used during submissions)\n   *  - null -> don't have a saved position, scroll to hash or top of page\n   */\n  restoreScrollPosition: number | false | null;\n\n  /**\n   * Indicate whether this navigation should skip resetting the scroll position\n   * if we are unable to restore the scroll position\n   */\n  preventScrollReset: boolean;\n\n  /**\n   * Tracks the state of the current navigation\n   */\n  navigation: Navigation;\n\n  /**\n   * Tracks any in-progress revalidations\n   */\n  revalidation: RevalidationState;\n\n  /**\n   * Data from the loaders for the current matches\n   */\n  loaderData: RouteData;\n\n  /**\n   * Data from the action for the current matches\n   */\n  actionData: RouteData | null;\n\n  /**\n   * Errors caught from loaders for the current matches\n   */\n  errors: RouteData | null;\n\n  /**\n   * Map of current fetchers\n   */\n  fetchers: Map<string, Fetcher>;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  activeDeferreds: Record<string, DeferredData> | null;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      viewTransitionOpts?: ViewTransitionOpts;\n      flushSync: boolean;\n    }\n  ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n  (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n  Idle: {\n    state: \"idle\";\n    location: undefined;\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\n  };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n  Idle: {\n    state: \"idle\";\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n  /**\n   * startNavigation does not need to complete the navigation because we\n   * redirected or got interrupted\n   */\n  shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * loaderData returned from the current set of loaders\n   */\n  loaderData?: RouterState[\"loaderData\"];\n  /**\n   * errors thrown from the current set of loaders\n   */\n  errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n  \"post\",\n  \"put\",\n  \"patch\",\n  \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\n  // Cleanup function for history\n  let unlistenHistory: (() => void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialMatchesIsFOW = false;\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    let error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname,\n    });\n    let { matches, route } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = { [route.id]: error };\n  }\n\n  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnNavigation` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatchesIsFOW = true;\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n      );\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\n\n  let router: Router;\n  let state: RouterState = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n    errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n    fetchers: new Map(),\n    blockers: new Map(),\n  };\n\n  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction: HistoryAction = HistoryAction.Pop;\n\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\n  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes: string[] = [];\n\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\n  // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n  let activeDeferreds = new Map<string, DeferredData>();\n\n  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n  // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(\n      ({ action: historyAction, location, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (unblockBlockerHistoryUpdate) {\n          unblockBlockerHistoryUpdate();\n          unblockBlockerHistoryUpdate = undefined;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n            unblockBlockerHistoryUpdate = resolve;\n          });\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked, after the url\n              // restoration is also complete.  See:\n              // https://github.com/remix-run/react-router/issues/11613\n              nextHistoryUpdatePromise.then(() => init.history.go(delta));\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\n    }\n\n    return router;\n  }\n\n  // Clean up a router and it's side effects\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Remove any lingering deleted fetchers that have already been removed\n    // from state.fetchers\n    deletedFetchers.forEach((key) => {\n      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n        deletedFetchersKeys.push(key);\n      }\n    });\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        viewTransitionOpts: opts.viewTransitionOpts,\n        flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    } else {\n      // We already called deleteFetcher() on these, can remove them from this\n      // Set now that we've handed the keys off to the data layer\n      deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n    }\n  }\n\n  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n  function completeNavigation(\n    location: Location,\n    newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n    { flushSync }: { flushSync?: boolean } = {}\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\n    }\n\n    if (isUninterruptedRevalidation) {\n      // If this was an uninterrupted revalidation then do not touch history\n    } else if (pendingAction === HistoryAction.Pop) {\n      // Do nothing for POP - URL has already been updated\n    } else if (pendingAction === HistoryAction.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === HistoryAction.Replace) {\n      init.history.replace(location, location.state);\n    }\n\n    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\n        ...newState, // matches, errors, fetchers go through as-is\n        actionData,\n        loaderData,\n        historyAction: pendingAction,\n        location,\n        initialized: true,\n        navigation: IDLE_NAVIGATION,\n        revalidation: \"idle\",\n        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n  }\n\n  // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  async function navigate(\n    to: number | To | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n    // URL from window.location, so we need to encode it here so the behavior\n    // remains the same as POP and non-data-router usages.  new URL() does all\n    // the same encoding we'd get from a history.pushState/window.location read\n    // without having to touch history\n    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\n    };\n\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n    let historyAction = HistoryAction.Push;\n\n    if (userReplace === true) {\n      historyAction = HistoryAction.Replace;\n    } else if (userReplace === false) {\n      // no-op\n    } else if (\n      submission != null &&\n      isMutationMethod(submission.formMethod) &&\n      submission.formAction === state.location.pathname + state.location.search\n    ) {\n      // By default on submissions to the current location we REPLACE so that\n      // users don't have to double-click the back button to get to the prior\n      // location.  If the user redirects to a different location from the\n      // action/loader this will be ignored and the redirect will be a PUSH\n      historyAction = HistoryAction.Replace;\n    }\n\n    let preventScrollReset =\n      opts && \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.viewTransition,\n      flushSync,\n    });\n  }\n\n  // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({ revalidation: \"loading\" });\n\n    // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n    if (state.navigation.state === \"submitting\") {\n      return;\n    }\n\n    // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true,\n      });\n      return;\n    }\n\n    // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n    startNavigation(\n      pendingAction || state.historyAction,\n      state.navigation.location,\n      {\n        overrideNavigation: state.navigation,\n        // Proxy through any rending view transition\n        enableViewTransition: pendingViewTransitionEnabled === true,\n      }\n    );\n  }\n\n  // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  async function startNavigation(\n    historyAction: HistoryAction,\n    location: Location,\n    opts?: {\n      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: boolean;\n    }\n  ): Promise<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches =\n      opts?.initialHydration &&\n      state.matches &&\n      state.matches.length > 0 &&\n      !initialMatchesIsFOW\n        ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n          state.matches\n        : matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial hydration will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      matches &&\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: opts.pendingError },\n      ];\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\n    );\n\n    if (shortCircuited) {\n      return;\n    }\n\n    // Clean up now that the action/loaders have completed.  Don't clean up if\n    // we short circuited because pendingNavigationController will have already\n    // been assigned to a new controller for the next navigation\n    pendingNavigationController = null;\n\n    completeNavigation(location, {\n      matches: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\n      loaderData,\n      errors,\n    });\n  }\n\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(\n    request: Request,\n    location: Location,\n    submission: Submission,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error: discoverResult.error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    // Call our action and get the result\n    let result: DataResult;\n    let actionMatch = getTargetMatch(matches, location);\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      result = {\n        type: ResultType.error,\n        error: getInternalRouterError(405, {\n          method: request.method,\n          pathname: location.pathname,\n          routeId: actionMatch.route.id,\n        }),\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        state,\n        request,\n        [actionMatch],\n        matches,\n        null\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        return { shortCircuited: true };\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      let replace: boolean;\n      if (opts && opts.replace != null) {\n        replace = opts.replace;\n      } else {\n        // If the user didn't explicity indicate replace behavior, replace if\n        // we redirected to the exact same location we're currently at to avoid\n        // double back-buttons\n        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename,\n          init.history,\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, true, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\n    };\n  }\n\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\n\n    // If this is an uninterrupted revalidation, we remain in our current idle\n    // state.  If not, we need to switch to our loading state and load data,\n    // preserving any new action data or existing action data (in the case of\n    // a revalidation interrupting an actionReload)\n    // If we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: discoverResult.error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\n    );\n\n    // Cancel pending deferreds for no-longer-matched routes or routes we're\n    // about to reload.  Note that if this is an action reload we would have\n    // already cancelled all pending deferreds so this would be a no-op\n    cancelActiveDeferreds(\n      (routeId) =>\n        !(matches && matches.some((m) => m.route.id === routeId)) ||\n        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n    );\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      abortFetcher(rf.key);\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        request\n      );\n\n    if (request.signal.aborted) {\n      return { shortCircuited: true };\n    }\n\n    // Clean up _after_ loaders have completed.  Don't clean up if we short\n    // circuited because fetchControllers would have been aborted and\n    // reassigned to new controllers for the next navigation\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      pendingActionResult,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Wire up subscribers to update loaderData as promises settle\n    activeDeferreds.forEach((deferredData, routeId) => {\n      deferredData.subscribe((aborted) => {\n        // Note: No need to updateState here since the TrackedPromise on\n        // loaderData is stable across resolve/reject\n        // Remove this instance if we were aborted or if promises have settled\n        if (aborted || deferredData.done) {\n          activeDeferreds.delete(routeId);\n        }\n      });\n    });\n\n    // Preserve SSR errors during partial hydration\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      errors = { ...state.errors, ...errors };\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\n  }\n\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ) {\n    if (isServer) {\n      throw new Error(\n        \"router.fetch() was called during the server render, but it shouldn't be. \" +\n          \"You are likely calling a useFetcher() method in the body of your component. \" +\n          \"Try moving it to a useEffect or a callback.\"\n      );\n    }\n\n    abortFetcher(key);\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        preventScrollReset,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      preventScrollReset,\n      submission\n    );\n  }\n\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    requestMatches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      state,\n      fetchRequest,\n      [match],\n      requestMatches,\n      key\n    );\n    let actionResult = actionResults[match.route.id];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by our own fetcher\n      // re-submit which would have put _new_ controller is in fetchControllers\n      if (fetchControllers.get(key) === abortController) {\n        fetchControllers.delete(key);\n      }\n      return;\n    }\n\n    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, false, {\n            fetcherSubmission: submission,\n            preventScrollReset,\n          });\n        }\n      }\n\n      // Process any non-redirect errors thrown\n      if (isErrorResult(actionResult)) {\n        setFetcherError(key, routeId, actionResult.error);\n        return;\n      }\n    }\n\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(\n      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, basename)\n        : state.matches;\n\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n\n    let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\n    );\n\n    // Put all revalidating fetchers into the loading state, except for the\n    // current fetcher which we want to keep in it's current loading state which\n    // contains it's action submission info + action data\n    revalidatingFetchers\n      .filter((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        abortFetcher(staleKey);\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    abortStaleFetchLoads(loadId);\n\n    // If we are currently in a navigation loading state and this fetcher is\n    // more recent than the navigation, we want the newer data so abort the\n    // navigation and complete it with the fetcher data\n    if (\n      state.navigation.state === \"loading\" &&\n      loadId > pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\n\n      completeNavigation(state.navigation.location, {\n        matches,\n        loaderData,\n        errors,\n        fetchers: new Map(state.fetchers),\n      });\n    } else {\n      // otherwise just update with the fetcher data, preserving any existing\n      // loaderData for loaders that did not need to reload.  We have to\n      // manually merge here since we aren't going through completeNavigation\n      updateState({\n        errors,\n        loaderData: mergeLoaderData(\n          state.loaderData,\n          loaderData,\n          matches,\n          errors\n        ),\n        fetchers: new Map(state.fetchers),\n      });\n      isRevalidationRequired = false;\n    }\n  }\n\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      state,\n      fetchRequest,\n      [match],\n      matches,\n      key\n    );\n    let result = results[match.route.id];\n\n    // Deferred isn't supported for fetcher loads, await everything and treat it\n    // as a normal load.  resolveDeferredData will return undefined if this\n    // fetcher gets aborted, so we just leave result untouched and short circuit\n    // below if that happens\n    if (isDeferredResult(result)) {\n      result =\n        (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n        result;\n    }\n\n    // We can delete this so long as we weren't aborted by our our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n\n    if (fetchRequest.signal.aborted) {\n      return;\n    }\n\n    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result, false, {\n          preventScrollReset,\n        });\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\n  }\n\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  async function startRedirectNavigation(\n    request: Request,\n    redirect: RedirectResult,\n    isNavigation: boolean,\n    {\n      submission,\n      fetcherSubmission,\n      preventScrollReset,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename,\n      init.history,\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(location);\n        }\n        return;\n      }\n    }\n\n    // There's no need to abort on redirects, since we don't detect the\n    // redirect until the action/loaders have settled\n    pendingNavigationController = null;\n\n    let redirectHistoryAction =\n      replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\n    }\n\n    // If this was a 307/308 submission we want to preserve the HTTP method and\n    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n    // redirected location\n    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    state: RouterState,\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    fetcherKey: string | null\n  ): Promise<Record<string, DataResult>> {\n    let results: Record<string, DataStrategyResult>;\n    let dataResults: Record<string, DataResult> = {};\n    try {\n      results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        state,\n        request,\n        matchesToLoad,\n        matches,\n        fetcherKey,\n        manifest,\n        mapRouteProperties\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      matchesToLoad.forEach((m) => {\n        dataResults[m.route.id] = {\n          type: ResultType.error,\n          error: e,\n        };\n      });\n      return dataResults;\n    }\n\n    for (let [routeId, result] of Object.entries(results)) {\n      if (isRedirectDataStrategyResultResult(result)) {\n        let response = result.result as Response;\n        dataResults[routeId] = {\n          type: ResultType.redirect,\n          response: normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            routeId,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          ),\n        };\n      } else {\n        dataResults[routeId] = await convertDataStrategyResultToDataResult(\n          result\n        );\n      }\n    }\n\n    return dataResults;\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    state: RouterState,\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    let currentMatches = state.matches;\n\n    // Kick off loaders and fetchers in parallel\n    let loaderResultsPromise = callDataStrategy(\n      \"loader\",\n      state,\n      request,\n      matchesToLoad,\n      matches,\n      null\n    );\n\n    let fetcherResultsPromise = Promise.all(\n      fetchersToLoad.map(async (f) => {\n        if (f.matches && f.match && f.controller) {\n          let results = await callDataStrategy(\n            \"loader\",\n            state,\n            createClientSideRequest(init.history, f.path, f.controller.signal),\n            [f.match],\n            f.matches,\n            f.key\n          );\n          let result = results[f.match.route.id];\n          // Fetcher results are keyed by fetcher key from here on out, not routeId\n          return { [f.key]: result };\n        } else {\n          return Promise.resolve({\n            [f.key]: {\n              type: ResultType.error,\n              error: getInternalRouterError(404, {\n                pathname: f.path,\n              }),\n            } as ErrorResult,\n          });\n        }\n      })\n    );\n\n    let loaderResults = await loaderResultsPromise;\n    let fetcherResults = (await fetcherResultsPromise).reduce(\n      (acc, r) => Object.assign(acc, r),\n      {}\n    );\n\n    await Promise.all([\n      resolveNavigationDeferredResults(\n        matches,\n        loaderResults,\n        request.signal,\n        currentMatches,\n        state.loaderData\n      ),\n      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\n  }\n\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n    // Abort in-flight fetcher loads\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.add(key);\n      }\n      abortFetcher(key);\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n    // If this fetcher was previously marked for deletion, unmark it since we\n    // have a new instance\n    if (deletedFetchers.has(key)) {\n      deletedFetchers.delete(key);\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n\n    // If we opted into the flag we can clear this now since we're calling\n    // deleteFetcher() at the end of updateState() and we've already handed the\n    // deleted fetcher keys off to the data layer.\n    // If not, we're eagerly calling deleteFetcher() and we need to keep this\n    // Set populated until the next updateState call, and we'll clear\n    // `deletedFetchers` then\n    if (future.v7_fetcherPersist) {\n      deletedFetchers.delete(key);\n    }\n\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    let count = (activeFetchers.get(key) || 0) - 1;\n    if (count <= 0) {\n      activeFetchers.delete(key);\n      deletedFetchers.add(key);\n      if (!future.v7_fetcherPersist) {\n        deleteFetcher(key);\n      }\n    } else {\n      activeFetchers.set(key, count);\n    }\n\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    if (controller) {\n      controller.abort();\n      fetchControllers.delete(key);\n    }\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\n    for (let key of fetchRedirectIds) {\n      let fetcher = state.fetchers.get(key);\n      invariant(fetcher, `Expected fetcher: ${key}`);\n      if (fetcher.state === \"loading\") {\n        fetchRedirectIds.delete(key);\n        doneKeys.push(key);\n        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\n  }\n\n  function abortStaleFetchLoads(landedId: number): boolean {\n    let yeetedKeys = [];\n    for (let [key, id] of fetchReloadIds) {\n      if (id < landedId) {\n        let fetcher = state.fetchers.get(key);\n        invariant(fetcher, `Expected fetcher: ${key}`);\n        if (fetcher.state === \"loading\") {\n          abortFetcher(key);\n          fetchReloadIds.delete(key);\n          yeetedKeys.push(key);\n        }\n      }\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n\n  function getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\n  }\n\n  function cancelActiveDeferreds(\n    predicate?: (routeId: string) => boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) => {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  }\n\n  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnNavigationImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        if (Object.keys(matches[0].params).length > 0) {\n          // If we matched a dynamic param or a splat, it might only be because\n          // we haven't yet discovered other routes that would match with a\n          // higher score.  Call patchRoutesOnNavigation just to be sure\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal,\n    fetcherKey?: string\n  ): Promise<DiscoverRoutesResult> {\n    if (!patchRoutesOnNavigationImpl) {\n      return { type: \"success\", matches };\n    }\n\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      let localManifest = manifest;\n      try {\n        await patchRoutesOnNavigationImpl({\n          signal,\n          path: pathname,\n          matches: partialMatches,\n          fetcherKey,\n          patch: (routeId, children) => {\n            if (signal.aborted) return;\n            patchRoutesImpl(\n              routeId,\n              children,\n              routesToUse,\n              localManifest,\n              mapRouteProperties\n            );\n          },\n        });\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR && !signal.aborted) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      if (newMatches) {\n        return { type: \"success\", matches: newMatches };\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // Avoid loops if the second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        (partialMatches.length === newPartialMatches.length &&\n          partialMatches.every(\n            (m, i) => m.route.id === newPartialMatches![i].route.id\n          ))\n      ) {\n        return { type: \"success\", matches: null };\n      }\n\n      partialMatches = newPartialMatches;\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\n    },\n    initialize,\n    subscribe,\n    enableScrollRestoration,\n    navigate,\n    fetch,\n    revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: (to: To) => init.history.createHref(to),\n    encodeLocation: (to: To) => init.history.encodeLocation(to),\n    getFetcher,\n    deleteFetcher: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   *\n   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\n    if (isResponse(result)) {\n      return result;\n    }\n\n    // When returning StaticHandlerContext, we patch back in the location here\n    // since we need it for React Context.  But this helps keep our submit and\n    // loadRouteData operating on a Request instead of a Location\n    return { location, basename, ...result };\n  }\n\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   *\n   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      false,\n      match\n    );\n\n    if (isResponse(result)) {\n      return result;\n    }\n\n    let error = result.errors ? Object.values(result.errors)[0] : undefined;\n    if (error !== undefined) {\n      // If we got back result.errors, that means the loader/action threw\n      // _something_ that wasn't a Response, but it's not guaranteed/required\n      // to be an `instanceof Error` either, so we have to use throw here to\n      // preserve the \"error\" state outside of queryImpl.\n      throw error;\n    }\n\n    // Pick off the right state value to return\n    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(\n          request,\n          matches,\n          routeMatch || getTargetMatch(matches, location),\n          requestContext,\n          dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        routeMatch\n      );\n      return isResponse(result)\n        ? result\n        : {\n            ...result,\n            actionData: null,\n            actionHeaders: {},\n          };\n    } catch (e) {\n      // If the user threw/returned a Response in callLoaderOrAction for a\n      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isDataStrategyResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\n      }\n      // Redirects are always returned since they don't propagate to catch\n      // boundaries\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n\n  async function submit(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    actionMatch: AgnosticDataRouteMatch,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        dataStrategy\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      // Uhhhh - this should never happen, we should always throw these from\n      // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n      // can get back on the \"throw all redirect responses\" train here should\n      // this ever happen :/\n      throw new Response(null, {\n        status: result.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    // Create a GET request for the loaders\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal,\n    });\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\n      );\n\n      // action status codes take precedence over loader status codes\n      return {\n        ...context,\n        statusCode: isRouteErrorResponse(result.error)\n          ? result.error.status\n          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\n  ): Promise<\n    | Omit<\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      >\n    | Response\n  > {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch?.route.id,\n      });\n    }\n\n    let requestMatches = routeMatch\n      ? [routeMatch]\n      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\n\n    // Short circuit if we have no loaders to run (query())\n    if (matchesToLoad.length === 0) {\n      return {\n        matches,\n        // Add a null for all matched routes for proper revalidation on the client\n        loaderData: matches.reduce(\n          (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null\n  ): Promise<Record<string, DataResult>> {\n    let results = await callDataStrategyImpl(\n      dataStrategy || defaultDataStrategy,\n      type,\n      null,\n      request,\n      matchesToLoad,\n      matches,\n      null,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    let dataResults: Record<string, DataResult> = {};\n    await Promise.all(\n      matches.map(async (match) => {\n        if (!(match.route.id in results)) {\n          return;\n        }\n        let result = results[match.route.id];\n        if (isRedirectDataStrategyResultResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            match.route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        dataResults[match.route.id] =\n          await convertDataStrategyResultToDataResult(result);\n      })\n    );\n    return dataResults;\n  }\n\n  return {\n    dataRoutes,\n    query,\n    queryRoute,\n  };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n  routes: AgnosticDataRouteObject[],\n  context: StaticHandlerContext,\n  error: any\n) {\n  let newContext: StaticHandlerContext = {\n    ...context,\n    statusCode: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Account for `?index` params when routing to the current location\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index && !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index&\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index && nakedIndex) {\n      // Remove existing ones when we're not\n      let params = new URLSearchParams(path.search);\n      let indexValues = params.getAll(\"index\");\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\n} {\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return { path };\n  }\n\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n  matches: AgnosticDataRouteMatch[],\n  boundaryId: string,\n  includeBoundary = false\n) {\n  let index = matches.findIndex((m) => m.route.id === boundaryId);\n  if (index >= 0) {\n    return matches.slice(0, includeBoundary ? index + 1 : index);\n  }\n  return matches;\n}\n\nfunction getMatchesToLoad(\n  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  initialHydration: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryMatches = matches;\n  if (initialHydration && state.errors) {\n    // On initial hydration, only consider matches up to _and including_ the boundary.\n    // This is inclusive to handle cases where a server loader ran successfully,\n    // a child server loader bubbled up to this route, but this route has\n    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n    // we have a complete version of `loaderData`\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      Object.keys(state.errors)[0],\n      true\n    );\n  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n    // If an action threw an error, we call loaders up to, but not including the\n    // boundary\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      pendingActionResult[0]\n    );\n  }\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (initialHydration) {\n      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for when we revalidate.  If the route\n    // provides it's own implementation, then we give them full control but\n    // provide this value so they can leverage it if needed after they check\n    // their own specific use cases\n    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial hydration (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      initialHydration ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\n      });\n    }\n  });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n  route: AgnosticDataRouteObject,\n  loaderData: RouteData | null | undefined,\n  errors: RouteData | null | undefined\n) {\n  // We dunno if we have a loader - gotta find out!\n  if (route.lazy) {\n    return true;\n  }\n\n  // No loader, nothing to initialize\n  if (!route.loader) {\n    return false;\n  }\n\n  let hasData = loaderData != null && loaderData[route.id] !== undefined;\n  let hasError = errors != null && errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData && hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -> [a, b]\n    !currentMatch ||\n    // [a, b] -> [a, c]\n    match.route.id !== currentMatch.route.id;\n\n  // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n  let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    (currentPath != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  let childrenToPatch: AgnosticDataRouteObject[];\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    if (!route.children) {\n      route.children = [];\n    }\n    childrenToPatch = route.children;\n  } else {\n    childrenToPatch = routesToUse;\n  }\n\n  // Don't patch in routes we already know about so that `patch` is idempotent\n  // to simplify user-land code. This is useful because we re-call the\n  // `patchRoutesOnNavigation` function for matched routes with params.\n  let uniqueChildren = children.filter(\n    (newRoute) =>\n      !childrenToPatch.some((existingRoute) =>\n        isSameRoute(newRoute, existingRoute)\n      )\n  );\n\n  let newRoutes = convertRoutesToDataRoutes(\n    uniqueChildren,\n    mapRouteProperties,\n    [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n    manifest\n  );\n\n  childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n  newRoute: AgnosticRouteObject,\n  existingRoute: AgnosticRouteObject\n): boolean {\n  // Most optimal check is by id\n  if (\n    \"id\" in newRoute &&\n    \"id\" in existingRoute &&\n    newRoute.id === existingRoute.id\n  ) {\n    return true;\n  }\n\n  // Second is by pathing differences\n  if (\n    !(\n      newRoute.index === existingRoute.index &&\n      newRoute.path === existingRoute.path &&\n      newRoute.caseSensitive === existingRoute.caseSensitive\n    )\n  ) {\n    return false;\n  }\n\n  // Pathless layout routes are trickier since we need to check children.\n  // If they have no children then they're the same as far as we can tell\n  if (\n    (!newRoute.children || newRoute.children.length === 0) &&\n    (!existingRoute.children || existingRoute.children.length === 0)\n  ) {\n    return true;\n  }\n\n  // Otherwise, we look to see if every child in the new route is already\n  // represented in the existing route's children\n  return newRoute.children!.every((aChild, i) =>\n    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n  );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n  matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n  let matchesToLoad = matches.filter((m) => m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n  return results.reduce(\n    (acc, result, i) =>\n      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n    {}\n  );\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  state: RouterState | null,\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  fetcherKey: string | null,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n  let loadRouteDefinitionsPromises = matches.map((m) =>\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) => {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n    // `resolve` encapsulates route.lazy(), executing the loader/action,\n    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users\n    // can pass a callback to take fine-grained control over the execution\n    // of the loader/action\n    let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n      if (\n        handlerOverride &&\n        request.method === \"GET\" &&\n        (match.route.lazy || match.route.loader)\n      ) {\n        shouldLoad = true;\n      }\n      return shouldLoad\n        ? callLoaderOrAction(\n            type,\n            request,\n            match,\n            loadRoutePromise,\n            handlerOverride,\n            requestContext\n          )\n        : Promise.resolve({ type: ResultType.data, result: undefined });\n    };\n\n    return {\n      ...match,\n      shouldLoad,\n      resolve,\n    };\n  });\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: dsMatches,\n    request,\n    params: matches[0].params,\n    fetcherKey,\n    context: requestContext,\n  });\n\n  // Wait for all routes to load here but 'swallow the error since we want\n  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n  // called from `match.resolve()`\n  try {\n    await Promise.all(loadRouteDefinitionsPromises);\n  } catch (e) {\n    // No-op\n  }\n\n  return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  loadRoutePromise: Promise<void> | undefined,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<DataStrategyResult> {\n  let result: DataStrategyResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<DataStrategyResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<DataStrategyResult> = (async () => {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n          : actualHandler());\n        return { type: \"data\", result: val };\n      } catch (e) {\n        return { type: \"error\", result: e };\n      }\n    })();\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    // If we have a route.lazy promise, await that first\n    if (loadRoutePromise) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadRoutePromise,\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadRoutePromise;\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.result !== undefined,\n      `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n        `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n        `function. Please return a value or \\`null\\`.`\n    );\n  } catch (e) {\n    // We should already be catching and converting normal handler executions to\n    // DataStrategyResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n  dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n  let { result, type } = dataStrategyResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\n      let contentType = result.headers.get(\"Content-Type\");\n      // Check between word boundaries instead of startsWith() due to the last\n      // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n      if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\n        headers: result.headers,\n      };\n    }\n\n    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers,\n    };\n  }\n\n  if (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n          headers: result.init?.headers\n            ? new Headers(result.init.headers)\n            : undefined,\n        };\n      }\n\n      // Convert thrown data() to ErrorResponse instances\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(\n          result.init?.status || 500,\n          undefined,\n          result.data\n        ),\n        statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n        headers: result.init?.headers\n          ? new Headers(result.init.headers)\n          : undefined,\n      };\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string,\n  historyInstance: History,\n): string {\n  // Match Chrome's behavior:\n  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n  let invalidProtocols = [\n    \"about:\",\n    \"blob:\",\n    \"chrome:\",\n    \"chrome-untrusted:\",\n    \"content:\",\n    \"data:\",\n    \"devtools:\",\n    \"file:\",\n    \"filesystem:\",\n    // eslint-disable-next-line no-script-url\n    \"javascript:\",\n  ];\n\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n    }\n  }\n\n  try {\n    let url = historyInstance.createURL(location);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n  } catch (e) {}\n\n  return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\n  return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n  let searchParams = new URLSearchParams();\n\n  for (let [key, value] of formData.entries()) {\n    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) => {\n    if (!(match.route.id in results)) {\n      return;\n    }\n    let id = match.route.id;\n    let result = results[id];\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\n      let error = result.error;\n      // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n      if (pendingError !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\n      }\n\n      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\n\n      // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (\n          result.statusCode != null &&\n          result.statusCode !== 200 &&\n          !foundError\n        ) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      } else {\n        loaderData[id] = result.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      }\n    }\n  });\n\n  // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n  if (pendingError !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[0]] = undefined;\n  }\n\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders,\n  };\n}\n\nfunction processLoaderData(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record<string, DataResult>,\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    results,\n    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  revalidatingFetchers.forEach((rf) => {\n    let { key, match, controller } = rf;\n    let result = fetcherResults[key];\n    invariant(result, \"Did not find corresponding fetcher result\");\n\n    // Process fetcher non-redirect errors\n    if (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      return;\n    } else if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = {\n          ...errors,\n          [boundaryMatch.route.id]: result.error,\n        };\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      invariant(false, \"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  });\n\n  return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n  loaderData: RouteData,\n  newLoaderData: RouteData,\n  matches: AgnosticDataRouteMatch[],\n  errors: RouteData | null | undefined\n): RouteData {\n  let mergedLoaderData = { ...newLoaderData };\n  for (let match of matches) {\n    let id = match.route.id;\n    if (newLoaderData.hasOwnProperty(id)) {\n      if (newLoaderData[id] !== undefined) {\n        mergedLoaderData[id] = newLoaderData[id];\n      } else {\n        // No-op - this is so we ignore existing data if we have a key in the\n        // incoming object with an undefined value, which is how we unset a prior\n        // loaderData if we encounter a loader error\n      }\n    } else if (loaderData[id] !== undefined && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\n      mergedLoaderData[id] = loaderData[id];\n    }\n\n    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n  matches: AgnosticDataRouteMatch[],\n  routeId?: string\n): AgnosticDataRouteMatch {\n  let eligibleMatches = routeId\n    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n    matches[0]\n  );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n  matches: AgnosticDataRouteMatch[];\n  route: AgnosticDataRouteObject;\n} {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route =\n    routes.length === 1\n      ? routes[0]\n      : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n          id: `__shim-error-route__`,\n        };\n\n  return {\n    matches: [\n      {\n        params: {},\n        pathname: \"\",\n        pathnameBase: \"\",\n        route,\n      },\n    ],\n    route,\n  };\n}\n\nfunction getInternalRouterError(\n  status: number,\n  {\n    pathname,\n    routeId,\n    method,\n    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\";\n    message?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = `No route matches URL \"${pathname}\"`;\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n        `did not provide an \\`action\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (method) {\n      errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n    }\n  }\n\n  return new ErrorResponseImpl(\n    status || 500,\n    statusText,\n    new Error(errorMessage),\n    true\n  );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n  results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i >= 0; i--) {\n    let [key, result] = entries[i];\n    if (isRedirectResult(result)) {\n      return { key, result };\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n  );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n  return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n  return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n  return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null &&\n    typeof value.status === \"number\" &&\n    typeof value.statusText === \"string\" &&\n    typeof value.headers === \"object\" &&\n    typeof value.body !== \"undefined\"\n  );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n  if (!isResponse(result)) {\n    return false;\n  }\n\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index < entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    let currentMatch = currentMatches.find(\n      (m) => m.route.id === match!.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null &&\n      !isNewRouteInstance(currentMatch, match) &&\n      (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) && isRevalidatingLoader) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      await resolveDeferredData(result, signal, false).then((result) => {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    if (isDeferredResult(result)) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      invariant(\n        controller,\n        \"Expected an AbortController for revalidating fetcher deferred result\"\n      );\n      await resolveDeferredData(result, controller.signal, true).then(\n        (result) => {\n          if (result) {\n            results[key] = result;\n          }\n        }\n      );\n    }\n  }\n}\n\nasync function resolveDeferredData(\n  result: DeferredResult,\n  signal: AbortSignal,\n  unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\n  }\n\n  if (unwrap) {\n    try {\n      return {\n        type: ResultType.data,\n        data: result.deferredData.unwrappedData,\n      };\n    } catch (e) {\n      // Handle any TrackedPromise._error values encountered while unwrapping\n      return {\n        type: ResultType.error,\n        error: e,\n      };\n    }\n  }\n\n  return {\n    type: ResultType.data,\n    data: result.deferredData.data,\n  };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n  return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n  matches: AgnosticDataRouteMatch[],\n  location: Location | string\n) {\n  let search =\n    typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (\n    matches[matches.length - 1].route.index &&\n    hasNakedIndexQuery(search || \"\")\n  ) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  }\n  // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAEA;;AAEG;IACSA,OAsBX;AAtBD,CAAA,UAAYA,MAAM,EAAA;AAChB;;;;;;AAMG;AACHA,EAAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW,CAAA;AAEX;;;;AAIG;AACHA,EAAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa,CAAA;AAEb;;;AAGG;AACHA,EAAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB,CAAA;AACrB,CAAC,EAtBWA,MAAM,KAANA,MAAM,GAsBjB,EAAA,CAAA,CAAA,CAAA;AAqKD,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AA+BpC;;;AAGG;AACa,SAAAC,mBAAmBA,CACjCC,OAAA,EAAkC;AAAA,EAAA,IAAlCA,OAAA,KAAA,KAAA,CAAA,EAAA;IAAAA,OAAA,GAAgC,EAAE,CAAA;AAAA,GAAA;EAElC,IAAI;IAAEC,cAAc,GAAG,CAAC,GAAG,CAAC;IAAEC,YAAY;AAAEC,IAAAA,QAAQ,GAAG,KAAA;AAAO,GAAA,GAAGH,OAAO,CAAA;EACxE,IAAII,OAAmB,CAAC;AACxBA,EAAAA,OAAO,GAAGH,cAAc,CAACI,GAAG,CAAC,CAACC,KAAK,EAAEC,KAAK,KACxCC,oBAAoB,CAClBF,KAAK,EACL,OAAOA,KAAK,KAAK,QAAQ,GAAG,IAAI,GAAGA,KAAK,CAACG,KAAK,EAC9CF,KAAK,KAAK,CAAC,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,EAAE;AAC9Bnf,MAAAA,IAAI,CAACiD,CAAC,CAAC,GAAG,CAAC,GAAGtF,CAAC,CAAC,CAAA;AACjB,KAAA;IACD,IAAI;AACFuhB,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5B9Z,uBAAuB,EACvB7T,IAAI,CAACC,SAAS,CAACmO,IAAI,CAAC,CACrB,CAAA;KACF,CAAC,OAAO7J,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OAAI,CACxE,CAAA;AACF,KAAA;AACF,GAAA;AACH,CAAA;AACA;;;;"}/**
 * @remix-run/router v1.23.4
 *
 * 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
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {}));
})(this, (function (exports) { 'use strict';

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }

  ////////////////////////////////////////////////////////////////////////////////
  //#region Types and Constants
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * Actions represent the type of change to a location value.
   */
  let Action = /*#__PURE__*/function (Action) {
    /**
     * A POP indicates a change to an arbitrary index in the history stack, such
     * as a back or forward navigation. It does not describe the direction of the
     * navigation, only that the current index changed.
     *
     * Note: This is the default action for newly created history objects.
     */
    Action["Pop"] = "POP";
    /**
     * A PUSH indicates a new entry being added to the history stack, such as when
     * a link is clicked and a new page loads. When this happens, all subsequent
     * entries in the stack are lost.
     */
    Action["Push"] = "PUSH";
    /**
     * A REPLACE indicates the entry at the current index in the history stack
     * being replaced by a new one.
     */
    Action["Replace"] = "REPLACE";
    return Action;
  }({});

  /**
   * The pathname, search, and hash values of a URL.
   */

  // TODO: (v7) Change the Location generic default from `any` to `unknown` and
  // remove Remix `useLocation` wrapper.

  /**
   * An entry in a history stack. A location contains information about the
   * URL path, as well as possibly some arbitrary state and a key.
   */

  /**
   * A change to the current location.
   */

  /**
   * A function that receives notifications about location changes.
   */

  /**
   * Describes a location that is the destination of some navigation, either via
   * `history.push` or `history.replace`. This may be either a URL or the pieces
   * of a URL path.
   */

  /**
   * A history is an interface to the navigation stack. The history serves as the
   * source of truth for the current location, as well as provides a set of
   * methods that may be used to change it.
   *
   * It is similar to the DOM's `window.history` object, but with a smaller, more
   * focused API.
   */

  const PopStateEventType = "popstate";
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Memory History
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * A user-supplied object that describes a location. Used when providing
   * entries to `createMemoryHistory` via its `initialEntries` option.
   */

  /**
   * A memory history stores locations in memory. This is useful in stateful
   * environments where there is no web browser, such as node tests or React
   * Native.
   */

  /**
   * Memory history stores the current location in memory. It is designed for use
   * in stateful non-browser environments like tests and React Native.
   */
  function createMemoryHistory(options) {
    if (options === void 0) {
      options = {};
    }
    let {
      initialEntries = ["/"],
      initialIndex,
      v5Compat = false
    } = options;
    let entries; // Declare so we can access from createMemoryLocation
    entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
    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;
  }
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Browser History
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * A browser history stores the current location in regular URLs in a web
   * browser environment. This is the standard for most web apps and provides the
   * cleanest URLs the browser's address bar.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
   */

  /**
   * Browser history stores the location in regular URLs. This is the standard for
   * most web apps, but it requires some configuration on the server to ensure you
   * serve the same app at multiple URLs.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
   */
  function createBrowserHistory(options) {
    if (options === void 0) {
      options = {};
    }
    function createBrowserLocation(window, globalHistory) {
      let {
        pathname,
        search,
        hash
      } = window.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(window, to) {
      return typeof to === "string" ? to : createPath(to);
    }
    return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
  }
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Hash History
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * A hash history stores the current location in the fragment identifier portion
   * of the URL in a web browser environment.
   *
   * This is ideal for apps that do not control the server for some reason
   * (because the fragment identifier is never sent to the server), including some
   * shared hosting environments that do not provide fine-grained controls over
   * which pages are served at which URLs.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
   */

  /**
   * Hash history stores the location in window.location.hash. This makes it ideal
   * for situations where you don't want to send the location to the server for
   * some reason, either because you do cannot configure it or the URL space is
   * reserved for something else.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
   */
  function createHashHistory(options) {
    if (options === void 0) {
      options = {};
    }
    function createHashLocation(window, globalHistory) {
      let {
        pathname = "/",
        search = "",
        hash = ""
      } = parsePath(window.location.hash.substr(1));

      // Hash URL should always have a leading / just like window.location.pathname
      // does, so if an app ends up at a route like /#something then we add a
      // leading slash so all of our path-matching behaves the same as if it would
      // in a browser router.  This is particularly important when there exists a
      // root splat route (<Route path="*">) since that matches internally against
      // "/*" and we'd expect /#something to 404 in a hash router app.
      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(window, to) {
      let base = window.document.querySelector("base");
      let href = "";
      if (base && base.getAttribute("href")) {
        let url = window.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);
  }
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region UTILS
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * @private
   */

  function invariant(value, message) {
    if (value === false || value === null || typeof value === "undefined") {
      throw new Error(message);
    }
  }
  function warning(cond, message) {
    if (!cond) {
      // eslint-disable-next-line no-console
      if (typeof console !== "undefined") console.warn(message);
      try {
        // Welcome to debugging history!
        //
        // This error is thrown as a convenience, so you can more easily
        // find the source for a warning that appears in the console by
        // enabling "pause on exceptions" in your JavaScript debugger.
        throw new Error(message);
        // eslint-disable-next-line no-empty
      } catch (e) {}
    }
  }
  function createKey() {
    return Math.random().toString(36).substr(2, 8);
  }

  /**
   * For browser-based histories, we combine the state and key into an object
   */
  function getHistoryState(location, index) {
    return {
      usr: location.state,
      key: location.key,
      idx: index
    };
  }

  /**
   * Creates a Location object with a unique key from the given Path
   */
  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;
  }

  /**
   * Creates a string URL path from the given pathname, search, and hash components.
   */
  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;
  }

  /**
   * Parses a string URL path into its separate pathname, search, and hash components.
   */
  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 = document.defaultView,
      v5Compat = false
    } = options;
    let globalHistory = window.history;
    let action = Action.Pop;
    let listener = null;
    let index = getIndex();
    // Index should only be null when we initialize. If not, it's because the
    // user called history.pushState or history.replaceState directly, in which
    // case we should log a warning as it will result in bugs.
    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...catch because iOS limits us to 100 pushState calls :/
      try {
        globalHistory.pushState(historyState, "", url);
      } catch (error) {
        // If the exception is because `state` can't be serialized, let that throw
        // outwards just like a replace call would so the dev knows the cause
        // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
        // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
        if (error instanceof DOMException && error.name === "DataCloneError") {
          throw error;
        }
        // They are going to lose state here, but there is no real
        // way to warn them about it since the page will refresh...
        window.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) {
      // window.location.origin is "null" (the literal string value) in Firefox
      // under certain conditions, notably when serving from a local HTML file
      // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
      let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
      let href = typeof to === "string" ? to : createPath(to);
      // Treating this as a full URL will strip any trailing spaces so we need to
      // pre-encode them since they might be part of a matching splat param from
      // an ancestor route
      href = href.replace(/ $/, "%20");
      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(window, globalHistory);
      },
      listen(fn) {
        if (listener) {
          throw new Error("A history only accepts one active listener");
        }
        window.addEventListener(PopStateEventType, handlePop);
        listener = fn;
        return () => {
          window.removeEventListener(PopStateEventType, handlePop);
          listener = null;
        };
      },
      createHref(to) {
        return createHref(window, to);
      },
      createURL,
      encodeLocation(to) {
        // Encode a Location the same way window.location would
        let url = createURL(to);
        return {
          pathname: url.pathname,
          search: url.search,
          hash: url.hash
        };
      },
      push,
      replace,
      go(n) {
        return globalHistory.go(n);
      }
    };
    return history;
  }

  //#endregion

  /**
   * Map of routeId -> data returned from a loader/action/error
   */

  let ResultType = /*#__PURE__*/function (ResultType) {
    ResultType["data"] = "data";
    ResultType["deferred"] = "deferred";
    ResultType["redirect"] = "redirect";
    ResultType["error"] = "error";
    return ResultType;
  }({});

  /**
   * Successful result from a loader or action
   */

  /**
   * Successful defer() result from a loader or action
   */

  /**
   * Redirect result from a loader or action
   */

  /**
   * Unsuccessful result from a loader or action
   */

  /**
   * Result from a loader or action - potentially successful or unsuccessful
   */

  /**
   * Users can specify either lowercase or uppercase form methods on `<Form>`,
   * useSubmit(), `<fetcher.Form>`, etc.
   */

  /**
   * Active navigation/fetcher form methods are exposed in lowercase on the
   * RouterState
   */

  /**
   * In v7, active navigation/fetcher form methods are exposed in uppercase on the
   * RouterState.  This is to align with the normalization done via fetch().
   */

  // Thanks https://github.com/sindresorhus/type-fest!

  /**
   * @private
   * Internal interface to pass around for action submissions, not intended for
   * external consumption
   */

  /**
   * @private
   * Arguments passed to route loader/action functions.  Same for now but we keep
   * this as a private implementation detail in case they diverge in the future.
   */

  // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
  //   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
  //   Also, make them a type alias instead of an interface

  /**
   * Arguments passed to loader functions
   */

  /**
   * Arguments passed to action functions
   */

  /**
   * Loaders and actions can return anything except `undefined` (`null` is a
   * valid return value if there is no data to return).  Responses are preferred
   * and will ease any future migration to Remix
   */

  /**
   * Route loader function signature
   */

  /**
   * Route action function signature
   */

  /**
   * Arguments passed to shouldRevalidate function
   */

  /**
   * Route shouldRevalidate function signature.  This runs after any submission
   * (navigation or fetcher), so we flatten the navigation/fetcher submission
   * onto the arguments.  It shouldn't matter whether it came from a navigation
   * or a fetcher, what really matters is the URLs and the formData since loaders
   * have to re-run based on the data models that were potentially mutated.
   */

  /**
   * Function provided by the framework-aware layers to set `hasErrorBoundary`
   * from the framework-aware `errorElement` prop
   *
   * @deprecated Use `mapRouteProperties` instead
   */

  /**
   * Result from a loader or action called via dataStrategy
   */

  /**
   * Function provided by the framework-aware layers to set any framework-specific
   * properties from framework-agnostic properties
   */

  /**
   * Keys we cannot change from within a lazy() function. We spread all other keys
   * onto the route. Either they're meaningful to the router, or they'll get
   * ignored.
   */

  const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);

  /**
   * lazy() function to load a route definition, which can add non-matching
   * related properties to a route
   */

  /**
   * Base RouteObject with common props shared by all types of routes
   */

  /**
   * Index routes must not have children
   */

  /**
   * Non-index routes may have children, but cannot have index
   */

  /**
   * A route object represents a logical route, with (optionally) its child
   * routes organized in a tree-like structure.
   */

  /**
   * A data route object, which is just a RouteObject with a required unique ID
   */

  // Recursive helper for finding path parameters in the absence of wildcards

  /**
   * Examples:
   * "/a/b/*" -> "*"
   * ":a" -> "a"
   * "/a/:b" -> "b"
   * "/a/blahblahblah:b" -> "b"
   * "/:a/:b" -> "a" | "b"
   * "/:a/b/:c/*" -> "a" | "c" | "*"
   */

  // Attempt to parse the given string segment. If it fails, then just return the
  // plain string type as a default fallback. Otherwise, return the union of the
  // parsed string literals that were referenced as dynamic segments in the route.

  /**
   * The parameters that were parsed from the URL path.
   */

  /**
   * A RouteMatch contains info about how a route matched a URL.
   */

  function isIndexRoute(route) {
    return route.index === true;
  }

  // Walk the route tree generating unique IDs where necessary, so we are working
  // solely with AgnosticDataRouteObject's within the Router
  function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
    if (parentPath === void 0) {
      parentPath = [];
    }
    if (manifest === void 0) {
      manifest = {};
    }
    return routes.map((route, index) => {
      let treePath = [...parentPath, String(index)];
      let id = typeof route.id === "string" ? route.id : treePath.join("-");
      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: undefined
        });
        manifest[id] = pathOrLayoutRoute;
        if (route.children) {
          pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
        }
        return pathOrLayoutRoute;
      }
    });
  }

  /**
   * Matches the given routes to a location and returns the match data.
   *
   * @see https://reactrouter.com/v6/utils/match-routes
   */
  function matchRoutes(routes, locationArg, basename) {
    if (basename === void 0) {
      basename = "/";
    }
    return matchRoutesImpl(routes, locationArg, basename, false);
  }
  function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
    let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
    let pathname = stripBasename(location.pathname || "/", basename);
    if (pathname == null) {
      return null;
    }
    let branches = flattenRoutes(routes);
    rankRouteBranches(branches);
    let matches = null;
    let decoded = decodePath(pathname);
    for (let i = 0; matches == null && i < branches.length; ++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.
      matches = matchRouteBranch(branches[i], decoded, allowPartial);
    }
    return matches;
  }
  function convertRouteMatchToUiMatch(match, loaderData) {
    let {
      route,
      pathname,
      params
    } = match;
    return {
      id: route.id,
      pathname,
      params,
      data: loaderData[route.id],
      handle: route.handle
    };
  }
  function flattenRoutes(routes, branches, parentsMeta, parentPath) {
    if (branches === void 0) {
      branches = [];
    }
    if (parentsMeta === void 0) {
      parentsMeta = [];
    }
    if (parentPath === void 0) {
      parentPath = "";
    }
    let flattenRoute = (route, index, relativePath) => {
      let meta = {
        relativePath: relativePath === undefined ? 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);

      // Add the children before adding this route to the array, so we traverse the
      // route tree depth-first and child routes appear before their parents in
      // the "flattened" version.
      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);
      }

      // Routes without a path shouldn't ever match by themselves unless they are
      // index routes, so don't add them to the list of possible branches.
      if (route.path == null && !route.index) {
        return;
      }
      branches.push({
        path,
        score: computeScore(path, route.index),
        routesMeta
      });
    };
    routes.forEach((route, index) => {
      var _route$path;
      // coarse-grain check for optional params
      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;
  }

  /**
   * Computes all combinations of optional path segments for a given path,
   * excluding combinations that are ambiguous and of lower priority.
   *
   * For example, `/one/:two?/three/:four?/:five?` explodes to:
   * - `/one/three`
   * - `/one/:two/three`
   * - `/one/three/:four`
   * - `/one/three/:five`
   * - `/one/:two/three/:four`
   * - `/one/:two/three/:five`
   * - `/one/three/:four/:five`
   * - `/one/:two/three/:four/:five`
   */
  function explodeOptionalSegments(path) {
    let segments = path.split("/");
    if (segments.length === 0) return [];
    let [first, ...rest] = segments;

    // Optional path segments are denoted by a trailing `?`
    let isOptional = first.endsWith("?");
    // Compute the corresponding required segment: `foo?` -> `foo`
    let required = first.replace(/\?$/, "");
    if (rest.length === 0) {
      // Intepret empty string as omitting an optional segment
      // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
      return isOptional ? [required, ""] : [required];
    }
    let restExploded = explodeOptionalSegments(rest.join("/"));
    let result = [];

    // All child paths with the prefix.  Do this for all children before the
    // optional version for all children, so we get consistent ordering where the
    // parent optional aspect is preferred as required.  Otherwise, we can get
    // child sections interspersed where deeper optional segments are higher than
    // parent optional segments, where for example, /:two would explode _earlier_
    // then /:one.  By always including the parent as required _for all children_
    // first, we avoid this issue
    result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));

    // Then, if this is an optional value, add all child versions without
    if (isOptional) {
      result.push(...restExploded);
    }

    // for absolute paths, ensure `/` instead of empty segment
    return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
  }
  function rankRouteBranches(branches) {
    branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
    : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
  }
  const paramRe = /^:[\w-]+$/;
  const dynamicSegmentValue = 3;
  const indexRouteValue = 2;
  const emptySegmentValue = 1;
  const staticSegmentValue = 10;
  const splatPenalty = -2;
  const isSplat = s => s === "*";
  function computeScore(path, index) {
    let segments = path.split("/");
    let initialScore = segments.length;
    if (segments.some(isSplat)) {
      initialScore += splatPenalty;
    }
    if (index) {
      initialScore += indexRouteValue;
    }
    return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
  }
  function compareIndexes(a, b) {
    let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[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] - b[b.length - 1] :
    // Otherwise, it doesn't really make sense to rank non-siblings by index,
    // so they sort equally.
    0;
  }
  function matchRouteBranch(branch, pathname, allowPartial) {
    if (allowPartial === void 0) {
      allowPartial = false;
    }
    let {
      routesMeta
    } = branch;
    let matchedParams = {};
    let matchedPathname = "/";
    let matches = [];
    for (let 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);
      let route = meta.route;
      if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
        match = matchPath({
          path: meta.relativePath,
          caseSensitive: meta.caseSensitive,
          end: false
        }, remainingPathname);
      }
      if (!match) {
        return null;
      }
      Object.assign(matchedParams, match.params);
      matches.push({
        // TODO: Can this as be avoided?
        params: matchedParams,
        pathname: joinPaths([matchedPathname, match.pathname]),
        pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
        route
      });
      if (match.pathnameBase !== "/") {
        matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
      }
    }
    return matches;
  }

  /**
   * Returns a path with params interpolated.
   *
   * @see https://reactrouter.com/v6/utils/generate-path
   */
  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(/\*$/, "/*");
    }

    // ensure `/` is added at the beginning if the path is absolute
    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;

      // only apply the splat if it's the last segment
      if (isLastSegment && segment === "*") {
        const star = "*";
        // Apply the splat
        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);
      }

      // Remove any optional markers from optional static segments
      return segment.replace(/\?$/g, "");
    })
    // Remove empty segments
    .filter(segment => !!segment);
    return prefix + segments.join("/");
  }

  /**
   * A PathPattern is used to match on some portion of a URL pathname.
   */

  /**
   * A PathMatch contains info about how a PathPattern matched on a URL pathname.
   */

  /**
   * Performs pattern matching on a URL pathname and returns information about
   * the match.
   *
   * @see https://reactrouter.com/v6/utils/match-path
   */
  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;
      // We need to compute the pathnameBase here using the raw splat value
      // instead of using params["*"] later because it will be decoded then
      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] = undefined;
      } else {
        memo[paramName] = (value || "").replace(/%2F/g, "/");
      }
      return memo;
    }, {});
    return {
      params,
      pathname: matchedPathname,
      pathnameBase,
      pattern
    };
  }
  function compilePath(path, caseSensitive, end) {
    if (caseSensitive === void 0) {
      caseSensitive = false;
    }
    if (end === void 0) {
      end = true;
    }
    warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
    let params = [];
    let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
    .replace(/^\/*/, "/") // Make sure it has a leading /
    .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
    .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
      params.push({
        paramName,
        isOptional: isOptional != null
      });
      return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
    });
    if (path.endsWith("*")) {
      params.push({
        paramName: "*"
      });
      regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
      : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
    } else if (end) {
      // When matching to the end, ignore trailing slashes
      regexpSource += "\\/*$";
    } else if (path !== "" && path !== "/") {
      // If our path is non-empty and contains anything beyond an initial slash,
      // then we have _some_ form of path in our regex, so we should expect to
      // match only if we find the end of this path segment.  Look for an optional
      // non-captured trailing slash (to match a portion of the URL) or the end
      // of the path (if we've matched to the end).  We used to do this with a
      // word boundary but that gives false positives on routes like
      // /user-preferences since `-` counts as a word boundary.
      regexpSource += "(?:(?=\\/|$))";
    } else ;
    let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
    return [matcher, params];
  }
  function decodePath(value) {
    try {
      return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
    } catch (error) {
      warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
      return value;
    }
  }

  /**
   * @private
   */
  function stripBasename(pathname, basename) {
    if (basename === "/") return pathname;
    if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
      return null;
    }

    // We want to leave trailing slash behavior in the user's control, so if they
    // specify a basename with a trailing slash, we should support it
    let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
    let nextChar = pathname.charAt(startIndex);
    if (nextChar && nextChar !== "/") {
      // pathname does not start with basename/
      return null;
    }
    return pathname.slice(startIndex) || "/";
  }

  /**
   * Returns a resolved path object relative to the given pathname.
   *
   * @see https://reactrouter.com/v6/utils/resolve-path
   */
  function resolvePath(to, fromPathname) {
    if (fromPathname === void 0) {
      fromPathname = "/";
    }
    let {
      pathname: toPathname,
      search = "",
      hash = ""
    } = typeof to === "string" ? parsePath(to) : to;
    let pathname;
    if (toPathname) {
      toPathname = removeDoubleSlashes(toPathname);
      if (toPathname.startsWith("/")) {
        pathname = resolvePathname(toPathname.substring(1), "/");
      } else {
        pathname = resolvePathname(toPathname, fromPathname);
      }
    } else {
      pathname = 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 === "..") {
        // Keep the root "" segment so the pathname starts at /
        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 <Link to=\"...\"> and the router will parse it for you.";
  }

  /**
   * @private
   *
   * When processing relative navigation we want to ignore ancestor routes that
   * do not contribute to the path, such that index/pathless layout routes don't
   * interfere.
   *
   * For example, when moving a route element into an index route and/or a
   * pathless layout route, relative link behavior contained within should stay
   * the same.  Both of the following examples should link back to the root:
   *
   *   <Route path="/">
   *     <Route path="accounts" element={<Link to=".."}>
   *   </Route>
   *
   *   <Route path="/">
   *     <Route path="accounts">
   *       <Route element={<AccountsLayout />}>       // <-- Does not contribute
   *         <Route index element={<Link to=".."} />  // <-- Does not contribute
   *       </Route
   *     </Route>
   *   </Route>
   */
  function getPathContributingMatches(matches) {
    return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
  }

  // Return the array of pathnames for the current route matches - used to
  // generate the routePathnames input for resolveTo()
  function getResolveToMatches(matches, v7_relativeSplatPath) {
    let pathMatches = getPathContributingMatches(matches);

    // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
    // match so we include splat values for "." links.  See:
    // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
    if (v7_relativeSplatPath) {
      return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
    }
    return pathMatches.map(match => match.pathnameBase);
  }

  /**
   * @private
   */
  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;

    // Routing is relative to the current pathname if explicitly requested.
    //
    // If a pathname is explicitly provided in `to`, it should be relative to the
    // route context. This is explained in `Note on `<Link to>` values` in our
    // migration guide from v5 as a means of disambiguation between `to` values
    // that begin with `/` and those that do not. However, this is problematic for
    // `to` values that do not provide a pathname. `to` can simply be a search or
    // hash string, in which case we should assume that the navigation is relative
    // to the current location's pathname and *not* the route pathname.
    if (toPathname == null) {
      from = locationPathname;
    } else {
      let routePathnameIndex = routePathnames.length - 1;

      // With relative="route" (the default), each leading .. segment means
      // "go up one route" instead of "go up one URL segment".  This is a key
      // difference from how <a href> works and a major reason we call this a
      // "to" value instead of a "href".
      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);

    // Ensure the pathname has a trailing slash if the original "to" had one
    let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
    // Or if this was a link to the current path which has a trailing slash
    let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
    if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
      path.pathname += "/";
    }
    return path;
  }

  /**
   * @private
   */
  function getToPathname(to) {
    // Empty strings should be treated the same as / paths
    return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
  }
  const removeDoubleSlashes = path => path.replace(/\/\/+/g, "/");

  /**
   * @private
   */
  const joinPaths = paths => removeDoubleSlashes(paths.join("/"));

  /**
   * @private
   */
  const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");

  /**
   * @private
   */
  const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;

  /**
   * @private
   */
  const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  /**
   * This is a shortcut for creating `application/json` responses. Converts `data`
   * to JSON and sets the `Content-Type` header.
   *
   * @deprecated The `json` method is deprecated in favor of returning raw objects.
   * This method will be removed in v7.
   */
  const json = function json(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
    }));
  };
  class DataWithResponseInit {
    constructor(data, init) {
      this.type = "DataWithResponseInit";
      this.data = data;
      this.init = init || null;
    }
  }

  /**
   * Create "responses" that contain `status`/`headers` without forcing
   * serialization into an actual `Response` - used by Remix single fetch
   */
  function data(data, init) {
    return new DataWithResponseInit(data, typeof init === "number" ? {
      status: init
    } : init);
  }
  class AbortedDeferredError extends Error {}
  class DeferredData {
    constructor(data, responseInit) {
      this.pendingKeysSet = new Set();
      this.subscribers = new Set();
      this.deferredKeys = [];
      invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");

      // Set up an AbortController + Promise we can race against to exit early
      // cancellation
      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) {
        // All incoming values were resolved
        this.unlistenAbortSignal();
      }
      this.init = responseInit;
    }
    trackPromise(key, value) {
      if (!(value instanceof Promise)) {
        return value;
      }
      this.deferredKeys.push(key);
      this.pendingKeysSet.add(key);

      // We store a little wrapper promise that will be extended with
      // _data/_error props upon resolve/reject
      let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));

      // Register rejection listeners to avoid uncaught promise rejections on
      // errors or aborted deferred values
      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) {
        // Nothing left to abort!
        this.unlistenAbortSignal();
      }

      // If the promise was resolved/rejected with undefined, we'll throw an error as you
      // should always resolve with a value or null
      if (error === undefined && data === undefined) {
        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 === undefined) {
        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, k) => this.pendingKeysSet.delete(k));
      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(aborted => {
            signal.removeEventListener("abort", onAbort);
            if (aborted || this.done) {
              resolve(aborted);
            }
          });
        });
      }
      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);
    }
  }
  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;
  }
  /**
   * @deprecated The `defer` method is deprecated in favor of returning raw
   * objects. This method will be removed in v7.
   */
  const defer = function defer(data, init) {
    if (init === void 0) {
      init = {};
    }
    let responseInit = typeof init === "number" ? {
      status: init
    } : init;
    return new DeferredData(data, responseInit);
  };
  /**
   * A redirect response. Sets the status code and the `Location` header.
   * Defaults to "302 Found".
   */
  const redirect = function redirect(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
    }));
  };

  /**
   * A redirect response that will force a document reload to the new location.
   * Sets the status code and the `Location` header.
   * Defaults to "302 Found".
   */
  const redirectDocument = (url, init) => {
    let response = redirect(url, init);
    response.headers.set("X-Remix-Reload-Document", "true");
    return response;
  };

  /**
   * A redirect response that will perform a `history.replaceState` instead of a
   * `history.pushState` for client-side navigation redirects.
   * Sets the status code and the `Location` header.
   * Defaults to "302 Found".
   */
  const replace = (url, init) => {
    let response = redirect(url, init);
    response.headers.set("X-Remix-Replace", "true");
    return response;
  };
  /**
   * @private
   * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
   *
   * We don't export the class for public use since it's an implementation
   * detail, but we export the interface above so folks can build their own
   * abstractions around instances via isRouteErrorResponse()
   */
  class ErrorResponseImpl {
    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;
      }
    }
  }

  /**
   * Check if the given error is an ErrorResponse generated from a 4xx/5xx
   * Response thrown from an action/loader
   */
  function isRouteErrorResponse(error) {
    return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  }

  ////////////////////////////////////////////////////////////////////////////////
  //#region Types and Constants
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * A Router instance manages all navigation and data loading/mutations
   */

  /**
   * State maintained internally by the router.  During a navigation, all states
   * reflect the the "old" location unless otherwise noted.
   */

  /**
   * Data that can be passed into hydrate a Router from SSR
   */

  /**
   * Future flags to toggle new feature behavior
   */

  /**
   * Initialization options for createRouter
   */

  /**
   * State returned from a server-side query() call
   */

  /**
   * A StaticHandler instance manages a singular SSR navigation/fetch event
   */

  /**
   * Subscriber function signature for changes to router state
   */

  /**
   * Function signature for determining the key to be used in scroll restoration
   * for a given location
   */

  /**
   * Function signature for determining the current scroll position
   */

  // Allowed for any navigation or fetch

  // Only allowed for navigations

  // Only allowed for submission navigations

  /**
   * Options for a navigate() call for a normal (non-submission) navigation
   */

  /**
   * Options for a navigate() call for a submission navigation
   */

  /**
   * Options to pass to navigate() for a navigation
   */

  /**
   * Options for a fetch() load
   */

  /**
   * Options for a fetch() submission
   */

  /**
   * Options to pass to fetch()
   */

  /**
   * Potential states for state.navigation
   */

  /**
   * Potential states for fetchers
   */

  /**
   * Cached info for active fetcher.load() instances so they can participate
   * in revalidation
   */

  /**
   * Identified fetcher.load() calls that need to be revalidated
   */

  const validMutationMethodsArr = ["post", "put", "patch", "delete"];
  const validMutationMethods = new Set(validMutationMethodsArr);
  const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
  const validRequestMethods = new Set(validRequestMethodsArr);
  const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
  const redirectPreserveMethodStatusCodes = new Set([307, 308]);
  const IDLE_NAVIGATION = {
    state: "idle",
    location: undefined,
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined
  };
  const IDLE_FETCHER = {
    state: "idle",
    data: undefined,
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined
  };
  const IDLE_BLOCKER = {
    state: "unblocked",
    proceed: undefined,
    reset: undefined,
    location: undefined
  };
  const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  const defaultMapRouteProperties = route => ({
    hasErrorBoundary: Boolean(route.hasErrorBoundary)
  });
  const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";

  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region createRouter
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * Create a router and listen to history POP navigations
   */
  function createRouter(init) {
    const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
    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) {
      // If they are still using the deprecated version, wrap it with the new API
      let detectErrorBoundary = init.detectErrorBoundary;
      mapRouteProperties = route => ({
        hasErrorBoundary: detectErrorBoundary(route)
      });
    } else {
      mapRouteProperties = defaultMapRouteProperties;
    }

    // Routes keyed by ID
    let manifest = {};
    // Routes in tree format for matching
    let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
    let inFlightDataRoutes;
    let basename = init.basename || "/";
    let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
    let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;

    // Config driven behavior flags
    let future = _extends({
      v7_fetcherPersist: false,
      v7_normalizeFormMethod: false,
      v7_partialHydration: false,
      v7_prependBasename: false,
      v7_relativeSplatPath: false,
      v7_skipActionErrorRevalidation: false
    }, init.future);
    // Cleanup function for history
    let unlistenHistory = null;
    // Externally-provided functions to call on all state changes
    let subscribers = new Set();
    // Externally-provided object to hold scroll restoration locations during routing
    let savedScrollPositions = null;
    // Externally-provided function to get scroll restoration keys
    let getScrollRestorationKey = null;
    // Externally-provided function to get current scroll position
    let getScrollPosition = null;
    // One-time flag to control the initial hydration scroll restoration.  Because
    // we don't get the saved positions from <ScrollRestoration /> until _after_
    // the initial render, we need to manually trigger a separate updateState to
    // send along the restoreScrollPosition
    // Set to true if we have `hydrationData` since we assume we were SSR'd and that
    // SSR did the initial scroll restoration.
    let initialScrollRestored = init.hydrationData != null;
    let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
    let initialMatchesIsFOW = false;
    let initialErrors = null;
    if (initialMatches == null && !patchRoutesOnNavigationImpl) {
      // If we do not match a user-provided-route, fall back to the root
      // to allow the error boundary to take over
      let error = getInternalRouterError(404, {
        pathname: init.history.location.pathname
      });
      let {
        matches,
        route
      } = getShortCircuitMatches(dataRoutes);
      initialMatches = matches;
      initialErrors = {
        [route.id]: error
      };
    }

    // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
    // our initial match is a splat route, clear them out so we run through lazy
    // discovery on hydration in case there's a more accurate lazy route match.
    // In SSR apps (with `hydrationData`), we expect that the server will send
    // up the proper matched routes so we don't want to run lazy discovery on
    // initial hydration and want to hydrate into the splat route.
    if (initialMatches && !init.hydrationData) {
      let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
      if (fogOfWar.active) {
        initialMatches = null;
      }
    }
    let initialized;
    if (!initialMatches) {
      initialized = false;
      initialMatches = [];

      // If partial hydration and fog of war is enabled, we will be running
      // `patchRoutesOnNavigation` during hydration so include any partial matches as
      // the initial matches so we can properly render `HydrateFallback`'s
      if (future.v7_partialHydration) {
        let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
        if (fogOfWar.active && fogOfWar.matches) {
          initialMatchesIsFOW = true;
          initialMatches = fogOfWar.matches;
        }
      }
    } else if (initialMatches.some(m => m.route.lazy)) {
      // All initialMatches need to be loaded before we're ready.  If we have lazy
      // functions around still then we'll need to run them in initialize()
      initialized = false;
    } else if (!initialMatches.some(m => m.route.loader)) {
      // If we've got no loaders to run, then we're good to go
      initialized = true;
    } else if (future.v7_partialHydration) {
      // If partial hydration is enabled, we're initialized so long as we were
      // provided with hydrationData for every route with a loader, and no loaders
      // were marked for explicit hydration
      let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
      let errors = init.hydrationData ? init.hydrationData.errors : null;
      // If errors exist, don't consider routes below the boundary
      if (errors) {
        let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
        initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
      } else {
        initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
      }
    } else {
      // Without partial hydration - we're initialized if we were provided any
      // hydrationData - which is expected to be complete
      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: new Map(),
      blockers: new Map()
    };

    // -- Stateful internal variables to manage navigations --
    // Current navigation in progress (to be committed in completeNavigation)
    let pendingAction = Action.Pop;

    // Should the current navigation prevent the scroll reset if scroll cannot
    // be restored?
    let pendingPreventScrollReset = false;

    // AbortController for the active navigation
    let pendingNavigationController;

    // Should the current navigation enable document.startViewTransition?
    let pendingViewTransitionEnabled = false;

    // Store applied view transitions so we can apply them on POP
    let appliedViewTransitions = new Map();

    // Cleanup function for persisting applied transitions to sessionStorage
    let removePageHideEventListener = null;

    // We use this to avoid touching history in completeNavigation if a
    // revalidation is entirely uninterrupted
    let isUninterruptedRevalidation = false;

    // Use this internal flag to force revalidation of all loaders:
    //  - submissions (completed or interrupted)
    //  - useRevalidator()
    //  - X-Remix-Revalidate (from redirect)
    let isRevalidationRequired = false;

    // Use this internal array to capture routes that require revalidation due
    // to a cancelled deferred on action submission
    let cancelledDeferredRoutes = [];

    // Use this internal array to capture fetcher loads that were cancelled by an
    // action navigation and require revalidation
    let cancelledFetcherLoads = new Set();

    // AbortControllers for any in-flight fetchers
    let fetchControllers = new Map();

    // Track loads based on the order in which they started
    let incrementingLoadId = 0;

    // Track the outstanding pending navigation data load to be compared against
    // the globally incrementing load when a fetcher load lands after a completed
    // navigation
    let pendingNavigationLoadId = -1;

    // Fetchers that triggered data reloads as a result of their actions
    let fetchReloadIds = new Map();

    // Fetchers that triggered redirect navigations
    let fetchRedirectIds = new Set();

    // Most recent href/match for fetcher.load calls for fetchers
    let fetchLoadMatches = new Map();

    // Ref-count mounted fetchers so we know when it's ok to clean them up
    let activeFetchers = new Map();

    // Fetchers that have requested a delete when using v7_fetcherPersist,
    // they'll be officially removed after they return to idle
    let deletedFetchers = new Set();

    // Store DeferredData instances for active route matches.  When a
    // route loader returns defer() we stick one in here.  Then, when a nested
    // promise resolves we update loaderData.  If a new navigation starts we
    // cancel active deferreds for eliminated routes.
    let activeDeferreds = new Map();

    // Store blocker functions in a separate Map outside of router state since
    // we don't need to update UI state if they change
    let blockerFunctions = new Map();

    // Flag to ignore the next history update, so we can revert the URL change on
    // a POP navigation that was blocked by the user without touching router state
    let unblockBlockerHistoryUpdate = undefined;

    // Initialize the router, all side effects should be kicked off from here.
    // Implemented as a Fluent API for ease of:
    //   let router = createRouter(init).initialize();
    function initialize() {
      // If history informs us of a POP navigation, start the navigation but do not update
      // state.  We'll update our own state once the navigation completes
      unlistenHistory = init.history.listen(_ref => {
        let {
          action: historyAction,
          location,
          delta
        } = _ref;
        // Ignore this event if it was just us resetting the URL from a
        // blocked POP navigation
        if (unblockBlockerHistoryUpdate) {
          unblockBlockerHistoryUpdate();
          unblockBlockerHistoryUpdate = undefined;
          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) {
          // Restore the URL to match the current UI, but don't update router state
          let nextHistoryUpdatePromise = new Promise(resolve => {
            unblockBlockerHistoryUpdate = resolve;
          });
          init.history.go(delta * -1);

          // Put the blocker into a blocked state
          updateBlocker(blockerKey, {
            state: "blocked",
            location,
            proceed() {
              updateBlocker(blockerKey, {
                state: "proceeding",
                proceed: undefined,
                reset: undefined,
                location
              });
              // Re-do the same POP navigation we just blocked, after the url
              // restoration is also complete.  See:
              // https://github.com/remix-run/react-router/issues/11613
              nextHistoryUpdatePromise.then(() => init.history.go(delta));
            },
            reset() {
              let blockers = new Map(state.blockers);
              blockers.set(blockerKey, IDLE_BLOCKER);
              updateState({
                blockers
              });
            }
          });
          return;
        }
        return startNavigation(historyAction, location);
      });
      if (isBrowser) {
        // FIXME: This feels gross.  How can we cleanup the lines between
        // scrollRestoration/appliedTransitions persistance?
        restoreAppliedTransitions(routerWindow, appliedViewTransitions);
        let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
        routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
        removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
      }

      // Kick off initial data load if needed.  Use Pop to avoid modifying history
      // Note we don't do any handling of lazy here.  For SPA's it'll get handled
      // in the normal navigation flow.  For SSR it's expected that lazy modules are
      // resolved prior to router creation since we can't go into a fallbackElement
      // UI for SSR'd apps
      if (!state.initialized) {
        startNavigation(Action.Pop, state.location, {
          initialHydration: true
        });
      }
      return router;
    }

    // Clean up a router and it's side effects
    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));
    }

    // Subscribe to state updates for the router
    function subscribe(fn) {
      subscribers.add(fn);
      return () => subscribers.delete(fn);
    }

    // Update our state and notify the calling context of the change
    function updateState(newState, opts) {
      if (opts === void 0) {
        opts = {};
      }
      state = _extends({}, state, newState);

      // Prep fetcher cleanup so we can tell the UI which fetcher data entries
      // can be removed
      let completedFetchers = [];
      let deletedFetchersKeys = [];
      if (future.v7_fetcherPersist) {
        state.fetchers.forEach((fetcher, key) => {
          if (fetcher.state === "idle") {
            if (deletedFetchers.has(key)) {
              // Unmounted from the UI and can be totally removed
              deletedFetchersKeys.push(key);
            } else {
              // Returned to idle but still mounted in the UI, so semi-remains for
              // revalidations and such
              completedFetchers.push(key);
            }
          }
        });
      }

      // Remove any lingering deleted fetchers that have already been removed
      // from state.fetchers
      deletedFetchers.forEach(key => {
        if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
          deletedFetchersKeys.push(key);
        }
      });

      // Iterate over a local copy so that if flushSync is used and we end up
      // removing and adding a new subscriber due to the useCallback dependencies,
      // we don't get ourselves into a loop calling the new subscriber immediately
      [...subscribers].forEach(subscriber => subscriber(state, {
        deletedFetchers: deletedFetchersKeys,
        viewTransitionOpts: opts.viewTransitionOpts,
        flushSync: opts.flushSync === true
      }));

      // Remove idle fetchers from state since we only care about in-flight fetchers.
      if (future.v7_fetcherPersist) {
        completedFetchers.forEach(key => state.fetchers.delete(key));
        deletedFetchersKeys.forEach(key => deleteFetcher(key));
      } else {
        // We already called deleteFetcher() on these, can remove them from this
        // Set now that we've handed the keys off to the data layer
        deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));
      }
    }

    // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
    // and setting state.[historyAction/location/matches] to the new route.
    // - Location is a required param
    // - Navigation will always be set to IDLE_NAVIGATION
    // - Can pass any other state in newState
    function completeNavigation(location, newState, _temp) {
      var _location$state, _location$state2;
      let {
        flushSync
      } = _temp === void 0 ? {} : _temp;
      // Deduce if we're in a loading/actionReload state:
      // - We have committed actionData in the store
      // - The current navigation was a mutation submission
      // - We're past the submitting state and into the loading state
      // - The location being loaded is not the result of a redirect
      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 {
          // Empty actionData -> clear prior actionData due to an action error
          actionData = null;
        }
      } else if (isActionReload) {
        // Keep the current data if we're wrapping up the action reload
        actionData = state.actionData;
      } else {
        // Clear actionData on any other completed navigations
        actionData = null;
      }

      // Always preserve any existing loaderData from re-used routes
      let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;

      // On a successful navigation we can assume we got through all blockers
      // so we can start fresh
      let blockers = state.blockers;
      if (blockers.size > 0) {
        blockers = new Map(blockers);
        blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
      }

      // Always respect the user flag.  Otherwise don't reset on mutation
      // submission navigations unless they redirect
      let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;

      // Commit any in-flight routes at the end of the HMR revalidation "navigation"
      if (inFlightDataRoutes) {
        dataRoutes = inFlightDataRoutes;
        inFlightDataRoutes = undefined;
      }
      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;

      // On POP, enable transitions if they were enabled on the original navigation
      if (pendingAction === Action.Pop) {
        // Forward takes precedence so they behave like the original navigation
        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)) {
          // If we don't have a previous forward nav, assume we're popping back to
          // the new location and enable if that location previously enabled
          viewTransitionOpts = {
            currentLocation: location,
            nextLocation: state.location
          };
        }
      } else if (pendingViewTransitionEnabled) {
        // Store the applied transition on PUSH/REPLACE
        let toPaths = appliedViewTransitions.get(state.location.pathname);
        if (toPaths) {
          toPaths.add(location.pathname);
        } else {
          toPaths = new Set([location.pathname]);
          appliedViewTransitions.set(state.location.pathname, toPaths);
        }
        viewTransitionOpts = {
          currentLocation: state.location,
          nextLocation: location
        };
      }
      updateState(_extends({}, newState, {
        // matches, errors, fetchers go through as-is
        actionData,
        loaderData,
        historyAction: pendingAction,
        location,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        revalidation: "idle",
        restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
        preventScrollReset,
        blockers
      }), {
        viewTransitionOpts,
        flushSync: flushSync === true
      });

      // Reset stateful navigation vars
      pendingAction = Action.Pop;
      pendingPreventScrollReset = false;
      pendingViewTransitionEnabled = false;
      isUninterruptedRevalidation = false;
      isRevalidationRequired = false;
      cancelledDeferredRoutes = [];
    }

    // Trigger a navigation event, which can either be a numerical POP or a PUSH
    // replace with an optional submission
    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);

      // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
      // URL from window.location, so we need to encode it here so the behavior
      // remains the same as POP and non-data-router usages.  new URL() does all
      // the same encoding we'd get from a history.pushState/window.location read
      // without having to touch history
      nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
      let userReplace = opts && opts.replace != null ? opts.replace : undefined;
      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) {
        // By default on submissions to the current location we REPLACE so that
        // users don't have to double-click the back button to get to the prior
        // location.  If the user redirects to a different location from the
        // action/loader this will be ignored and the redirect will be a PUSH
        historyAction = Action.Replace;
      }
      let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
      let flushSync = (opts && opts.flushSync) === true;
      let blockerKey = shouldBlockNavigation({
        currentLocation,
        nextLocation,
        historyAction
      });
      if (blockerKey) {
        // Put the blocker into a blocked state
        updateBlocker(blockerKey, {
          state: "blocked",
          location: nextLocation,
          proceed() {
            updateBlocker(blockerKey, {
              state: "proceeding",
              proceed: undefined,
              reset: undefined,
              location: nextLocation
            });
            // Send the same navigation through
            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.viewTransition,
        flushSync
      });
    }

    // Revalidate all current loaders.  If a navigation is in progress or if this
    // is interrupted by a navigation, allow this to "succeed" by calling all
    // loaders during the next loader round
    function revalidate() {
      interruptActiveLoads();
      updateState({
        revalidation: "loading"
      });

      // If we're currently submitting an action, we don't need to start a new
      // navigation, we'll just let the follow up loader execution call all loaders
      if (state.navigation.state === "submitting") {
        return;
      }

      // If we're currently in an idle state, start a new navigation for the current
      // action/location and mark it as uninterrupted, which will skip the history
      // update in completeNavigation
      if (state.navigation.state === "idle") {
        startNavigation(state.historyAction, state.location, {
          startUninterruptedRevalidation: true
        });
        return;
      }

      // Otherwise, if we're currently in a loading state, just start a new
      // navigation to the navigation.location but do not trigger an uninterrupted
      // revalidation so that history correctly updates once the navigation completes
      startNavigation(pendingAction || state.historyAction, state.navigation.location, {
        overrideNavigation: state.navigation,
        // Proxy through any rending view transition
        enableViewTransition: pendingViewTransitionEnabled === true
      });
    }

    // Start a navigation to the given action/location.  Can optionally provide a
    // overrideNavigation which will override the normalLoad in the case of a redirect
    // navigation
    async function startNavigation(historyAction, location, opts) {
      // Abort any in-progress navigations and start a new one. Unset any ongoing
      // uninterrupted revalidations unless told otherwise, since we want this
      // new navigation to update history normally
      pendingNavigationController && pendingNavigationController.abort();
      pendingNavigationController = null;
      pendingAction = historyAction;
      isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;

      // Save the current scroll position every time we start a new navigation,
      // and track whether we should reset scroll on completion
      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 = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?
      // `matchRoutes()` has already been called if we're in here via `router.initialize()`
      state.matches : matchRoutes(routesToUse, location, basename);
      let flushSync = (opts && opts.flushSync) === true;

      // Short circuit if it's only a hash change and not a revalidation or
      // mutation submission.
      //
      // Ignore on initial page loads because since the initial hydration will always
      // be "same hash".  For example, on /page#hash and submit a <Form method="post">
      // which will default to a navigation to /page
      if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
        completeNavigation(location, {
          matches
        }, {
          flushSync
        });
        return;
      }
      let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
      if (fogOfWar.active && fogOfWar.matches) {
        matches = fogOfWar.matches;
      }

      // Short circuit with a 404 on the root error boundary if we match nothing
      if (!matches) {
        let {
          error,
          notFoundMatches,
          route
        } = handleNavigational404(location.pathname);
        completeNavigation(location, {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error
          }
        }, {
          flushSync
        });
        return;
      }

      // Create a controller/Request for this navigation
      pendingNavigationController = new AbortController();
      let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
      let pendingActionResult;
      if (opts && opts.pendingError) {
        // If we have a pendingError, it means the user attempted a GET submission
        // with binary FormData so assign here and skip to handleLoaders.  That
        // way we handle calling loaders above the boundary etc.  It's not really
        // different from an actionError in that sense.
        pendingActionResult = [findNearestBoundary(matches).route.id, {
          type: ResultType.error,
          error: opts.pendingError
        }];
      } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
        // Call action if we received an action submission
        let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
          replace: opts.replace,
          flushSync
        });
        if (actionResult.shortCircuited) {
          return;
        }

        // If we received a 404 from handleAction, it's because we couldn't lazily
        // discover the destination route so we don't want to call loaders
        if (actionResult.pendingActionResult) {
          let [routeId, result] = actionResult.pendingActionResult;
          if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
            pendingNavigationController = null;
            completeNavigation(location, {
              matches: actionResult.matches,
              loaderData: {},
              errors: {
                [routeId]: result.error
              }
            });
            return;
          }
        }
        matches = actionResult.matches || matches;
        pendingActionResult = actionResult.pendingActionResult;
        loadingNavigation = getLoadingNavigation(location, opts.submission);
        flushSync = false;
        // No need to do fog of war matching again on loader execution
        fogOfWar.active = false;

        // Create a GET request for the loaders
        request = createClientSideRequest(init.history, request.url, request.signal);
      }

      // Call loaders
      let {
        shortCircuited,
        matches: updatedMatches,
        loaderData,
        errors
      } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
      if (shortCircuited) {
        return;
      }

      // Clean up now that the action/loaders have completed.  Don't clean up if
      // we short circuited because pendingNavigationController will have already
      // been assigned to a new controller for the next navigation
      pendingNavigationController = null;
      completeNavigation(location, _extends({
        matches: updatedMatches || matches
      }, getActionDataForCommit(pendingActionResult), {
        loaderData,
        errors
      }));
    }

    // Call the action matched by the leaf route for this navigation and handle
    // redirects/errors
    async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
      if (opts === void 0) {
        opts = {};
      }
      interruptActiveLoads();

      // Put us in a submitting state
      let navigation = getSubmittingNavigation(location, submission);
      updateState({
        navigation
      }, {
        flushSync: opts.flushSync === true
      });
      if (isFogOfWar) {
        let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
        if (discoverResult.type === "aborted") {
          return {
            shortCircuited: true
          };
        } else if (discoverResult.type === "error") {
          let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
          return {
            matches: discoverResult.partialMatches,
            pendingActionResult: [boundaryId, {
              type: ResultType.error,
              error: discoverResult.error
            }]
          };
        } else if (!discoverResult.matches) {
          let {
            notFoundMatches,
            error,
            route
          } = handleNavigational404(location.pathname);
          return {
            matches: notFoundMatches,
            pendingActionResult: [route.id, {
              type: ResultType.error,
              error
            }]
          };
        } else {
          matches = discoverResult.matches;
        }
      }

      // Call our action and get the result
      let result;
      let actionMatch = getTargetMatch(matches, location);
      if (!actionMatch.route.action && !actionMatch.route.lazy) {
        result = {
          type: ResultType.error,
          error: getInternalRouterError(405, {
            method: request.method,
            pathname: location.pathname,
            routeId: actionMatch.route.id
          })
        };
      } else {
        let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
        result = results[actionMatch.route.id];
        if (request.signal.aborted) {
          return {
            shortCircuited: true
          };
        }
      }
      if (isRedirectResult(result)) {
        let replace;
        if (opts && opts.replace != null) {
          replace = opts.replace;
        } else {
          // If the user didn't explicity indicate replace behavior, replace if
          // we redirected to the exact same location we're currently at to avoid
          // double back-buttons
          let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
          replace = location === state.location.pathname + state.location.search;
        }
        await startRedirectNavigation(request, result, true, {
          submission,
          replace
        });
        return {
          shortCircuited: true
        };
      }
      if (isDeferredResult(result)) {
        throw getInternalRouterError(400, {
          type: "defer-action"
        });
      }
      if (isErrorResult(result)) {
        // Store off the pending error - we use it to determine which loaders
        // to call and will commit it when we complete the navigation
        let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);

        // By default, all submissions to the current location are REPLACE
        // navigations, but if the action threw an error that'll be rendered in
        // an errorElement, we fall back to PUSH so that the user can use the
        // back button to get back to the pre-submission form location to try
        // again
        if ((opts && opts.replace) !== true) {
          pendingAction = Action.Push;
        }
        return {
          matches,
          pendingActionResult: [boundaryMatch.route.id, result]
        };
      }
      return {
        matches,
        pendingActionResult: [actionMatch.route.id, result]
      };
    }

    // Call all applicable loaders for the given matches, handling redirects,
    // errors, etc.
    async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
      // Figure out the right navigation we want to use for data loading
      let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);

      // If this was a redirect from an action we don't have a "submission" but
      // we have it on the loading navigation so use that if available
      let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);

      // If this is an uninterrupted revalidation, we remain in our current idle
      // state.  If not, we need to switch to our loading state and load data,
      // preserving any new action data or existing action data (in the case of
      // a revalidation interrupting an actionReload)
      // If we have partialHydration enabled, then don't update the state for the
      // initial data load since it's not a "navigation"
      let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);

      // When fog of war is enabled, we enter our `loading` state earlier so we
      // can discover new routes during the `loading` state.  We skip this if
      // we've already run actions since we would have done our matching already.
      // If the children() function threw then, we want to proceed with the
      // partial matches it discovered.
      if (isFogOfWar) {
        if (shouldUpdateNavigationState) {
          let actionData = getUpdatedActionData(pendingActionResult);
          updateState(_extends({
            navigation: loadingNavigation
          }, actionData !== undefined ? {
            actionData
          } : {}), {
            flushSync
          });
        }
        let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
        if (discoverResult.type === "aborted") {
          return {
            shortCircuited: true
          };
        } else if (discoverResult.type === "error") {
          let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
          return {
            matches: discoverResult.partialMatches,
            loaderData: {},
            errors: {
              [boundaryId]: discoverResult.error
            }
          };
        } else if (!discoverResult.matches) {
          let {
            error,
            notFoundMatches,
            route
          } = handleNavigational404(location.pathname);
          return {
            matches: notFoundMatches,
            loaderData: {},
            errors: {
              [route.id]: error
            }
          };
        } else {
          matches = discoverResult.matches;
        }
      }
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);

      // Cancel pending deferreds for no-longer-matched routes or routes we're
      // about to reload.  Note that if this is an action reload we would have
      // already cancelled all pending deferreds so this would be a no-op
      cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
      pendingNavigationLoadId = ++incrementingLoadId;

      // Short circuit if we have no loaders to run
      if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
        let updatedFetchers = markFetchRedirectsDone();
        completeNavigation(location, _extends({
          matches,
          loaderData: {},
          // Commit pending error if we're short circuiting
          errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
            [pendingActionResult[0]]: pendingActionResult[1].error
          } : null
        }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
          fetchers: new Map(state.fetchers)
        } : {}), {
          flushSync
        });
        return {
          shortCircuited: true
        };
      }
      if (shouldUpdateNavigationState) {
        let updates = {};
        if (!isFogOfWar) {
          // Only update navigation/actionNData if we didn't already do it above
          updates.navigation = loadingNavigation;
          let actionData = getUpdatedActionData(pendingActionResult);
          if (actionData !== undefined) {
            updates.actionData = actionData;
          }
        }
        if (revalidatingFetchers.length > 0) {
          updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
        }
        updateState(updates, {
          flushSync
        });
      }
      revalidatingFetchers.forEach(rf => {
        abortFetcher(rf.key);
        if (rf.controller) {
          // Fetchers use an independent AbortController so that aborting a fetcher
          // (via deleteFetcher) does not abort the triggering navigation that
          // triggered the revalidation
          fetchControllers.set(rf.key, rf.controller);
        }
      });

      // Proxy navigation abort through to revalidation fetchers
      let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
      if (pendingNavigationController) {
        pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
      }
      let {
        loaderResults,
        fetcherResults
      } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
      if (request.signal.aborted) {
        return {
          shortCircuited: true
        };
      }

      // Clean up _after_ loaders have completed.  Don't clean up if we short
      // circuited because fetchControllers would have been aborted and
      // reassigned to new controllers for the next navigation
      if (pendingNavigationController) {
        pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
      }
      revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));

      // If any loaders returned a redirect Response, start a new REPLACE navigation
      let redirect = findRedirect(loaderResults);
      if (redirect) {
        await startRedirectNavigation(request, redirect.result, true, {
          replace
        });
        return {
          shortCircuited: true
        };
      }
      redirect = findRedirect(fetcherResults);
      if (redirect) {
        // If this redirect came from a fetcher make sure we mark it in
        // fetchRedirectIds so it doesn't get revalidated on the next set of
        // loader executions
        fetchRedirectIds.add(redirect.key);
        await startRedirectNavigation(request, redirect.result, true, {
          replace
        });
        return {
          shortCircuited: true
        };
      }

      // Process and commit output from loaders
      let {
        loaderData,
        errors
      } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);

      // Wire up subscribers to update loaderData as promises settle
      activeDeferreds.forEach((deferredData, routeId) => {
        deferredData.subscribe(aborted => {
          // Note: No need to updateState here since the TrackedPromise on
          // loaderData is stable across resolve/reject
          // Remove this instance if we were aborted or if promises have settled
          if (aborted || deferredData.done) {
            activeDeferreds.delete(routeId);
          }
        });
      });

      // Preserve SSR errors during partial hydration
      if (future.v7_partialHydration && initialHydration && state.errors) {
        errors = _extends({}, state.errors, errors);
      }
      let updatedFetchers = markFetchRedirectsDone();
      let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
      let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
      return _extends({
        matches,
        loaderData,
        errors
      }, shouldUpdateFetchers ? {
        fetchers: new Map(state.fetchers)
      } : {});
    }
    function getUpdatedActionData(pendingActionResult) {
      if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
        // This is cast to `any` currently because `RouteData`uses any and it
        // would be a breaking change to use any.
        // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
        return {
          [pendingActionResult[0]]: pendingActionResult[1].data
        };
      } else if (state.actionData) {
        if (Object.keys(state.actionData).length === 0) {
          return null;
        } else {
          return state.actionData;
        }
      }
    }
    function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
      revalidatingFetchers.forEach(rf => {
        let fetcher = state.fetchers.get(rf.key);
        let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
        state.fetchers.set(rf.key, revalidatingFetcher);
      });
      return new Map(state.fetchers);
    }

    // Trigger a fetcher load/submit for the given fetcher key
    function fetch(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.");
      }
      abortFetcher(key);
      let flushSync = (opts && opts.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);
      let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
      if (fogOfWar.active && fogOfWar.matches) {
        matches = fogOfWar.matches;
      }
      if (!matches) {
        setFetcherError(key, routeId, getInternalRouterError(404, {
          pathname: normalizedPath
        }), {
          flushSync
        });
        return;
      }
      let {
        path,
        submission,
        error
      } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
      if (error) {
        setFetcherError(key, routeId, error, {
          flushSync
        });
        return;
      }
      let match = getTargetMatch(matches, path);
      let preventScrollReset = (opts && opts.preventScrollReset) === true;
      if (submission && isMutationMethod(submission.formMethod)) {
        handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
        return;
      }

      // Store off the match so we can call it's shouldRevalidate on subsequent
      // revalidations
      fetchLoadMatches.set(key, {
        routeId,
        path
      });
      handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
    }

    // Call the action for the matched fetcher.submit(), and then handle redirects,
    // errors, and revalidation
    async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
      interruptActiveLoads();
      fetchLoadMatches.delete(key);
      function detectAndHandle405Error(m) {
        if (!m.route.action && !m.route.lazy) {
          let error = getInternalRouterError(405, {
            method: submission.formMethod,
            pathname: path,
            routeId: routeId
          });
          setFetcherError(key, routeId, error, {
            flushSync
          });
          return true;
        }
        return false;
      }
      if (!isFogOfWar && detectAndHandle405Error(match)) {
        return;
      }

      // Put this fetcher into it's submitting state
      let existingFetcher = state.fetchers.get(key);
      updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
        flushSync
      });
      let abortController = new AbortController();
      let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
      if (isFogOfWar) {
        let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
        if (discoverResult.type === "aborted") {
          return;
        } else if (discoverResult.type === "error") {
          setFetcherError(key, routeId, discoverResult.error, {
            flushSync
          });
          return;
        } else if (!discoverResult.matches) {
          setFetcherError(key, routeId, getInternalRouterError(404, {
            pathname: path
          }), {
            flushSync
          });
          return;
        } else {
          requestMatches = discoverResult.matches;
          match = getTargetMatch(requestMatches, path);
          if (detectAndHandle405Error(match)) {
            return;
          }
        }
      }

      // Call the action for the fetcher
      fetchControllers.set(key, abortController);
      let originatingLoadId = incrementingLoadId;
      let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
      let actionResult = actionResults[match.route.id];
      if (fetchRequest.signal.aborted) {
        // We can delete this so long as we weren't aborted by our own fetcher
        // re-submit which would have put _new_ controller is in fetchControllers
        if (fetchControllers.get(key) === abortController) {
          fetchControllers.delete(key);
        }
        return;
      }

      // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
      // or redirects processed for unmounted fetchers so we just revert them to
      // idle
      if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
        if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        }
        // Let SuccessResult's fall through for revalidation
      } else {
        if (isRedirectResult(actionResult)) {
          fetchControllers.delete(key);
          if (pendingNavigationLoadId > originatingLoadId) {
            // A new navigation was kicked off after our action started, so that
            // should take precedence over this redirect navigation.  We already
            // set isRevalidationRequired so all loaders for the new route should
            // fire unless opted out via shouldRevalidate
            updateFetcherState(key, getDoneFetcher(undefined));
            return;
          } else {
            fetchRedirectIds.add(key);
            updateFetcherState(key, getLoadingFetcher(submission));
            return startRedirectNavigation(fetchRequest, actionResult, false, {
              fetcherSubmission: submission,
              preventScrollReset
            });
          }
        }

        // Process any non-redirect errors thrown
        if (isErrorResult(actionResult)) {
          setFetcherError(key, routeId, actionResult.error);
          return;
        }
      }
      if (isDeferredResult(actionResult)) {
        throw getInternalRouterError(400, {
          type: "defer-action"
        });
      }

      // Start the data load for current matches, or the next location if we're
      // in the middle of a navigation
      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, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);

      // Put all revalidating fetchers into the loading state, except for the
      // current fetcher which we want to keep in it's current loading state which
      // contains it's action submission info + action data
      revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
        let staleKey = rf.key;
        let existingFetcher = state.fetchers.get(staleKey);
        let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
        state.fetchers.set(staleKey, revalidatingFetcher);
        abortFetcher(staleKey);
        if (rf.controller) {
          fetchControllers.set(staleKey, rf.controller);
        }
      });
      updateState({
        fetchers: new Map(state.fetchers)
      });
      let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
      abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
      let {
        loaderResults,
        fetcherResults
      } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
      if (abortController.signal.aborted) {
        return;
      }
      abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
      fetchReloadIds.delete(key);
      fetchControllers.delete(key);
      revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
      let redirect = findRedirect(loaderResults);
      if (redirect) {
        return startRedirectNavigation(revalidationRequest, redirect.result, false, {
          preventScrollReset
        });
      }
      redirect = findRedirect(fetcherResults);
      if (redirect) {
        // If this redirect came from a fetcher make sure we mark it in
        // fetchRedirectIds so it doesn't get revalidated on the next set of
        // loader executions
        fetchRedirectIds.add(redirect.key);
        return startRedirectNavigation(revalidationRequest, redirect.result, false, {
          preventScrollReset
        });
      }

      // Process and commit output from loaders
      let {
        loaderData,
        errors
      } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);

      // Since we let revalidations complete even if the submitting fetcher was
      // deleted, only put it back to idle if it hasn't been deleted
      if (state.fetchers.has(key)) {
        let doneFetcher = getDoneFetcher(actionResult.data);
        state.fetchers.set(key, doneFetcher);
      }
      abortStaleFetchLoads(loadId);

      // If we are currently in a navigation loading state and this fetcher is
      // more recent than the navigation, we want the newer data so abort the
      // navigation and complete it with the fetcher data
      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 {
        // otherwise just update with the fetcher data, preserving any existing
        // loaderData for loaders that did not need to reload.  We have to
        // manually merge here since we aren't going through completeNavigation
        updateState({
          errors,
          loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
          fetchers: new Map(state.fetchers)
        });
        isRevalidationRequired = false;
      }
    }

    // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
    async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
      let existingFetcher = state.fetchers.get(key);
      updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
        flushSync
      });
      let abortController = new AbortController();
      let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
      if (isFogOfWar) {
        let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
        if (discoverResult.type === "aborted") {
          return;
        } else if (discoverResult.type === "error") {
          setFetcherError(key, routeId, discoverResult.error, {
            flushSync
          });
          return;
        } else if (!discoverResult.matches) {
          setFetcherError(key, routeId, getInternalRouterError(404, {
            pathname: path
          }), {
            flushSync
          });
          return;
        } else {
          matches = discoverResult.matches;
          match = getTargetMatch(matches, path);
        }
      }

      // Call the loader for this fetcher route match
      fetchControllers.set(key, abortController);
      let originatingLoadId = incrementingLoadId;
      let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
      let result = results[match.route.id];

      // Deferred isn't supported for fetcher loads, await everything and treat it
      // as a normal load.  resolveDeferredData will return undefined if this
      // fetcher gets aborted, so we just leave result untouched and short circuit
      // below if that happens
      if (isDeferredResult(result)) {
        result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
      }

      // We can delete this so long as we weren't aborted by our our own fetcher
      // re-load which would have put _new_ controller is in fetchControllers
      if (fetchControllers.get(key) === abortController) {
        fetchControllers.delete(key);
      }
      if (fetchRequest.signal.aborted) {
        return;
      }

      // We don't want errors bubbling up or redirects followed for unmounted
      // fetchers, so short circuit here if it was removed from the UI
      if (deletedFetchers.has(key)) {
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      }

      // If the loader threw a redirect Response, start a new REPLACE navigation
      if (isRedirectResult(result)) {
        if (pendingNavigationLoadId > originatingLoadId) {
          // A new navigation was kicked off after our loader started, so that
          // should take precedence over this redirect navigation
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        } else {
          fetchRedirectIds.add(key);
          await startRedirectNavigation(fetchRequest, result, false, {
            preventScrollReset
          });
          return;
        }
      }

      // Process any non-redirect errors thrown
      if (isErrorResult(result)) {
        setFetcherError(key, routeId, result.error);
        return;
      }
      invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");

      // Put the fetcher back into an idle state
      updateFetcherState(key, getDoneFetcher(result.data));
    }

    /**
     * Utility function to handle redirects returned from an action or loader.
     * Normally, a redirect "replaces" the navigation that triggered it.  So, for
     * example:
     *
     *  - user is on /a
     *  - user clicks a link to /b
     *  - loader for /b redirects to /c
     *
     * In a non-JS app the browser would track the in-flight navigation to /b and
     * then replace it with /c when it encountered the redirect response.  In
     * the end it would only ever update the URL bar with /c.
     *
     * In client-side routing using pushState/replaceState, we aim to emulate
     * this behavior and we also do not update history until the end of the
     * navigation (including processed redirects).  This means that we never
     * actually touch history until we've processed redirects, so we just use
     * the history action from the original navigation (PUSH or REPLACE).
     */
    async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
      let {
        submission,
        fetcherSubmission,
        preventScrollReset,
        replace
      } = _temp2 === void 0 ? {} : _temp2;
      if (redirect.response.headers.has("X-Remix-Revalidate")) {
        isRevalidationRequired = true;
      }
      let location = redirect.response.headers.get("Location");
      invariant(location, "Expected a Location header on the redirect Response");
      location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
      let redirectLocation = createLocation(state.location, location, {
        _isRedirect: true
      });
      if (isBrowser) {
        let isDocumentReload = false;
        if (redirect.response.headers.has("X-Remix-Reload-Document")) {
          // Hard reload if the response contained X-Remix-Reload-Document
          isDocumentReload = true;
        } else if (ABSOLUTE_URL_REGEX.test(location)) {
          const url = init.history.createURL(location);
          isDocumentReload =
          // Hard reload if it's an absolute URL to a new origin
          url.origin !== routerWindow.location.origin ||
          // Hard reload if it's an absolute URL that does not match our basename
          stripBasename(url.pathname, basename) == null;
        }
        if (isDocumentReload) {
          if (replace) {
            routerWindow.location.replace(location);
          } else {
            routerWindow.location.assign(location);
          }
          return;
        }
      }

      // There's no need to abort on redirects, since we don't detect the
      // redirect until the action/loaders have settled
      pendingNavigationController = null;
      let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;

      // Use the incoming submission if provided, fallback on the active one in
      // state.navigation
      let {
        formMethod,
        formAction,
        formEncType
      } = state.navigation;
      if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
        submission = getSubmissionFromNavigation(state.navigation);
      }

      // If this was a 307/308 submission we want to preserve the HTTP method and
      // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
      // redirected location
      let activeSubmission = submission || fetcherSubmission;
      if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
        await startNavigation(redirectHistoryAction, redirectLocation, {
          submission: _extends({}, activeSubmission, {
            formAction: location
          }),
          // Preserve these flags across redirects
          preventScrollReset: preventScrollReset || pendingPreventScrollReset,
          enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
        });
      } else {
        // If we have a navigation submission, we will preserve it through the
        // redirect navigation
        let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
        await startNavigation(redirectHistoryAction, redirectLocation, {
          overrideNavigation,
          // Send fetcher submissions through for shouldRevalidate
          fetcherSubmission,
          // Preserve these flags across redirects
          preventScrollReset: preventScrollReset || pendingPreventScrollReset,
          enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
        });
      }
    }

    // Utility wrapper for calling dataStrategy client-side without having to
    // pass around the manifest, mapRouteProperties, etc.
    async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
      let results;
      let dataResults = {};
      try {
        results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
      } catch (e) {
        // If the outer dataStrategy method throws, just return the error for all
        // matches - and it'll naturally bubble to the root
        matchesToLoad.forEach(m => {
          dataResults[m.route.id] = {
            type: ResultType.error,
            error: e
          };
        });
        return dataResults;
      }
      for (let [routeId, result] of Object.entries(results)) {
        if (isRedirectDataStrategyResultResult(result)) {
          let response = result.result;
          dataResults[routeId] = {
            type: ResultType.redirect,
            response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
          };
        } else {
          dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
        }
      }
      return dataResults;
    }
    async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
      let currentMatches = state.matches;

      // Kick off loaders and fetchers in parallel
      let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
      let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
        if (f.matches && f.match && f.controller) {
          let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
          let result = results[f.match.route.id];
          // Fetcher results are keyed by fetcher key from here on out, not routeId
          return {
            [f.key]: result
          };
        } else {
          return Promise.resolve({
            [f.key]: {
              type: ResultType.error,
              error: getInternalRouterError(404, {
                pathname: f.path
              })
            }
          });
        }
      }));
      let loaderResults = await loaderResultsPromise;
      let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
      await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
      return {
        loaderResults,
        fetcherResults
      };
    }
    function interruptActiveLoads() {
      // Every interruption triggers a revalidation
      isRevalidationRequired = true;

      // Cancel pending route-level deferreds and mark cancelled routes for
      // revalidation
      cancelledDeferredRoutes.push(...cancelActiveDeferreds());

      // Abort in-flight fetcher loads
      fetchLoadMatches.forEach((_, key) => {
        if (fetchControllers.has(key)) {
          cancelledFetcherLoads.add(key);
        }
        abortFetcher(key);
      });
    }
    function updateFetcherState(key, fetcher, opts) {
      if (opts === void 0) {
        opts = {};
      }
      state.fetchers.set(key, fetcher);
      updateState({
        fetchers: new Map(state.fetchers)
      }, {
        flushSync: (opts && opts.flushSync) === true
      });
    }
    function setFetcherError(key, routeId, error, opts) {
      if (opts === void 0) {
        opts = {};
      }
      let boundaryMatch = findNearestBoundary(state.matches, routeId);
      deleteFetcher(key);
      updateState({
        errors: {
          [boundaryMatch.route.id]: error
        },
        fetchers: new Map(state.fetchers)
      }, {
        flushSync: (opts && opts.flushSync) === true
      });
    }
    function getFetcher(key) {
      activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
      // If this fetcher was previously marked for deletion, unmark it since we
      // have a new instance
      if (deletedFetchers.has(key)) {
        deletedFetchers.delete(key);
      }
      return state.fetchers.get(key) || IDLE_FETCHER;
    }
    function deleteFetcher(key) {
      let fetcher = state.fetchers.get(key);
      // Don't abort the controller if this is a deletion of a fetcher.submit()
      // in it's loading phase since - we don't want to abort the corresponding
      // revalidation and want them to complete and land
      if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
        abortFetcher(key);
      }
      fetchLoadMatches.delete(key);
      fetchReloadIds.delete(key);
      fetchRedirectIds.delete(key);

      // If we opted into the flag we can clear this now since we're calling
      // deleteFetcher() at the end of updateState() and we've already handed the
      // deleted fetcher keys off to the data layer.
      // If not, we're eagerly calling deleteFetcher() and we need to keep this
      // Set populated until the next updateState call, and we'll clear
      // `deletedFetchers` then
      if (future.v7_fetcherPersist) {
        deletedFetchers.delete(key);
      }
      cancelledFetcherLoads.delete(key);
      state.fetchers.delete(key);
    }
    function deleteFetcherAndUpdateState(key) {
      let count = (activeFetchers.get(key) || 0) - 1;
      if (count <= 0) {
        activeFetchers.delete(key);
        deletedFetchers.add(key);
        if (!future.v7_fetcherPersist) {
          deleteFetcher(key);
        }
      } else {
        activeFetchers.set(key, count);
      }
      updateState({
        fetchers: new Map(state.fetchers)
      });
    }
    function abortFetcher(key) {
      let controller = fetchControllers.get(key);
      if (controller) {
        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);
    }

    // Utility function to update blockers, ensuring valid state transitions
    function updateBlocker(key, newBlocker) {
      let blocker = state.blockers.get(key) || IDLE_BLOCKER;

      // Poor mans state machine :)
      // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
      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;
      }

      // We ony support a single active blocker at the moment since we don't have
      // any compelling use cases for multi-blocker yet
      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") {
        // If the blocker is currently proceeding, we don't need to re-check
        // it and can let this navigation continue
        return;
      }

      // At this point, we know we're unblocked/blocked so we need to check the
      // user-provided blocker function
      if (blockerFunction({
        currentLocation,
        nextLocation,
        historyAction
      })) {
        return blockerKey;
      }
    }
    function handleNavigational404(pathname) {
      let error = getInternalRouterError(404, {
        pathname
      });
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let {
        matches,
        route
      } = getShortCircuitMatches(routesToUse);

      // Cancel all pending deferred on 404s since we don't keep any routes
      cancelActiveDeferreds();
      return {
        notFoundMatches: matches,
        route,
        error
      };
    }
    function cancelActiveDeferreds(predicate) {
      let cancelledRouteIds = [];
      activeDeferreds.forEach((dfd, routeId) => {
        if (!predicate || predicate(routeId)) {
          // Cancel the deferred - but do not remove from activeDeferreds here -
          // we rely on the subscribers to do that so our tests can assert proper
          // cleanup via _internalActiveDeferreds
          dfd.cancel();
          cancelledRouteIds.push(routeId);
          activeDeferreds.delete(routeId);
        }
      });
      return cancelledRouteIds;
    }

    // Opt in to capturing and reporting scroll positions during navigations,
    // used by the <ScrollRestoration> component
    function enableScrollRestoration(positions, getPosition, getKey) {
      savedScrollPositions = positions;
      getScrollPosition = getPosition;
      getScrollRestorationKey = getKey || null;

      // Perform initial hydration scroll restoration, since we miss the boat on
      // the initial updateState() because we've not yet rendered <ScrollRestoration/>
      // and therefore have no savedScrollPositions available
      if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
        initialScrollRestored = true;
        let y = getSavedScrollPosition(state.location, state.matches);
        if (y != null) {
          updateState({
            restoreScrollPosition: y
          });
        }
      }
      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 y = savedScrollPositions[key];
        if (typeof y === "number") {
          return y;
        }
      }
      return null;
    }
    function checkFogOfWar(matches, routesToUse, pathname) {
      if (patchRoutesOnNavigationImpl) {
        if (!matches) {
          let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
          return {
            active: true,
            matches: fogMatches || []
          };
        } else {
          if (Object.keys(matches[0].params).length > 0) {
            // If we matched a dynamic param or a splat, it might only be because
            // we haven't yet discovered other routes that would match with a
            // higher score.  Call patchRoutesOnNavigation just to be sure
            let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
            return {
              active: true,
              matches: partialMatches
            };
          }
        }
      }
      return {
        active: false,
        matches: null
      };
    }
    async function discoverRoutes(matches, pathname, signal, fetcherKey) {
      if (!patchRoutesOnNavigationImpl) {
        return {
          type: "success",
          matches
        };
      }
      let partialMatches = matches;
      while (true) {
        let isNonHMR = inFlightDataRoutes == null;
        let routesToUse = inFlightDataRoutes || dataRoutes;
        let localManifest = manifest;
        try {
          await patchRoutesOnNavigationImpl({
            signal,
            path: pathname,
            matches: partialMatches,
            fetcherKey,
            patch: (routeId, children) => {
              if (signal.aborted) return;
              patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
            }
          });
        } catch (e) {
          return {
            type: "error",
            error: e,
            partialMatches
          };
        } finally {
          // If we are not in the middle of an HMR revalidation and we changed the
          // routes, provide a new identity so when we `updateState` at the end of
          // this navigation/fetch `router.routes` will be a new identity and
          // trigger a re-run of memoized `router.routes` dependencies.
          // HMR will already update the identity and reflow when it lands
          // `inFlightDataRoutes` in `completeNavigation`
          if (isNonHMR && !signal.aborted) {
            dataRoutes = [...dataRoutes];
          }
        }
        if (signal.aborted) {
          return {
            type: "aborted"
          };
        }
        let newMatches = matchRoutes(routesToUse, pathname, basename);
        if (newMatches) {
          return {
            type: "success",
            matches: newMatches
          };
        }
        let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);

        // Avoid loops if the second pass results in the same partial matches
        if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
          return {
            type: "success",
            matches: null
          };
        }
        partialMatches = newPartialMatches;
      }
    }
    function _internalSetRoutes(newRoutes) {
      manifest = {};
      inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
    }
    function patchRoutes(routeId, children) {
      let isNonHMR = inFlightDataRoutes == null;
      let routesToUse = inFlightDataRoutes || dataRoutes;
      patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);

      // If we are not in the middle of an HMR revalidation and we changed the
      // routes, provide a new identity and trigger a reflow via `updateState`
      // to re-run memoized `router.routes` dependencies.
      // HMR will already update the identity and reflow when it lands
      // `inFlightDataRoutes` in `completeNavigation`
      if (isNonHMR) {
        dataRoutes = [...dataRoutes];
        updateState({});
      }
    }
    router = {
      get basename() {
        return basename;
      },
      get future() {
        return future;
      },
      get state() {
        return state;
      },
      get routes() {
        return dataRoutes;
      },
      get window() {
        return routerWindow;
      },
      initialize,
      subscribe,
      enableScrollRestoration,
      navigate,
      fetch,
      revalidate,
      // Passthrough to history-aware createHref used by useHref so we get proper
      // hash-aware URLs in DOM paths
      createHref: to => init.history.createHref(to),
      encodeLocation: to => init.history.encodeLocation(to),
      getFetcher,
      deleteFetcher: deleteFetcherAndUpdateState,
      dispose,
      getBlocker,
      deleteBlocker,
      patchRoutes,
      _internalFetchControllers: fetchControllers,
      _internalActiveDeferreds: activeDeferreds,
      // TODO: Remove setRoutes, it's temporary to avoid dealing with
      // updating the tree while validating the update algorithm.
      _internalSetRoutes
    };
    return router;
  }
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region createStaticHandler
  ////////////////////////////////////////////////////////////////////////////////

  const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");

  /**
   * Future flags to toggle new feature behavior
   */

  function createStaticHandler(routes, opts) {
    invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
    let manifest = {};
    let basename = (opts ? opts.basename : null) || "/";
    let mapRouteProperties;
    if (opts != null && opts.mapRouteProperties) {
      mapRouteProperties = opts.mapRouteProperties;
    } else if (opts != null && opts.detectErrorBoundary) {
      // If they are still using the deprecated version, wrap it with the new API
      let detectErrorBoundary = opts.detectErrorBoundary;
      mapRouteProperties = route => ({
        hasErrorBoundary: detectErrorBoundary(route)
      });
    } else {
      mapRouteProperties = defaultMapRouteProperties;
    }
    // Config driven behavior flags
    let future = _extends({
      v7_relativeSplatPath: false,
      v7_throwAbortReason: false
    }, opts ? opts.future : null);
    let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);

    /**
     * The query() method is intended for document requests, in which we want to
     * call an optional action and potentially multiple loaders for all nested
     * routes.  It returns a StaticHandlerContext object, which is very similar
     * to the router state (location, loaderData, actionData, errors, etc.) and
     * also adds SSR-specific information such as the statusCode and headers
     * from action/loaders Responses.
     *
     * It _should_ never throw and should report all errors through the
     * returned context.errors object, properly associating errors to their error
     * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be
     * used to emulate React error boundaries during SSr by performing a second
     * pass only down to the boundaryId.
     *
     * The one exception where we do not return a StaticHandlerContext is when a
     * redirect response is returned or thrown from any action/loader.  We
     * propagate that out and return the raw Response so the HTTP server can
     * return it directly.
     *
     * - `opts.requestContext` is an optional server context that will be passed
     *   to actions/loaders in the `context` parameter
     * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
     *   the bubbling of errors which allows single-fetch-type implementations
     *   where the client will handle the bubbling and we may need to return data
     *   for the handling route
     */
    async function query(request, _temp3) {
      let {
        requestContext,
        skipLoaderErrorBubbling,
        dataStrategy
      } = _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);

      // SSR supports HEAD requests while SPA doesn't
      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, dataStrategy || null, skipLoaderErrorBubbling === true, null);
      if (isResponse(result)) {
        return result;
      }

      // When returning StaticHandlerContext, we patch back in the location here
      // since we need it for React Context.  But this helps keep our submit and
      // loadRouteData operating on a Request instead of a Location
      return _extends({
        location,
        basename
      }, result);
    }

    /**
     * The queryRoute() method is intended for targeted route requests, either
     * for fetch ?_data requests or resource route requests.  In this case, we
     * are only ever calling a single action or loader, and we are returning the
     * returned value directly.  In most cases, this will be a Response returned
     * from the action/loader, but it may be a primitive or other value as well -
     * and in such cases the calling context should handle that accordingly.
     *
     * We do respect the throw/return differentiation, so if an action/loader
     * throws, then this method will throw the value.  This is important so we
     * can do proper boundary identification in Remix where a thrown Response
     * must go to the Catch Boundary but a returned Response is happy-path.
     *
     * One thing to note is that any Router-initiated Errors that make sense
     * to associate with a status code will be thrown as an ErrorResponse
     * instance which include the raw Error, such that the calling context can
     * serialize the error as they see fit while including the proper response
     * code.  Examples here are 404 and 405 errors that occur prior to reaching
     * any user-defined loaders.
     *
     * - `opts.routeId` allows you to specify the specific route handler to call.
     *   If not provided the handler will determine the proper route by matching
     *   against `request.url`
     * - `opts.requestContext` is an optional server context that will be passed
     *    to actions/loaders in the `context` parameter
     */
    async function queryRoute(request, _temp4) {
      let {
        routeId,
        requestContext,
        dataStrategy
      } = _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);

      // SSR supports HEAD requests while SPA doesn't
      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) {
        // This should never hit I don't think?
        throw getInternalRouterError(404, {
          pathname: location.pathname
        });
      }
      let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
      if (isResponse(result)) {
        return result;
      }
      let error = result.errors ? Object.values(result.errors)[0] : undefined;
      if (error !== undefined) {
        // If we got back result.errors, that means the loader/action threw
        // _something_ that wasn't a Response, but it's not guaranteed/required
        // to be an `instanceof Error` either, so we have to use throw here to
        // preserve the "error" state outside of queryImpl.
        throw error;
      }

      // Pick off the right state value to return
      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 undefined;
    }
    async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
      invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
      try {
        if (isMutationMethod(request.method.toLowerCase())) {
          let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
          return result;
        }
        let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
        return isResponse(result) ? result : _extends({}, result, {
          actionData: null,
          actionHeaders: {}
        });
      } catch (e) {
        // If the user threw/returned a Response in callLoaderOrAction for a
        // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
        // and then return or throw the raw Response here accordingly
        if (isDataStrategyResult(e) && isResponse(e.result)) {
          if (e.type === ResultType.error) {
            throw e.result;
          }
          return e.result;
        }
        // Redirects are always returned since they don't propagate to catch
        // boundaries
        if (isRedirectResponse(e)) {
          return e;
        }
        throw e;
      }
    }
    async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
      let result;
      if (!actionMatch.route.action && !actionMatch.route.lazy) {
        let error = getInternalRouterError(405, {
          method: request.method,
          pathname: new URL(request.url).pathname,
          routeId: actionMatch.route.id
        });
        if (isRouteRequest) {
          throw error;
        }
        result = {
          type: ResultType.error,
          error
        };
      } else {
        let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
        result = results[actionMatch.route.id];
        if (request.signal.aborted) {
          throwStaticHandlerAbortedError(request, isRouteRequest, future);
        }
      }
      if (isRedirectResult(result)) {
        // Uhhhh - this should never happen, we should always throw these from
        // callLoaderOrAction, but the type narrowing here keeps TS happy and we
        // can get back on the "throw all redirect responses" train here should
        // this ever happen :/
        throw new Response(null, {
          status: result.response.status,
          headers: {
            Location: result.response.headers.get("Location")
          }
        });
      }
      if (isDeferredResult(result)) {
        let error = getInternalRouterError(400, {
          type: "defer-action"
        });
        if (isRouteRequest) {
          throw error;
        }
        result = {
          type: ResultType.error,
          error
        };
      }
      if (isRouteRequest) {
        // Note: This should only be non-Response values if we get here, since
        // isRouteRequest should throw any Response received in callLoaderOrAction
        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
        };
      }

      // Create a GET request for the loaders
      let loaderRequest = new Request(request.url, {
        headers: request.headers,
        redirect: request.redirect,
        signal: request.signal
      });
      if (isErrorResult(result)) {
        // Store off the pending error - we use it to determine which loaders
        // to call and will commit it when we complete the navigation
        let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
        let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);

        // action status codes take precedence over loader status codes
        return _extends({}, context, {
          statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
          actionData: null,
          actionHeaders: _extends({}, result.headers ? {
            [actionMatch.route.id]: result.headers
          } : {})
        });
      }
      let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
      return _extends({}, context, {
        actionData: {
          [actionMatch.route.id]: result.data
        }
      }, result.statusCode ? {
        statusCode: result.statusCode
      } : {}, {
        actionHeaders: result.headers ? {
          [actionMatch.route.id]: result.headers
        } : {}
      });
    }
    async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
      let isRouteRequest = routeMatch != null;

      // Short circuit if we have no loaders to run (queryRoute())
      if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
        throw getInternalRouterError(400, {
          method: request.method,
          pathname: new URL(request.url).pathname,
          routeId: routeMatch == null ? void 0 : routeMatch.route.id
        });
      }
      let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
      let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);

      // Short circuit if we have no loaders to run (query())
      if (matchesToLoad.length === 0) {
        return {
          matches,
          // Add a null for all matched routes for proper revalidation on the client
          loaderData: matches.reduce((acc, m) => Object.assign(acc, {
            [m.route.id]: null
          }), {}),
          errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
            [pendingActionResult[0]]: pendingActionResult[1].error
          } : null,
          statusCode: 200,
          loaderHeaders: {},
          activeDeferreds: null
        };
      }
      let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future);
      }

      // Process and commit output from loaders
      let activeDeferreds = new Map();
      let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);

      // Add a null for any non-loader matches for proper revalidation on the client
      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
      });
    }

    // Utility wrapper for calling dataStrategy server-side without having to
    // pass around the manifest, mapRouteProperties, etc.
    async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
      let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
      let dataResults = {};
      await Promise.all(matches.map(async match => {
        if (!(match.route.id in results)) {
          return;
        }
        let result = results[match.route.id];
        if (isRedirectDataStrategyResultResult(result)) {
          let response = result.result;
          // Throw redirects and let the server handle them with an HTTP redirect
          throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
        }
        if (isResponse(result.result) && isRouteRequest) {
          // For SSR single-route requests, we want to hand Responses back
          // directly without unwrapping
          throw result;
        }
        dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
      }));
      return dataResults;
    }
    return {
      dataRoutes,
      query,
      queryRoute
    };
  }

  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Helpers
  ////////////////////////////////////////////////////////////////////////////////

  /**
   * Given an existing StaticHandlerContext and an error thrown at render time,
   * provide an updated StaticHandlerContext suitable for a second SSR render
   */
  function getStaticContextFromError(routes, context, error) {
    let newContext = _extends({}, context, {
      statusCode: isRouteErrorResponse(error) ? error.status : 500,
      errors: {
        [context._deepestRenderedBoundaryId || routes[0].id]: error
      }
    });
    return newContext;
  }
  function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
    if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
      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 !== undefined);
  }
  function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
    let contextualMatches;
    let activeRouteMatch;
    if (fromRouteId) {
      // Grab matches up to the calling route so our route-relative logic is
      // relative to the correct source route
      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];
    }

    // Resolve the relative path
    let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");

    // When `to` is not specified we inherit search/hash from the current
    // location, unlike when to="." and we just inherit the path.
    // See https://github.com/remix-run/remix/issues/927
    if (to == null) {
      path.search = location.search;
      path.hash = location.hash;
    }

    // Account for `?index` params when routing to the current location
    if ((to == null || to === "" || to === ".") && activeRouteMatch) {
      let nakedIndex = hasNakedIndexQuery(path.search);
      if (activeRouteMatch.route.index && !nakedIndex) {
        // Add one when we're targeting an index route
        path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
      } else if (!activeRouteMatch.route.index && nakedIndex) {
        // Remove existing ones when we're not
        let params = new URLSearchParams(path.search);
        let indexValues = params.getAll("index");
        params.delete("index");
        indexValues.filter(v => v).forEach(v => params.append("index", v));
        let qs = params.toString();
        path.search = qs ? "?" + qs : "";
      }
    }

    // If we're operating within a basename, prepend it to the pathname.  If
    // this is a root navigation, then just use the raw basename which allows
    // the basename to have full control over the presence of a trailing slash
    // on root actions
    if (prependBasename && basename !== "/") {
      path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
    }
    return createPath(path);
  }

  // Normalize navigation options by converting formMethod=GET formData objects to
  // URLSearchParams so they behave identically to links with query params
  function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
    // Return location verbatim on non-submission navigations
    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"
      })
    });

    // Create a Submission on non-GET navigations
    let rawFormMethod = opts.formMethod || "get";
    let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
    let formAction = stripHashFromPath(path);
    if (opts.body !== undefined) {
      if (opts.formEncType === "text/plain") {
        // text only support POST/PUT/PATCH/DELETE submissions
        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: undefined,
            json: undefined,
            text
          }
        };
      } else if (opts.formEncType === "application/json") {
        // json only supports POST/PUT/PATCH/DELETE submissions
        if (!isMutationMethod(formMethod)) {
          return getInvalidBodyError();
        }
        try {
          let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
          return {
            path,
            submission: {
              formMethod,
              formAction,
              formEncType: opts.formEncType,
              formData: undefined,
              json,
              text: undefined
            }
          };
        } 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: undefined,
      text: undefined
    };
    if (isMutationMethod(submission.formMethod)) {
      return {
        path,
        submission
      };
    }

    // Flatten submission onto URLSearchParams for GET submissions
    let parsedPath = parsePath(path);
    // On GET navigation submissions we can drop the ?index param from the
    // resulting location since all loaders will run.  But fetcher GET submissions
    // only run a single loader so we need to preserve any incoming ?index params
    if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
      searchParams.append("index", "");
    }
    parsedPath.search = "?" + searchParams;
    return {
      path: createPath(parsedPath),
      submission
    };
  }

  // Filter out all routes at/below any caught error as they aren't going to
  // render so we don't need to load them
  function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
    if (includeBoundary === void 0) {
      includeBoundary = false;
    }
    let index = matches.findIndex(m => m.route.id === boundaryId);
    if (index >= 0) {
      return matches.slice(0, includeBoundary ? index + 1 : index);
    }
    return matches;
  }
  function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
    let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
    let currentUrl = history.createURL(state.location);
    let nextUrl = history.createURL(location);

    // Pick navigation matches that are net-new or qualify for revalidation
    let boundaryMatches = matches;
    if (initialHydration && state.errors) {
      // On initial hydration, only consider matches up to _and including_ the boundary.
      // This is inclusive to handle cases where a server loader ran successfully,
      // a child server loader bubbled up to this route, but this route has
      // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
      // we have a complete version of `loaderData`
      boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
    } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
      // If an action threw an error, we call loaders up to, but not including the
      // boundary
      boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
    }

    // Don't revalidate loaders by default after action 4xx/5xx responses
    // when the flag is enabled.  They can still opt-into revalidation via
    // `shouldRevalidate` via `actionResult`
    let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
    let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
    let navigationMatches = boundaryMatches.filter((match, index) => {
      let {
        route
      } = match;
      if (route.lazy) {
        // We haven't loaded this route yet so we don't know if it's got a loader!
        return true;
      }
      if (route.loader == null) {
        return false;
      }
      if (initialHydration) {
        return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
      }

      // Always call the loader on new route instances and pending defer cancellations
      if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
        return true;
      }

      // This is the default implementation for when we revalidate.  If the route
      // provides it's own implementation, then we give them full control but
      // provide this value so they can leverage it if needed after they check
      // their own specific use cases
      let currentRouteMatch = state.matches[index];
      let nextRouteMatch = match;
      return shouldRevalidateLoader(match, _extends({
        currentUrl,
        currentParams: currentRouteMatch.params,
        nextUrl,
        nextParams: nextRouteMatch.params
      }, submission, {
        actionResult,
        actionStatus,
        defaultShouldRevalidate: shouldSkipRevalidation ? false :
        // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
        isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
        // Search params affect all loaders
        currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
      }));
    });

    // Pick fetcher.loads that need to be revalidated
    let revalidatingFetchers = [];
    fetchLoadMatches.forEach((f, key) => {
      // Don't revalidate:
      //  - on initial hydration (shouldn't be any fetchers then anyway)
      //  - if fetcher won't be present in the subsequent render
      //    - no longer matches the URL (v7_fetcherPersist=false)
      //    - was unmounted but persisted due to v7_fetcherPersist=true
      if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
        return;
      }
      let fetcherMatches = matchRoutes(routesToUse, f.path, basename);

      // If the fetcher path no longer matches, push it in with null matches so
      // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is
      // currently only a use-case for Remix HMR where the route tree can change
      // at runtime and remove a route previously loaded via a fetcher
      if (!fetcherMatches) {
        revalidatingFetchers.push({
          key,
          routeId: f.routeId,
          path: f.path,
          matches: null,
          match: null,
          controller: null
        });
        return;
      }

      // Revalidating fetchers are decoupled from the route matches since they
      // load from a static href.  They revalidate based on explicit revalidation
      // (submission, useRevalidator, or X-Remix-Revalidate)
      let fetcher = state.fetchers.get(key);
      let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
      let shouldRevalidate = false;
      if (fetchRedirectIds.has(key)) {
        // Never trigger a revalidation of an actively redirecting fetcher
        shouldRevalidate = false;
      } else if (cancelledFetcherLoads.has(key)) {
        // Always mark for revalidation if the fetcher was cancelled
        cancelledFetcherLoads.delete(key);
        shouldRevalidate = true;
      } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
        // If the fetcher hasn't ever completed loading yet, then this isn't a
        // revalidation, it would just be a brand new load if an explicit
        // revalidation is required
        shouldRevalidate = isRevalidationRequired;
      } else {
        // Otherwise fall back on any user-defined shouldRevalidate, defaulting
        // to explicit revalidations only
        shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
          currentUrl,
          currentParams: state.matches[state.matches.length - 1].params,
          nextUrl,
          nextParams: matches[matches.length - 1].params
        }, submission, {
          actionResult,
          actionStatus,
          defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
        }));
      }
      if (shouldRevalidate) {
        revalidatingFetchers.push({
          key,
          routeId: f.routeId,
          path: f.path,
          matches: fetcherMatches,
          match: fetcherMatch,
          controller: new AbortController()
        });
      }
    });
    return [navigationMatches, revalidatingFetchers];
  }
  function shouldLoadRouteOnHydration(route, loaderData, errors) {
    // We dunno if we have a loader - gotta find out!
    if (route.lazy) {
      return true;
    }

    // No loader, nothing to initialize
    if (!route.loader) {
      return false;
    }
    let hasData = loaderData != null && loaderData[route.id] !== undefined;
    let hasError = errors != null && errors[route.id] !== undefined;

    // Don't run if we error'd during SSR
    if (!hasData && hasError) {
      return false;
    }

    // Explicitly opting-in to running on hydration
    if (typeof route.loader === "function" && route.loader.hydrate === true) {
      return true;
    }

    // Otherwise, run if we're not yet initialized with anything
    return !hasData && !hasError;
  }
  function isNewLoader(currentLoaderData, currentMatch, match) {
    let isNew =
    // [a] -> [a, b]
    !currentMatch ||
    // [a, b] -> [a, c]
    match.route.id !== currentMatch.route.id;

    // Handle the case that we don't have data for a re-used route, potentially
    // from a prior error or from a cancelled pending deferred
    let isMissingData = currentLoaderData[match.route.id] === undefined;

    // Always load if this is a net-new route or we don't yet have data
    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;
  }
  function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
    var _childrenToPatch;
    let childrenToPatch;
    if (routeId) {
      let route = manifest[routeId];
      invariant(route, "No route found to patch children into: routeId = " + routeId);
      if (!route.children) {
        route.children = [];
      }
      childrenToPatch = route.children;
    } else {
      childrenToPatch = routesToUse;
    }

    // Don't patch in routes we already know about so that `patch` is idempotent
    // to simplify user-land code. This is useful because we re-call the
    // `patchRoutesOnNavigation` function for matched routes with params.
    let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
    let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
    childrenToPatch.push(...newRoutes);
  }
  function isSameRoute(newRoute, existingRoute) {
    // Most optimal check is by id
    if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
      return true;
    }

    // Second is by pathing differences
    if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
      return false;
    }

    // Pathless layout routes are trickier since we need to check children.
    // If they have no children then they're the same as far as we can tell
    if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
      return true;
    }

    // Otherwise, we look to see if every child in the new route is already
    // represented in the existing route's children
    return newRoute.children.every((aChild, i) => {
      var _existingRoute$childr;
      return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
    });
  }

  /**
   * Execute route.lazy() methods to lazily load route modules (loader, action,
   * shouldRevalidate) and update the routeManifest in place which shares objects
   * with dataRoutes so those get updated as well.
   */
  async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
    if (!route.lazy) {
      return;
    }
    let lazyRoute = await route.lazy();

    // If the lazy route function was executed and removed by another parallel
    // call then we can return - first lazy() to finish wins because the return
    // value of lazy is expected to be static
    if (!route.lazy) {
      return;
    }
    let routeToUpdate = manifest[route.id];
    invariant(routeToUpdate, "No route found in manifest");

    // Update the route in place.  This should be safe because there's no way
    // we could yet be sitting on this route as we can't get there without
    // resolving lazy() first.
    //
    // This is different than the HMR "update" use-case where we may actively be
    // on the route being updated.  The main concern boils down to "does this
    // mutation affect any ongoing navigations or any current state.matches
    // values?".  If not, it should be safe to update in place.
    let routeUpdates = {};
    for (let lazyRouteProperty in lazyRoute) {
      let staticRouteValue = routeToUpdate[lazyRouteProperty];
      let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
      // 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];
      }
    }

    // Mutate the route with the provided updates.  Do this first so we pass
    // the updated version to mapRouteProperties
    Object.assign(routeToUpdate, routeUpdates);

    // Mutate the `hasErrorBoundary` property on the route based on the route
    // updates and remove the `lazy` function so we don't resolve the lazy
    // route again.
    Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
      lazy: undefined
    }));
  }

  // Default implementation of `dataStrategy` which fetches all loaders in parallel
  async function defaultDataStrategy(_ref4) {
    let {
      matches
    } = _ref4;
    let matchesToLoad = matches.filter(m => m.shouldLoad);
    let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
    return results.reduce((acc, result, i) => Object.assign(acc, {
      [matchesToLoad[i].route.id]: result
    }), {});
  }
  async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
    let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
    let dsMatches = matches.map((match, i) => {
      let loadRoutePromise = loadRouteDefinitionsPromises[i];
      let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
      // `resolve` encapsulates route.lazy(), executing the loader/action,
      // and mapping return values/thrown errors to a `DataStrategyResult`.  Users
      // can pass a callback to take fine-grained control over the execution
      // of the loader/action
      let resolve = async handlerOverride => {
        if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
          shouldLoad = true;
        }
        return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
          type: ResultType.data,
          result: undefined
        });
      };
      return _extends({}, match, {
        shouldLoad,
        resolve
      });
    });

    // Send all matches here to allow for a middleware-type implementation.
    // handler will be a no-op for unneeded routes and we filter those results
    // back out below.
    let results = await dataStrategyImpl({
      matches: dsMatches,
      request,
      params: matches[0].params,
      fetcherKey,
      context: requestContext
    });

    // Wait for all routes to load here but 'swallow the error since we want
    // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
    // called from `match.resolve()`
    try {
      await Promise.all(loadRouteDefinitionsPromises);
    } catch (e) {
      // No-op
    }
    return results;
  }

  // Default logic for calling a loader/action is the user has no specified a dataStrategy
  async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
    let result;
    let onReject;
    let runHandler = handler => {
      // Setup a promise we can race against so that abort signals short circuit
      let reject;
      // This will never resolve so safe to type it as Promise<DataStrategyResult> to
      // satisfy the function return value
      let abortPromise = new Promise((_, r) => reject = r);
      onReject = () => reject();
      request.signal.addEventListener("abort", onReject);
      let actualHandler = ctx => {
        if (typeof handler !== "function") {
          return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
        }
        return handler({
          request,
          params: match.params,
          context: staticContext
        }, ...(ctx !== undefined ? [ctx] : []));
      };
      let handlerPromise = (async () => {
        try {
          let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
          return {
            type: "data",
            result: val
          };
        } catch (e) {
          return {
            type: "error",
            result: e
          };
        }
      })();
      return Promise.race([handlerPromise, abortPromise]);
    };
    try {
      let handler = match.route[type];

      // If we have a route.lazy promise, await that first
      if (loadRoutePromise) {
        if (handler) {
          // Run statically defined handler in parallel with lazy()
          let handlerError;
          let [value] = await Promise.all([
          // If the handler throws, don't let it immediately bubble out,
          // since we need to let the lazy() execution finish so we know if this
          // route has a boundary that can handle the error
          runHandler(handler).catch(e => {
            handlerError = e;
          }), loadRoutePromise]);
          if (handlerError !== undefined) {
            throw handlerError;
          }
          result = value;
        } else {
          // Load lazy route module, then run any returned handler
          await loadRoutePromise;
          handler = match.route[type];
          if (handler) {
            // Handler still runs even if we got interrupted to maintain consistency
            // with un-abortable behavior of handler execution on non-lazy or
            // previously-lazy-loaded routes
            result = await runHandler(handler);
          } else if (type === "action") {
            let url = new URL(request.url);
            let pathname = url.pathname + url.search;
            throw getInternalRouterError(405, {
              method: request.method,
              pathname,
              routeId: match.route.id
            });
          } else {
            // lazy() route has no loader to run.  Short circuit here so we don't
            // hit the invariant below that errors on returning undefined.
            return {
              type: ResultType.data,
              result: undefined
            };
          }
        }
      } else if (!handler) {
        let url = new URL(request.url);
        let pathname = url.pathname + url.search;
        throw getInternalRouterError(404, {
          pathname
        });
      } else {
        result = await runHandler(handler);
      }
      invariant(result.result !== undefined, "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) {
      // We should already be catching and converting normal handler executions to
      // DataStrategyResults and returning them, so anything that throws here is an
      // unexpected error we still need to wrap
      return {
        type: ResultType.error,
        result: e
      };
    } finally {
      if (onReject) {
        request.signal.removeEventListener("abort", onReject);
      }
    }
    return result;
  }
  async function convertDataStrategyResultToDataResult(dataStrategyResult) {
    let {
      result,
      type
    } = dataStrategyResult;
    if (isResponse(result)) {
      let data;
      try {
        let contentType = result.headers.get("Content-Type");
        // Check between word boundaries instead of startsWith() due to the last
        // paragraph of https://httpwg.org/specs/rfc9110.html#field.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 (type === ResultType.error) {
        return {
          type: ResultType.error,
          error: new ErrorResponseImpl(result.status, result.statusText, data),
          statusCode: result.status,
          headers: result.headers
        };
      }
      return {
        type: ResultType.data,
        data,
        statusCode: result.status,
        headers: result.headers
      };
    }
    if (type === ResultType.error) {
      if (isDataWithResponseInit(result)) {
        var _result$init3, _result$init4;
        if (result.data instanceof Error) {
          var _result$init, _result$init2;
          return {
            type: ResultType.error,
            error: result.data,
            statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
            headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined
          };
        }

        // Convert thrown data() to ErrorResponse instances
        return {
          type: ResultType.error,
          error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),
          statusCode: isRouteErrorResponse(result) ? result.status : undefined,
          headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined
        };
      }
      return {
        type: ResultType.error,
        error: result,
        statusCode: isRouteErrorResponse(result) ? result.status : undefined
      };
    }
    if (isDeferredData(result)) {
      var _result$init5, _result$init6;
      return {
        type: ResultType.deferred,
        deferredData: result,
        statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
        headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
      };
    }
    if (isDataWithResponseInit(result)) {
      var _result$init7, _result$init8;
      return {
        type: ResultType.data,
        data: result.data,
        statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
        headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined
      };
    }
    return {
      type: ResultType.data,
      data: result
    };
  }

  // Support relative routing in internal redirects
  function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
    let location = response.headers.get("Location");
    invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
    if (!ABSOLUTE_URL_REGEX.test(location)) {
      let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
      location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
      response.headers.set("Location", location);
    }
    return response;
  }
  function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
    // Match Chrome's behavior:
    // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
    let invalidProtocols = ["about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:",
    // eslint-disable-next-line no-script-url
    "javascript:"];
    if (ABSOLUTE_URL_REGEX.test(location)) {
      // Strip off the protocol+origin for same-origin + same-basename absolute redirects
      let normalizedLocation = location;
      let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
      if (invalidProtocols.includes(url.protocol)) {
        throw new Error("Invalid redirect location");
      }
      let isSameBasename = stripBasename(url.pathname, basename) != null;
      if (url.origin === currentUrl.origin && isSameBasename) {
        return removeDoubleSlashes(url.pathname) + url.search + url.hash;
      }
    }
    try {
      let url = historyInstance.createURL(location);
      if (invalidProtocols.includes(url.protocol)) {
        throw new Error("Invalid redirect location");
      }
    } catch (e) {}
    return location;
  }

  // Utility method for creating the Request instances for loaders/actions during
  // client-side navigations and fetches.  During SSR we will always have a
  // Request instance from the static handler (query/queryRoute)
  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;
      // Didn't think we needed this but it turns out unlike other methods, patch
      // won't be properly normalized to uppercase and results in a 405 error.
      // See: https://fetch.spec.whatwg.org/#concept-method
      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") {
        // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
        init.body = submission.text;
      } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
        // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
        init.body = convertFormDataToSearchParams(submission.formData);
      } else {
        // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
        init.body = submission.formData;
      }
    }
    return new Request(url, init);
  }
  function convertFormDataToSearchParams(formData) {
    let searchParams = new URLSearchParams();
    for (let [key, value] of formData.entries()) {
      // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
      searchParams.append(key, typeof value === "string" ? value : value.name);
    }
    return searchParams;
  }
  function convertSearchParamsToFormData(searchParams) {
    let formData = new FormData();
    for (let [key, value] of searchParams.entries()) {
      formData.append(key, value);
    }
    return formData;
  }
  function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
    // Fill in loaderData/errors from our loaders
    let loaderData = {};
    let errors = null;
    let statusCode;
    let foundError = false;
    let loaderHeaders = {};
    let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;

    // Process loader results into state.loaderData/state.errors
    matches.forEach(match => {
      if (!(match.route.id in results)) {
        return;
      }
      let id = match.route.id;
      let result = results[id];
      invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
      if (isErrorResult(result)) {
        let error = result.error;
        // If we have a pending action error, we report it at the highest-route
        // that throws a loader error, and then clear it out to indicate that
        // it was consumed
        if (pendingError !== undefined) {
          error = pendingError;
          pendingError = undefined;
        }
        errors = errors || {};
        if (skipLoaderErrorBubbling) {
          errors[id] = error;
        } else {
          // Look upwards from the matched route for the closest ancestor error
          // boundary, defaulting to the root match.  Prefer higher error values
          // if lower errors bubble to the same boundary
          let boundaryMatch = findNearestBoundary(matches, id);
          if (errors[boundaryMatch.route.id] == null) {
            errors[boundaryMatch.route.id] = error;
          }
        }

        // Clear our any prior loaderData for the throwing route
        loaderData[id] = undefined;

        // Once we find our first (highest) error, we set the status code and
        // prevent deeper status codes from overriding
        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;
          // Error status codes always override success status codes, but if all
          // loaders are successful we take the deepest status code.
          if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
            statusCode = result.statusCode;
          }
          if (result.headers) {
            loaderHeaders[id] = result.headers;
          }
        } else {
          loaderData[id] = result.data;
          // Error status codes always override success status codes, but if all
          // loaders are successful we take the deepest status code.
          if (result.statusCode && result.statusCode !== 200 && !foundError) {
            statusCode = result.statusCode;
          }
          if (result.headers) {
            loaderHeaders[id] = result.headers;
          }
        }
      }
    });

    // If we didn't consume the pending action error (i.e., all loaders
    // resolved), then consume it here.  Also clear out any loaderData for the
    // throwing route
    if (pendingError !== undefined && pendingActionResult) {
      errors = {
        [pendingActionResult[0]]: pendingError
      };
      loaderData[pendingActionResult[0]] = undefined;
    }
    return {
      loaderData,
      errors,
      statusCode: statusCode || 200,
      loaderHeaders
    };
  }
  function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
    let {
      loaderData,
      errors
    } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
    );

    // Process results from our revalidating fetchers
    revalidatingFetchers.forEach(rf => {
      let {
        key,
        match,
        controller
      } = rf;
      let result = fetcherResults[key];
      invariant(result, "Did not find corresponding fetcher result");

      // Process fetcher non-redirect errors
      if (controller && controller.signal.aborted) {
        // Nothing to do for aborted fetchers
        return;
      } 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)) {
        // Should never get here, redirects should get processed above, but we
        // keep this to type narrow to a success result in the else
        invariant(false, "Unhandled fetcher revalidation redirect");
      } else if (isDeferredResult(result)) {
        // Should never get here, deferred data should be awaited for fetchers
        // in resolveDeferredResults
        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] !== undefined) {
          mergedLoaderData[id] = newLoaderData[id];
        }
      } else if (loaderData[id] !== undefined && match.route.loader) {
        // Preserve existing keys not included in newLoaderData and where a loader
        // wasn't removed by HMR
        mergedLoaderData[id] = loaderData[id];
      }
      if (errors && errors.hasOwnProperty(id)) {
        // Don't keep any loader data below the boundary
        break;
      }
    }
    return mergedLoaderData;
  }
  function getActionDataForCommit(pendingActionResult) {
    if (!pendingActionResult) {
      return {};
    }
    return isErrorResult(pendingActionResult[1]) ? {
      // Clear out prior actionData on errors
      actionData: {}
    } : {
      actionData: {
        [pendingActionResult[0]]: pendingActionResult[1].data
      }
    };
  }

  // Find the nearest error boundary, looking upwards from the leaf route (or the
  // route specified by routeId) for the closest ancestor error boundary,
  // defaulting to the root match
  function findNearestBoundary(matches, routeId) {
    let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
    return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
  }
  function getShortCircuitMatches(routes) {
    // Prefer a root layout route if present, otherwise shim in a route object
    let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
      id: "__shim-error-route__"
    };
    return {
      matches: [{
        params: {},
        pathname: "",
        pathnameBase: "",
        route
      }],
      route
    };
  }
  function getInternalRouterError(status, _temp5) {
    let {
      pathname,
      routeId,
      method,
      type,
      message
    } = _temp5 === void 0 ? {} : _temp5;
    let statusText = "Unknown Server Error";
    let errorMessage = "Unknown @remix-run/router error";
    if (status === 400) {
      statusText = "Bad Request";
      if (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);
  }

  // Find any returned redirect errors, starting from the lowest match
  function findRedirect(results) {
    let entries = Object.entries(results);
    for (let i = entries.length - 1; i >= 0; i--) {
      let [key, result] = entries[i];
      if (isRedirectResult(result)) {
        return {
          key,
          result
        };
      }
    }
  }
  function stripHashFromPath(path) {
    let parsedPath = typeof path === "string" ? parsePath(path) : path;
    return createPath(_extends({}, parsedPath, {
      hash: ""
    }));
  }
  function isHashChangeOnly(a, b) {
    if (a.pathname !== b.pathname || a.search !== b.search) {
      return false;
    }
    if (a.hash === "") {
      // /page -> /page#hash
      return b.hash !== "";
    } else if (a.hash === b.hash) {
      // /page#hash -> /page#hash
      return true;
    } else if (b.hash !== "") {
      // /page#hash -> /page#other
      return true;
    }

    // If the hash is removed the browser will re-perform a request to the server
    // /page#hash -> /page
    return false;
  }
  function isDataStrategyResult(result) {
    return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
  }
  function isRedirectDataStrategyResultResult(result) {
    return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  }
  function isDeferredResult(result) {
    return result.type === ResultType.deferred;
  }
  function isErrorResult(result) {
    return result.type === ResultType.error;
  }
  function isRedirectResult(result) {
    return (result && result.type) === ResultType.redirect;
  }
  function isDataWithResponseInit(value) {
    return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  }
  function isDeferredData(value) {
    let deferred = value;
    return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
  }
  function isResponse(value) {
    return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  }
  function isRedirectResponse(result) {
    if (!isResponse(result)) {
      return false;
    }
    let status = result.status;
    let location = result.headers.get("Location");
    return status >= 300 && status <= 399 && location != null;
  }
  function isValidMethod(method) {
    return validRequestMethods.has(method.toLowerCase());
  }
  function isMutationMethod(method) {
    return validMutationMethods.has(method.toLowerCase());
  }
  async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
    let entries = Object.entries(results);
    for (let index = 0; index < entries.length; index++) {
      let [routeId, result] = entries[index];
      let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
      // If we don't have a match, then we can have a deferred result to do
      // anything with.  This is for revalidating fetchers where the route was
      // removed during HMR
      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]) !== undefined;
      if (isDeferredResult(result) && isRevalidatingLoader) {
        // Note: we do not have to touch activeDeferreds here since we race them
        // against the signal in resolveDeferredData and they'll get aborted
        // there if needed
        await resolveDeferredData(result, signal, false).then(result => {
          if (result) {
            results[routeId] = result;
          }
        });
      }
    }
  }
  async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
    for (let index = 0; index < revalidatingFetchers.length; index++) {
      let {
        key,
        routeId,
        controller
      } = revalidatingFetchers[index];
      let result = results[key];
      let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
      // If we don't have a match, then we can have a deferred result to do
      // anything with.  This is for revalidating fetchers where the route was
      // removed during HMR
      if (!match) {
        continue;
      }
      if (isDeferredResult(result)) {
        // Note: we do not have to touch activeDeferreds here since we race them
        // against the signal in resolveDeferredData and they'll get aborted
        // there if needed
        invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
        await resolveDeferredData(result, controller.signal, true).then(result => {
          if (result) {
            results[key] = result;
          }
        });
      }
    }
  }
  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) {
        // Handle any TrackedPromise._error values encountered while unwrapping
        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 the leaf index route when index is present
      return matches[matches.length - 1];
    }
    // Otherwise grab the deepest "path contributing" match (ignoring index and
    // pathless layout routes)
    let pathMatches = getPathContributingMatches(matches);
    return pathMatches[pathMatches.length - 1];
  }
  function getSubmissionFromNavigation(navigation) {
    let {
      formMethod,
      formAction,
      formEncType,
      text,
      formData,
      json
    } = navigation;
    if (!formMethod || !formAction || !formEncType) {
      return;
    }
    if (text != null) {
      return {
        formMethod,
        formAction,
        formEncType,
        formData: undefined,
        json: undefined,
        text
      };
    } else if (formData != null) {
      return {
        formMethod,
        formAction,
        formEncType,
        formData,
        json: undefined,
        text: undefined
      };
    } else if (json !== undefined) {
      return {
        formMethod,
        formAction,
        formEncType,
        formData: undefined,
        json,
        text: undefined
      };
    }
  }
  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: undefined,
        formAction: undefined,
        formEncType: undefined,
        formData: undefined,
        json: undefined,
        text: undefined
      };
      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: undefined,
        formAction: undefined,
        formEncType: undefined,
        formData: undefined,
        json: undefined,
        text: undefined,
        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 : undefined
    };
    return fetcher;
  }
  function getDoneFetcher(data) {
    let fetcher = {
      state: "idle",
      formMethod: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
      data
    };
    return fetcher;
  }
  function restoreAppliedTransitions(_window, transitions) {
    try {
      let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
      if (sessionPositions) {
        let json = JSON.parse(sessionPositions);
        for (let [k, v] of Object.entries(json || {})) {
          if (v && Array.isArray(v)) {
            transitions.set(k, new Set(v || []));
          }
        }
      }
    } catch (e) {
      // no-op, use default empty object
    }
  }
  function persistAppliedTransitions(_window, transitions) {
    if (transitions.size > 0) {
      let json = {};
      for (let [k, v] of transitions) {
        json[k] = [...v];
      }
      try {
        _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
      } catch (error) {
        warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
      }
    }
  }
  //#endregion

  exports.AbortedDeferredError = AbortedDeferredError;
  exports.Action = Action;
  exports.IDLE_BLOCKER = IDLE_BLOCKER;
  exports.IDLE_FETCHER = IDLE_FETCHER;
  exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
  exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
  exports.UNSAFE_DeferredData = DeferredData;
  exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl;
  exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch;
  exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
  exports.UNSAFE_decodePath = decodePath;
  exports.UNSAFE_getResolveToMatches = getResolveToMatches;
  exports.UNSAFE_invariant = invariant;
  exports.UNSAFE_warning = warning;
  exports.createBrowserHistory = createBrowserHistory;
  exports.createHashHistory = createHashHistory;
  exports.createMemoryHistory = createMemoryHistory;
  exports.createPath = createPath;
  exports.createRouter = createRouter;
  exports.createStaticHandler = createStaticHandler;
  exports.data = data;
  exports.defer = defer;
  exports.generatePath = generatePath;
  exports.getStaticContextFromError = getStaticContextFromError;
  exports.getToPathname = getToPathname;
  exports.isDataWithResponseInit = isDataWithResponseInit;
  exports.isDeferredData = isDeferredData;
  exports.isRouteErrorResponse = isRouteErrorResponse;
  exports.joinPaths = joinPaths;
  exports.json = json;
  exports.matchPath = matchPath;
  exports.matchRoutes = matchRoutes;
  exports.normalizePathname = normalizePathname;
  exports.parsePath = parsePath;
  exports.redirect = redirect;
  exports.redirectDocument = redirectDocument;
  exports.replace = replace;
  exports.resolvePath = resolvePath;
  exports.resolveTo = resolveTo;
  exports.stripBasename = stripBasename;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=router.umd.js.map
{"version":3,"file":"router.umd.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n\n  /**\n   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n  idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 1 });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nexport function warning(cond: any, message: string) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience, so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\n  };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n  current: string | Location,\n  to: To,\n  state: any = null,\n  key?: string\n): Readonly<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): URL {\n    // window.location.origin is \"null\" (the literal string value) in Firefox\n    // under certain conditions, notably when serving from a local HTML file\n    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n    let base =\n      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\n    invariant(\n      base,\n      `No window.location.(origin|href) available to create URL for href: ${href}`\n    );\n    return new URL(href, base);\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n  [routeId: string]: any;\n}\n\nexport enum ResultType {\n  data = \"data\",\n  deferred = \"deferred\",\n  redirect = \"redirect\",\n  error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n  type: ResultType.data;\n  data: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n  type: ResultType.deferred;\n  deferredData: DeferredData;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n  | SuccessResult\n  | DeferredResult\n  | RedirectResult\n  | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\n    };\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n  currentUrl: URL;\n  currentParams: AgnosticDataRouteMatch[\"params\"];\n  nextUrl: URL;\n  nextParams: AgnosticDataRouteMatch[\"params\"];\n  formMethod?: Submission[\"formMethod\"];\n  formAction?: Submission[\"formAction\"];\n  formEncType?: Submission[\"formEncType\"];\n  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature.  This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments.  It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n  (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => DataFunctionReturnValue\n  ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n  fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n  signal: AbortSignal;\n  path: string;\n  matches: M[];\n  fetcherKey: string | undefined;\n  patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param extends `${infer Optional}?`\n      ? Optional\n      : Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\" | \"/*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if you could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(index)];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(\n      route.index !== true || !route.children,\n      `Cannot specify children on an index route`\n    );\n    invariant(\n      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\n\n      return pathOrLayoutRoute;\n    }\n  });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  let decoded = decodePath(pathname);\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array, so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children, so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explode _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string,\n  allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\n\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams as Params<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, compiledParams] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let params: CompiledPathParam[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex, so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\n  } catch (error) {\n    warning(\n      false,\n      `The URL path \"${value}\" could not be decoded because it is is a ` +\n        `malformed URL segment. This is probably due to a bad percent ` +\n        `encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n  pathname: string,\n  basename: string\n): string | null {\n  if (basename === \"/\") return pathname;\n\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  }\n\n  // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n  let startIndex = basename.endsWith(\"/\")\n    ? basename.length - 1\n    : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n\n  return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\",\n  } = typeof to === \"string\" ? parsePath(to) : to;\n\n  let pathname: string;\n  if (toPathname) {\n    toPathname = removeDoubleSlashes(toPathname);\n    if (toPathname.startsWith(\"/\")) {\n      pathname = resolvePathname(toPathname.substring(1), \"/\");\n    } else {\n      pathname = resolvePathname(toPathname, fromPathname);\n    }\n  } else {\n    pathname = fromPathname;\n  }\n\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash),\n  };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\n\n  relativeSegments.forEach((segment) => {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n  toArg: To,\n  routePathnames: string[],\n  locationPathname: string,\n  isPathRelative = false\n): Path {\n  let to: Partial<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || (to as Path).pathname === \"\"\n    ? \"/\"\n    : typeof to === \"string\"\n    ? parsePath(to).pathname\n    : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n  path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n  removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n  data: Data,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  let headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n\n  return new Response(JSON.stringify(data), {\n    ...responseInit,\n    headers,\n  });\n};\n\nexport class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\n  );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n    invariant(\n      data && typeof data === \"object\" && !Array.isArray(data),\n      \"defer() only accepts plain objects\"\n    );\n\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject: (e: AbortedDeferredError) => void;\n    this.abortPromise = new Promise((_, r) => (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =>\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =>\n      this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n\n    this.data = Object.entries(data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: this.trackPromise(key, value),\n        }),\n      {}\n    );\n\n    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.add(key);\n\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n      (data) => this.onSettle(promise, key, undefined, data as unknown),\n      (error) => this.onSettle(promise, key, error as unknown)\n    );\n\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () => true });\n    return promise;\n  }\n\n  private onSettle(\n    promise: TrackedPromise,\n    key: string,\n    error: unknown,\n    data?: unknown\n  ): unknown {\n    if (\n      this.controller.signal.aborted &&\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      return Promise.reject(error);\n    }\n\n    this.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(true);\n  }\n\n  async resolveData(signal: AbortSignal) {\n    let aborted = false;\n    if (!this.done) {\n      let onAbort = () => this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) => {\n        this.subscribe((aborted) => {\n          signal.removeEventListener(\"abort\", onAbort);\n          if (aborted || this.done) {\n            resolve(aborted);\n          }\n        });\n      });\n    }\n    return aborted;\n  }\n\n  get done() {\n    return this.pendingKeysSet.size === 0;\n  }\n\n  get unwrappedData() {\n    invariant(\n      this.data !== null && this.done,\n      \"Can only unwrap data on initialized and settled deferreds\"\n    );\n\n    return Object.entries(this.data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: unwrapTrackedPromise(value),\n        }),\n      {}\n    );\n  }\n\n  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\n  }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n  return (\n    value instanceof Promise && (value as TrackedPromise)._tracked === true\n  );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\n\nexport type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n  url: string,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = { status: responseInit };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n\n  return new Response(null, {\n    ...responseInit,\n    headers,\n  });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private internal: boolean;\n\n  constructor(\n    status: number,\n    statusText: string | undefined,\n    data: any,\n    internal = false\n  ) {\n    this.status = status;\n    this.statusText = statusText || \"\";\n    this.internal = internal;\n    if (data instanceof Error) {\n      this.data = data.toString();\n      this.error = data;\n    } else {\n      this.data = data;\n    }\n  }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  DataStrategyResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnNavigationFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  removeDoubleSlashes,\n  resolveTo,\n  stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the basename for the router\n   */\n  get basename(): RouterInit[\"basename\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the future config for the router\n   */\n  get future(): FutureConfig;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the current state of the router\n   */\n  get state(): RouterState;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the routes for this router instance\n   */\n  get routes(): AgnosticDataRouteObject[];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Initialize the router, including adding history listeners and kicking off\n   * initial data fetches.  Returns a function to cleanup listeners and abort\n   * any in-progress loads\n   */\n  initialize(): Router;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Subscribe to router.state updates\n   *\n   * @param fn function to call with the new state\n   */\n  subscribe(fn: RouterSubscriber): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Enable scroll restoration behavior in the router\n   *\n   * @param savedScrollPositions Object that will manage positions, in case\n   *                             it's being restored from sessionStorage\n   * @param getScrollPosition    Function to get the active Y scroll position\n   * @param getKey               Function to get the key to use for restoration\n   */\n  enableScrollRestoration(\n    savedScrollPositions: Record<string, number>,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Navigate forward/backward in the history stack\n   * @param to Delta to move in the history stack\n   */\n  navigate(to: number): Promise<void>;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a fetcher load/submission\n   *\n   * @param key     Fetcher key\n   * @param routeId Route that owns the fetcher\n   * @param href    href to fetch\n   * @param opts    Fetcher options, (method, submission, etc.)\n   */\n  fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a revalidation of all current route loaders and fetcher loads\n   */\n  revalidate(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to create an href for the given location\n   * @param location\n   */\n  createHref(location: Location | URL): string;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to URL encode a destination path according to the internal\n   * history implementation\n   * @param to\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get/create a fetcher for the given key\n   * @param key\n   */\n  getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete the fetcher for a given key\n   * @param key\n   */\n  deleteFetcher(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Cleanup listeners and abort any in-progress loads\n   */\n  dispose(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal fetch AbortControllers accessed by unit tests\n   */\n  _internalFetchControllers: Map<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router.  During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n  /**\n   * The action of the most recent navigation\n   */\n  historyAction: HistoryAction;\n\n  /**\n   * The current location reflected by the router\n   */\n  location: Location;\n\n  /**\n   * The current set of route matches\n   */\n  matches: AgnosticDataRouteMatch[];\n\n  /**\n   * Tracks whether we've completed our initial data load\n   */\n  initialized: boolean;\n\n  /**\n   * Current scroll position we should start at for a new view\n   *  - number -> scroll position to restore to\n   *  - false -> do not restore scroll at all (used during submissions)\n   *  - null -> don't have a saved position, scroll to hash or top of page\n   */\n  restoreScrollPosition: number | false | null;\n\n  /**\n   * Indicate whether this navigation should skip resetting the scroll position\n   * if we are unable to restore the scroll position\n   */\n  preventScrollReset: boolean;\n\n  /**\n   * Tracks the state of the current navigation\n   */\n  navigation: Navigation;\n\n  /**\n   * Tracks any in-progress revalidations\n   */\n  revalidation: RevalidationState;\n\n  /**\n   * Data from the loaders for the current matches\n   */\n  loaderData: RouteData;\n\n  /**\n   * Data from the action for the current matches\n   */\n  actionData: RouteData | null;\n\n  /**\n   * Errors caught from loaders for the current matches\n   */\n  errors: RouteData | null;\n\n  /**\n   * Map of current fetchers\n   */\n  fetchers: Map<string, Fetcher>;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  activeDeferreds: Record<string, DeferredData> | null;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      viewTransitionOpts?: ViewTransitionOpts;\n      flushSync: boolean;\n    }\n  ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n  (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n  Idle: {\n    state: \"idle\";\n    location: undefined;\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\n  };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n  Idle: {\n    state: \"idle\";\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n  /**\n   * startNavigation does not need to complete the navigation because we\n   * redirected or got interrupted\n   */\n  shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * loaderData returned from the current set of loaders\n   */\n  loaderData?: RouterState[\"loaderData\"];\n  /**\n   * errors thrown from the current set of loaders\n   */\n  errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n  \"post\",\n  \"put\",\n  \"patch\",\n  \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\n  // Cleanup function for history\n  let unlistenHistory: (() => void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialMatchesIsFOW = false;\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    let error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname,\n    });\n    let { matches, route } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = { [route.id]: error };\n  }\n\n  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnNavigation` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatchesIsFOW = true;\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n      );\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\n\n  let router: Router;\n  let state: RouterState = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n    errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n    fetchers: new Map(),\n    blockers: new Map(),\n  };\n\n  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction: HistoryAction = HistoryAction.Pop;\n\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\n  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes: string[] = [];\n\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\n  // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n  let activeDeferreds = new Map<string, DeferredData>();\n\n  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n  // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(\n      ({ action: historyAction, location, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (unblockBlockerHistoryUpdate) {\n          unblockBlockerHistoryUpdate();\n          unblockBlockerHistoryUpdate = undefined;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n            unblockBlockerHistoryUpdate = resolve;\n          });\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked, after the url\n              // restoration is also complete.  See:\n              // https://github.com/remix-run/react-router/issues/11613\n              nextHistoryUpdatePromise.then(() => init.history.go(delta));\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\n    }\n\n    return router;\n  }\n\n  // Clean up a router and it's side effects\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Remove any lingering deleted fetchers that have already been removed\n    // from state.fetchers\n    deletedFetchers.forEach((key) => {\n      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n        deletedFetchersKeys.push(key);\n      }\n    });\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        viewTransitionOpts: opts.viewTransitionOpts,\n        flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    } else {\n      // We already called deleteFetcher() on these, can remove them from this\n      // Set now that we've handed the keys off to the data layer\n      deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n    }\n  }\n\n  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n  function completeNavigation(\n    location: Location,\n    newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n    { flushSync }: { flushSync?: boolean } = {}\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\n    }\n\n    if (isUninterruptedRevalidation) {\n      // If this was an uninterrupted revalidation then do not touch history\n    } else if (pendingAction === HistoryAction.Pop) {\n      // Do nothing for POP - URL has already been updated\n    } else if (pendingAction === HistoryAction.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === HistoryAction.Replace) {\n      init.history.replace(location, location.state);\n    }\n\n    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\n        ...newState, // matches, errors, fetchers go through as-is\n        actionData,\n        loaderData,\n        historyAction: pendingAction,\n        location,\n        initialized: true,\n        navigation: IDLE_NAVIGATION,\n        revalidation: \"idle\",\n        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n  }\n\n  // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  async function navigate(\n    to: number | To | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n    // URL from window.location, so we need to encode it here so the behavior\n    // remains the same as POP and non-data-router usages.  new URL() does all\n    // the same encoding we'd get from a history.pushState/window.location read\n    // without having to touch history\n    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\n    };\n\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n    let historyAction = HistoryAction.Push;\n\n    if (userReplace === true) {\n      historyAction = HistoryAction.Replace;\n    } else if (userReplace === false) {\n      // no-op\n    } else if (\n      submission != null &&\n      isMutationMethod(submission.formMethod) &&\n      submission.formAction === state.location.pathname + state.location.search\n    ) {\n      // By default on submissions to the current location we REPLACE so that\n      // users don't have to double-click the back button to get to the prior\n      // location.  If the user redirects to a different location from the\n      // action/loader this will be ignored and the redirect will be a PUSH\n      historyAction = HistoryAction.Replace;\n    }\n\n    let preventScrollReset =\n      opts && \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.viewTransition,\n      flushSync,\n    });\n  }\n\n  // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({ revalidation: \"loading\" });\n\n    // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n    if (state.navigation.state === \"submitting\") {\n      return;\n    }\n\n    // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true,\n      });\n      return;\n    }\n\n    // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n    startNavigation(\n      pendingAction || state.historyAction,\n      state.navigation.location,\n      {\n        overrideNavigation: state.navigation,\n        // Proxy through any rending view transition\n        enableViewTransition: pendingViewTransitionEnabled === true,\n      }\n    );\n  }\n\n  // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  async function startNavigation(\n    historyAction: HistoryAction,\n    location: Location,\n    opts?: {\n      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: boolean;\n    }\n  ): Promise<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches =\n      opts?.initialHydration &&\n      state.matches &&\n      state.matches.length > 0 &&\n      !initialMatchesIsFOW\n        ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n          state.matches\n        : matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial hydration will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      matches &&\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: opts.pendingError },\n      ];\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\n    );\n\n    if (shortCircuited) {\n      return;\n    }\n\n    // Clean up now that the action/loaders have completed.  Don't clean up if\n    // we short circuited because pendingNavigationController will have already\n    // been assigned to a new controller for the next navigation\n    pendingNavigationController = null;\n\n    completeNavigation(location, {\n      matches: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\n      loaderData,\n      errors,\n    });\n  }\n\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(\n    request: Request,\n    location: Location,\n    submission: Submission,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error: discoverResult.error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    // Call our action and get the result\n    let result: DataResult;\n    let actionMatch = getTargetMatch(matches, location);\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      result = {\n        type: ResultType.error,\n        error: getInternalRouterError(405, {\n          method: request.method,\n          pathname: location.pathname,\n          routeId: actionMatch.route.id,\n        }),\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        state,\n        request,\n        [actionMatch],\n        matches,\n        null\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        return { shortCircuited: true };\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      let replace: boolean;\n      if (opts && opts.replace != null) {\n        replace = opts.replace;\n      } else {\n        // If the user didn't explicity indicate replace behavior, replace if\n        // we redirected to the exact same location we're currently at to avoid\n        // double back-buttons\n        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename,\n          init.history,\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, true, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\n    };\n  }\n\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\n\n    // If this is an uninterrupted revalidation, we remain in our current idle\n    // state.  If not, we need to switch to our loading state and load data,\n    // preserving any new action data or existing action data (in the case of\n    // a revalidation interrupting an actionReload)\n    // If we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: discoverResult.error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\n    );\n\n    // Cancel pending deferreds for no-longer-matched routes or routes we're\n    // about to reload.  Note that if this is an action reload we would have\n    // already cancelled all pending deferreds so this would be a no-op\n    cancelActiveDeferreds(\n      (routeId) =>\n        !(matches && matches.some((m) => m.route.id === routeId)) ||\n        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n    );\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      abortFetcher(rf.key);\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        request\n      );\n\n    if (request.signal.aborted) {\n      return { shortCircuited: true };\n    }\n\n    // Clean up _after_ loaders have completed.  Don't clean up if we short\n    // circuited because fetchControllers would have been aborted and\n    // reassigned to new controllers for the next navigation\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      pendingActionResult,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Wire up subscribers to update loaderData as promises settle\n    activeDeferreds.forEach((deferredData, routeId) => {\n      deferredData.subscribe((aborted) => {\n        // Note: No need to updateState here since the TrackedPromise on\n        // loaderData is stable across resolve/reject\n        // Remove this instance if we were aborted or if promises have settled\n        if (aborted || deferredData.done) {\n          activeDeferreds.delete(routeId);\n        }\n      });\n    });\n\n    // Preserve SSR errors during partial hydration\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      errors = { ...state.errors, ...errors };\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\n  }\n\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ) {\n    if (isServer) {\n      throw new Error(\n        \"router.fetch() was called during the server render, but it shouldn't be. \" +\n          \"You are likely calling a useFetcher() method in the body of your component. \" +\n          \"Try moving it to a useEffect or a callback.\"\n      );\n    }\n\n    abortFetcher(key);\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        preventScrollReset,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      preventScrollReset,\n      submission\n    );\n  }\n\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    requestMatches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      state,\n      fetchRequest,\n      [match],\n      requestMatches,\n      key\n    );\n    let actionResult = actionResults[match.route.id];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by our own fetcher\n      // re-submit which would have put _new_ controller is in fetchControllers\n      if (fetchControllers.get(key) === abortController) {\n        fetchControllers.delete(key);\n      }\n      return;\n    }\n\n    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, false, {\n            fetcherSubmission: submission,\n            preventScrollReset,\n          });\n        }\n      }\n\n      // Process any non-redirect errors thrown\n      if (isErrorResult(actionResult)) {\n        setFetcherError(key, routeId, actionResult.error);\n        return;\n      }\n    }\n\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(\n      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, basename)\n        : state.matches;\n\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n\n    let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\n    );\n\n    // Put all revalidating fetchers into the loading state, except for the\n    // current fetcher which we want to keep in it's current loading state which\n    // contains it's action submission info + action data\n    revalidatingFetchers\n      .filter((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        abortFetcher(staleKey);\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    abortStaleFetchLoads(loadId);\n\n    // If we are currently in a navigation loading state and this fetcher is\n    // more recent than the navigation, we want the newer data so abort the\n    // navigation and complete it with the fetcher data\n    if (\n      state.navigation.state === \"loading\" &&\n      loadId > pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\n\n      completeNavigation(state.navigation.location, {\n        matches,\n        loaderData,\n        errors,\n        fetchers: new Map(state.fetchers),\n      });\n    } else {\n      // otherwise just update with the fetcher data, preserving any existing\n      // loaderData for loaders that did not need to reload.  We have to\n      // manually merge here since we aren't going through completeNavigation\n      updateState({\n        errors,\n        loaderData: mergeLoaderData(\n          state.loaderData,\n          loaderData,\n          matches,\n          errors\n        ),\n        fetchers: new Map(state.fetchers),\n      });\n      isRevalidationRequired = false;\n    }\n  }\n\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      state,\n      fetchRequest,\n      [match],\n      matches,\n      key\n    );\n    let result = results[match.route.id];\n\n    // Deferred isn't supported for fetcher loads, await everything and treat it\n    // as a normal load.  resolveDeferredData will return undefined if this\n    // fetcher gets aborted, so we just leave result untouched and short circuit\n    // below if that happens\n    if (isDeferredResult(result)) {\n      result =\n        (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n        result;\n    }\n\n    // We can delete this so long as we weren't aborted by our our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n\n    if (fetchRequest.signal.aborted) {\n      return;\n    }\n\n    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result, false, {\n          preventScrollReset,\n        });\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\n  }\n\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  async function startRedirectNavigation(\n    request: Request,\n    redirect: RedirectResult,\n    isNavigation: boolean,\n    {\n      submission,\n      fetcherSubmission,\n      preventScrollReset,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename,\n      init.history,\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(location);\n        }\n        return;\n      }\n    }\n\n    // There's no need to abort on redirects, since we don't detect the\n    // redirect until the action/loaders have settled\n    pendingNavigationController = null;\n\n    let redirectHistoryAction =\n      replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\n    }\n\n    // If this was a 307/308 submission we want to preserve the HTTP method and\n    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n    // redirected location\n    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    state: RouterState,\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    fetcherKey: string | null\n  ): Promise<Record<string, DataResult>> {\n    let results: Record<string, DataStrategyResult>;\n    let dataResults: Record<string, DataResult> = {};\n    try {\n      results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        state,\n        request,\n        matchesToLoad,\n        matches,\n        fetcherKey,\n        manifest,\n        mapRouteProperties\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      matchesToLoad.forEach((m) => {\n        dataResults[m.route.id] = {\n          type: ResultType.error,\n          error: e,\n        };\n      });\n      return dataResults;\n    }\n\n    for (let [routeId, result] of Object.entries(results)) {\n      if (isRedirectDataStrategyResultResult(result)) {\n        let response = result.result as Response;\n        dataResults[routeId] = {\n          type: ResultType.redirect,\n          response: normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            routeId,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          ),\n        };\n      } else {\n        dataResults[routeId] = await convertDataStrategyResultToDataResult(\n          result\n        );\n      }\n    }\n\n    return dataResults;\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    state: RouterState,\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    let currentMatches = state.matches;\n\n    // Kick off loaders and fetchers in parallel\n    let loaderResultsPromise = callDataStrategy(\n      \"loader\",\n      state,\n      request,\n      matchesToLoad,\n      matches,\n      null\n    );\n\n    let fetcherResultsPromise = Promise.all(\n      fetchersToLoad.map(async (f) => {\n        if (f.matches && f.match && f.controller) {\n          let results = await callDataStrategy(\n            \"loader\",\n            state,\n            createClientSideRequest(init.history, f.path, f.controller.signal),\n            [f.match],\n            f.matches,\n            f.key\n          );\n          let result = results[f.match.route.id];\n          // Fetcher results are keyed by fetcher key from here on out, not routeId\n          return { [f.key]: result };\n        } else {\n          return Promise.resolve({\n            [f.key]: {\n              type: ResultType.error,\n              error: getInternalRouterError(404, {\n                pathname: f.path,\n              }),\n            } as ErrorResult,\n          });\n        }\n      })\n    );\n\n    let loaderResults = await loaderResultsPromise;\n    let fetcherResults = (await fetcherResultsPromise).reduce(\n      (acc, r) => Object.assign(acc, r),\n      {}\n    );\n\n    await Promise.all([\n      resolveNavigationDeferredResults(\n        matches,\n        loaderResults,\n        request.signal,\n        currentMatches,\n        state.loaderData\n      ),\n      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\n  }\n\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n    // Abort in-flight fetcher loads\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.add(key);\n      }\n      abortFetcher(key);\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n    // If this fetcher was previously marked for deletion, unmark it since we\n    // have a new instance\n    if (deletedFetchers.has(key)) {\n      deletedFetchers.delete(key);\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n\n    // If we opted into the flag we can clear this now since we're calling\n    // deleteFetcher() at the end of updateState() and we've already handed the\n    // deleted fetcher keys off to the data layer.\n    // If not, we're eagerly calling deleteFetcher() and we need to keep this\n    // Set populated until the next updateState call, and we'll clear\n    // `deletedFetchers` then\n    if (future.v7_fetcherPersist) {\n      deletedFetchers.delete(key);\n    }\n\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    let count = (activeFetchers.get(key) || 0) - 1;\n    if (count <= 0) {\n      activeFetchers.delete(key);\n      deletedFetchers.add(key);\n      if (!future.v7_fetcherPersist) {\n        deleteFetcher(key);\n      }\n    } else {\n      activeFetchers.set(key, count);\n    }\n\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    if (controller) {\n      controller.abort();\n      fetchControllers.delete(key);\n    }\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\n    for (let key of fetchRedirectIds) {\n      let fetcher = state.fetchers.get(key);\n      invariant(fetcher, `Expected fetcher: ${key}`);\n      if (fetcher.state === \"loading\") {\n        fetchRedirectIds.delete(key);\n        doneKeys.push(key);\n        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\n  }\n\n  function abortStaleFetchLoads(landedId: number): boolean {\n    let yeetedKeys = [];\n    for (let [key, id] of fetchReloadIds) {\n      if (id < landedId) {\n        let fetcher = state.fetchers.get(key);\n        invariant(fetcher, `Expected fetcher: ${key}`);\n        if (fetcher.state === \"loading\") {\n          abortFetcher(key);\n          fetchReloadIds.delete(key);\n          yeetedKeys.push(key);\n        }\n      }\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n\n  function getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\n  }\n\n  function cancelActiveDeferreds(\n    predicate?: (routeId: string) => boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) => {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  }\n\n  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnNavigationImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        if (Object.keys(matches[0].params).length > 0) {\n          // If we matched a dynamic param or a splat, it might only be because\n          // we haven't yet discovered other routes that would match with a\n          // higher score.  Call patchRoutesOnNavigation just to be sure\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal,\n    fetcherKey?: string\n  ): Promise<DiscoverRoutesResult> {\n    if (!patchRoutesOnNavigationImpl) {\n      return { type: \"success\", matches };\n    }\n\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      let localManifest = manifest;\n      try {\n        await patchRoutesOnNavigationImpl({\n          signal,\n          path: pathname,\n          matches: partialMatches,\n          fetcherKey,\n          patch: (routeId, children) => {\n            if (signal.aborted) return;\n            patchRoutesImpl(\n              routeId,\n              children,\n              routesToUse,\n              localManifest,\n              mapRouteProperties\n            );\n          },\n        });\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR && !signal.aborted) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      if (newMatches) {\n        return { type: \"success\", matches: newMatches };\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // Avoid loops if the second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        (partialMatches.length === newPartialMatches.length &&\n          partialMatches.every(\n            (m, i) => m.route.id === newPartialMatches![i].route.id\n          ))\n      ) {\n        return { type: \"success\", matches: null };\n      }\n\n      partialMatches = newPartialMatches;\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\n    },\n    initialize,\n    subscribe,\n    enableScrollRestoration,\n    navigate,\n    fetch,\n    revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: (to: To) => init.history.createHref(to),\n    encodeLocation: (to: To) => init.history.encodeLocation(to),\n    getFetcher,\n    deleteFetcher: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   *\n   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\n    if (isResponse(result)) {\n      return result;\n    }\n\n    // When returning StaticHandlerContext, we patch back in the location here\n    // since we need it for React Context.  But this helps keep our submit and\n    // loadRouteData operating on a Request instead of a Location\n    return { location, basename, ...result };\n  }\n\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   *\n   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      false,\n      match\n    );\n\n    if (isResponse(result)) {\n      return result;\n    }\n\n    let error = result.errors ? Object.values(result.errors)[0] : undefined;\n    if (error !== undefined) {\n      // If we got back result.errors, that means the loader/action threw\n      // _something_ that wasn't a Response, but it's not guaranteed/required\n      // to be an `instanceof Error` either, so we have to use throw here to\n      // preserve the \"error\" state outside of queryImpl.\n      throw error;\n    }\n\n    // Pick off the right state value to return\n    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(\n          request,\n          matches,\n          routeMatch || getTargetMatch(matches, location),\n          requestContext,\n          dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        routeMatch\n      );\n      return isResponse(result)\n        ? result\n        : {\n            ...result,\n            actionData: null,\n            actionHeaders: {},\n          };\n    } catch (e) {\n      // If the user threw/returned a Response in callLoaderOrAction for a\n      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isDataStrategyResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\n      }\n      // Redirects are always returned since they don't propagate to catch\n      // boundaries\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n\n  async function submit(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    actionMatch: AgnosticDataRouteMatch,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        dataStrategy\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      // Uhhhh - this should never happen, we should always throw these from\n      // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n      // can get back on the \"throw all redirect responses\" train here should\n      // this ever happen :/\n      throw new Response(null, {\n        status: result.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    // Create a GET request for the loaders\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal,\n    });\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\n      );\n\n      // action status codes take precedence over loader status codes\n      return {\n        ...context,\n        statusCode: isRouteErrorResponse(result.error)\n          ? result.error.status\n          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\n  ): Promise<\n    | Omit<\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      >\n    | Response\n  > {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch?.route.id,\n      });\n    }\n\n    let requestMatches = routeMatch\n      ? [routeMatch]\n      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\n\n    // Short circuit if we have no loaders to run (query())\n    if (matchesToLoad.length === 0) {\n      return {\n        matches,\n        // Add a null for all matched routes for proper revalidation on the client\n        loaderData: matches.reduce(\n          (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null\n  ): Promise<Record<string, DataResult>> {\n    let results = await callDataStrategyImpl(\n      dataStrategy || defaultDataStrategy,\n      type,\n      null,\n      request,\n      matchesToLoad,\n      matches,\n      null,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    let dataResults: Record<string, DataResult> = {};\n    await Promise.all(\n      matches.map(async (match) => {\n        if (!(match.route.id in results)) {\n          return;\n        }\n        let result = results[match.route.id];\n        if (isRedirectDataStrategyResultResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            match.route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        dataResults[match.route.id] =\n          await convertDataStrategyResultToDataResult(result);\n      })\n    );\n    return dataResults;\n  }\n\n  return {\n    dataRoutes,\n    query,\n    queryRoute,\n  };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n  routes: AgnosticDataRouteObject[],\n  context: StaticHandlerContext,\n  error: any\n) {\n  let newContext: StaticHandlerContext = {\n    ...context,\n    statusCode: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Account for `?index` params when routing to the current location\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index && !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index&\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index && nakedIndex) {\n      // Remove existing ones when we're not\n      let params = new URLSearchParams(path.search);\n      let indexValues = params.getAll(\"index\");\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\n} {\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return { path };\n  }\n\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n  matches: AgnosticDataRouteMatch[],\n  boundaryId: string,\n  includeBoundary = false\n) {\n  let index = matches.findIndex((m) => m.route.id === boundaryId);\n  if (index >= 0) {\n    return matches.slice(0, includeBoundary ? index + 1 : index);\n  }\n  return matches;\n}\n\nfunction getMatchesToLoad(\n  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  initialHydration: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryMatches = matches;\n  if (initialHydration && state.errors) {\n    // On initial hydration, only consider matches up to _and including_ the boundary.\n    // This is inclusive to handle cases where a server loader ran successfully,\n    // a child server loader bubbled up to this route, but this route has\n    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n    // we have a complete version of `loaderData`\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      Object.keys(state.errors)[0],\n      true\n    );\n  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n    // If an action threw an error, we call loaders up to, but not including the\n    // boundary\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      pendingActionResult[0]\n    );\n  }\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (initialHydration) {\n      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for when we revalidate.  If the route\n    // provides it's own implementation, then we give them full control but\n    // provide this value so they can leverage it if needed after they check\n    // their own specific use cases\n    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial hydration (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      initialHydration ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\n      });\n    }\n  });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n  route: AgnosticDataRouteObject,\n  loaderData: RouteData | null | undefined,\n  errors: RouteData | null | undefined\n) {\n  // We dunno if we have a loader - gotta find out!\n  if (route.lazy) {\n    return true;\n  }\n\n  // No loader, nothing to initialize\n  if (!route.loader) {\n    return false;\n  }\n\n  let hasData = loaderData != null && loaderData[route.id] !== undefined;\n  let hasError = errors != null && errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData && hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -> [a, b]\n    !currentMatch ||\n    // [a, b] -> [a, c]\n    match.route.id !== currentMatch.route.id;\n\n  // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n  let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    (currentPath != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  let childrenToPatch: AgnosticDataRouteObject[];\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    if (!route.children) {\n      route.children = [];\n    }\n    childrenToPatch = route.children;\n  } else {\n    childrenToPatch = routesToUse;\n  }\n\n  // Don't patch in routes we already know about so that `patch` is idempotent\n  // to simplify user-land code. This is useful because we re-call the\n  // `patchRoutesOnNavigation` function for matched routes with params.\n  let uniqueChildren = children.filter(\n    (newRoute) =>\n      !childrenToPatch.some((existingRoute) =>\n        isSameRoute(newRoute, existingRoute)\n      )\n  );\n\n  let newRoutes = convertRoutesToDataRoutes(\n    uniqueChildren,\n    mapRouteProperties,\n    [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n    manifest\n  );\n\n  childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n  newRoute: AgnosticRouteObject,\n  existingRoute: AgnosticRouteObject\n): boolean {\n  // Most optimal check is by id\n  if (\n    \"id\" in newRoute &&\n    \"id\" in existingRoute &&\n    newRoute.id === existingRoute.id\n  ) {\n    return true;\n  }\n\n  // Second is by pathing differences\n  if (\n    !(\n      newRoute.index === existingRoute.index &&\n      newRoute.path === existingRoute.path &&\n      newRoute.caseSensitive === existingRoute.caseSensitive\n    )\n  ) {\n    return false;\n  }\n\n  // Pathless layout routes are trickier since we need to check children.\n  // If they have no children then they're the same as far as we can tell\n  if (\n    (!newRoute.children || newRoute.children.length === 0) &&\n    (!existingRoute.children || existingRoute.children.length === 0)\n  ) {\n    return true;\n  }\n\n  // Otherwise, we look to see if every child in the new route is already\n  // represented in the existing route's children\n  return newRoute.children!.every((aChild, i) =>\n    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n  );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n  matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n  let matchesToLoad = matches.filter((m) => m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n  return results.reduce(\n    (acc, result, i) =>\n      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n    {}\n  );\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  state: RouterState | null,\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  fetcherKey: string | null,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n  let loadRouteDefinitionsPromises = matches.map((m) =>\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) => {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n    // `resolve` encapsulates route.lazy(), executing the loader/action,\n    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users\n    // can pass a callback to take fine-grained control over the execution\n    // of the loader/action\n    let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n      if (\n        handlerOverride &&\n        request.method === \"GET\" &&\n        (match.route.lazy || match.route.loader)\n      ) {\n        shouldLoad = true;\n      }\n      return shouldLoad\n        ? callLoaderOrAction(\n            type,\n            request,\n            match,\n            loadRoutePromise,\n            handlerOverride,\n            requestContext\n          )\n        : Promise.resolve({ type: ResultType.data, result: undefined });\n    };\n\n    return {\n      ...match,\n      shouldLoad,\n      resolve,\n    };\n  });\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: dsMatches,\n    request,\n    params: matches[0].params,\n    fetcherKey,\n    context: requestContext,\n  });\n\n  // Wait for all routes to load here but 'swallow the error since we want\n  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n  // called from `match.resolve()`\n  try {\n    await Promise.all(loadRouteDefinitionsPromises);\n  } catch (e) {\n    // No-op\n  }\n\n  return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  loadRoutePromise: Promise<void> | undefined,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<DataStrategyResult> {\n  let result: DataStrategyResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<DataStrategyResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<DataStrategyResult> = (async () => {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n          : actualHandler());\n        return { type: \"data\", result: val };\n      } catch (e) {\n        return { type: \"error\", result: e };\n      }\n    })();\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    // If we have a route.lazy promise, await that first\n    if (loadRoutePromise) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadRoutePromise,\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadRoutePromise;\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.result !== undefined,\n      `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n        `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n        `function. Please return a value or \\`null\\`.`\n    );\n  } catch (e) {\n    // We should already be catching and converting normal handler executions to\n    // DataStrategyResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n  dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n  let { result, type } = dataStrategyResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\n      let contentType = result.headers.get(\"Content-Type\");\n      // Check between word boundaries instead of startsWith() due to the last\n      // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n      if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\n        headers: result.headers,\n      };\n    }\n\n    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers,\n    };\n  }\n\n  if (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n          headers: result.init?.headers\n            ? new Headers(result.init.headers)\n            : undefined,\n        };\n      }\n\n      // Convert thrown data() to ErrorResponse instances\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(\n          result.init?.status || 500,\n          undefined,\n          result.data\n        ),\n        statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n        headers: result.init?.headers\n          ? new Headers(result.init.headers)\n          : undefined,\n      };\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string,\n  historyInstance: History,\n): string {\n  // Match Chrome's behavior:\n  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n  let invalidProtocols = [\n    \"about:\",\n    \"blob:\",\n    \"chrome:\",\n    \"chrome-untrusted:\",\n    \"content:\",\n    \"data:\",\n    \"devtools:\",\n    \"file:\",\n    \"filesystem:\",\n    // eslint-disable-next-line no-script-url\n    \"javascript:\",\n  ];\n\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n    }\n  }\n\n  try {\n    let url = historyInstance.createURL(location);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n  } catch (e) {}\n\n  return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\n  return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n  let searchParams = new URLSearchParams();\n\n  for (let [key, value] of formData.entries()) {\n    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) => {\n    if (!(match.route.id in results)) {\n      return;\n    }\n    let id = match.route.id;\n    let result = results[id];\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\n      let error = result.error;\n      // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n      if (pendingError !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\n      }\n\n      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\n\n      // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (\n          result.statusCode != null &&\n          result.statusCode !== 200 &&\n          !foundError\n        ) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      } else {\n        loaderData[id] = result.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      }\n    }\n  });\n\n  // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n  if (pendingError !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[0]] = undefined;\n  }\n\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders,\n  };\n}\n\nfunction processLoaderData(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record<string, DataResult>,\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    results,\n    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  revalidatingFetchers.forEach((rf) => {\n    let { key, match, controller } = rf;\n    let result = fetcherResults[key];\n    invariant(result, \"Did not find corresponding fetcher result\");\n\n    // Process fetcher non-redirect errors\n    if (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      return;\n    } else if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = {\n          ...errors,\n          [boundaryMatch.route.id]: result.error,\n        };\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      invariant(false, \"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  });\n\n  return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n  loaderData: RouteData,\n  newLoaderData: RouteData,\n  matches: AgnosticDataRouteMatch[],\n  errors: RouteData | null | undefined\n): RouteData {\n  let mergedLoaderData = { ...newLoaderData };\n  for (let match of matches) {\n    let id = match.route.id;\n    if (newLoaderData.hasOwnProperty(id)) {\n      if (newLoaderData[id] !== undefined) {\n        mergedLoaderData[id] = newLoaderData[id];\n      } else {\n        // No-op - this is so we ignore existing data if we have a key in the\n        // incoming object with an undefined value, which is how we unset a prior\n        // loaderData if we encounter a loader error\n      }\n    } else if (loaderData[id] !== undefined && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\n      mergedLoaderData[id] = loaderData[id];\n    }\n\n    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n  matches: AgnosticDataRouteMatch[],\n  routeId?: string\n): AgnosticDataRouteMatch {\n  let eligibleMatches = routeId\n    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n    matches[0]\n  );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n  matches: AgnosticDataRouteMatch[];\n  route: AgnosticDataRouteObject;\n} {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route =\n    routes.length === 1\n      ? routes[0]\n      : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n          id: `__shim-error-route__`,\n        };\n\n  return {\n    matches: [\n      {\n        params: {},\n        pathname: \"\",\n        pathnameBase: \"\",\n        route,\n      },\n    ],\n    route,\n  };\n}\n\nfunction getInternalRouterError(\n  status: number,\n  {\n    pathname,\n    routeId,\n    method,\n    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\";\n    message?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = `No route matches URL \"${pathname}\"`;\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n        `did not provide an \\`action\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (method) {\n      errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n    }\n  }\n\n  return new ErrorResponseImpl(\n    status || 500,\n    statusText,\n    new Error(errorMessage),\n    true\n  );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n  results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i >= 0; i--) {\n    let [key, result] = entries[i];\n    if (isRedirectResult(result)) {\n      return { key, result };\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n  );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n  return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n  return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n  return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null &&\n    typeof value.status === \"number\" &&\n    typeof value.statusText === \"string\" &&\n    typeof value.headers === \"object\" &&\n    typeof value.body !== \"undefined\"\n  );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n  if (!isResponse(result)) {\n    return false;\n  }\n\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index < entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    let currentMatch = currentMatches.find(\n      (m) => m.route.id === match!.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null &&\n      !isNewRouteInstance(currentMatch, match) &&\n      (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) && isRevalidatingLoader) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      await resolveDeferredData(result, signal, false).then((result) => {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    if (isDeferredResult(result)) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      invariant(\n        controller,\n        \"Expected an AbortController for revalidating fetcher deferred result\"\n      );\n      await resolveDeferredData(result, controller.signal, true).then(\n        (result) => {\n          if (result) {\n            results[key] = result;\n          }\n        }\n      );\n    }\n  }\n}\n\nasync function resolveDeferredData(\n  result: DeferredResult,\n  signal: AbortSignal,\n  unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\n  }\n\n  if (unwrap) {\n    try {\n      return {\n        type: ResultType.data,\n        data: result.deferredData.unwrappedData,\n      };\n    } catch (e) {\n      // Handle any TrackedPromise._error values encountered while unwrapping\n      return {\n        type: ResultType.error,\n        error: e,\n      };\n    }\n  }\n\n  return {\n    type: ResultType.data,\n    data: result.deferredData.data,\n  };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n  return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n  matches: AgnosticDataRouteMatch[],\n  location: Location | string\n) {\n  let search =\n    typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (\n    matches[matches.length - 1].route.index &&\n    hasNakedIndexQuery(search || \"\")\n  ) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  }\n  // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;;EAEA;EACA;EACA;AACYA,MAAAA,MAAM,0BAANA,MAAM,EAAA;EAChB;EACF;EACA;EACA;EACA;EACA;EACA;IAPYA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;EAUhB;EACF;EACA;EACA;EACA;IAdYA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;EAiBhB;EACF;EACA;EACA;IApBYA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;EAAA,EAAA,OAANA,MAAM,CAAA;EAAA,CAAA,CAAA,EAAA,EAAA;;EAwBlB;EACA;EACA;;EAkBA;EACA;;EAEA;EACA;EACA;EACA;;EAgBA;EACA;EACA;;EAkBA;EACA;EACA;;EAKA;EACA;E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CAACiG,gBAAgB,CAAC,CAAA;EACvC,MAAA,KAAK,IAAI,CAACnc,CAAC,EAAEtF,CAAC,CAAC,IAAIxB,MAAM,CAAC/L,OAAO,CAAC4P,IAAI,IAAI,EAAE,CAAC,EAAE;UAC7C,IAAIrC,CAAC,IAAIsD,KAAK,CAACC,OAAO,CAACvD,CAAC,CAAC,EAAE;EACzBwhB,UAAAA,WAAW,CAAC5e,GAAG,CAAC0C,CAAC,EAAE,IAAIrM,GAAG,CAAC+G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;EACtC,SAAA;EACF,OAAA;EACF,KAAA;KACD,CAAC,OAAO3I,CAAC,EAAE;EACV;EAAA,GAAA;EAEJ,CAAA;EAEA,SAAS4V,yBAAyBA,CAChCsU,OAAe,EACfC,WAAqC,EACrC;EACA,EAAA,IAAIA,WAAW,CAAC/b,IAAI,GAAG,CAAC,EAAE;MACxB,IAAIpD,IAA8B,GAAG,EAAE,CAAA;MACvC,KAAK,IAAI,CAACiD,CAAC,EAAEtF,CAAC,CAAC,IAAIwhB,WAAW,EAAE;EAC9Bnf,MAAAA,IAAI,CAACiD,CAAC,CAAC,GAAG,CAAC,GAAGtF,CAAC,CAAC,CAAA;EAClB,KAAA;MACA,IAAI;EACFuhB,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5B9Z,uBAAuB,EACvB7T,IAAI,CAACC,SAAS,CAACmO,IAAI,CACrB,CAAC,CAAA;OACF,CAAC,OAAO7J,KAAK,EAAE;EACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;EACH,KAAA;EACF,GAAA;EACF,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}/**
 * @remix-run/router v1.23.4
 *
 * 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
 */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).RemixRouter={})}(this,function(e){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)({}).hasOwnProperty.call(r,a)&&(e[a]=r[a])}return e},t.apply(null,arguments)}let r=function(e){return e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE",e}({});const a="popstate";function n(e,t){if(!1===e||null==e)throw new Error(t)}function o(e,t){if(!e){"undefined"!=typeof console&&console.warn(t);try{throw new Error(t)}catch(e){}}}function i(e,t){return{usr:e.state,key:e.key,idx:t}}function s(e,r,a,n){return void 0===a&&(a=null),t({pathname:"string"==typeof e?e:e.pathname,search:"",hash:""},"string"==typeof r?u(r):r,{state:a,key:r&&r.key||n||Math.random().toString(36).substr(2,8)})}function l(e){let{pathname:t="/",search:r="",hash:a=""}=e;return r&&"?"!==r&&(t+="?"===r.charAt(0)?r:"?"+r),a&&"#"!==a&&(t+="#"===a.charAt(0)?a:"#"+a),t}function u(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let a=e.indexOf("?");a>=0&&(t.search=e.substr(a),e=e.substr(0,a)),e&&(t.pathname=e)}return t}function c(e,o,u,c){void 0===c&&(c={});let{window:d=document.defaultView,v5Compat:h=!1}=c,f=d.history,p=r.Pop,m=null,y=v();function v(){return(f.state||{idx:null}).idx}function g(){p=r.Pop;let e=v(),t=null==e?null:e-y;y=e,m&&m({action:p,location:w.location,delta:t})}function b(e){let t="null"!==d.location.origin?d.location.origin:d.location.href,r="string"==typeof e?e:l(e);return r=r.replace(/ $/,"%20"),n(t,"No window.location.(origin|href) available to create URL for href: "+r),new URL(r,t)}null==y&&(y=0,f.replaceState(t({},f.state,{idx:y}),""));let w={get action(){return p},get location(){return e(d,f)},listen(e){if(m)throw new Error("A history only accepts one active listener");return d.addEventListener(a,g),m=e,()=>{d.removeEventListener(a,g),m=null}},createHref:e=>o(d,e),createURL:b,encodeLocation(e){let t=b(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){p=r.Push;let a=s(w.location,e,t);u&&u(a,e),y=v()+1;let n=i(a,y),o=w.createHref(a);try{f.pushState(n,"",o)}catch(e){if(e instanceof DOMException&&"DataCloneError"===e.name)throw e;d.location.assign(o)}h&&m&&m({action:p,location:w.location,delta:1})},replace:function(e,t){p=r.Replace;let a=s(w.location,e,t);u&&u(a,e),y=v();let n=i(a,y),o=w.createHref(a);f.replaceState(n,"",o),h&&m&&m({action:p,location:w.location,delta:0})},go:e=>f.go(e)};return w}let d=function(e){return e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error",e}({});const h=new Set(["lazy","caseSensitive","path","id","index","children"]);function f(e,r,a,o){return void 0===a&&(a=[]),void 0===o&&(o={}),e.map((e,i)=>{let s=[...a,String(i)],l="string"==typeof e.id?e.id:s.join("-");if(n(!0!==e.index||!e.children,"Cannot specify children on an index route"),n(!o[l],'Found a route id collision on id "'+l+"\".  Route id's must be globally unique within Data Router usages"),function(e){return!0===e.index}(e)){let a=t({},e,r(e),{id:l});return o[l]=a,a}{let a=t({},e,r(e),{id:l,children:void 0});return o[l]=a,e.children&&(a.children=f(e.children,r,s,o)),a}})}function p(e,t,r){return void 0===r&&(r="/"),m(e,t,r,!1)}function m(e,t,r,a){let n=j(("string"==typeof t?u(t):t).pathname||"/",r);if(null==n)return null;let o=v(e);!function(e){e.sort((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){let r=e.length===t.length&&e.slice(0,-1).every((e,r)=>e===t[r]);return r?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)))}(o);let i=null,s=M(n);for(let e=0;null==i&&e<o.length;++e)i=L(o[e],s,a);return i}function y(e,t){let{route:r,pathname:a,params:n}=e;return{id:r.id,pathname:a,params:n,data:t[r.id],handle:r.handle}}function v(e,t,r,a){void 0===t&&(t=[]),void 0===r&&(r=[]),void 0===a&&(a="");let o=(e,o,i)=>{let s={relativePath:void 0===i?e.path||"":i,caseSensitive:!0===e.caseSensitive,childrenIndex:o,route:e};s.relativePath.startsWith("/")&&(n(s.relativePath.startsWith(a),'Absolute route path "'+s.relativePath+'" nested under path "'+a+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),s.relativePath=s.relativePath.slice(a.length));let l=H([a,s.relativePath]),u=r.concat(s);e.children&&e.children.length>0&&(n(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+l+'".'),v(e.children,t,u,l)),(null!=e.path||e.index)&&t.push({path:l,score:x(l,e.index),routesMeta:u})};return e.forEach((e,t)=>{var r;if(""!==e.path&&null!=(r=e.path)&&r.includes("?"))for(let r of g(e.path))o(e,t,r);else o(e,t)}),t}function g(e){let t=e.split("/");if(0===t.length)return[];let[r,...a]=t,n=r.endsWith("?"),o=r.replace(/\?$/,"");if(0===a.length)return n?[o,""]:[o];let i=g(a.join("/")),s=[];return s.push(...i.map(e=>""===e?o:[o,e].join("/"))),n&&s.push(...i),s.map(t=>e.startsWith("/")&&""===t?"/":t)}const b=/^:[\w-]+$/,w=3,S=2,D=1,R=10,E=-2,P=e=>"*"===e;function x(e,t){let r=e.split("/"),a=r.length;return r.some(P)&&(a+=E),t&&(a+=S),r.filter(e=>!P(e)).reduce((e,t)=>e+(b.test(t)?w:""===t?D:R),a)}function L(e,t,r){void 0===r&&(r=!1);let{routesMeta:a}=e,n={},o="/",i=[];for(let e=0;e<a.length;++e){let s=a[e],l=e===a.length-1,u="/"===o?t:t.slice(o.length)||"/",c=A({path:s.relativePath,caseSensitive:s.caseSensitive,end:l},u),d=s.route;if(!c&&l&&r&&!a[a.length-1].route.index&&(c=A({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},u)),!c)return null;Object.assign(n,c.params),i.push({params:n,pathname:H([o,c.pathname]),pathnameBase:z(H([o,c.pathnameBase])),route:d}),"/"!==c.pathnameBase&&(o=H([o,c.pathnameBase]))}return i}function A(e,t){"string"==typeof e&&(e={path:e,caseSensitive:!1,end:!0});let[r,a]=function(e,t,r){void 0===t&&(t=!1);void 0===r&&(r=!0);o("*"===e||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were "'+e.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+e.replace(/\*$/,"/*")+'".');let a=[],n="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(e,t,r)=>(a.push({paramName:t,isOptional:null!=r}),r?"/?([^\\/]+)?":"/([^\\/]+)"));e.endsWith("*")?(a.push({paramName:"*"}),n+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?n+="\\/*$":""!==e&&"/"!==e&&(n+="(?:(?=\\/|$))");let i=new RegExp(n,t?void 0:"i");return[i,a]}(e.path,e.caseSensitive,e.end),n=t.match(r);if(!n)return null;let i=n[0],s=i.replace(/(.)\/+$/,"$1"),l=n.slice(1);return{params:a.reduce((e,t,r)=>{let{paramName:a,isOptional:n}=t;if("*"===a){let e=l[r]||"";s=i.slice(0,i.length-e.length).replace(/(.)\/+$/,"$1")}const o=l[r];return e[a]=n&&!o?void 0:(o||"").replace(/%2F/g,"/"),e},{}),pathname:i,pathnameBase:s,pattern:e}}function M(e){try{return e.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(t){return o(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function j(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,a=e.charAt(r);return a&&"/"!==a?null:e.slice(r)||"/"}function k(e,t){void 0===t&&(t="/");let r,{pathname:a,search:n="",hash:o=""}="string"==typeof e?u(e):e;return a?(a=I(a),r=a.startsWith("/")?C(a.substring(1),"/"):C(a,t)):r=t,{pathname:r,search:F(n),hash:N(o)}}function C(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(e=>{".."===e?r.length>1&&r.pop():"."!==e&&r.push(e)}),r.length>1?r.join("/"):"/"}function _(e,t,r,a){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(a)+"].  Please separate it out to the `to."+r+'` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.'}function T(e){return e.filter((e,t)=>0===t||e.route.path&&e.route.path.length>0)}function U(e,t){let r=T(e);return t?r.map((e,t)=>t===r.length-1?e.pathname:e.pathnameBase):r.map(e=>e.pathnameBase)}function O(e,r,a,o){let i;void 0===o&&(o=!1),"string"==typeof e?i=u(e):(i=t({},e),n(!i.pathname||!i.pathname.includes("?"),_("?","pathname","search",i)),n(!i.pathname||!i.pathname.includes("#"),_("#","pathname","hash",i)),n(!i.search||!i.search.includes("#"),_("#","search","hash",i)));let s,l=""===e||""===i.pathname,c=l?"/":i.pathname;if(null==c)s=a;else{let e=r.length-1;if(!o&&c.startsWith("..")){let t=c.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?r[e]:"/"}let d=k(i,s),h=c&&"/"!==c&&c.endsWith("/"),f=(l||"."===c)&&a.endsWith("/");return d.pathname.endsWith("/")||!h&&!f||(d.pathname+="/"),d}const I=e=>e.replace(/\/\/+/g,"/"),H=e=>I(e.join("/")),z=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),F=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",N=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";class B{constructor(e,t){this.type="DataWithResponseInit",this.data=e,this.init=t||null}}class W extends Error{}class ${constructor(e,t){let r;this.pendingKeysSet=new Set,this.subscribers=new Set,this.deferredKeys=[],n(e&&"object"==typeof e&&!Array.isArray(e),"defer() only accepts plain objects"),this.abortPromise=new Promise((e,t)=>r=t),this.controller=new AbortController;let a=()=>r(new W("Deferred data aborted"));this.unlistenAbortSignal=()=>this.controller.signal.removeEventListener("abort",a),this.controller.signal.addEventListener("abort",a),this.data=Object.entries(e).reduce((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:this.trackPromise(r,a)})},{}),this.done&&this.unlistenAbortSignal(),this.init=t}trackPromise(e,t){if(!(t instanceof Promise))return t;this.deferredKeys.push(e),this.pendingKeysSet.add(e);let r=Promise.race([t,this.abortPromise]).then(t=>this.onSettle(r,e,void 0,t),t=>this.onSettle(r,e,t));return r.catch(()=>{}),Object.defineProperty(r,"_tracked",{get:()=>!0}),r}onSettle(e,t,r,a){if(this.controller.signal.aborted&&r instanceof W)return this.unlistenAbortSignal(),Object.defineProperty(e,"_error",{get:()=>r}),Promise.reject(r);if(this.pendingKeysSet.delete(t),this.done&&this.unlistenAbortSignal(),void 0===r&&void 0===a){let r=new Error('Deferred data for key "'+t+'" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');return Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)}return void 0===a?(Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)):(Object.defineProperty(e,"_data",{get:()=>a}),this.emit(!1,t),a)}emit(e,t){this.subscribers.forEach(r=>r(e,t))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}cancel(){this.controller.abort(),this.pendingKeysSet.forEach((e,t)=>this.pendingKeysSet.delete(t)),this.emit(!0)}async resolveData(e){let t=!1;if(!this.done){let r=()=>this.cancel();e.addEventListener("abort",r),t=await new Promise(t=>{this.subscribe(a=>{e.removeEventListener("abort",r),(a||this.done)&&t(a)})})}return t}get done(){return 0===this.pendingKeysSet.size}get unwrappedData(){return n(null!==this.data&&this.done,"Can only unwrap data on initialized and settled deferreds"),Object.entries(this.data).reduce((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:q(a)})},{})}get pendingKeys(){return Array.from(this.pendingKeysSet)}}function q(e){if(!function(e){return e instanceof Promise&&!0===e._tracked}(e))return e;if(e._error)throw e._error;return e._data}const K=function(e,r){void 0===r&&(r=302);let a=r;"number"==typeof a?a={status:a}:void 0===a.status&&(a.status=302);let n=new Headers(a.headers);return n.set("Location",e),new Response(null,t({},a,{headers:n}))};class Y{constructor(e,t,r,a){void 0===a&&(a=!1),this.status=e,this.statusText=t||"",this.internal=a,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function J(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"boolean"==typeof e.internal&&"data"in e}const V=["post","put","patch","delete"],X=new Set(V),G=["get",...V],Q=new Set(G),Z=new Set([301,302,303,307,308]),ee=new Set([307,308]),te={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},re={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ae={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},ne=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,oe=e=>({hasErrorBoundary:Boolean(e.hasErrorBoundary)}),ie="remix-router-transitions";const se=Symbol("deferred");function le(e,t,r){if(r.v7_throwAbortReason&&void 0!==e.signal.reason)throw e.signal.reason;throw new Error((t?"queryRoute":"query")+"() call aborted: "+e.method+" "+e.url)}function ue(e,t,r,a,n,o,i,s){let u,c;if(i){u=[];for(let e of t)if(u.push(e),e.route.id===i){c=e;break}}else u=t,c=t[t.length-1];let d=O(n||".",U(u,o),j(e.pathname,r)||e.pathname,"path"===s);if(null==n&&(d.search=e.search,d.hash=e.hash),(null==n||""===n||"."===n)&&c){let e=Ye(d.search);if(c.route.index&&!e)d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index";else if(!c.route.index&&e){let e=new URLSearchParams(d.search),t=e.getAll("index");e.delete("index"),t.filter(e=>e).forEach(t=>e.append("index",t));let r=e.toString();d.search=r?"?"+r:""}}return a&&"/"!==r&&(d.pathname="/"===d.pathname?r:H([r,d.pathname])),l(d)}function ce(e,t,r,a){if(!a||!function(e){return null!=e&&("formData"in e&&null!=e.formData||"body"in e&&void 0!==e.body)}(a))return{path:r};if(a.formMethod&&!Be(a.formMethod))return{path:r,error:Ce(405,{method:a.formMethod})};let o,i,s=()=>({path:r,error:Ce(400,{type:"invalid-body"})}),c=a.formMethod||"get",d=e?c.toUpperCase():c.toLowerCase(),h=Te(r);if(void 0!==a.body){if("text/plain"===a.formEncType){if(!We(d))return s();let e="string"==typeof a.body?a.body:a.body instanceof FormData||a.body instanceof URLSearchParams?Array.from(a.body.entries()).reduce((e,t)=>{let[r,a]=t;return""+e+r+"="+a+"\n"},""):String(a.body);return{path:r,submission:{formMethod:d,formAction:h,formEncType:a.formEncType,formData:void 0,json:void 0,text:e}}}if("application/json"===a.formEncType){if(!We(d))return s();try{let e="string"==typeof a.body?JSON.parse(a.body):a.body;return{path:r,submission:{formMethod:d,formAction:h,formEncType:a.formEncType,formData:void 0,json:e,text:void 0}}}catch(e){return s()}}}if(n("function"==typeof FormData,"FormData is not available in this environment"),a.formData)o=Ee(a.formData),i=a.formData;else if(a.body instanceof FormData)o=Ee(a.body),i=a.body;else if(a.body instanceof URLSearchParams)o=a.body,i=Pe(o);else if(null==a.body)o=new URLSearchParams,i=new FormData;else try{o=new URLSearchParams(a.body),i=Pe(o)}catch(e){return s()}let f={formMethod:d,formAction:h,formEncType:a&&a.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(We(f.formMethod))return{path:r,submission:f};let p=u(r);return t&&p.search&&Ye(p.search)&&o.append("index",""),p.search="?"+o,{path:l(p),submission:f}}function de(e,t,r){void 0===r&&(r=!1);let a=e.findIndex(e=>e.route.id===t);return a>=0?e.slice(0,r?a+1:a):e}function he(e,r,a,n,o,i,s,l,u,c,d,h,f,m,y,v){let g=v?Ie(v[1])?v[1].error:v[1].data:void 0,b=e.createURL(r.location),w=e.createURL(o),S=a;i&&r.errors?S=de(a,Object.keys(r.errors)[0],!0):v&&Ie(v[1])&&(S=de(a,v[0]));let D=v?v[1].statusCode:void 0,R=s&&D&&D>=400,E=S.filter((e,a)=>{let{route:o}=e;if(o.lazy)return!0;if(null==o.loader)return!1;if(i)return fe(o,r.loaderData,r.errors);if(function(e,t,r){let a=!t||r.route.id!==t.route.id,n=void 0===e[r.route.id];return a||n}(r.loaderData,r.matches[a],e)||u.some(t=>t===e.route.id))return!0;let s=r.matches[a],c=e;return me(e,t({currentUrl:b,currentParams:s.params,nextUrl:w,nextParams:c.params},n,{actionResult:g,actionStatus:D,defaultShouldRevalidate:!R&&(l||b.pathname+b.search===w.pathname+w.search||b.search!==w.search||pe(s,c))}))}),P=[];return h.forEach((e,o)=>{if(i||!a.some(t=>t.route.id===e.routeId)||d.has(o))return;let s=p(m,e.path,y);if(!s)return void P.push({key:o,routeId:e.routeId,path:e.path,matches:null,match:null,controller:null});let u=r.fetchers.get(o),h=Je(s,e.path),v=!1;f.has(o)?v=!1:c.has(o)?(c.delete(o),v=!0):v=u&&"idle"!==u.state&&void 0===u.data?l:me(h,t({currentUrl:b,currentParams:r.matches[r.matches.length-1].params,nextUrl:w,nextParams:a[a.length-1].params},n,{actionResult:g,actionStatus:D,defaultShouldRevalidate:!R&&l})),v&&P.push({key:o,routeId:e.routeId,path:e.path,matches:s,match:h,controller:new AbortController})}),[E,P]}function fe(e,t,r){if(e.lazy)return!0;if(!e.loader)return!1;let a=null!=t&&void 0!==t[e.id],n=null!=r&&void 0!==r[e.id];return!(!a&&n)&&("function"==typeof e.loader&&!0===e.loader.hydrate||!a&&!n)}function pe(e,t){let r=e.route.path;return e.pathname!==t.pathname||null!=r&&r.endsWith("*")&&e.params["*"]!==t.params["*"]}function me(e,t){if(e.route.shouldRevalidate){let r=e.route.shouldRevalidate(t);if("boolean"==typeof r)return r}return t.defaultShouldRevalidate}function ye(e,t,r,a,o){var i;let s;if(e){let t=a[e];n(t,"No route found to patch children into: routeId = "+e),t.children||(t.children=[]),s=t.children}else s=r;let l=f(t.filter(e=>!s.some(t=>ve(e,t))),o,[e||"_","patch",String((null==(i=s)?void 0:i.length)||"0")],a);s.push(...l)}function ve(e,t){return"id"in e&&"id"in t&&e.id===t.id||e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive&&(!(e.children&&0!==e.children.length||t.children&&0!==t.children.length)||e.children.every((e,r)=>{var a;return null==(a=t.children)?void 0:a.some(t=>ve(e,t))}))}async function ge(e){let{matches:t}=e,r=t.filter(e=>e.shouldLoad);return(await Promise.all(r.map(e=>e.resolve()))).reduce((e,t,a)=>Object.assign(e,{[r[a].route.id]:t}),{})}async function be(e,r,a,i,s,l,u,c,f,p){let m=l.map(e=>e.route.lazy?async function(e,r,a){if(!e.lazy)return;let i=await e.lazy();if(!e.lazy)return;let s=a[e.id];n(s,"No route found in manifest");let l={};for(let e in i){let t=void 0!==s[e]&&"hasErrorBoundary"!==e;o(!t,'Route "'+s.id+'" has a static property "'+e+'" defined but its lazy function is also returning a value for this property. The lazy route property "'+e+'" will be ignored.'),t||h.has(e)||(l[e]=i[e])}Object.assign(s,l),Object.assign(s,t({},r(s),{lazy:void 0}))}(e.route,f,c):void 0),y=l.map((e,a)=>{let o=m[a],l=s.some(t=>t.route.id===e.route.id);return t({},e,{shouldLoad:l,resolve:async t=>(t&&"GET"===i.method&&(e.route.lazy||e.route.loader)&&(l=!0),l?async function(e,t,r,a,o,i){let s,l,u=a=>{let n,s=new Promise((e,t)=>n=t);l=()=>n(),t.signal.addEventListener("abort",l);let u=n=>"function"!=typeof a?Promise.reject(new Error('You cannot call the handler for a route which defines a boolean "'+e+'" [routeId: '+r.route.id+"]")):a({request:t,params:r.params,context:i},...void 0!==n?[n]:[]),c=(async()=>{try{return{type:"data",result:await(o?o(e=>u(e)):u())}}catch(e){return{type:"error",result:e}}})();return Promise.race([c,s])};try{let o=r.route[e];if(a)if(o){let e,[t]=await Promise.all([u(o).catch(t=>{e=t}),a]);if(void 0!==e)throw e;s=t}else{if(await a,o=r.route[e],!o){if("action"===e){let e=new URL(t.url),a=e.pathname+e.search;throw Ce(405,{method:t.method,pathname:a,routeId:r.route.id})}return{type:d.data,result:void 0}}s=await u(o)}else{if(!o){let e=new URL(t.url);throw Ce(404,{pathname:e.pathname+e.search})}s=await u(o)}n(void 0!==s.result,"You defined "+("action"===e?"an action":"a loader")+' for route "'+r.route.id+"\" but didn't return anything from your `"+e+"` function. Please return a value or `null`.")}catch(e){return{type:d.error,result:e}}finally{l&&t.signal.removeEventListener("abort",l)}return s}(r,i,e,o,t,p):Promise.resolve({type:d.data,result:void 0}))})}),v=await e({matches:y,request:i,params:l[0].params,fetcherKey:u,context:p});try{await Promise.all(m)}catch(e){}return v}async function we(e){let{result:t,type:r}=e;if(Ne(t)){let e;try{let r=t.headers.get("Content-Type");e=r&&/\bapplication\/json\b/.test(r)?null==t.body?null:await t.json():await t.text()}catch(e){return{type:d.error,error:e}}return r===d.error?{type:d.error,error:new Y(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:d.data,data:e,statusCode:t.status,headers:t.headers}}var a,n,o,i,s,l,u,c;return r===d.error?ze(t)?t.data instanceof Error?{type:d.error,error:t.data,statusCode:null==(o=t.init)?void 0:o.status,headers:null!=(i=t.init)&&i.headers?new Headers(t.init.headers):void 0}:{type:d.error,error:new Y((null==(a=t.init)?void 0:a.status)||500,void 0,t.data),statusCode:J(t)?t.status:void 0,headers:null!=(n=t.init)&&n.headers?new Headers(t.init.headers):void 0}:{type:d.error,error:t,statusCode:J(t)?t.status:void 0}:Fe(t)?{type:d.deferred,deferredData:t,statusCode:null==(s=t.init)?void 0:s.status,headers:(null==(l=t.init)?void 0:l.headers)&&new Headers(t.init.headers)}:ze(t)?{type:d.data,data:t.data,statusCode:null==(u=t.init)?void 0:u.status,headers:null!=(c=t.init)&&c.headers?new Headers(t.init.headers):void 0}:{type:d.data,data:t}}function Se(e,t,r,a,o,i){let s=e.headers.get("Location");if(n(s,"Redirects returned/thrown from loaders/actions must have a Location header"),!ne.test(s)){let n=a.slice(0,a.findIndex(e=>e.route.id===r)+1);s=ue(new URL(t.url),n,o,!0,s,i),e.headers.set("Location",s)}return e}function De(e,t,r,a){let n=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];if(ne.test(e)){let a=e,o=a.startsWith("//")?new URL(t.protocol+a):new URL(a);if(n.includes(o.protocol))throw new Error("Invalid redirect location");let i=null!=j(o.pathname,r);if(o.origin===t.origin&&i)return I(o.pathname)+o.search+o.hash}try{let t=a.createURL(e);if(n.includes(t.protocol))throw new Error("Invalid redirect location")}catch(e){}return e}function Re(e,t,r,a){let n=e.createURL(Te(t)).toString(),o={signal:r};if(a&&We(a.formMethod)){let{formMethod:e,formEncType:t}=a;o.method=e.toUpperCase(),"application/json"===t?(o.headers=new Headers({"Content-Type":t}),o.body=JSON.stringify(a.json)):"text/plain"===t?o.body=a.text:"application/x-www-form-urlencoded"===t&&a.formData?o.body=Ee(a.formData):o.body=a.formData}return new Request(n,o)}function Ee(e){let t=new URLSearchParams;for(let[r,a]of e.entries())t.append(r,"string"==typeof a?a:a.name);return t}function Pe(e){let t=new FormData;for(let[r,a]of e.entries())t.append(r,a);return t}function xe(e,t,r,a,o){let i,s={},l=null,u=!1,c={},d=r&&Ie(r[1])?r[1].error:void 0;return e.forEach(r=>{if(!(r.route.id in t))return;let h=r.route.id,f=t[h];if(n(!He(f),"Cannot handle redirect results in processLoaderData"),Ie(f)){let t=f.error;if(void 0!==d&&(t=d,d=void 0),l=l||{},o)l[h]=t;else{let r=je(e,h);null==l[r.route.id]&&(l[r.route.id]=t)}s[h]=void 0,u||(u=!0,i=J(f.error)?f.error.status:500),f.headers&&(c[h]=f.headers)}else Oe(f)?(a.set(h,f.deferredData),s[h]=f.deferredData.data,null==f.statusCode||200===f.statusCode||u||(i=f.statusCode),f.headers&&(c[h]=f.headers)):(s[h]=f.data,f.statusCode&&200!==f.statusCode&&!u&&(i=f.statusCode),f.headers&&(c[h]=f.headers))}),void 0!==d&&r&&(l={[r[0]]:d},s[r[0]]=void 0),{loaderData:s,errors:l,statusCode:i||200,loaderHeaders:c}}function Le(e,r,a,o,i,s,l){let{loaderData:u,errors:c}=xe(r,a,o,l,!1);return i.forEach(r=>{let{key:a,match:o,controller:i}=r,l=s[a];if(n(l,"Did not find corresponding fetcher result"),!i||!i.signal.aborted)if(Ie(l)){let r=je(e.matches,null==o?void 0:o.route.id);c&&c[r.route.id]||(c=t({},c,{[r.route.id]:l.error})),e.fetchers.delete(a)}else if(He(l))n(!1,"Unhandled fetcher revalidation redirect");else if(Oe(l))n(!1,"Unhandled fetcher deferred data");else{let t=Qe(l.data);e.fetchers.set(a,t)}}),{loaderData:u,errors:c}}function Ae(e,r,a,n){let o=t({},r);for(let t of a){let a=t.route.id;if(r.hasOwnProperty(a)?void 0!==r[a]&&(o[a]=r[a]):void 0!==e[a]&&t.route.loader&&(o[a]=e[a]),n&&n.hasOwnProperty(a))break}return o}function Me(e){return e?Ie(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function je(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>!0===e.route.hasErrorBoundary)||e[0]}function ke(e){let t=1===e.length?e[0]:e.find(e=>e.index||!e.path||"/"===e.path)||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Ce(e,t){let{pathname:r,routeId:a,method:n,type:o,message:i}=void 0===t?{}:t,s="Unknown Server Error",l="Unknown @remix-run/router error";return 400===e?(s="Bad Request",n&&r&&a?l="You made a "+n+' request to "'+r+'" but did not provide a `loader` for route "'+a+'", so there is no way to handle the request.':"defer-action"===o?l="defer() is not supported in actions":"invalid-body"===o&&(l="Unable to encode submission body")):403===e?(s="Forbidden",l='Route "'+a+'" does not match URL "'+r+'"'):404===e?(s="Not Found",l='No route matches URL "'+r+'"'):405===e&&(s="Method Not Allowed",n&&r&&a?l="You made a "+n.toUpperCase()+' request to "'+r+'" but did not provide an `action` for route "'+a+'", so there is no way to handle the request.':n&&(l='Invalid request method "'+n.toUpperCase()+'"')),new Y(e||500,s,new Error(l),!0)}function _e(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[r,a]=t[e];if(He(a))return{key:r,result:a}}}function Te(e){return l(t({},"string"==typeof e?u(e):e,{hash:""}))}function Ue(e){return Ne(e.result)&&Z.has(e.result.status)}function Oe(e){return e.type===d.deferred}function Ie(e){return e.type===d.error}function He(e){return(e&&e.type)===d.redirect}function ze(e){return"object"==typeof e&&null!=e&&"type"in e&&"data"in e&&"init"in e&&"DataWithResponseInit"===e.type}function Fe(e){let t=e;return t&&"object"==typeof t&&"object"==typeof t.data&&"function"==typeof t.subscribe&&"function"==typeof t.cancel&&"function"==typeof t.resolveData}function Ne(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"object"==typeof e.headers&&void 0!==e.body}function Be(e){return Q.has(e.toLowerCase())}function We(e){return X.has(e.toLowerCase())}async function $e(e,t,r,a,n){let o=Object.entries(t);for(let i=0;i<o.length;i++){let[s,l]=o[i],u=e.find(e=>(null==e?void 0:e.route.id)===s);if(!u)continue;let c=a.find(e=>e.route.id===u.route.id),d=null!=c&&!pe(c,u)&&void 0!==(n&&n[u.route.id]);Oe(l)&&d&&await Ke(l,r,!1).then(e=>{e&&(t[s]=e)})}}async function qe(e,t,r){for(let a=0;a<r.length;a++){let{key:o,routeId:i,controller:s}=r[a],l=t[o];e.find(e=>(null==e?void 0:e.route.id)===i)&&(Oe(l)&&(n(s,"Expected an AbortController for revalidating fetcher deferred result"),await Ke(l,s.signal,!0).then(e=>{e&&(t[o]=e)})))}}async function Ke(e,t,r){if(void 0===r&&(r=!1),!await e.deferredData.resolveData(t)){if(r)try{return{type:d.data,data:e.deferredData.unwrappedData}}catch(e){return{type:d.error,error:e}}return{type:d.data,data:e.deferredData.data}}}function Ye(e){return new URLSearchParams(e).getAll("index").some(e=>""===e)}function Je(e,t){let r="string"==typeof t?u(t).search:t.search;if(e[e.length-1].route.index&&Ye(r||""))return e[e.length-1];let a=T(e);return a[a.length-1]}function Ve(e){let{formMethod:t,formAction:r,formEncType:a,text:n,formData:o,json:i}=e;if(t&&r&&a)return null!=n?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:void 0,text:n}:null!=o?{formMethod:t,formAction:r,formEncType:a,formData:o,json:void 0,text:void 0}:void 0!==i?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:i,text:void 0}:void 0}function Xe(e,t){if(t){return{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}return{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Ge(e,t){if(e){return{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}}return{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Qe(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}e.AbortedDeferredError=W,e.Action=r,e.IDLE_BLOCKER=ae,e.IDLE_FETCHER=re,e.IDLE_NAVIGATION=te,e.UNSAFE_DEFERRED_SYMBOL=se,e.UNSAFE_DeferredData=$,e.UNSAFE_ErrorResponseImpl=Y,e.UNSAFE_convertRouteMatchToUiMatch=y,e.UNSAFE_convertRoutesToDataRoutes=f,e.UNSAFE_decodePath=M,e.UNSAFE_getResolveToMatches=U,e.UNSAFE_invariant=n,e.UNSAFE_warning=o,e.createBrowserHistory=function(e){return void 0===e&&(e={}),c(function(e,t){let{pathname:r,search:a,hash:n}=e.location;return s("",{pathname:r,search:a,hash:n},t.state&&t.state.usr||null,t.state&&t.state.key||"default")},function(e,t){return"string"==typeof t?t:l(t)},null,e)},e.createHashHistory=function(e){return void 0===e&&(e={}),c(function(e,t){let{pathname:r="/",search:a="",hash:n=""}=u(e.location.hash.substr(1));return r.startsWith("/")||r.startsWith(".")||(r="/"+r),s("",{pathname:r,search:a,hash:n},t.state&&t.state.usr||null,t.state&&t.state.key||"default")},function(e,t){let r=e.document.querySelector("base"),a="";if(r&&r.getAttribute("href")){let t=e.location.href,r=t.indexOf("#");a=-1===r?t:t.slice(0,r)}return a+"#"+("string"==typeof t?t:l(t))},function(e,t){o("/"===e.pathname.charAt(0),"relative pathnames are not supported in hash history.push("+JSON.stringify(t)+")")},e)},e.createMemoryHistory=function(e){void 0===e&&(e={});let t,{initialEntries:a=["/"],initialIndex:n,v5Compat:i=!1}=e;t=a.map((e,t)=>m(e,"string"==typeof e?null:e.state,0===t?"default":void 0));let c=f(null==n?t.length-1:n),d=r.Pop,h=null;function f(e){return Math.min(Math.max(e,0),t.length-1)}function p(){return t[c]}function m(e,r,a){void 0===r&&(r=null);let n=s(t?p().pathname:"/",e,r,a);return o("/"===n.pathname.charAt(0),"relative pathnames are not supported in memory history: "+JSON.stringify(e)),n}function y(e){return"string"==typeof e?e:l(e)}return{get index(){return c},get action(){return d},get location(){return p()},createHref:y,createURL:e=>new URL(y(e),"http://localhost"),encodeLocation(e){let t="string"==typeof e?u(e):e;return{pathname:t.pathname||"",search:t.search||"",hash:t.hash||""}},push(e,a){d=r.Push;let n=m(e,a);c+=1,t.splice(c,t.length,n),i&&h&&h({action:d,location:n,delta:1})},replace(e,a){d=r.Replace;let n=m(e,a);t[c]=n,i&&h&&h({action:d,location:n,delta:0})},go(e){d=r.Pop;let a=f(c+e),n=t[a];c=a,h&&h({action:d,location:n,delta:e})},listen:e=>(h=e,()=>{h=null})}},e.createPath=l,e.createRouter=function(e){const a=e.window?e.window:"undefined"!=typeof window?window:void 0,i=void 0!==a&&void 0!==a.document&&void 0!==a.document.createElement,l=!i;let u;if(n(e.routes.length>0,"You must provide a non-empty routes array to createRouter"),e.mapRouteProperties)u=e.mapRouteProperties;else if(e.detectErrorBoundary){let t=e.detectErrorBoundary;u=e=>({hasErrorBoundary:t(e)})}else u=oe;let c,h,v,g={},b=f(e.routes,u,void 0,g),w=e.basename||"/",S=e.dataStrategy||ge,D=e.patchRoutesOnNavigation,R=t({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),E=null,P=new Set,x=null,L=null,A=null,M=null!=e.hydrationData,k=p(b,e.history.location,w),C=!1,_=null;if(null==k&&!D){let t=Ce(404,{pathname:e.history.location.pathname}),{matches:r,route:a}=ke(b);k=r,_={[a.id]:t}}if(k&&!e.hydrationData){ct(k,b,e.history.location.pathname).active&&(k=null)}if(k)if(k.some(e=>e.route.lazy))h=!1;else if(k.some(e=>e.route.loader))if(R.v7_partialHydration){let t=e.hydrationData?e.hydrationData.loaderData:null,r=e.hydrationData?e.hydrationData.errors:null;if(r){let e=k.findIndex(e=>void 0!==r[e.route.id]);h=k.slice(0,e+1).every(e=>!fe(e.route,t,r))}else h=k.every(e=>!fe(e.route,t,r))}else h=null!=e.hydrationData;else h=!0;else if(h=!1,k=[],R.v7_partialHydration){let t=ct(null,b,e.history.location.pathname);t.active&&t.matches&&(C=!0,k=t.matches)}let T,U,O={historyAction:e.history.action,location:e.history.location,matches:k,initialized:h,navigation:te,restoreScrollPosition:null==e.hydrationData&&null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||_,fetchers:new Map,blockers:new Map},I=r.Pop,H=!1,z=!1,F=new Map,N=null,B=!1,W=!1,$=[],q=new Set,K=new Map,Y=0,V=-1,X=new Map,G=new Set,Q=new Map,Z=new Map,se=new Set,le=new Map,de=new Map;function pe(e,r){void 0===r&&(r={}),O=t({},O,e);let a=[],n=[];R.v7_fetcherPersist&&O.fetchers.forEach((e,t)=>{"idle"===e.state&&(se.has(t)?n.push(t):a.push(t))}),se.forEach(e=>{O.fetchers.has(e)||K.has(e)||n.push(e)}),[...P].forEach(e=>e(O,{deletedFetchers:n,viewTransitionOpts:r.viewTransitionOpts,flushSync:!0===r.flushSync})),R.v7_fetcherPersist?(a.forEach(e=>O.fetchers.delete(e)),n.forEach(e=>Ye(e))):n.forEach(e=>se.delete(e))}function me(a,n,o){var i,s;let l,{flushSync:u}=void 0===o?{}:o,d=null!=O.actionData&&null!=O.navigation.formMethod&&We(O.navigation.formMethod)&&"loading"===O.navigation.state&&!0!==(null==(i=a.state)?void 0:i._isRedirect);l=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:d?O.actionData:null;let h=n.loaderData?Ae(O.loaderData,n.loaderData,n.matches||[],n.errors):O.loaderData,f=O.blockers;f.size>0&&(f=new Map(f),f.forEach((e,t)=>f.set(t,ae)));let p,m=!0===H||null!=O.navigation.formMethod&&We(O.navigation.formMethod)&&!0!==(null==(s=a.state)?void 0:s._isRedirect);if(c&&(b=c,c=void 0),B||I===r.Pop||(I===r.Push?e.history.push(a,a.state):I===r.Replace&&e.history.replace(a,a.state)),I===r.Pop){let e=F.get(O.location.pathname);e&&e.has(a.pathname)?p={currentLocation:O.location,nextLocation:a}:F.has(a.pathname)&&(p={currentLocation:a,nextLocation:O.location})}else if(z){let e=F.get(O.location.pathname);e?e.add(a.pathname):(e=new Set([a.pathname]),F.set(O.location.pathname,e)),p={currentLocation:O.location,nextLocation:a}}pe(t({},n,{actionData:l,loaderData:h,historyAction:I,location:a,initialized:!0,navigation:te,revalidation:"idle",restoreScrollPosition:ut(a,n.matches||O.matches),preventScrollReset:m,blockers:f}),{viewTransitionOpts:p,flushSync:!0===u}),I=r.Pop,H=!1,z=!1,B=!1,W=!1,$=[]}async function ve(a,n,o){T&&T.abort(),T=null,I=a,B=!0===(o&&o.startUninterruptedRevalidation),function(e,t){if(x&&A){let r=lt(e,t);x[r]=A()}}(O.location,O.matches),H=!0===(o&&o.preventScrollReset),z=!0===(o&&o.enableViewTransition);let i=c||b,s=o&&o.overrideNavigation,l=null!=o&&o.initialHydration&&O.matches&&O.matches.length>0&&!C?O.matches:p(i,n,w),u=!0===(o&&o.flushSync);if(l&&O.initialized&&!W&&function(e,t){if(e.pathname!==t.pathname||e.search!==t.search)return!1;if(""===e.hash)return""!==t.hash;if(e.hash===t.hash)return!0;if(""!==t.hash)return!0;return!1}(O.location,n)&&!(o&&o.submission&&We(o.submission.formMethod)))return void me(n,{matches:l},{flushSync:u});let h=ct(l,i,n.pathname);if(h.active&&h.matches&&(l=h.matches),!l){let{error:e,notFoundMatches:t,route:r}=it(n.pathname);return void me(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:u})}T=new AbortController;let f,m=Re(e.history,n,T.signal,o&&o.submission);if(o&&o.pendingError)f=[je(l).route.id,{type:d.error,error:o.pendingError}];else if(o&&o.submission&&We(o.submission.formMethod)){let t=await async function(t,a,n,o,i,s){void 0===s&&(s={});ze();let l,u=function(e,t){let r={state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text};return r}(a,n);if(pe({navigation:u},{flushSync:!0===s.flushSync}),i){let e=await dt(o,a.pathname,t.signal);if("aborted"===e.type)return{shortCircuited:!0};if("error"===e.type){let t=je(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:d.error,error:e.error}]}}if(!e.matches){let{notFoundMatches:e,error:t,route:r}=it(a.pathname);return{matches:e,pendingActionResult:[r.id,{type:d.error,error:t}]}}o=e.matches}let c=Je(o,a);if(c.route.action||c.route.lazy){if(l=(await xe("action",O,t,[c],o,null))[c.route.id],t.signal.aborted)return{shortCircuited:!0}}else l={type:d.error,error:Ce(405,{method:t.method,pathname:a.pathname,routeId:c.route.id})};if(He(l)){let r;if(s&&null!=s.replace)r=s.replace;else{r=De(l.response.headers.get("Location"),new URL(t.url),w,e.history)===O.location.pathname+O.location.search}return await Pe(t,l,!0,{submission:n,replace:r}),{shortCircuited:!0}}if(Oe(l))throw Ce(400,{type:"defer-action"});if(Ie(l)){let e=je(o,c.route.id);return!0!==(s&&s.replace)&&(I=r.Push),{matches:o,pendingActionResult:[e.route.id,l]}}return{matches:o,pendingActionResult:[c.route.id,l]}}(m,n,o.submission,l,h.active,{replace:o.replace,flushSync:u});if(t.shortCircuited)return;if(t.pendingActionResult){let[e,r]=t.pendingActionResult;if(Ie(r)&&J(r.error)&&404===r.error.status)return T=null,void me(n,{matches:t.matches,loaderData:{},errors:{[e]:r.error}})}l=t.matches||l,f=t.pendingActionResult,s=Xe(n,o.submission),u=!1,h.active=!1,m=Re(e.history,m.url,m.signal)}let{shortCircuited:y,matches:v,loaderData:g,errors:S}=await async function(r,a,n,o,i,s,l,u,d,h,f){let p=i||Xe(a,s),m=s||l||Ve(p),y=!(B||R.v7_partialHydration&&d);if(o){if(y){let e=Ee(f);pe(t({navigation:p},void 0!==e?{actionData:e}:{}),{flushSync:h})}let e=await dt(n,a.pathname,r.signal);if("aborted"===e.type)return{shortCircuited:!0};if("error"===e.type){let t=je(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(!e.matches){let{error:e,notFoundMatches:t,route:r}=it(a.pathname);return{matches:t,loaderData:{},errors:{[r.id]:e}}}n=e.matches}let v=c||b,[g,S]=he(e.history,O,n,m,a,R.v7_partialHydration&&!0===d,R.v7_skipActionErrorRevalidation,W,$,q,se,Q,G,v,w,f);if(st(e=>!(n&&n.some(t=>t.route.id===e))||g&&g.some(t=>t.route.id===e)),V=++Y,0===g.length&&0===S.length){let e=tt();return me(a,t({matches:n,loaderData:{},errors:f&&Ie(f[1])?{[f[0]]:f[1].error}:null},Me(f),e?{fetchers:new Map(O.fetchers)}:{}),{flushSync:h}),{shortCircuited:!0}}if(y){let e={};if(!o){e.navigation=p;let t=Ee(f);void 0!==t&&(e.actionData=t)}S.length>0&&(e.fetchers=function(e){return e.forEach(e=>{let t=O.fetchers.get(e.key),r=Ge(void 0,t?t.data:void 0);O.fetchers.set(e.key,r)}),new Map(O.fetchers)}(S)),pe(e,{flushSync:h})}S.forEach(e=>{Ze(e.key),e.controller&&K.set(e.key,e.controller)});let D=()=>S.forEach(e=>Ze(e.key));T&&T.signal.addEventListener("abort",D);let{loaderResults:E,fetcherResults:P}=await Te(O,n,g,S,r);if(r.signal.aborted)return{shortCircuited:!0};T&&T.signal.removeEventListener("abort",D);S.forEach(e=>K.delete(e.key));let x=_e(E);if(x)return await Pe(r,x.result,!0,{replace:u}),{shortCircuited:!0};if(x=_e(P),x)return G.add(x.key),await Pe(r,x.result,!0,{replace:u}),{shortCircuited:!0};let{loaderData:L,errors:A}=Le(O,n,E,f,S,P,le);le.forEach((e,t)=>{e.subscribe(r=>{(r||e.done)&&le.delete(t)})}),R.v7_partialHydration&&d&&O.errors&&(A=t({},O.errors,A));let M=tt(),j=rt(V),k=M||j||S.length>0;return t({matches:n,loaderData:L,errors:A},k?{fetchers:new Map(O.fetchers)}:{})}(m,n,l,h.active,s,o&&o.submission,o&&o.fetcherSubmission,o&&o.replace,o&&!0===o.initialHydration,u,f);y||(T=null,me(n,t({matches:v||l},Me(f),{loaderData:g,errors:S})))}function Ee(e){return e&&!Ie(e[1])?{[e[0]]:e[1].data}:O.actionData?0===Object.keys(O.actionData).length?null:O.actionData:void 0}async function Pe(o,l,u,c){let{submission:d,fetcherSubmission:h,preventScrollReset:f,replace:p}=void 0===c?{}:c;l.response.headers.has("X-Remix-Revalidate")&&(W=!0);let m=l.response.headers.get("Location");n(m,"Expected a Location header on the redirect Response"),m=De(m,new URL(o.url),w,e.history);let y=s(O.location,m,{_isRedirect:!0});if(i){let t=!1;if(l.response.headers.has("X-Remix-Reload-Document"))t=!0;else if(ne.test(m)){const r=e.history.createURL(m);t=r.origin!==a.location.origin||null==j(r.pathname,w)}if(t)return void(p?a.location.replace(m):a.location.assign(m))}T=null;let v=!0===p||l.response.headers.has("X-Remix-Replace")?r.Replace:r.Push,{formMethod:g,formAction:b,formEncType:S}=O.navigation;!d&&!h&&g&&b&&S&&(d=Ve(O.navigation));let D=d||h;if(ee.has(l.response.status)&&D&&We(D.formMethod))await ve(v,y,{submission:t({},D,{formAction:m}),preventScrollReset:f||H,enableViewTransition:u?z:void 0});else{let e=Xe(y,d);await ve(v,y,{overrideNavigation:e,fetcherSubmission:h,preventScrollReset:f||H,enableViewTransition:u?z:void 0})}}async function xe(e,t,r,a,n,o){let i,s={};try{i=await be(S,e,t,r,a,n,o,g,u)}catch(e){return a.forEach(t=>{s[t.route.id]={type:d.error,error:e}}),s}for(let[e,t]of Object.entries(i))if(Ue(t)){let a=t.result;s[e]={type:d.redirect,response:Se(a,r,e,n,w,R.v7_relativeSplatPath)}}else s[e]=await we(t);return s}async function Te(t,r,a,n,o){let i=t.matches,s=xe("loader",t,o,a,r,null),l=Promise.all(n.map(async r=>{if(r.matches&&r.match&&r.controller){let a=(await xe("loader",t,Re(e.history,r.path,r.controller.signal),[r.match],r.matches,r.key))[r.match.route.id];return{[r.key]:a}}return Promise.resolve({[r.key]:{type:d.error,error:Ce(404,{pathname:r.path})}})})),u=await s,c=(await l).reduce((e,t)=>Object.assign(e,t),{});return await Promise.all([$e(r,u,o.signal,i,t.loaderData),qe(r,c,n)]),{loaderResults:u,fetcherResults:c}}function ze(){W=!0,$.push(...st()),Q.forEach((e,t)=>{K.has(t)&&q.add(t),Ze(t)})}function Fe(e,t,r){void 0===r&&(r={}),O.fetchers.set(e,t),pe({fetchers:new Map(O.fetchers)},{flushSync:!0===(r&&r.flushSync)})}function Ne(e,t,r,a){void 0===a&&(a={});let n=je(O.matches,t);Ye(e),pe({errors:{[n.route.id]:r},fetchers:new Map(O.fetchers)},{flushSync:!0===(a&&a.flushSync)})}function Be(e){return Z.set(e,(Z.get(e)||0)+1),se.has(e)&&se.delete(e),O.fetchers.get(e)||re}function Ye(e){let t=O.fetchers.get(e);!K.has(e)||t&&"loading"===t.state&&X.has(e)||Ze(e),Q.delete(e),X.delete(e),G.delete(e),R.v7_fetcherPersist&&se.delete(e),q.delete(e),O.fetchers.delete(e)}function Ze(e){let t=K.get(e);t&&(t.abort(),K.delete(e))}function et(e){for(let t of e){let e=Qe(Be(t).data);O.fetchers.set(t,e)}}function tt(){let e=[],t=!1;for(let r of G){let a=O.fetchers.get(r);n(a,"Expected fetcher: "+r),"loading"===a.state&&(G.delete(r),e.push(r),t=!0)}return et(e),t}function rt(e){let t=[];for(let[r,a]of X)if(a<e){let e=O.fetchers.get(r);n(e,"Expected fetcher: "+r),"loading"===e.state&&(Ze(r),X.delete(r),t.push(r))}return et(t),t.length>0}function at(e){O.blockers.delete(e),de.delete(e)}function nt(e,t){let r=O.blockers.get(e)||ae;n("unblocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"proceeding"===t.state||"blocked"===r.state&&"unblocked"===t.state||"proceeding"===r.state&&"unblocked"===t.state,"Invalid blocker state transition: "+r.state+" -> "+t.state);let a=new Map(O.blockers);a.set(e,t),pe({blockers:a})}function ot(e){let{currentLocation:t,nextLocation:r,historyAction:a}=e;if(0===de.size)return;de.size>1&&o(!1,"A router only supports one blocker at a time");let n=Array.from(de.entries()),[i,s]=n[n.length-1],l=O.blockers.get(i);return l&&"proceeding"===l.state?void 0:s({currentLocation:t,nextLocation:r,historyAction:a})?i:void 0}function it(e){let t=Ce(404,{pathname:e}),r=c||b,{matches:a,route:n}=ke(r);return st(),{notFoundMatches:a,route:n,error:t}}function st(e){let t=[];return le.forEach((r,a)=>{e&&!e(a)||(r.cancel(),t.push(a),le.delete(a))}),t}function lt(e,t){if(L){return L(e,t.map(e=>y(e,O.loaderData)))||e.key}return e.key}function ut(e,t){if(x){let r=lt(e,t),a=x[r];if("number"==typeof a)return a}return null}function ct(e,t,r){if(D){if(!e){return{active:!0,matches:m(t,r,w,!0)||[]}}if(Object.keys(e[0].params).length>0){return{active:!0,matches:m(t,r,w,!0)}}}return{active:!1,matches:null}}async function dt(e,t,r,a){if(!D)return{type:"success",matches:e};let n=e;for(;;){let e=null==c,o=c||b,i=g;try{await D({signal:r,path:t,matches:n,fetcherKey:a,patch:(e,t)=>{r.aborted||ye(e,t,o,i,u)}})}catch(e){return{type:"error",error:e,partialMatches:n}}finally{e&&!r.aborted&&(b=[...b])}if(r.aborted)return{type:"aborted"};let s=p(o,t,w);if(s)return{type:"success",matches:s};let l=m(o,t,w,!0);if(!l||n.length===l.length&&n.every((e,t)=>e.route.id===l[t].route.id))return{type:"success",matches:null};n=l}}return v={get basename(){return w},get future(){return R},get state(){return O},get routes(){return b},get window(){return a},initialize:function(){if(E=e.history.listen(t=>{let{action:r,location:a,delta:n}=t;if(U)return U(),void(U=void 0);o(0===de.size||null!=n,"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 i=ot({currentLocation:O.location,nextLocation:a,historyAction:r});if(i&&null!=n){let t=new Promise(e=>{U=e});return e.history.go(-1*n),void nt(i,{state:"blocked",location:a,proceed(){nt(i,{state:"proceeding",proceed:void 0,reset:void 0,location:a}),t.then(()=>e.history.go(n))},reset(){let e=new Map(O.blockers);e.set(i,ae),pe({blockers:e})}})}return ve(r,a)}),i){!function(e,t){try{let r=e.sessionStorage.getItem(ie);if(r){let e=JSON.parse(r);for(let[r,a]of Object.entries(e||{}))a&&Array.isArray(a)&&t.set(r,new Set(a||[]))}}catch(e){}}(a,F);let e=()=>function(e,t){if(t.size>0){let r={};for(let[e,a]of t)r[e]=[...a];try{e.sessionStorage.setItem(ie,JSON.stringify(r))}catch(e){o(!1,"Failed to save applied view transitions in sessionStorage ("+e+").")}}}(a,F);a.addEventListener("pagehide",e),N=()=>a.removeEventListener("pagehide",e)}return O.initialized||ve(r.Pop,O.location,{initialHydration:!0}),v},subscribe:function(e){return P.add(e),()=>P.delete(e)},enableScrollRestoration:function(e,t,r){if(x=e,A=t,L=r||null,!M&&O.navigation===te){M=!0;let e=ut(O.location,O.matches);null!=e&&pe({restoreScrollPosition:e})}return()=>{x=null,A=null,L=null}},navigate:async function a(n,o){if("number"==typeof n)return void e.history.go(n);let i=ue(O.location,O.matches,w,R.v7_prependBasename,n,R.v7_relativeSplatPath,null==o?void 0:o.fromRouteId,null==o?void 0:o.relative),{path:l,submission:u,error:c}=ce(R.v7_normalizeFormMethod,!1,i,o),d=O.location,h=s(O.location,l,o&&o.state);h=t({},h,e.history.encodeLocation(h));let f=o&&null!=o.replace?o.replace:void 0,p=r.Push;!0===f?p=r.Replace:!1===f||null!=u&&We(u.formMethod)&&u.formAction===O.location.pathname+O.location.search&&(p=r.Replace);let m=o&&"preventScrollReset"in o?!0===o.preventScrollReset:void 0,y=!0===(o&&o.flushSync),v=ot({currentLocation:d,nextLocation:h,historyAction:p});if(!v)return await ve(p,h,{submission:u,pendingError:c,preventScrollReset:m,replace:o&&o.replace,enableViewTransition:o&&o.viewTransition,flushSync:y});nt(v,{state:"blocked",location:h,proceed(){nt(v,{state:"proceeding",proceed:void 0,reset:void 0,location:h}),a(n,o)},reset(){let e=new Map(O.blockers);e.set(v,ae),pe({blockers:e})}})},fetch:function(t,r,a,o){if(l)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.");Ze(t);let i=!0===(o&&o.flushSync),s=c||b,u=ue(O.location,O.matches,w,R.v7_prependBasename,a,R.v7_relativeSplatPath,r,null==o?void 0:o.relative),d=p(s,u,w),h=ct(d,s,u);if(h.active&&h.matches&&(d=h.matches),!d)return void Ne(t,r,Ce(404,{pathname:u}),{flushSync:i});let{path:f,submission:m,error:y}=ce(R.v7_normalizeFormMethod,!0,u,o);if(y)return void Ne(t,r,y,{flushSync:i});let v=Je(d,f),g=!0===(o&&o.preventScrollReset);m&&We(m.formMethod)?async function(t,r,a,o,i,s,l,u,d){function h(e){if(!e.route.action&&!e.route.lazy){let e=Ce(405,{method:d.formMethod,pathname:a,routeId:r});return Ne(t,r,e,{flushSync:l}),!0}return!1}if(ze(),Q.delete(t),!s&&h(o))return;let f=O.fetchers.get(t);Fe(t,function(e,t){let r={state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0};return r}(d,f),{flushSync:l});let m=new AbortController,y=Re(e.history,a,m.signal,d);if(s){let e=await dt(i,new URL(y.url).pathname,y.signal,t);if("aborted"===e.type)return;if("error"===e.type)return void Ne(t,r,e.error,{flushSync:l});if(!e.matches)return void Ne(t,r,Ce(404,{pathname:a}),{flushSync:l});if(h(o=Je(i=e.matches,a)))return}K.set(t,m);let v=Y,g=await xe("action",O,y,[o],i,t),S=g[o.route.id];if(y.signal.aborted)return void(K.get(t)===m&&K.delete(t));if(R.v7_fetcherPersist&&se.has(t)){if(He(S)||Ie(S))return void Fe(t,Qe(void 0))}else{if(He(S))return K.delete(t),V>v?void Fe(t,Qe(void 0)):(G.add(t),Fe(t,Ge(d)),Pe(y,S,!1,{fetcherSubmission:d,preventScrollReset:u}));if(Ie(S))return void Ne(t,r,S.error)}if(Oe(S))throw Ce(400,{type:"defer-action"});let D=O.navigation.location||O.location,E=Re(e.history,D,m.signal),P=c||b,x="idle"!==O.navigation.state?p(P,O.navigation.location,w):O.matches;n(x,"Didn't find any matches after fetcher action");let L=++Y;X.set(t,L);let A=Ge(d,S.data);O.fetchers.set(t,A);let[M,j]=he(e.history,O,x,d,D,!1,R.v7_skipActionErrorRevalidation,W,$,q,se,Q,G,P,w,[o.route.id,S]);j.filter(e=>e.key!==t).forEach(e=>{let t=e.key,r=O.fetchers.get(t),a=Ge(void 0,r?r.data:void 0);O.fetchers.set(t,a),Ze(t),e.controller&&K.set(t,e.controller)}),pe({fetchers:new Map(O.fetchers)});let k=()=>j.forEach(e=>Ze(e.key));m.signal.addEventListener("abort",k);let{loaderResults:C,fetcherResults:_}=await Te(O,x,M,j,E);if(m.signal.aborted)return;m.signal.removeEventListener("abort",k),X.delete(t),K.delete(t),j.forEach(e=>K.delete(e.key));let U=_e(C);if(U)return Pe(E,U.result,!1,{preventScrollReset:u});if(U=_e(_),U)return G.add(U.key),Pe(E,U.result,!1,{preventScrollReset:u});let{loaderData:H,errors:z}=Le(O,x,C,void 0,j,_,le);if(O.fetchers.has(t)){let e=Qe(S.data);O.fetchers.set(t,e)}rt(L),"loading"===O.navigation.state&&L>V?(n(I,"Expected pending action"),T&&T.abort(),me(O.navigation.location,{matches:x,loaderData:H,errors:z,fetchers:new Map(O.fetchers)})):(pe({errors:z,loaderData:Ae(O.loaderData,H,x,z),fetchers:new Map(O.fetchers)}),W=!1)}(t,r,f,v,d,h.active,i,g,m):(Q.set(t,{routeId:r,path:f}),async function(t,r,a,o,i,s,l,u,c){let d=O.fetchers.get(t);Fe(t,Ge(c,d?d.data:void 0),{flushSync:l});let h=new AbortController,f=Re(e.history,a,h.signal);if(s){let e=await dt(i,new URL(f.url).pathname,f.signal,t);if("aborted"===e.type)return;if("error"===e.type)return void Ne(t,r,e.error,{flushSync:l});if(!e.matches)return void Ne(t,r,Ce(404,{pathname:a}),{flushSync:l});o=Je(i=e.matches,a)}K.set(t,h);let p=Y,m=await xe("loader",O,f,[o],i,t),y=m[o.route.id];Oe(y)&&(y=await Ke(y,f.signal,!0)||y);K.get(t)===h&&K.delete(t);if(f.signal.aborted)return;if(se.has(t))return void Fe(t,Qe(void 0));if(He(y))return V>p?void Fe(t,Qe(void 0)):(G.add(t),void await Pe(f,y,!1,{preventScrollReset:u}));if(Ie(y))return void Ne(t,r,y.error);n(!Oe(y),"Unhandled fetcher deferred data"),Fe(t,Qe(y.data))}(t,r,f,v,d,h.active,i,g,m))},revalidate:function(){ze(),pe({revalidation:"loading"}),"submitting"!==O.navigation.state&&("idle"!==O.navigation.state?ve(I||O.historyAction,O.navigation.location,{overrideNavigation:O.navigation,enableViewTransition:!0===z}):ve(O.historyAction,O.location,{startUninterruptedRevalidation:!0}))},createHref:t=>e.history.createHref(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Be,deleteFetcher:function(e){let t=(Z.get(e)||0)-1;t<=0?(Z.delete(e),se.add(e),R.v7_fetcherPersist||Ye(e)):Z.set(e,t),pe({fetchers:new Map(O.fetchers)})},dispose:function(){E&&E(),N&&N(),P.clear(),T&&T.abort(),O.fetchers.forEach((e,t)=>Ye(t)),O.blockers.forEach((e,t)=>at(t))},getBlocker:function(e,t){let r=O.blockers.get(e)||ae;return de.get(e)!==t&&de.set(e,t),r},deleteBlocker:at,patchRoutes:function(e,t){let r=null==c;ye(e,t,c||b,g,u),r&&(b=[...b],pe({}))},_internalFetchControllers:K,_internalActiveDeferreds:le,_internalSetRoutes:function(e){g={},c=f(e,u,void 0,g)}},v},e.createStaticHandler=function(e,r){n(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let a,o={},i=(r?r.basename:null)||"/";if(null!=r&&r.mapRouteProperties)a=r.mapRouteProperties;else if(null!=r&&r.detectErrorBoundary){let e=r.detectErrorBoundary;a=t=>({hasErrorBoundary:e(t)})}else a=oe;let u=t({v7_relativeSplatPath:!1,v7_throwAbortReason:!1},r?r.future:null),c=f(e,a,void 0,o);async function h(e,r,a,o,i,s,l){n(e.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(We(e.method.toLowerCase())){let n=await async function(e,r,a,n,o,i,s){let l;if(a.route.action||a.route.lazy){l=(await y("action",e,[a],r,s,n,o))[a.route.id],e.signal.aborted&&le(e,s,u)}else{let t=Ce(405,{method:e.method,pathname:new URL(e.url).pathname,routeId:a.route.id});if(s)throw t;l={type:d.error,error:t}}if(He(l))throw new Response(null,{status:l.response.status,headers:{Location:l.response.headers.get("Location")}});if(Oe(l)){let e=Ce(400,{type:"defer-action"});if(s)throw e;l={type:d.error,error:e}}if(s){if(Ie(l))throw l.error;return{matches:[a],loaderData:{},actionData:{[a.route.id]:l.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let c=new Request(e.url,{headers:e.headers,redirect:e.redirect,signal:e.signal});if(Ie(l)){let e=i?a:je(r,a.route.id);return t({},await m(c,r,n,o,i,null,[e.route.id,l]),{statusCode:J(l.error)?l.error.status:null!=l.statusCode?l.statusCode:500,actionData:null,actionHeaders:t({},l.headers?{[a.route.id]:l.headers}:{})})}let h=await m(c,r,n,o,i,null);return t({},h,{actionData:{[a.route.id]:l.data}},l.statusCode?{statusCode:l.statusCode}:{},{actionHeaders:l.headers?{[a.route.id]:l.headers}:{}})}(e,a,l||Je(a,r),o,i,s,null!=l);return n}let n=await m(e,a,o,i,s,l);return Ne(n)?n:t({},n,{actionData:null,actionHeaders:{}})}catch(e){if(null!=(c=e)&&"object"==typeof c&&"type"in c&&"result"in c&&(c.type===d.data||c.type===d.error)&&Ne(e.result)){if(e.type===d.error)throw e.result;return e.result}if(function(e){if(!Ne(e))return!1;let t=e.status,r=e.headers.get("Location");return t>=300&&t<=399&&null!=r}(e))return e;throw e}var c}async function m(e,r,a,n,o,i,s){let l=null!=i;if(l&&(null==i||!i.route.loader)&&(null==i||!i.route.lazy))throw Ce(400,{method:e.method,pathname:new URL(e.url).pathname,routeId:null==i?void 0:i.route.id});let c=(i?[i]:s&&Ie(s[1])?de(r,s[0]):r).filter(e=>e.route.loader||e.route.lazy);if(0===c.length)return{matches:r,loaderData:r.reduce((e,t)=>Object.assign(e,{[t.route.id]:null}),{}),errors:s&&Ie(s[1])?{[s[0]]:s[1].error}:null,statusCode:200,loaderHeaders:{},activeDeferreds:null};let d=await y("loader",e,c,r,l,a,n);e.signal.aborted&&le(e,l,u);let h=new Map,f=xe(r,d,s,h,o),p=new Set(c.map(e=>e.route.id));return r.forEach(e=>{p.has(e.route.id)||(f.loaderData[e.route.id]=null)}),t({},f,{matches:r,activeDeferreds:h.size>0?Object.fromEntries(h.entries()):null})}async function y(e,t,r,n,s,l,c){let d=await be(c||ge,e,null,t,r,n,null,o,a,l),h={};return await Promise.all(n.map(async e=>{if(!(e.route.id in d))return;let r=d[e.route.id];if(Ue(r)){throw Se(r.result,t,e.route.id,n,i,u.v7_relativeSplatPath)}if(Ne(r.result)&&s)throw r;h[e.route.id]=await we(r)})),h}return{dataRoutes:c,query:async function(e,r){let{requestContext:a,skipLoaderErrorBubbling:n,dataStrategy:o}=void 0===r?{}:r,u=new URL(e.url),d=e.method,f=s("",l(u),null,"default"),m=p(c,f,i);if(!Be(d)&&"HEAD"!==d){let e=Ce(405,{method:d}),{matches:t,route:r}=ke(c);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}if(!m){let e=Ce(404,{pathname:f.pathname}),{matches:t,route:r}=ke(c);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let y=await h(e,f,m,a,o||null,!0===n,null);return Ne(y)?y:t({location:f,basename:i},y)},queryRoute:async function(e,t){let{routeId:r,requestContext:a,dataStrategy:n}=void 0===t?{}:t,o=new URL(e.url),u=e.method,d=s("",l(o),null,"default"),f=p(c,d,i);if(!Be(u)&&"HEAD"!==u&&"OPTIONS"!==u)throw Ce(405,{method:u});if(!f)throw Ce(404,{pathname:d.pathname});let m=r?f.find(e=>e.route.id===r):Je(f,d);if(r&&!m)throw Ce(403,{pathname:d.pathname,routeId:r});if(!m)throw Ce(404,{pathname:d.pathname});let y=await h(e,d,f,a,n||null,!1,m);if(Ne(y))return y;let v=y.errors?Object.values(y.errors)[0]:void 0;if(void 0!==v)throw v;if(y.actionData)return Object.values(y.actionData)[0];if(y.loaderData){var g;let e=Object.values(y.loaderData)[0];return null!=(g=y.activeDeferreds)&&g[m.route.id]&&(e[se]=y.activeDeferreds[m.route.id]),e}}}},e.data=function(e,t){return new B(e,"number"==typeof t?{status:t}:t)},e.defer=function(e,t){return void 0===t&&(t={}),new $(e,"number"==typeof t?{status:t}:t)},e.generatePath=function(e,t){void 0===t&&(t={});let r=e;r.endsWith("*")&&"*"!==r&&!r.endsWith("/*")&&(o(!1,'Route path "'+r+'" will be treated as if it were "'+r.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+r.replace(/\*$/,"/*")+'".'),r=r.replace(/\*$/,"/*"));const a=r.startsWith("/")?"/":"",i=e=>null==e?"":"string"==typeof e?e:String(e);return a+r.split(/\/+/).map((e,r,a)=>{if(r===a.length-1&&"*"===e){return i(t["*"])}const o=e.match(/^:([\w-]+)(\??)$/);if(o){const[,e,r]=o;let a=t[e];return n("?"===r||null!=a,'Missing ":'+e+'" param'),i(a)}return e.replace(/\?$/g,"")}).filter(e=>!!e).join("/")},e.getStaticContextFromError=function(e,r,a){return t({},r,{statusCode:J(a)?a.status:500,errors:{[r._deepestRenderedBoundaryId||e[0].id]:a}})},e.getToPathname=function(e){return""===e||""===e.pathname?"/":"string"==typeof e?u(e).pathname:e.pathname},e.isDataWithResponseInit=ze,e.isDeferredData=Fe,e.isRouteErrorResponse=J,e.joinPaths=H,e.json=function(e,r){void 0===r&&(r={});let a="number"==typeof r?{status:r}:r,n=new Headers(a.headers);return n.has("Content-Type")||n.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),t({},a,{headers:n}))},e.matchPath=A,e.matchRoutes=p,e.normalizePathname=z,e.parsePath=u,e.redirect=K,e.redirectDocument=(e,t)=>{let r=K(e,t);return r.headers.set("X-Remix-Reload-Document","true"),r},e.replace=(e,t)=>{let r=K(e,t);return r.headers.set("X-Remix-Replace","true"),r},e.resolvePath=k,e.resolveTo=O,e.stripBasename=j,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=router.umd.min.js.map
{"version":3,"file":"router.umd.min.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n\n  /**\n   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n  idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 1 });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nexport function warning(cond: any, message: string) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience, so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\n  };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n  current: string | Location,\n  to: To,\n  state: any = null,\n  key?: string\n): Readonly<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): URL {\n    // window.location.origin is \"null\" (the literal string value) in Firefox\n    // under certain conditions, notably when serving from a local HTML file\n    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n    let base =\n      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\n    invariant(\n      base,\n      `No window.location.(origin|href) available to create URL for href: ${href}`\n    );\n    return new URL(href, base);\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n  [routeId: string]: any;\n}\n\nexport enum ResultType {\n  data = \"data\",\n  deferred = \"deferred\",\n  redirect = \"redirect\",\n  error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n  type: ResultType.data;\n  data: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n  type: ResultType.deferred;\n  deferredData: DeferredData;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n  | SuccessResult\n  | DeferredResult\n  | RedirectResult\n  | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\n    };\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n  currentUrl: URL;\n  currentParams: AgnosticDataRouteMatch[\"params\"];\n  nextUrl: URL;\n  nextParams: AgnosticDataRouteMatch[\"params\"];\n  formMethod?: Submission[\"formMethod\"];\n  formAction?: Submission[\"formAction\"];\n  formEncType?: Submission[\"formEncType\"];\n  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature.  This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments.  It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n  (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => DataFunctionReturnValue\n  ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n  fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n  signal: AbortSignal;\n  path: string;\n  matches: M[];\n  fetcherKey: string | undefined;\n  patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param extends `${infer Optional}?`\n      ? Optional\n      : Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\" | \"/*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if you could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(index)];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(\n      route.index !== true || !route.children,\n      `Cannot specify children on an index route`\n    );\n    invariant(\n      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\n\n      return pathOrLayoutRoute;\n    }\n  });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  let decoded = decodePath(pathname);\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array, so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children, so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explode _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string,\n  allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\n\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams as Params<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, compiledParams] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let params: CompiledPathParam[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex, so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\n  } catch (error) {\n    warning(\n      false,\n      `The URL path \"${value}\" could not be decoded because it is is a ` +\n        `malformed URL segment. This is probably due to a bad percent ` +\n        `encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n  pathname: string,\n  basename: string\n): string | null {\n  if (basename === \"/\") return pathname;\n\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  }\n\n  // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n  let startIndex = basename.endsWith(\"/\")\n    ? basename.length - 1\n    : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n\n  return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\",\n  } = typeof to === \"string\" ? parsePath(to) : to;\n\n  let pathname: string;\n  if (toPathname) {\n    toPathname = removeDoubleSlashes(toPathname);\n    if (toPathname.startsWith(\"/\")) {\n      pathname = resolvePathname(toPathname.substring(1), \"/\");\n    } else {\n      pathname = resolvePathname(toPathname, fromPathname);\n    }\n  } else {\n    pathname = fromPathname;\n  }\n\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash),\n  };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\n\n  relativeSegments.forEach((segment) => {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n  toArg: To,\n  routePathnames: string[],\n  locationPathname: string,\n  isPathRelative = false\n): Path {\n  let to: Partial<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || (to as Path).pathname === \"\"\n    ? \"/\"\n    : typeof to === \"string\"\n    ? parsePath(to).pathname\n    : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n  path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n  removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n  data: Data,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  let headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n\n  return new Response(JSON.stringify(data), {\n    ...responseInit,\n    headers,\n  });\n};\n\nexport class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\n  );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n    invariant(\n      data && typeof data === \"object\" && !Array.isArray(data),\n      \"defer() only accepts plain objects\"\n    );\n\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject: (e: AbortedDeferredError) => void;\n    this.abortPromise = new Promise((_, r) => (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =>\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =>\n      this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n\n    this.data = Object.entries(data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: this.trackPromise(key, value),\n        }),\n      {}\n    );\n\n    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.add(key);\n\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n      (data) => this.onSettle(promise, key, undefined, data as unknown),\n      (error) => this.onSettle(promise, key, error as unknown)\n    );\n\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () => true });\n    return promise;\n  }\n\n  private onSettle(\n    promise: TrackedPromise,\n    key: string,\n    error: unknown,\n    data?: unknown\n  ): unknown {\n    if (\n      this.controller.signal.aborted &&\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      return Promise.reject(error);\n    }\n\n    this.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(true);\n  }\n\n  async resolveData(signal: AbortSignal) {\n    let aborted = false;\n    if (!this.done) {\n      let onAbort = () => this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) => {\n        this.subscribe((aborted) => {\n          signal.removeEventListener(\"abort\", onAbort);\n          if (aborted || this.done) {\n            resolve(aborted);\n          }\n        });\n      });\n    }\n    return aborted;\n  }\n\n  get done() {\n    return this.pendingKeysSet.size === 0;\n  }\n\n  get unwrappedData() {\n    invariant(\n      this.data !== null && this.done,\n      \"Can only unwrap data on initialized and settled deferreds\"\n    );\n\n    return Object.entries(this.data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: unwrapTrackedPromise(value),\n        }),\n      {}\n    );\n  }\n\n  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\n  }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n  return (\n    value instanceof Promise && (value as TrackedPromise)._tracked === true\n  );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\n\nexport type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n  url: string,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = { status: responseInit };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n\n  return new Response(null, {\n    ...responseInit,\n    headers,\n  });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private internal: boolean;\n\n  constructor(\n    status: number,\n    statusText: string | undefined,\n    data: any,\n    internal = false\n  ) {\n    this.status = status;\n    this.statusText = statusText || \"\";\n    this.internal = internal;\n    if (data instanceof Error) {\n      this.data = data.toString();\n      this.error = data;\n    } else {\n      this.data = data;\n    }\n  }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  DataStrategyResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnNavigationFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  removeDoubleSlashes,\n  resolveTo,\n  stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the basename for the router\n   */\n  get basename(): RouterInit[\"basename\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the future config for the router\n   */\n  get future(): FutureConfig;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the current state of the router\n   */\n  get state(): RouterState;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the routes for this router instance\n   */\n  get routes(): AgnosticDataRouteObject[];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Initialize the router, including adding history listeners and kicking off\n   * initial data fetches.  Returns a function to cleanup listeners and abort\n   * any in-progress loads\n   */\n  initialize(): Router;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Subscribe to router.state updates\n   *\n   * @param fn function to call with the new state\n   */\n  subscribe(fn: RouterSubscriber): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Enable scroll restoration behavior in the router\n   *\n   * @param savedScrollPositions Object that will manage positions, in case\n   *                             it's being restored from sessionStorage\n   * @param getScrollPosition    Function to get the active Y scroll position\n   * @param getKey               Function to get the key to use for restoration\n   */\n  enableScrollRestoration(\n    savedScrollPositions: Record<string, number>,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Navigate forward/backward in the history stack\n   * @param to Delta to move in the history stack\n   */\n  navigate(to: number): Promise<void>;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a fetcher load/submission\n   *\n   * @param key     Fetcher key\n   * @param routeId Route that owns the fetcher\n   * @param href    href to fetch\n   * @param opts    Fetcher options, (method, submission, etc.)\n   */\n  fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a revalidation of all current route loaders and fetcher loads\n   */\n  revalidate(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to create an href for the given location\n   * @param location\n   */\n  createHref(location: Location | URL): string;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to URL encode a destination path according to the internal\n   * history implementation\n   * @param to\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get/create a fetcher for the given key\n   * @param key\n   */\n  getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete the fetcher for a given key\n   * @param key\n   */\n  deleteFetcher(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Cleanup listeners and abort any in-progress loads\n   */\n  dispose(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal fetch AbortControllers accessed by unit tests\n   */\n  _internalFetchControllers: Map<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router.  During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n  /**\n   * The action of the most recent navigation\n   */\n  historyAction: HistoryAction;\n\n  /**\n   * The current location reflected by the router\n   */\n  location: Location;\n\n  /**\n   * The current set of route matches\n   */\n  matches: AgnosticDataRouteMatch[];\n\n  /**\n   * Tracks whether we've completed our initial data load\n   */\n  initialized: boolean;\n\n  /**\n   * Current scroll position we should start at for a new view\n   *  - number -> scroll position to restore to\n   *  - false -> do not restore scroll at all (used during submissions)\n   *  - null -> don't have a saved position, scroll to hash or top of page\n   */\n  restoreScrollPosition: number | false | null;\n\n  /**\n   * Indicate whether this navigation should skip resetting the scroll position\n   * if we are unable to restore the scroll position\n   */\n  preventScrollReset: boolean;\n\n  /**\n   * Tracks the state of the current navigation\n   */\n  navigation: Navigation;\n\n  /**\n   * Tracks any in-progress revalidations\n   */\n  revalidation: RevalidationState;\n\n  /**\n   * Data from the loaders for the current matches\n   */\n  loaderData: RouteData;\n\n  /**\n   * Data from the action for the current matches\n   */\n  actionData: RouteData | null;\n\n  /**\n   * Errors caught from loaders for the current matches\n   */\n  errors: RouteData | null;\n\n  /**\n   * Map of current fetchers\n   */\n  fetchers: Map<string, Fetcher>;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  activeDeferreds: Record<string, DeferredData> | null;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      viewTransitionOpts?: ViewTransitionOpts;\n      flushSync: boolean;\n    }\n  ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n  (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n  Idle: {\n    state: \"idle\";\n    location: undefined;\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\n  };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n  Idle: {\n    state: \"idle\";\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n  /**\n   * startNavigation does not need to complete the navigation because we\n   * redirected or got interrupted\n   */\n  shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * loaderData returned from the current set of loaders\n   */\n  loaderData?: RouterState[\"loaderData\"];\n  /**\n   * errors thrown from the current set of loaders\n   */\n  errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n  \"post\",\n  \"put\",\n  \"patch\",\n  \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\n  // Cleanup function for history\n  let unlistenHistory: (() => void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialMatchesIsFOW = false;\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    let error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname,\n    });\n    let { matches, route } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = { [route.id]: error };\n  }\n\n  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnNavigation` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatchesIsFOW = true;\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n      );\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\n\n  let router: Router;\n  let state: RouterState = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n    errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n    fetchers: new Map(),\n    blockers: new Map(),\n  };\n\n  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction: HistoryAction = HistoryAction.Pop;\n\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\n  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes: string[] = [];\n\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\n  // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n  let activeDeferreds = new Map<string, DeferredData>();\n\n  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n  // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(\n      ({ action: historyAction, location, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (unblockBlockerHistoryUpdate) {\n          unblockBlockerHistoryUpdate();\n          unblockBlockerHistoryUpdate = undefined;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n            unblockBlockerHistoryUpdate = resolve;\n          });\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked, after the url\n              // restoration is also complete.  See:\n              // https://github.com/remix-run/react-router/issues/11613\n              nextHistoryUpdatePromise.then(() => init.history.go(delta));\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\n    }\n\n    return router;\n  }\n\n  // Clean up a router and it's side effects\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Remove any lingering deleted fetchers that have already been removed\n    // from state.fetchers\n    deletedFetchers.forEach((key) => {\n      if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n        deletedFetchersKeys.push(key);\n      }\n    });\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        viewTransitionOpts: opts.viewTransitionOpts,\n        flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    } else {\n      // We already called deleteFetcher() on these, can remove them from this\n      // Set now that we've handed the keys off to the data layer\n      deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n    }\n  }\n\n  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n  function completeNavigation(\n    location: Location,\n    newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n    { flushSync }: { flushSync?: boolean } = {}\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\n    }\n\n    if (isUninterruptedRevalidation) {\n      // If this was an uninterrupted revalidation then do not touch history\n    } else if (pendingAction === HistoryAction.Pop) {\n      // Do nothing for POP - URL has already been updated\n    } else if (pendingAction === HistoryAction.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === HistoryAction.Replace) {\n      init.history.replace(location, location.state);\n    }\n\n    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\n        ...newState, // matches, errors, fetchers go through as-is\n        actionData,\n        loaderData,\n        historyAction: pendingAction,\n        location,\n        initialized: true,\n        navigation: IDLE_NAVIGATION,\n        revalidation: \"idle\",\n        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n  }\n\n  // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  async function navigate(\n    to: number | To | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n    // URL from window.location, so we need to encode it here so the behavior\n    // remains the same as POP and non-data-router usages.  new URL() does all\n    // the same encoding we'd get from a history.pushState/window.location read\n    // without having to touch history\n    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\n    };\n\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n    let historyAction = HistoryAction.Push;\n\n    if (userReplace === true) {\n      historyAction = HistoryAction.Replace;\n    } else if (userReplace === false) {\n      // no-op\n    } else if (\n      submission != null &&\n      isMutationMethod(submission.formMethod) &&\n      submission.formAction === state.location.pathname + state.location.search\n    ) {\n      // By default on submissions to the current location we REPLACE so that\n      // users don't have to double-click the back button to get to the prior\n      // location.  If the user redirects to a different location from the\n      // action/loader this will be ignored and the redirect will be a PUSH\n      historyAction = HistoryAction.Replace;\n    }\n\n    let preventScrollReset =\n      opts && \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.viewTransition,\n      flushSync,\n    });\n  }\n\n  // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({ revalidation: \"loading\" });\n\n    // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n    if (state.navigation.state === \"submitting\") {\n      return;\n    }\n\n    // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true,\n      });\n      return;\n    }\n\n    // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n    startNavigation(\n      pendingAction || state.historyAction,\n      state.navigation.location,\n      {\n        overrideNavigation: state.navigation,\n        // Proxy through any rending view transition\n        enableViewTransition: pendingViewTransitionEnabled === true,\n      }\n    );\n  }\n\n  // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  async function startNavigation(\n    historyAction: HistoryAction,\n    location: Location,\n    opts?: {\n      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: boolean;\n    }\n  ): Promise<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches =\n      opts?.initialHydration &&\n      state.matches &&\n      state.matches.length > 0 &&\n      !initialMatchesIsFOW\n        ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n          state.matches\n        : matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial hydration will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      matches &&\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: opts.pendingError },\n      ];\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\n    );\n\n    if (shortCircuited) {\n      return;\n    }\n\n    // Clean up now that the action/loaders have completed.  Don't clean up if\n    // we short circuited because pendingNavigationController will have already\n    // been assigned to a new controller for the next navigation\n    pendingNavigationController = null;\n\n    completeNavigation(location, {\n      matches: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\n      loaderData,\n      errors,\n    });\n  }\n\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(\n    request: Request,\n    location: Location,\n    submission: Submission,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error: discoverResult.error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    // Call our action and get the result\n    let result: DataResult;\n    let actionMatch = getTargetMatch(matches, location);\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      result = {\n        type: ResultType.error,\n        error: getInternalRouterError(405, {\n          method: request.method,\n          pathname: location.pathname,\n          routeId: actionMatch.route.id,\n        }),\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        state,\n        request,\n        [actionMatch],\n        matches,\n        null\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        return { shortCircuited: true };\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      let replace: boolean;\n      if (opts && opts.replace != null) {\n        replace = opts.replace;\n      } else {\n        // If the user didn't explicity indicate replace behavior, replace if\n        // we redirected to the exact same location we're currently at to avoid\n        // double back-buttons\n        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename,\n          init.history,\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, true, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\n    };\n  }\n\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\n\n    // If this is an uninterrupted revalidation, we remain in our current idle\n    // state.  If not, we need to switch to our loading state and load data,\n    // preserving any new action data or existing action data (in the case of\n    // a revalidation interrupting an actionReload)\n    // If we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: discoverResult.error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\n    );\n\n    // Cancel pending deferreds for no-longer-matched routes or routes we're\n    // about to reload.  Note that if this is an action reload we would have\n    // already cancelled all pending deferreds so this would be a no-op\n    cancelActiveDeferreds(\n      (routeId) =>\n        !(matches && matches.some((m) => m.route.id === routeId)) ||\n        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n    );\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      abortFetcher(rf.key);\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        request\n      );\n\n    if (request.signal.aborted) {\n      return { shortCircuited: true };\n    }\n\n    // Clean up _after_ loaders have completed.  Don't clean up if we short\n    // circuited because fetchControllers would have been aborted and\n    // reassigned to new controllers for the next navigation\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      pendingActionResult,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Wire up subscribers to update loaderData as promises settle\n    activeDeferreds.forEach((deferredData, routeId) => {\n      deferredData.subscribe((aborted) => {\n        // Note: No need to updateState here since the TrackedPromise on\n        // loaderData is stable across resolve/reject\n        // Remove this instance if we were aborted or if promises have settled\n        if (aborted || deferredData.done) {\n          activeDeferreds.delete(routeId);\n        }\n      });\n    });\n\n    // Preserve SSR errors during partial hydration\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      errors = { ...state.errors, ...errors };\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\n  }\n\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(\n    key: string,\n    routeId: string,\n    href: string | null,\n    opts?: RouterFetchOptions\n  ) {\n    if (isServer) {\n      throw new Error(\n        \"router.fetch() was called during the server render, but it shouldn't be. \" +\n          \"You are likely calling a useFetcher() method in the body of your component. \" +\n          \"Try moving it to a useEffect or a callback.\"\n      );\n    }\n\n    abortFetcher(key);\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        preventScrollReset,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      preventScrollReset,\n      submission\n    );\n  }\n\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    requestMatches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      state,\n      fetchRequest,\n      [match],\n      requestMatches,\n      key\n    );\n    let actionResult = actionResults[match.route.id];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by our own fetcher\n      // re-submit which would have put _new_ controller is in fetchControllers\n      if (fetchControllers.get(key) === abortController) {\n        fetchControllers.delete(key);\n      }\n      return;\n    }\n\n    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, false, {\n            fetcherSubmission: submission,\n            preventScrollReset,\n          });\n        }\n      }\n\n      // Process any non-redirect errors thrown\n      if (isErrorResult(actionResult)) {\n        setFetcherError(key, routeId, actionResult.error);\n        return;\n      }\n    }\n\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\n    }\n\n    // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(\n      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, basename)\n        : state.matches;\n\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n\n    let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\n    );\n\n    // Put all revalidating fetchers into the loading state, except for the\n    // current fetcher which we want to keep in it's current loading state which\n    // contains it's action submission info + action data\n    revalidatingFetchers\n      .filter((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        abortFetcher(staleKey);\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    abortStaleFetchLoads(loadId);\n\n    // If we are currently in a navigation loading state and this fetcher is\n    // more recent than the navigation, we want the newer data so abort the\n    // navigation and complete it with the fetcher data\n    if (\n      state.navigation.state === \"loading\" &&\n      loadId > pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\n\n      completeNavigation(state.navigation.location, {\n        matches,\n        loaderData,\n        errors,\n        fetchers: new Map(state.fetchers),\n      });\n    } else {\n      // otherwise just update with the fetcher data, preserving any existing\n      // loaderData for loaders that did not need to reload.  We have to\n      // manually merge here since we aren't going through completeNavigation\n      updateState({\n        errors,\n        loaderData: mergeLoaderData(\n          state.loaderData,\n          loaderData,\n          matches,\n          errors\n        ),\n        fetchers: new Map(state.fetchers),\n      });\n      isRevalidationRequired = false;\n    }\n  }\n\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    matches: AgnosticDataRouteMatch[],\n    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        new URL(fetchRequest.url).pathname,\n        fetchRequest.signal,\n        key\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      state,\n      fetchRequest,\n      [match],\n      matches,\n      key\n    );\n    let result = results[match.route.id];\n\n    // Deferred isn't supported for fetcher loads, await everything and treat it\n    // as a normal load.  resolveDeferredData will return undefined if this\n    // fetcher gets aborted, so we just leave result untouched and short circuit\n    // below if that happens\n    if (isDeferredResult(result)) {\n      result =\n        (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n        result;\n    }\n\n    // We can delete this so long as we weren't aborted by our our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n\n    if (fetchRequest.signal.aborted) {\n      return;\n    }\n\n    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result, false, {\n          preventScrollReset,\n        });\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\n  }\n\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  async function startRedirectNavigation(\n    request: Request,\n    redirect: RedirectResult,\n    isNavigation: boolean,\n    {\n      submission,\n      fetcherSubmission,\n      preventScrollReset,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename,\n      init.history,\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(location);\n        }\n        return;\n      }\n    }\n\n    // There's no need to abort on redirects, since we don't detect the\n    // redirect until the action/loaders have settled\n    pendingNavigationController = null;\n\n    let redirectHistoryAction =\n      replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\n    }\n\n    // If this was a 307/308 submission we want to preserve the HTTP method and\n    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n    // redirected location\n    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    state: RouterState,\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    fetcherKey: string | null\n  ): Promise<Record<string, DataResult>> {\n    let results: Record<string, DataStrategyResult>;\n    let dataResults: Record<string, DataResult> = {};\n    try {\n      results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        state,\n        request,\n        matchesToLoad,\n        matches,\n        fetcherKey,\n        manifest,\n        mapRouteProperties\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      matchesToLoad.forEach((m) => {\n        dataResults[m.route.id] = {\n          type: ResultType.error,\n          error: e,\n        };\n      });\n      return dataResults;\n    }\n\n    for (let [routeId, result] of Object.entries(results)) {\n      if (isRedirectDataStrategyResultResult(result)) {\n        let response = result.result as Response;\n        dataResults[routeId] = {\n          type: ResultType.redirect,\n          response: normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            routeId,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          ),\n        };\n      } else {\n        dataResults[routeId] = await convertDataStrategyResultToDataResult(\n          result\n        );\n      }\n    }\n\n    return dataResults;\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    state: RouterState,\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    let currentMatches = state.matches;\n\n    // Kick off loaders and fetchers in parallel\n    let loaderResultsPromise = callDataStrategy(\n      \"loader\",\n      state,\n      request,\n      matchesToLoad,\n      matches,\n      null\n    );\n\n    let fetcherResultsPromise = Promise.all(\n      fetchersToLoad.map(async (f) => {\n        if (f.matches && f.match && f.controller) {\n          let results = await callDataStrategy(\n            \"loader\",\n            state,\n            createClientSideRequest(init.history, f.path, f.controller.signal),\n            [f.match],\n            f.matches,\n            f.key\n          );\n          let result = results[f.match.route.id];\n          // Fetcher results are keyed by fetcher key from here on out, not routeId\n          return { [f.key]: result };\n        } else {\n          return Promise.resolve({\n            [f.key]: {\n              type: ResultType.error,\n              error: getInternalRouterError(404, {\n                pathname: f.path,\n              }),\n            } as ErrorResult,\n          });\n        }\n      })\n    );\n\n    let loaderResults = await loaderResultsPromise;\n    let fetcherResults = (await fetcherResultsPromise).reduce(\n      (acc, r) => Object.assign(acc, r),\n      {}\n    );\n\n    await Promise.all([\n      resolveNavigationDeferredResults(\n        matches,\n        loaderResults,\n        request.signal,\n        currentMatches,\n        state.loaderData\n      ),\n      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\n  }\n\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n    // Abort in-flight fetcher loads\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.add(key);\n      }\n      abortFetcher(key);\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n    // If this fetcher was previously marked for deletion, unmark it since we\n    // have a new instance\n    if (deletedFetchers.has(key)) {\n      deletedFetchers.delete(key);\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n\n    // If we opted into the flag we can clear this now since we're calling\n    // deleteFetcher() at the end of updateState() and we've already handed the\n    // deleted fetcher keys off to the data layer.\n    // If not, we're eagerly calling deleteFetcher() and we need to keep this\n    // Set populated until the next updateState call, and we'll clear\n    // `deletedFetchers` then\n    if (future.v7_fetcherPersist) {\n      deletedFetchers.delete(key);\n    }\n\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    let count = (activeFetchers.get(key) || 0) - 1;\n    if (count <= 0) {\n      activeFetchers.delete(key);\n      deletedFetchers.add(key);\n      if (!future.v7_fetcherPersist) {\n        deleteFetcher(key);\n      }\n    } else {\n      activeFetchers.set(key, count);\n    }\n\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    if (controller) {\n      controller.abort();\n      fetchControllers.delete(key);\n    }\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\n    for (let key of fetchRedirectIds) {\n      let fetcher = state.fetchers.get(key);\n      invariant(fetcher, `Expected fetcher: ${key}`);\n      if (fetcher.state === \"loading\") {\n        fetchRedirectIds.delete(key);\n        doneKeys.push(key);\n        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\n  }\n\n  function abortStaleFetchLoads(landedId: number): boolean {\n    let yeetedKeys = [];\n    for (let [key, id] of fetchReloadIds) {\n      if (id < landedId) {\n        let fetcher = state.fetchers.get(key);\n        invariant(fetcher, `Expected fetcher: ${key}`);\n        if (fetcher.state === \"loading\") {\n          abortFetcher(key);\n          fetchReloadIds.delete(key);\n          yeetedKeys.push(key);\n        }\n      }\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n\n  function getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\n  }\n\n  function cancelActiveDeferreds(\n    predicate?: (routeId: string) => boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) => {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  }\n\n  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnNavigationImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        if (Object.keys(matches[0].params).length > 0) {\n          // If we matched a dynamic param or a splat, it might only be because\n          // we haven't yet discovered other routes that would match with a\n          // higher score.  Call patchRoutesOnNavigation just to be sure\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal,\n    fetcherKey?: string\n  ): Promise<DiscoverRoutesResult> {\n    if (!patchRoutesOnNavigationImpl) {\n      return { type: \"success\", matches };\n    }\n\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      let localManifest = manifest;\n      try {\n        await patchRoutesOnNavigationImpl({\n          signal,\n          path: pathname,\n          matches: partialMatches,\n          fetcherKey,\n          patch: (routeId, children) => {\n            if (signal.aborted) return;\n            patchRoutesImpl(\n              routeId,\n              children,\n              routesToUse,\n              localManifest,\n              mapRouteProperties\n            );\n          },\n        });\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR && !signal.aborted) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      if (newMatches) {\n        return { type: \"success\", matches: newMatches };\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // Avoid loops if the second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        (partialMatches.length === newPartialMatches.length &&\n          partialMatches.every(\n            (m, i) => m.route.id === newPartialMatches![i].route.id\n          ))\n      ) {\n        return { type: \"success\", matches: null };\n      }\n\n      partialMatches = newPartialMatches;\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\n    },\n    initialize,\n    subscribe,\n    enableScrollRestoration,\n    navigate,\n    fetch,\n    revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: (to: To) => init.history.createHref(to),\n    encodeLocation: (to: To) => init.history.encodeLocation(to),\n    getFetcher,\n    deleteFetcher: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   *\n   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\n    if (isResponse(result)) {\n      return result;\n    }\n\n    // When returning StaticHandlerContext, we patch back in the location here\n    // since we need it for React Context.  But this helps keep our submit and\n    // loadRouteData operating on a Request instead of a Location\n    return { location, basename, ...result };\n  }\n\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   *\n   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      false,\n      match\n    );\n\n    if (isResponse(result)) {\n      return result;\n    }\n\n    let error = result.errors ? Object.values(result.errors)[0] : undefined;\n    if (error !== undefined) {\n      // If we got back result.errors, that means the loader/action threw\n      // _something_ that wasn't a Response, but it's not guaranteed/required\n      // to be an `instanceof Error` either, so we have to use throw here to\n      // preserve the \"error\" state outside of queryImpl.\n      throw error;\n    }\n\n    // Pick off the right state value to return\n    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(\n          request,\n          matches,\n          routeMatch || getTargetMatch(matches, location),\n          requestContext,\n          dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        routeMatch\n      );\n      return isResponse(result)\n        ? result\n        : {\n            ...result,\n            actionData: null,\n            actionHeaders: {},\n          };\n    } catch (e) {\n      // If the user threw/returned a Response in callLoaderOrAction for a\n      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isDataStrategyResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\n      }\n      // Redirects are always returned since they don't propagate to catch\n      // boundaries\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n\n  async function submit(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    actionMatch: AgnosticDataRouteMatch,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        dataStrategy\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      // Uhhhh - this should never happen, we should always throw these from\n      // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n      // can get back on the \"throw all redirect responses\" train here should\n      // this ever happen :/\n      throw new Response(null, {\n        status: result.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    // Create a GET request for the loaders\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal,\n    });\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\n      );\n\n      // action status codes take precedence over loader status codes\n      return {\n        ...context,\n        statusCode: isRouteErrorResponse(result.error)\n          ? result.error.status\n          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\n  ): Promise<\n    | Omit<\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      >\n    | Response\n  > {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch?.route.id,\n      });\n    }\n\n    let requestMatches = routeMatch\n      ? [routeMatch]\n      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\n\n    // Short circuit if we have no loaders to run (query())\n    if (matchesToLoad.length === 0) {\n      return {\n        matches,\n        // Add a null for all matched routes for proper revalidation on the client\n        loaderData: matches.reduce(\n          (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null\n  ): Promise<Record<string, DataResult>> {\n    let results = await callDataStrategyImpl(\n      dataStrategy || defaultDataStrategy,\n      type,\n      null,\n      request,\n      matchesToLoad,\n      matches,\n      null,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    let dataResults: Record<string, DataResult> = {};\n    await Promise.all(\n      matches.map(async (match) => {\n        if (!(match.route.id in results)) {\n          return;\n        }\n        let result = results[match.route.id];\n        if (isRedirectDataStrategyResultResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            match.route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        dataResults[match.route.id] =\n          await convertDataStrategyResultToDataResult(result);\n      })\n    );\n    return dataResults;\n  }\n\n  return {\n    dataRoutes,\n    query,\n    queryRoute,\n  };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n  routes: AgnosticDataRouteObject[],\n  context: StaticHandlerContext,\n  error: any\n) {\n  let newContext: StaticHandlerContext = {\n    ...context,\n    statusCode: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Account for `?index` params when routing to the current location\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index && !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index&\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index && nakedIndex) {\n      // Remove existing ones when we're not\n      let params = new URLSearchParams(path.search);\n      let indexValues = params.getAll(\"index\");\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\n} {\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return { path };\n  }\n\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n  matches: AgnosticDataRouteMatch[],\n  boundaryId: string,\n  includeBoundary = false\n) {\n  let index = matches.findIndex((m) => m.route.id === boundaryId);\n  if (index >= 0) {\n    return matches.slice(0, includeBoundary ? index + 1 : index);\n  }\n  return matches;\n}\n\nfunction getMatchesToLoad(\n  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  initialHydration: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryMatches = matches;\n  if (initialHydration && state.errors) {\n    // On initial hydration, only consider matches up to _and including_ the boundary.\n    // This is inclusive to handle cases where a server loader ran successfully,\n    // a child server loader bubbled up to this route, but this route has\n    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n    // we have a complete version of `loaderData`\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      Object.keys(state.errors)[0],\n      true\n    );\n  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n    // If an action threw an error, we call loaders up to, but not including the\n    // boundary\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      pendingActionResult[0]\n    );\n  }\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (initialHydration) {\n      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for when we revalidate.  If the route\n    // provides it's own implementation, then we give them full control but\n    // provide this value so they can leverage it if needed after they check\n    // their own specific use cases\n    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial hydration (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      initialHydration ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\n      });\n    }\n  });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n  route: AgnosticDataRouteObject,\n  loaderData: RouteData | null | undefined,\n  errors: RouteData | null | undefined\n) {\n  // We dunno if we have a loader - gotta find out!\n  if (route.lazy) {\n    return true;\n  }\n\n  // No loader, nothing to initialize\n  if (!route.loader) {\n    return false;\n  }\n\n  let hasData = loaderData != null && loaderData[route.id] !== undefined;\n  let hasError = errors != null && errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData && hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -> [a, b]\n    !currentMatch ||\n    // [a, b] -> [a, c]\n    match.route.id !== currentMatch.route.id;\n\n  // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n  let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    (currentPath != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  let childrenToPatch: AgnosticDataRouteObject[];\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    if (!route.children) {\n      route.children = [];\n    }\n    childrenToPatch = route.children;\n  } else {\n    childrenToPatch = routesToUse;\n  }\n\n  // Don't patch in routes we already know about so that `patch` is idempotent\n  // to simplify user-land code. This is useful because we re-call the\n  // `patchRoutesOnNavigation` function for matched routes with params.\n  let uniqueChildren = children.filter(\n    (newRoute) =>\n      !childrenToPatch.some((existingRoute) =>\n        isSameRoute(newRoute, existingRoute)\n      )\n  );\n\n  let newRoutes = convertRoutesToDataRoutes(\n    uniqueChildren,\n    mapRouteProperties,\n    [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n    manifest\n  );\n\n  childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n  newRoute: AgnosticRouteObject,\n  existingRoute: AgnosticRouteObject\n): boolean {\n  // Most optimal check is by id\n  if (\n    \"id\" in newRoute &&\n    \"id\" in existingRoute &&\n    newRoute.id === existingRoute.id\n  ) {\n    return true;\n  }\n\n  // Second is by pathing differences\n  if (\n    !(\n      newRoute.index === existingRoute.index &&\n      newRoute.path === existingRoute.path &&\n      newRoute.caseSensitive === existingRoute.caseSensitive\n    )\n  ) {\n    return false;\n  }\n\n  // Pathless layout routes are trickier since we need to check children.\n  // If they have no children then they're the same as far as we can tell\n  if (\n    (!newRoute.children || newRoute.children.length === 0) &&\n    (!existingRoute.children || existingRoute.children.length === 0)\n  ) {\n    return true;\n  }\n\n  // Otherwise, we look to see if every child in the new route is already\n  // represented in the existing route's children\n  return newRoute.children!.every((aChild, i) =>\n    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n  );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n  matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n  let matchesToLoad = matches.filter((m) => m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n  return results.reduce(\n    (acc, result, i) =>\n      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n    {}\n  );\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  state: RouterState | null,\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  fetcherKey: string | null,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n  let loadRouteDefinitionsPromises = matches.map((m) =>\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) => {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n    // `resolve` encapsulates route.lazy(), executing the loader/action,\n    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users\n    // can pass a callback to take fine-grained control over the execution\n    // of the loader/action\n    let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n      if (\n        handlerOverride &&\n        request.method === \"GET\" &&\n        (match.route.lazy || match.route.loader)\n      ) {\n        shouldLoad = true;\n      }\n      return shouldLoad\n        ? callLoaderOrAction(\n            type,\n            request,\n            match,\n            loadRoutePromise,\n            handlerOverride,\n            requestContext\n          )\n        : Promise.resolve({ type: ResultType.data, result: undefined });\n    };\n\n    return {\n      ...match,\n      shouldLoad,\n      resolve,\n    };\n  });\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: dsMatches,\n    request,\n    params: matches[0].params,\n    fetcherKey,\n    context: requestContext,\n  });\n\n  // Wait for all routes to load here but 'swallow the error since we want\n  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n  // called from `match.resolve()`\n  try {\n    await Promise.all(loadRouteDefinitionsPromises);\n  } catch (e) {\n    // No-op\n  }\n\n  return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  loadRoutePromise: Promise<void> | undefined,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<DataStrategyResult> {\n  let result: DataStrategyResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<DataStrategyResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<DataStrategyResult> = (async () => {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n          : actualHandler());\n        return { type: \"data\", result: val };\n      } catch (e) {\n        return { type: \"error\", result: e };\n      }\n    })();\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    // If we have a route.lazy promise, await that first\n    if (loadRoutePromise) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadRoutePromise,\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadRoutePromise;\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.result !== undefined,\n      `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n        `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n        `function. Please return a value or \\`null\\`.`\n    );\n  } catch (e) {\n    // We should already be catching and converting normal handler executions to\n    // DataStrategyResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n  dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n  let { result, type } = dataStrategyResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\n      let contentType = result.headers.get(\"Content-Type\");\n      // Check between word boundaries instead of startsWith() due to the last\n      // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n      if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\n        headers: result.headers,\n      };\n    }\n\n    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers,\n    };\n  }\n\n  if (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n          headers: result.init?.headers\n            ? new Headers(result.init.headers)\n            : undefined,\n        };\n      }\n\n      // Convert thrown data() to ErrorResponse instances\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(\n          result.init?.status || 500,\n          undefined,\n          result.data\n        ),\n        statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n        headers: result.init?.headers\n          ? new Headers(result.init.headers)\n          : undefined,\n      };\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string,\n  historyInstance: History,\n): string {\n  // Match Chrome's behavior:\n  // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n  let invalidProtocols = [\n    \"about:\",\n    \"blob:\",\n    \"chrome:\",\n    \"chrome-untrusted:\",\n    \"content:\",\n    \"data:\",\n    \"devtools:\",\n    \"file:\",\n    \"filesystem:\",\n    // eslint-disable-next-line no-script-url\n    \"javascript:\",\n  ];\n\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n    }\n  }\n\n  try {\n    let url = historyInstance.createURL(location);\n    if (invalidProtocols.includes(url.protocol)) {\n      throw new Error(\"Invalid redirect location\");\n    }\n  } catch (e) {}\n\n  return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\n  return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n  let searchParams = new URLSearchParams();\n\n  for (let [key, value] of formData.entries()) {\n    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) => {\n    if (!(match.route.id in results)) {\n      return;\n    }\n    let id = match.route.id;\n    let result = results[id];\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\n      let error = result.error;\n      // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n      if (pendingError !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\n      }\n\n      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\n\n      // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (\n          result.statusCode != null &&\n          result.statusCode !== 200 &&\n          !foundError\n        ) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      } else {\n        loaderData[id] = result.data;\n        // Error status codes always override success status codes, but if all\n        // loaders are successful we take the deepest status code.\n        if (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\n      }\n    }\n  });\n\n  // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n  if (pendingError !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[0]] = undefined;\n  }\n\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders,\n  };\n}\n\nfunction processLoaderData(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record<string, DataResult>,\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    results,\n    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  revalidatingFetchers.forEach((rf) => {\n    let { key, match, controller } = rf;\n    let result = fetcherResults[key];\n    invariant(result, \"Did not find corresponding fetcher result\");\n\n    // Process fetcher non-redirect errors\n    if (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      return;\n    } else if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = {\n          ...errors,\n          [boundaryMatch.route.id]: result.error,\n        };\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      invariant(false, \"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  });\n\n  return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n  loaderData: RouteData,\n  newLoaderData: RouteData,\n  matches: AgnosticDataRouteMatch[],\n  errors: RouteData | null | undefined\n): RouteData {\n  let mergedLoaderData = { ...newLoaderData };\n  for (let match of matches) {\n    let id = match.route.id;\n    if (newLoaderData.hasOwnProperty(id)) {\n      if (newLoaderData[id] !== undefined) {\n        mergedLoaderData[id] = newLoaderData[id];\n      } else {\n        // No-op - this is so we ignore existing data if we have a key in the\n        // incoming object with an undefined value, which is how we unset a prior\n        // loaderData if we encounter a loader error\n      }\n    } else if (loaderData[id] !== undefined && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\n      mergedLoaderData[id] = loaderData[id];\n    }\n\n    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n  matches: AgnosticDataRouteMatch[],\n  routeId?: string\n): AgnosticDataRouteMatch {\n  let eligibleMatches = routeId\n    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n    matches[0]\n  );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n  matches: AgnosticDataRouteMatch[];\n  route: AgnosticDataRouteObject;\n} {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route =\n    routes.length === 1\n      ? routes[0]\n      : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n          id: `__shim-error-route__`,\n        };\n\n  return {\n    matches: [\n      {\n        params: {},\n        pathname: \"\",\n        pathnameBase: \"\",\n        route,\n      },\n    ],\n    route,\n  };\n}\n\nfunction getInternalRouterError(\n  status: number,\n  {\n    pathname,\n    routeId,\n    method,\n    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\";\n    message?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = `No route matches URL \"${pathname}\"`;\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n        `did not provide an \\`action\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (method) {\n      errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n    }\n  }\n\n  return new ErrorResponseImpl(\n    status || 500,\n    statusText,\n    new Error(errorMessage),\n    true\n  );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n  results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i >= 0; i--) {\n    let [key, result] = entries[i];\n    if (isRedirectResult(result)) {\n      return { key, result };\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n  );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n  return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n  return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n  return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null &&\n    typeof value.status === \"number\" &&\n    typeof value.statusText === \"string\" &&\n    typeof value.headers === \"object\" &&\n    typeof value.body !== \"undefined\"\n  );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n  if (!isResponse(result)) {\n    return false;\n  }\n\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index < entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    let currentMatch = currentMatches.find(\n      (m) => m.route.id === match!.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null &&\n      !isNewRouteInstance(currentMatch, match) &&\n      (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) && isRevalidatingLoader) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      await resolveDeferredData(result, signal, false).then((result) => {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    if (isDeferredResult(result)) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      invariant(\n        controller,\n        \"Expected an AbortController for revalidating fetcher deferred result\"\n      );\n      await resolveDeferredData(result, controller.signal, true).then(\n        (result) => {\n          if (result) {\n            results[key] = result;\n          }\n        }\n      );\n    }\n  }\n}\n\nasync function resolveDeferredData(\n  result: DeferredResult,\n  signal: AbortSignal,\n  unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\n  }\n\n  if (unwrap) {\n    try {\n      return {\n        type: ResultType.data,\n        data: result.deferredData.unwrappedData,\n      };\n    } catch (e) {\n      // Handle any TrackedPromise._error values encountered while unwrapping\n      return {\n        type: ResultType.error,\n        error: e,\n      };\n    }\n  }\n\n  return {\n    type: ResultType.data,\n    data: result.deferredData.data,\n  };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n  return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n  matches: AgnosticDataRouteMatch[],\n  location: Location | string\n) {\n  let search =\n    typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (\n    matches[matches.length - 1].route.index &&\n    hasNakedIndexQuery(search || \"\")\n  ) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  }\n  // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","invariant","value","message","Error","warning","cond","console","warn","e","getHistoryState","location","index","usr","state","key","idx","createLocation","current","to","_extends","pathname","search","hash","parsePath","Math","random","toString","substr","createPath","_ref","charAt","path","parsedPath","hashIndex","indexOf","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","options","window","document","defaultView","v5Compat","globalHistory","history","action","Pop","listener","getIndex","handlePop","nextIndex","delta","createURL","base","origin","href","replace","URL","replaceState","listen","fn","addEventListener","removeEventListener","encodeLocation","url","push","Push","historyState","pushState","error","DOMException","name","assign","Replace","go","n","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","map","route","treePath","String","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","undefined","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","sort","a","b","score","siblings","length","slice","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","startsWith","joinPaths","concat","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","_","paramName","RegExp","compilePath","captureGroups","memo","splatValue","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","pop","getInvalidPathError","char","field","dest","JSON","stringify","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","DataWithResponseInit","constructor","init","this","type","AbortedDeferredError","DeferredData","responseInit","reject","pendingKeysSet","subscribers","deferredKeys","Array","isArray","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","entries","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","_tracked","isTrackedPromise","_error","_data","defer","redirect","status","headers","Headers","set","Response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","json","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","UNSAFE_DEFERRED_SYMBOL","Symbol","throwStaticHandlerAbortedError","request","isRouteRequest","future","v7_throwAbortReason","reason","method","normalizeTo","prependBasename","fromRouteId","relative","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeNavigateOptions","normalizeFormMethod","isFetcher","opts","body","isSubmissionNavigation","isValidMethod","getInternalRouterError","searchParams","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","isMutationMethod","FormData","submission","parse","convertFormDataToSearchParams","convertSearchParamsToFormData","getLoaderMatchesUntilBoundary","boundaryId","includeBoundary","findIndex","m","getMatchesToLoad","initialHydration","skipActionErrorRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","deletedFetchers","fetchLoadMatches","fetchRedirectIds","routesToUse","pendingActionResult","actionResult","isErrorResult","currentUrl","nextUrl","boundaryMatches","errors","keys","actionStatus","statusCode","shouldSkipRevalidation","navigationMatches","lazy","loader","shouldLoadRouteOnHydration","currentLoaderData","currentMatch","isNew","isMissingData","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","revalidatingFetchers","f","routeId","has","fetcherMatches","fetcher","fetchers","fetcherMatch","getTargetMatch","shouldRevalidate","hasData","hasError","hydrate","currentPath","loaderMatch","arg","routeChoice","patchRoutesImpl","_childrenToPatch","childrenToPatch","newRoutes","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","async","defaultDataStrategy","_ref4","matchesToLoad","shouldLoad","all","callDataStrategyImpl","dataStrategyImpl","fetcherKey","requestContext","loadRouteDefinitionsPromises","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","loadLazyRouteModule","dsMatches","loadRoutePromise","handlerOverride","staticContext","onReject","runHandler","handler","actualHandler","ctx","context","handlerPromise","handlerError","callLoaderOrAction","results","convertDataStrategyResultToDataResult","dataStrategyResult","isResponse","contentType","_result$init3","_result$init4","_result$init","_result$init2","_result$init5","_result$init6","_result$init7","_result$init8","isDataWithResponseInit","isDeferredData","deferred","deferredData","normalizeRelativeRoutingRedirectResponse","response","trimmedMatches","normalizeRedirectLocation","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","createClientSideRequest","Request","processRouteLoaderData","activeDeferreds","skipLoaderErrorBubbling","foundError","loaderHeaders","pendingError","isRedirectResult","boundaryMatch","findNearestBoundary","isDeferredResult","processLoaderData","fetcherResults","rf","doneFetcher","getDoneFetcher","mergeLoaderData","newLoaderData","mergedLoaderData","hasOwnProperty","getActionDataForCommit","actionData","reverse","find","getShortCircuitMatches","_temp5","errorMessage","findRedirect","isRedirectDataStrategyResultResult","resolveNavigationDeferredResults","currentMatches","isRevalidatingLoader","resolveDeferredData","resolveFetcherDeferredResults","unwrap","getSubmissionFromNavigation","navigation","getLoadingNavigation","getLoadingFetcher","querySelector","getAttribute","initialEntries","initialIndex","entry","createMemoryLocation","clampIndex","min","max","getCurrentLocation","nextLocation","splice","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","inFlightDataRoutes","initialized","router","dataRoutes","dataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","checkFogOfWar","active","fogOfWar","pendingNavigationController","unblockBlockerHistoryUpdate","historyAction","restoreScrollPosition","preventScrollReset","revalidation","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","activeFetchers","blockerFunctions","updateState","newState","completedFetchers","deletedFetchersKeys","viewTransitionOpts","flushSync","deleteFetcher","completeNavigation","_temp","_location$state","_location$state2","isActionReload","_isRedirect","priorPaths","currentLocation","toPaths","getSavedScrollPosition","startNavigation","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","loadingNavigation","overrideNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","isFogOfWar","interruptActiveLoads","getSubmittingNavigation","discoverResult","discoverRoutes","shortCircuited","partialMatches","actionMatch","callDataStrategy","startRedirectNavigation","handleAction","updatedMatches","fetcherSubmission","activeSubmission","shouldUpdateNavigationState","getUpdatedActionData","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","revalidatingFetcher","getUpdatedRevalidatingFetchers","abortFetcher","abortPendingFetchRevalidations","loaderResults","callLoadersAndMaybeResolveData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","dataResults","fetchersToLoad","loaderResultsPromise","fetcherResultsPromise","updateFetcherState","setFetcherError","getFetcher","markFetchersDone","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","blockerKey","blockerFunction","predicate","cancelledRouteIds","dfd","y","isNonHMR","localManifest","patch","newMatches","newPartialMatches","initialize","nextHistoryUpdatePromise","_window","transitions","sessionPositions","sessionStorage","getItem","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","userReplace","viewTransition","fetch","requestMatches","detectAndHandle405Error","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","handleFetcherLoader","revalidate","count","dispose","clear","getBlocker","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","_internalSetRoutes","queryImpl","routeMatch","Location","actionHeaders","loaderRequest","loadRouteData","submit","isRedirectResponse","executedLoaders","fromEntries","query","_temp3","methodNotAllowedMatches","queryRoute","_temp4","values","_result$activeDeferre","originalPath","prefix","p","array","keyMatch","opt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6CkC,SAAC2G,EAAMkG,QAAI,IAAJA,IAAAA,EAAO,CAAA,GAC9C,IAAIK,EAA+B,iBAATL,EAAoB,CAAEwD,OAAQxD,GAASA,EAE7DyD,EAAU,IAAIC,QAAQrD,EAAaoD,SAKvC,OAJKA,EAAQoH,IAAI,iBACfpH,EAAQE,IAAI,eAAgB,mCAGvB,IAAIC,SAASjF,KAAKC,UAAU9E,GAAK5G,EAAA,CAAA,EACnCmN,EAAY,CACfoD,YAEJ,oGA0QkDuc,CAAC/pB,EAAK+J,KACtD,IAAIqP,EAAW9L,EAAStN,EAAK+J,GAE7B,OADAqP,EAAS5L,QAAQE,IAAI,0BAA2B,QACzC0L,aASgC5Z,CAACQ,EAAK+J,KAC7C,IAAIqP,EAAW9L,EAAStN,EAAK+J,GAE7B,OADAqP,EAAS5L,QAAQE,IAAI,kBAAmB,QACjC0L"}MIT License

Copyright (c) 2020 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
  "name": "ajv-formats",
  "version": "2.1.1",
  "description": "Format validation for Ajv v7+",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": [
    "src/",
    "dist/"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ajv-validator/ajv-formats.git"
  },
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://github.com/ajv-validator/ajv-formats#readme",
  "dependencies": {
    "ajv": "^8.0.0"
  },
  "peerDependencies": {
    "ajv": "^8.0.0"
  },
  "peerDependenciesMeta": {
    "ajv": {
      "optional": true
    }
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.3.0",
    "@types/jest": "^26.0.5",
    "@types/node": "^14.10.1",
    "@typescript-eslint/eslint-plugin": "^3.7.0",
    "@typescript-eslint/parser": "^3.7.0",
    "ajv": "^8.0.0",
    "eslint": "^7.5.0",
    "eslint-config-prettier": "^6.11.0",
    "husky": "^4.2.5",
    "jest": "^26.1.0",
    "json-schema-test": "^2.0.0",
    "lint-staged": "^10.2.11",
    "prettier": "^2.3.2",
    "ts-jest": "^26.1.3",
    "typescript": "^4.0.0"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{md,json,yaml,js,ts}": "prettier --write"
  }
}import type {Format, FormatDefinition} from "ajv"
import type {FormatValidator, FormatCompare} from "ajv/dist/types"

export type FormatMode = "fast" | "full"

export type FormatName =
  | "date"
  | "time"
  | "date-time"
  | "duration"
  | "uri"
  | "uri-reference"
  | "uri-template"
  | "url"
  | "email"
  | "hostname"
  | "ipv4"
  | "ipv6"
  | "regex"
  | "uuid"
  | "json-pointer"
  | "json-pointer-uri-fragment"
  | "relative-json-pointer"
  | "byte"
  | "int32"
  | "int64"
  | "float"
  | "double"
  | "password"
  | "binary"

export type DefinedFormats = {
  [key in FormatName]: Format
}

function fmtDef(
  validate: RegExp | FormatValidator<string>,
  compare: FormatCompare<string>
): FormatDefinition<string> {
  return {validate, compare}
}

export const fullFormats: DefinedFormats = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: fmtDef(date, compareDate),
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: fmtDef(time, compareTime),
  "date-time": fmtDef(date_time, compareDateTime),
  // duration: https://tools.ietf.org/html/rfc3339#appendix-A
  duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
  uri,
  "uri-reference":
    /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
  // uri-template: https://tools.ietf.org/html/rfc6570
  "uri-template":
    /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
  // For the source: https://gist.github.com/dperini/729294
  // For test cases: https://mathiasbynens.be/demo/url-regex
  url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
  email:
    /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname:
    /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
  regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
  "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
  // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
  // byte: https://github.com/miguelmota/is-base64
  byte,
  // signed 32 bit integer
  int32: {type: "number", validate: validateInt32},
  // signed 64 bit integer
  int64: {type: "number", validate: validateInt64},
  // C-type float
  float: {type: "number", validate: validateNumber},
  // C-type double
  double: {type: "number", validate: validateNumber},
  // hint to the UI to hide input strings
  password: true,
  // unchecked string payload
  binary: true,
}

export const fastFormats: DefinedFormats = {
  ...fullFormats,
  date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
  time: fmtDef(
    /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
    compareTime
  ),
  "date-time": fmtDef(
    /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
    compareDateTime
  ),
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
  "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
  email:
    /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
}

export const formatNames = Object.keys(fullFormats) as FormatName[]

function isLeapYear(year: number): boolean {
  // https://tools.ietf.org/html/rfc3339#appendix-C
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
}

const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

function date(str: string): boolean {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  const matches: string[] | null = DATE.exec(str)
  if (!matches) return false
  const year: number = +matches[1]
  const month: number = +matches[2]
  const day: number = +matches[3]
  return (
    month >= 1 &&
    month <= 12 &&
    day >= 1 &&
    day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])
  )
}

function compareDate(d1: string, d2: string): number | undefined {
  if (!(d1 && d2)) return undefined
  if (d1 > d2) return 1
  if (d1 < d2) return -1
  return 0
}

const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i

function time(str: string, withTimeZone?: boolean): boolean {
  const matches: string[] | null = TIME.exec(str)
  if (!matches) return false

  const hour: number = +matches[1]
  const minute: number = +matches[2]
  const second: number = +matches[3]
  const timeZone: string = matches[5]
  return (
    ((hour <= 23 && minute <= 59 && second <= 59) ||
      (hour === 23 && minute === 59 && second === 60)) &&
    (!withTimeZone || timeZone !== "")
  )
}

function compareTime(t1: string, t2: string): number | undefined {
  if (!(t1 && t2)) return undefined
  const a1 = TIME.exec(t1)
  const a2 = TIME.exec(t2)
  if (!(a1 && a2)) return undefined
  t1 = a1[1] + a1[2] + a1[3] + (a1[4] || "")
  t2 = a2[1] + a2[2] + a2[3] + (a2[4] || "")
  if (t1 > t2) return 1
  if (t1 < t2) return -1
  return 0
}

const DATE_TIME_SEPARATOR = /t|\s/i
function date_time(str: string): boolean {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  const dateTime: string[] = str.split(DATE_TIME_SEPARATOR)
  return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true)
}

function compareDateTime(dt1: string, dt2: string): number | undefined {
  if (!(dt1 && dt2)) return undefined
  const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR)
  const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR)
  const res = compareDate(d1, d2)
  if (res === undefined) return undefined
  return res || compareTime(t1, t2)
}

const NOT_URI_FRAGMENT = /\/|:/
const URI =
  /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i

function uri(str: string): boolean {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str)
}

const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm

function byte(str: string): boolean {
  BYTE.lastIndex = 0
  return BYTE.test(str)
}

const MIN_INT32 = -(2 ** 31)
const MAX_INT32 = 2 ** 31 - 1

function validateInt32(value: number): boolean {
  return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32
}

function validateInt64(value: number): boolean {
  // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64
  return Number.isInteger(value)
}

function validateNumber(): boolean {
  return true
}

const Z_ANCHOR = /[^\\]\\Z/
function regex(str: string): boolean {
  if (Z_ANCHOR.test(str)) return false
  try {
    new RegExp(str)
    return true
  } catch (e) {
    return false
  }
}
import {
  DefinedFormats,
  FormatMode,
  FormatName,
  formatNames,
  fastFormats,
  fullFormats,
} from "./formats"
import formatLimit from "./limit"
import type Ajv from "ajv"
import type {Plugin, Format} from "ajv"
import {_, Name} from "ajv/dist/compile/codegen"

export {FormatMode, FormatName} from "./formats"
export {LimitFormatError} from "./limit"
export interface FormatOptions {
  mode?: FormatMode
  formats?: FormatName[]
  keywords?: boolean
}

export type FormatsPluginOptions = FormatName[] | FormatOptions

export interface FormatsPlugin extends Plugin<FormatsPluginOptions> {
  get: (format: FormatName, mode?: FormatMode) => Format
}

const fullName = new Name("fullFormats")
const fastName = new Name("fastFormats")

const formatsPlugin: FormatsPlugin = (
  ajv: Ajv,
  opts: FormatsPluginOptions = {keywords: true}
): Ajv => {
  if (Array.isArray(opts)) {
    addFormats(ajv, opts, fullFormats, fullName)
    return ajv
  }
  const [formats, exportName] =
    opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName]
  const list = opts.formats || formatNames
  addFormats(ajv, list, formats, exportName)
  if (opts.keywords) formatLimit(ajv)
  return ajv
}

formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => {
  const formats = mode === "fast" ? fastFormats : fullFormats
  const f = formats[name]
  if (!f) throw new Error(`Unknown format "${name}"`)
  return f
}

function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {
  ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}`
  for (const f of list) ajv.addFormat(f, fs[f])
}

module.exports = exports = formatsPlugin
Object.defineProperty(exports, "__esModule", {value: true})

export default formatsPlugin
import type Ajv from "ajv"
import type {
  Plugin,
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  Code,
  Name,
  ErrorObject,
} from "ajv"
import type {AddedFormat} from "ajv/dist/types"
import type {Rule} from "ajv/dist/compile/rules"
import {KeywordCxt} from "ajv"
import {_, str, or, getProperty, operators} from "ajv/dist/compile/codegen"

type Kwd = "formatMaximum" | "formatMinimum" | "formatExclusiveMaximum" | "formatExclusiveMinimum"

type Comparison = "<=" | ">=" | "<" | ">"

const ops = operators

const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {
  formatMaximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT},
  formatMinimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT},
  formatExclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE},
  formatExclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE},
}

export type LimitFormatError = ErrorObject<Kwd, {limit: string; comparison: Comparison}>

const error: KeywordErrorDefinition = {
  message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,
  params: ({keyword, schemaCode}) =>
    _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,
}

export const formatLimitDefinition: CodeKeywordDefinition = {
  keyword: Object.keys(KWDs),
  type: "string",
  schemaType: "string",
  $data: true,
  error,
  code(cxt) {
    const {gen, data, schemaCode, keyword, it} = cxt
    const {opts, self} = it
    if (!opts.validateFormats) return

    const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, "format")
    if (fCxt.$data) validate$DataFormat()
    else validateFormat()

    function validate$DataFormat(): void {
      const fmts = gen.scopeValue("formats", {
        ref: self.formats,
        code: opts.code.formats,
      })
      const fmt = gen.const("fmt", _`${fmts}[${fCxt.schemaCode}]`)
      cxt.fail$data(
        or(
          _`typeof ${fmt} != "object"`,
          _`${fmt} instanceof RegExp`,
          _`typeof ${fmt}.compare != "function"`,
          compareCode(fmt)
        )
      )
    }

    function validateFormat(): void {
      const format = fCxt.schema as string
      const fmtDef: AddedFormat | undefined = self.formats[format]
      if (!fmtDef || fmtDef === true) return
      if (
        typeof fmtDef != "object" ||
        fmtDef instanceof RegExp ||
        typeof fmtDef.compare != "function"
      ) {
        throw new Error(`"${keyword}": format "${format}" does not define "compare" function`)
      }
      const fmt = gen.scopeValue("formats", {
        key: format,
        ref: fmtDef,
        code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined,
      })

      cxt.fail$data(compareCode(fmt))
    }

    function compareCode(fmt: Name): Code {
      return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0`
    }
  },
  dependencies: ["format"],
}

const formatLimitPlugin: Plugin<undefined> = (ajv: Ajv): Ajv => {
  ajv.addKeyword(formatLimitDefinition)
  return ajv
}

export default formatLimitPlugin
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
function fmtDef(validate, compare) {
    return { validate, compare };
}
exports.fullFormats = {
    // date: http://tools.ietf.org/html/rfc3339#section-5.6
    date: fmtDef(date, compareDate),
    // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
    time: fmtDef(time, compareTime),
    "date-time": fmtDef(date_time, compareDateTime),
    // duration: https://tools.ietf.org/html/rfc3339#appendix-A
    duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
    uri,
    "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
    // uri-template: https://tools.ietf.org/html/rfc6570
    "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
    // For the source: https://gist.github.com/dperini/729294
    // For test cases: https://mathiasbynens.be/demo/url-regex
    url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
    email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
    hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
    // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
    ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
    ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
    regex,
    // uuid: http://tools.ietf.org/html/rfc4122
    uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
    // JSON-pointer: https://tools.ietf.org/html/rfc6901
    // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
    "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
    "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
    // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
    "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
    // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
    // byte: https://github.com/miguelmota/is-base64
    byte,
    // signed 32 bit integer
    int32: { type: "number", validate: validateInt32 },
    // signed 64 bit integer
    int64: { type: "number", validate: validateInt64 },
    // C-type float
    float: { type: "number", validate: validateNumber },
    // C-type double
    double: { type: "number", validate: validateNumber },
    // hint to the UI to hide input strings
    password: true,
    // unchecked string payload
    binary: true,
};
exports.fastFormats = {
    ...exports.fullFormats,
    date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
    time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareTime),
    "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
    // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
    uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
    "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
    // email (sources from jsen validator):
    // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
    // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
    email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
};
exports.formatNames = Object.keys(exports.fullFormats);
function isLeapYear(year) {
    // https://tools.ietf.org/html/rfc3339#appendix-C
    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function date(str) {
    // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const year = +matches[1];
    const month = +matches[2];
    const day = +matches[3];
    return (month >= 1 &&
        month <= 12 &&
        day >= 1 &&
        day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));
}
function compareDate(d1, d2) {
    if (!(d1 && d2))
        return undefined;
    if (d1 > d2)
        return 1;
    if (d1 < d2)
        return -1;
    return 0;
}
const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
function time(str, withTimeZone) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hour = +matches[1];
    const minute = +matches[2];
    const second = +matches[3];
    const timeZone = matches[5];
    return (((hour <= 23 && minute <= 59 && second <= 59) ||
        (hour === 23 && minute === 59 && second === 60)) &&
        (!withTimeZone || timeZone !== ""));
}
function compareTime(t1, t2) {
    if (!(t1 && t2))
        return undefined;
    const a1 = TIME.exec(t1);
    const a2 = TIME.exec(t2);
    if (!(a1 && a2))
        return undefined;
    t1 = a1[1] + a1[2] + a1[3] + (a1[4] || "");
    t2 = a2[1] + a2[2] + a2[3] + (a2[4] || "");
    if (t1 > t2)
        return 1;
    if (t1 < t2)
        return -1;
    return 0;
}
const DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dateTime = str.split(DATE_TIME_SEPARATOR);
    return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true);
}
function compareDateTime(dt1, dt2) {
    if (!(dt1 && dt2))
        return undefined;
    const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
    const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
    const res = compareDate(d1, d2);
    if (res === undefined)
        return undefined;
    return res || compareTime(t1, t2);
}
const NOT_URI_FRAGMENT = /\/|:/;
const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
function uri(str) {
    // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
    return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
function byte(str) {
    BYTE.lastIndex = 0;
    return BYTE.test(str);
}
const MIN_INT32 = -(2 ** 31);
const MAX_INT32 = 2 ** 31 - 1;
function validateInt32(value) {
    return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
}
function validateInt64(value) {
    // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64
    return Number.isInteger(value);
}
function validateNumber() {
    return true;
}
const Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
    if (Z_ANCHOR.test(str))
        return false;
    try {
        new RegExp(str);
        return true;
    }
    catch (e) {
        return false;
    }
}
//# sourceMappingURL=formats.js.map{"version":3,"file":"formats.js","sourceRoot":"","sources":["../src/formats.ts"],"names":[],"mappings":";;;AAmCA,SAAS,MAAM,CACb,QAA0C,EAC1C,OAA8B;IAE9B,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAA;AAC5B,CAAC;AAEY,QAAA,WAAW,GAAmB;IACzC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC;IAC/B,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC;IAC/B,WAAW,EAAE,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC;IAC/C,2DAA2D;IAC3D,QAAQ,EAAE,wEAAwE;IAClF,GAAG;IACH,eAAe,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;AACnC,CAAC;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAA;AAC/B,MAAM,GAAG,GACP,8nCAA8nC,CAAA;AAEhoC,SAAS,GAAG,CAAC,GAAW;IACtB,gGAAgG;IAChG,OAAO,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACpD,CAAC;AAED,MAAM,IAAI,GAAG,oEAAoE,CAAA;AAEjF,SAAS,IAAI,CAAC,GAAW;IACvB,IAAI,CAAC,SAAS,GAAG,CAAC,CAAA;IAClB,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACvB,CAAC;AAED,MAAM,SAAS,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;AAC5B,MAAM,SAAS,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAE7B,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,SAAS,IAAI,KAAK,IAAI,SAAS,CAAA;AAC5E,CAAC;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,4FAA4F;IAC5F,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAChC,CAAC;AAED,SAAS,cAAc;IACrB,OAAO,IAAI,CAAA;AACb,CAAC;AAED,MAAM,QAAQ,GAAG,UAAU,CAAA;AAC3B,SAAS,KAAK,CAAC,GAAW;IACxB,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAA;IACpC,IAAI;QACF,IAAI,MAAM,CAAC,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAA;KACb;AACH,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const formats_1 = require("./formats");
const limit_1 = require("./limit");
const codegen_1 = require("ajv/dist/compile/codegen");
const fullName = new codegen_1.Name("fullFormats");
const fastName = new codegen_1.Name("fastFormats");
const formatsPlugin = (ajv, opts = { keywords: true }) => {
    if (Array.isArray(opts)) {
        addFormats(ajv, opts, formats_1.fullFormats, fullName);
        return ajv;
    }
    const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
    const list = opts.formats || formats_1.formatNames;
    addFormats(ajv, list, formats, exportName);
    if (opts.keywords)
        limit_1.default(ajv);
    return ajv;
};
formatsPlugin.get = (name, mode = "full") => {
    const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
    const f = formats[name];
    if (!f)
        throw new Error(`Unknown format "${name}"`);
    return f;
};
function addFormats(ajv, list, fs, exportName) {
    var _a;
    var _b;
    (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = codegen_1._ `require("ajv-formats/dist/formats").${exportName}`);
    for (const f of list)
        ajv.addFormat(f, fs[f]);
}
module.exports = exports = formatsPlugin;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = formatsPlugin;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,uCAOkB;AAClB,mCAAiC;AAGjC,sDAAgD;AAgBhD,MAAM,QAAQ,GAAG,IAAI,cAAI,CAAC,aAAa,CAAC,CAAA;AACxC,MAAM,QAAQ,GAAG,IAAI,cAAI,CAAC,aAAa,CAAC,CAAA;AAExC,MAAM,aAAa,GAAkB,CACnC,GAAQ,EACR,OAA6B,EAAC,QAAQ,EAAE,IAAI,EAAC,EACxC,EAAE;IACP,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACvB,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,qBAAW,EAAE,QAAQ,CAAC,CAAA;QAC5C,OAAO,GAAG,CAAA;KACX;IACD,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GACzB,IA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
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatLimitDefinition = void 0;
const ajv_1 = require("ajv");
const codegen_1 = require("ajv/dist/compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => codegen_1.str `should be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => codegen_1._ `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
exports.formatLimitDefinition = {
    keyword: Object.keys(KWDs),
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self } = it;
        if (!opts.validateFormats)
            return;
        const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
        if (fCxt.$data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fmt = gen.const("fmt", codegen_1._ `${fmts}[${fCxt.schemaCode}]`);
            cxt.fail$data(codegen_1.or(codegen_1._ `typeof ${fmt} != "object"`, codegen_1._ `${fmt} instanceof RegExp`, codegen_1._ `typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
            const format = fCxt.schema;
            const fmtDef = self.formats[format];
            if (!fmtDef || fmtDef === true)
                return;
            if (typeof fmtDef != "object" ||
                fmtDef instanceof RegExp ||
                typeof fmtDef.compare != "function") {
                throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
            }
            const fmt = gen.scopeValue("formats", {
                key: format,
                ref: fmtDef,
                code: opts.code.formats ? codegen_1._ `${opts.code.formats}${codegen_1.getProperty(format)}` : undefined,
            });
            cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
            return codegen_1._ `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
    },
    dependencies: ["format"],
};
const formatLimitPlugin = (ajv) => {
    ajv.addKeyword(exports.formatLimitDefinition);
    return ajv;
};
exports.default = formatLimitPlugin;
//# sourceMappingURL=limit.js.map{"version":3,"file":"limit.js","sourceRoot":"","sources":["../src/limit.ts"],"names":[],"mappings":";;;AAWA,6BAA8B;AAC9B,sDAA2E;AAM3E,MAAM,GAAG,GAAG,mBAAS,CAAA;AAErB,MAAM,IAAI,GAA4D;IACpE,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IAC/D,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAChE,CAAA;AAID,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,aAAG,CAAA,aAAa,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,IAAI,UAAU,EAAE;IAC9F,MAAM,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAChC,WAAC,CAAA,gBAAgB,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,YAAY,UAAU,GAAG;CACvE,CAAA;AAEY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AAO,CAAC,MAAM,CAAC,CAAA;YAC5D,IAAI,CAAC,MAAM,IAAI,MAAM,KAAK,IAAI;gBAAE,OAAM;YACtC,IACE,OAAO,MAAM,IAAI,QAAQ;gBACzB,MAAM,YAAY,MAAM;gBACxB,OAAO,MAAM,CAAC,OAAO,IAAI,UAAU,EACnC;gBACA,MAAM,IAAI,KAAK,CAAC,IAAI,OAAO,cAAc,MAAM,sCAAsC,CAAC,CAAA;aACvF;YACD,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE;gBACpC,GAAG,EAAE,MAAM;gBACX,GAAG,EAAE,MAAM;gBACX,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,WAAC,CAAA,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,GAAG,qBAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;aACpF,CAAC,CAAA;YAEF,GAAG,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAA;QACjC,CAAC;QAED,SAAS,WAAW,CAAC,GAAS;YAC5B,OAAO,WAAC,CAAA,GAAG,GAAG,YAAY,IAAI,KAAK,UAAU,KAAK,IAAI,CAAC,OAAc,CAAC,CAAC,IAAI,IAAI,CAAA;QACjF,CAAC;IACH,CAAC;IACD,YAAY,EAAE,CAAC,QAAQ,CAAC;CACzB,CAAA;AAED,MAAM,iBAAiB,GAAsB,CAAC,GAAQ,EAAO,EAAE;IAC7D,GAAG,CAAC,UAAU,CAAC,6BAAqB,CAAC,CAAA;IACrC,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,kBAAe,iBAAiB,CAAA"}
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
v10.12.0
The MIT License (MIT)

Copyright (c) 2020-present Fabio Spampinato

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
{
  "name": "atomically",
  "description": "Read and write files atomically and reliably.",
  "version": "1.7.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "license": "MIT",
  "author": {
    "name": "Fabio Spampinato",
    "email": "spampinabio@gmail.com"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/fabiospampinato/atomically.git"
  },
  "engines": {
    "node": ">=10.12.0"
  },
  "dependencies": {},
  "devDependencies": {
    "@types/node": "^12.7.2",
    "lodash": "^4.17.19",
    "mkdirp": "^1.0.4",
    "promise-resolve-timeout": "^1.2.1",
    "require-inject": "^1.4.4",
    "rimraf": "^3.0.2",
    "tap": "^14.10.7",
    "typescript": "^3.5.3",
    "typescript-transform-export-interop": "^1.0.2",
    "write-file-atomic": "^3.0.3"
  }
}{
  "compilerOptions": {
    "alwaysStrict": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "inlineSourceMap": false,
    "jsx": "react",
    "lib": ["dom", "scripthost", "es2015", "es2016", "es2017", "es2018", "es2019", "es2020"],
    "module": "commonjs",
    "moduleResolution": "node",
    "newLine": "LF",
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "outDir": "dist",
    "pretty": true,
    "strictNullChecks": true,
    "target": "es2018"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}

/* IMPORT */

const fs = require ( 'fs' ),
      os = require ( 'os' ),
      path = require ( 'path' ),
      delay = require ( 'promise-resolve-timeout' ),
      writeFileAtomic = require ( 'write-file-atomic' ),
      {writeFile, writeFileSync} = require ( '../dist' );

/* BENCHMARK */

const TEMP = os.tmpdir (),
      DST = i => path.join ( TEMP, `atomically-temp-${i}.txt` ),
      ITERATIONS = 250;

const runSingleAsync = async ( name, fn, buffer, options ) => {
  console.time ( name );
  for ( let i = 0; i < ITERATIONS; i++ ) {
    await fn ( DST ( i ), buffer, options );
  }
  console.timeEnd ( name );
  await delay ( 1000 );
};

const runSingleSync = async ( name, fn, buffer, options ) => {
  console.time ( name );
  for ( let i = 0; i < ITERATIONS; i++ ) {
    fn ( DST ( i ), buffer, options );
  }
  console.timeEnd ( name );
  await delay ( 1000 );
};

const runAllDummy = () => { // Preparation run
  runSingleSync ( 'dummy', fs.writeFileSync, '' );
};

const runAllAsync = async ( name, buffer ) => {
  await runSingleAsync ( `${name} -> async -> write-file-atomic`, writeFileAtomic, buffer );
  await runSingleAsync ( `${name} -> async -> write-file-atomic (fastest)`, writeFileAtomic, buffer, { fsync: false } );
  await runSingleAsync ( `${name} -> async -> atomically`, writeFile, buffer );
  await runSingleAsync ( `${name} -> async -> atomically (faster)`, writeFile, buffer, { mode: false, chown: false, fsyncWait: false } );
  await runSingleAsync ( `${name} -> async -> atomically (fastest)`, writeFile, buffer, { mode: false, chown: false, fsync: false } );
};

const runAllSync = ( name, buffer ) => {
  runSingleSync ( `${name} -> sync -> write-file-atomic`, writeFileAtomic.sync, buffer );
  runSingleSync ( `${name} -> sync -> write-file-atomic (fastest)`, writeFileAtomic.sync, buffer, { fsync: false } );
  runSingleSync ( `${name} -> sync -> atomically`, writeFileSync, buffer );
  runSingleSync ( `${name} -> sync -> atomically (faster)`, writeFileSync, buffer, { mode: false, chown: false, fsyncWait: false } );
  runSingleSync ( `${name} -> sync -> atomically (fastest)`, writeFileSync, buffer, { mode: false, chown: false, fsync: false } );
};

const runAll = async ( name, buffer ) => {
  await runAllAsync ( name, buffer );
  console.log ( '-------------------' );
  runAllSync ( name, buffer );
};

const run = async () => {
  runAllDummy ();
  console.log ( '===================' );
  await runAll ( '100kb', Buffer.allocUnsafe ( 100 * 1024 ) );
  console.log ( '===================' );
  await runAll ( '10kb', Buffer.allocUnsafe ( 10 * 1024 ) );
  console.log ( '===================' );
  await runAll ( '1kb', Buffer.allocUnsafe ( 1024 ) );
  console.log ( '===================' );
};

run ();

/* CONSTS */

const DEFAULT_ENCODING = 'utf8';

const DEFAULT_FILE_MODE = 0o666;

const DEFAULT_FOLDER_MODE = 0o777;

const DEFAULT_READ_OPTIONS = {};

const DEFAULT_WRITE_OPTIONS = {};

const DEFAULT_TIMEOUT_ASYNC = 5000;

const DEFAULT_TIMEOUT_SYNC = 100;

const IS_POSIX = !!process.getuid;

const IS_USER_ROOT = process.getuid ? !process.getuid () : false;

const LIMIT_BASENAME_LENGTH = 128; //TODO: fetch the real limit from the filesystem //TODO: fetch the whole-path length limit too

const LIMIT_FILES_DESCRIPTORS = 10000; //TODO: fetch the real limit from the filesystem

const NOOP = () => {};

/* EXPORT */

export {DEFAULT_ENCODING, DEFAULT_FILE_MODE, DEFAULT_FOLDER_MODE, DEFAULT_READ_OPTIONS, DEFAULT_WRITE_OPTIONS, DEFAULT_TIMEOUT_ASYNC, DEFAULT_TIMEOUT_SYNC, IS_POSIX, IS_USER_ROOT, LIMIT_BASENAME_LENGTH, LIMIT_FILES_DESCRIPTORS, NOOP};

/* IMPORT */

import * as path from 'path';
import {DEFAULT_ENCODING, DEFAULT_FILE_MODE, DEFAULT_FOLDER_MODE, DEFAULT_READ_OPTIONS, DEFAULT_WRITE_OPTIONS, DEFAULT_TIMEOUT_ASYNC, DEFAULT_TIMEOUT_SYNC, IS_POSIX} from './consts';
import FS from './utils/fs';
import Lang from './utils/lang';
import Scheduler from './utils/scheduler';
import Temp from './utils/temp';
import {Callback, Data, Disposer, Path, ReadOptions, WriteOptions} from './types';

/* ATOMICALLY */

function readFile ( filePath: Path, options: string | ReadOptions & { encoding: string } ): Promise<string>;
function readFile ( filePath: Path, options?: ReadOptions ): Promise<Buffer>;
function readFile ( filePath: Path, options: string | ReadOptions = DEFAULT_READ_OPTIONS ): Promise<Buffer | string> {

  if ( Lang.isString ( options ) ) return readFile ( filePath, { encoding: options } );

  const timeout = Date.now () + ( options.timeout ?? DEFAULT_TIMEOUT_ASYNC );

  return FS.readFileRetry ( timeout )( filePath, options );

};

function readFileSync ( filePath: Path, options: string | ReadOptions & { encoding: string } ): string;
function readFileSync ( filePath: Path, options?: ReadOptions ): Buffer;
function readFileSync ( filePath: Path, options: string | ReadOptions = DEFAULT_READ_OPTIONS ): Buffer | string {

  if ( Lang.isString ( options ) ) return readFileSync ( filePath, { encoding: options } );

  const timeout = Date.now () + ( options.timeout ?? DEFAULT_TIMEOUT_SYNC );

  return FS.readFileSyncRetry ( timeout )( filePath, options );

};

const writeFile = ( filePath: Path, data: Data, options?: string | WriteOptions | Callback, callback?: Callback ): Promise<void> => {

  if ( Lang.isFunction ( options ) ) return writeFile ( filePath, data, DEFAULT_WRITE_OPTIONS, options );

  const promise = writeFileAsync ( filePath, data, options );

  if ( callback ) promise.then ( callback, callback );

  return promise;

};

const writeFileAsync = async ( filePath: Path, data: Data, options: string | WriteOptions = DEFAULT_WRITE_OPTIONS ): Promise<void> => {

  if ( Lang.isString ( options ) ) return writeFileAsync ( filePath, data, { encoding: options } );

  const timeout = Date.now () + ( options.timeout ?? DEFAULT_TIMEOUT_ASYNC );

  let schedulerCustomDisposer: Disposer | null = null,
      schedulerDisposer: Disposer | null = null,
      tempDisposer: Disposer | null = null,
      tempPath: string | null = null,
      fd: number | null = null;

  try {

    if ( options.schedule ) schedulerCustomDisposer = await options.schedule ( filePath );

    schedulerDisposer = await Scheduler.schedule ( filePath );

    filePath = await FS.realpathAttempt ( filePath ) || filePath;

    [tempPath, tempDisposer] = Temp.get ( filePath, options.tmpCreate || Temp.create, !( options.tmpPurge === false ) );

    const useStatChown = IS_POSIX && Lang.isUndefined ( options.chown ),
          useStatMode = Lang.isUndefined ( options.mode );

    if ( useStatChown || useStatMode ) {

      const stat = await FS.statAttempt ( filePath );

      if ( stat ) {

        options = { ...options };

        if ( useStatChown ) options.chown = { uid: stat.uid, gid: stat.gid };

        if ( useStatMode ) options.mode = stat.mode;

      }

    }

    const parentPath = path.dirname ( filePath );

    await FS.mkdirAttempt ( parentPath, {
      mode: DEFAULT_FOLDER_MODE,
      recursive: true
    });

    fd = await FS.openRetry ( timeout )( tempPath, 'w', options.mode || DEFAULT_FILE_MODE );

    if ( options.tmpCreated ) options.tmpCreated ( tempPath );

    if ( Lang.isString ( data ) ) {

      await FS.writeRetry ( timeout )( fd, data, 0, options.encoding || DEFAULT_ENCODING );

    } else if ( !Lang.isUndefined ( data ) ) {

      await FS.writeRetry ( timeout )( fd, data, 0, data.length, 0 );

    }

    if ( options.fsync !== false ) {

      if ( options.fsyncWait !== false ) {

        await FS.fsyncRetry ( timeout )( fd );

      } else {

        FS.fsyncAttempt ( fd );

      }

    }

    await FS.closeRetry ( timeout )( fd );

    fd = null;

    if ( options.chown ) await FS.chownAttempt ( tempPath, options.chown.uid, options.chown.gid );

    if ( options.mode ) await FS.chmodAttempt ( tempPath, options.mode );

    try {

      await FS.renameRetry ( timeout )( tempPath, filePath );

    } catch ( error ) {

      if ( error.code !== 'ENAMETOOLONG' ) throw error;

      await FS.renameRetry ( timeout )( tempPath, Temp.truncate ( filePath ) );

    }

    tempDisposer ();

    tempPath = null;

  } finally {

    if ( fd ) await FS.closeAttempt ( fd );

    if ( tempPath ) Temp.purge ( tempPath );

    if ( schedulerCustomDisposer ) schedulerCustomDisposer ();

    if ( schedulerDisposer ) schedulerDisposer ();

  }

};

const writeFileSync = ( filePath: Path, data: Data, options: string | WriteOptions = DEFAULT_WRITE_OPTIONS ): void => {

  if ( Lang.isString ( options ) ) return writeFileSync ( filePath, data, { encoding: options } );

  const timeout = Date.now () + ( options.timeout ?? DEFAULT_TIMEOUT_SYNC );

  let tempDisposer: Disposer | null = null,
      tempPath: string | null = null,
      fd: number | null = null;

  try {

    filePath = FS.realpathSyncAttempt ( filePath ) || filePath;

    [tempPath, tempDisposer] = Temp.get ( filePath, options.tmpCreate || Temp.create, !( options.tmpPurge === false ) );

    const useStatChown = IS_POSIX && Lang.isUndefined ( options.chown ),
          useStatMode = Lang.isUndefined ( options.mode );

    if ( useStatChown || useStatMode ) {

      const stat = FS.statSyncAttempt ( filePath );

      if ( stat ) {

        options = { ...options };

        if ( useStatChown ) options.chown = { uid: stat.uid, gid: stat.gid };

        if ( useStatMode ) options.mode = stat.mode;

      }

    }

    const parentPath = path.dirname ( filePath );

    FS.mkdirSyncAttempt ( parentPath, {
      mode: DEFAULT_FOLDER_MODE,
      recursive: true
    });

    fd = FS.openSyncRetry ( timeout )( tempPath, 'w', options.mode || DEFAULT_FILE_MODE );

    if ( options.tmpCreated ) options.tmpCreated ( tempPath );

    if ( Lang.isString ( data ) ) {

      FS.writeSyncRetry ( timeout )( fd, data, 0, options.encoding || DEFAULT_ENCODING );

    } else if ( !Lang.isUndefined ( data ) ) {

      FS.writeSyncRetry ( timeout )( fd, data, 0, data.length, 0 );

    }

    if ( options.fsync !== false ) {

      if ( options.fsyncWait !== false ) {

        FS.fsyncSyncRetry ( timeout )( fd );

      } else {

        FS.fsyncAttempt ( fd );

      }

    }

    FS.closeSyncRetry ( timeout )( fd );

    fd = null;

    if ( options.chown ) FS.chownSyncAttempt ( tempPath, options.chown.uid, options.chown.gid );

    if ( options.mode ) FS.chmodSyncAttempt ( tempPath, options.mode );

    try {

      FS.renameSyncRetry ( timeout )( tempPath, filePath );

    } catch ( error ) {

      if ( error.code !== 'ENAMETOOLONG' ) throw error;

      FS.renameSyncRetry ( timeout )( tempPath, Temp.truncate ( filePath ) );

    }

    tempDisposer ();

    tempPath = null;

  } finally {

    if ( fd ) FS.closeSyncAttempt ( fd );

    if ( tempPath ) Temp.purge ( tempPath );

  }

};

/* EXPORT */

export {readFile, readFileSync, writeFile, writeFileSync};

/* TYPES */

type Callback = ( error: Exception | void ) => any;

type Data = Buffer | string | undefined;

type Disposer = () => void;

type Exception = NodeJS.ErrnoException;

type FN<Arguments extends any[] = any[], Return = any> = ( ...args: Arguments ) => Return;

type Path = string;

type ReadOptions = {
  encoding?: string | null,
  mode?: string | number | false,
  timeout?: number
};

type WriteOptions = {
  chown?: { gid: number, uid: number } | false,
  encoding?: string | null,
  fsync?: boolean,
  fsyncWait?: boolean,
  mode?: string | number | false,
  schedule?: ( filePath: string ) => Promise<Disposer>,
  timeout?: number,
  tmpCreate?: ( filePath: string ) => string,
  tmpCreated?: ( filePath: string ) => any,
  tmpPurge?: boolean
};

/* EXPORT */

export {Callback, Data, Disposer, Exception, FN, Path, ReadOptions, WriteOptions};

/* IMPORT */

import {NOOP} from '../consts';
import {Exception, FN} from '../types';

/* ATTEMPTIFY */

//TODO: Maybe publish this as a standalone package
//FIXME: The type castings here aren't exactly correct

const attemptifyAsync = <T extends FN> ( fn: T, onError: FN<[Exception]> = NOOP ): T => {

  return function () {

    return fn.apply ( undefined, arguments ).catch ( onError );

  } as T;

};

const attemptifySync = <T extends FN> ( fn: T, onError: FN<[Exception]> = NOOP ): T => {

  return function () {

    try {

      return fn.apply ( undefined, arguments );

    } catch ( error ) {

      return onError ( error );

    }

  } as T;

};

/* EXPORT */

export {attemptifyAsync, attemptifySync};

/* IMPORT */

import * as fs from 'fs';
import {promisify} from 'util';
import {attemptifyAsync, attemptifySync} from './attemptify';
import Handlers from './fs_handlers';
import {retryifyAsync, retryifySync} from './retryify';

/* FS */

const FS = {

  chmodAttempt: attemptifyAsync ( promisify ( fs.chmod ), Handlers.onChangeError ),
  chownAttempt: attemptifyAsync ( promisify ( fs.chown ), Handlers.onChangeError ),
  closeAttempt: attemptifyAsync ( promisify ( fs.close ) ),
  fsyncAttempt: attemptifyAsync ( promisify ( fs.fsync ) ),
  mkdirAttempt: attemptifyAsync ( promisify ( fs.mkdir ) ),
  realpathAttempt: attemptifyAsync ( promisify ( fs.realpath ) ),
  statAttempt: attemptifyAsync ( promisify ( fs.stat ) ),
  unlinkAttempt: attemptifyAsync ( promisify ( fs.unlink ) ),

  closeRetry: retryifyAsync ( promisify ( fs.close ), Handlers.isRetriableError ),
  fsyncRetry: retryifyAsync ( promisify ( fs.fsync ), Handlers.isRetriableError ),
  openRetry: retryifyAsync ( promisify ( fs.open ), Handlers.isRetriableError ),
  readFileRetry: retryifyAsync ( promisify ( fs.readFile ), Handlers.isRetriableError ),
  renameRetry: retryifyAsync ( promisify ( fs.rename ), Handlers.isRetriableError ),
  statRetry: retryifyAsync ( promisify ( fs.stat ), Handlers.isRetriableError ),
  writeRetry: retryifyAsync ( promisify ( fs.write ), Handlers.isRetriableError ),

  chmodSyncAttempt: attemptifySync ( fs.chmodSync, Handlers.onChangeError ),
  chownSyncAttempt: attemptifySync ( fs.chownSync, Handlers.onChangeError ),
  closeSyncAttempt: attemptifySync ( fs.closeSync ),
  mkdirSyncAttempt: attemptifySync ( fs.mkdirSync ),
  realpathSyncAttempt: attemptifySync ( fs.realpathSync ),
  statSyncAttempt: attemptifySync ( fs.statSync ),
  unlinkSyncAttempt: attemptifySync ( fs.unlinkSync ),

  closeSyncRetry: retryifySync ( fs.closeSync, Handlers.isRetriableError ),
  fsyncSyncRetry: retryifySync ( fs.fsyncSync, Handlers.isRetriableError ),
  openSyncRetry: retryifySync ( fs.openSync, Handlers.isRetriableError ),
  readFileSyncRetry: retryifySync ( fs.readFileSync, Handlers.isRetriableError ),
  renameSyncRetry: retryifySync ( fs.renameSync, Handlers.isRetriableError ),
  statSyncRetry: retryifySync ( fs.statSync, Handlers.isRetriableError ),
  writeSyncRetry: retryifySync ( fs.writeSync, Handlers.isRetriableError )

};

/* EXPORT */

export default FS;

/* IMPORT */

import {IS_USER_ROOT} from '../consts';
import {Exception} from '../types';

/* FS HANDLERS */

const Handlers = {

  isChangeErrorOk: ( error: Exception ): boolean => { //URL: https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342

    const {code} = error;

    if ( code === 'ENOSYS' ) return true;

    if ( !IS_USER_ROOT && ( code === 'EINVAL' || code === 'EPERM' ) ) return true;

    return false;

  },

  isRetriableError: ( error: Exception ): boolean => {

    const {code} = error;

    if ( code === 'EMFILE' || code === 'ENFILE' || code === 'EAGAIN' || code === 'EBUSY' || code === 'EACCESS' || code === 'EACCS' || code === 'EPERM' ) return true;

    return false;

  },

  onChangeError: ( error: Exception ): void => {

    if ( Handlers.isChangeErrorOk ( error ) ) return;

    throw error;

  }

};

/* EXPORT */

export default Handlers;

/* LANG */

const Lang = {

  isFunction: ( x: any ): x is Function => {

    return typeof x === 'function';

  },

  isString: ( x: any ): x is string => {

    return typeof x === 'string';

  },

  isUndefined: ( x: any ): x is undefined => {

    return typeof x === 'undefined';

  }

};

/* EXPORT */

export default Lang;

/* IMPORT */

import {Exception, FN} from '../types';
import RetryfyQueue from './retryify_queue';

/* RETRYIFY */

const retryifyAsync = <T extends FN> ( fn: T, isRetriableError: FN<[Exception], boolean | void> ): FN<[number], T> => {

  return function ( timestamp: number ) {

    return function attempt () {

      return RetryfyQueue.schedule ().then ( cleanup => {

        return fn.apply ( undefined, arguments ).then ( result => {

          cleanup ();

          return result;

        }, error => {

          cleanup ();

          if ( Date.now () >= timestamp ) throw error;

          if ( isRetriableError ( error ) ) {

            const delay = Math.round ( 100 + ( 400 * Math.random () ) ),
                  delayPromise = new Promise ( resolve => setTimeout ( resolve, delay ) );

            return delayPromise.then ( () => attempt.apply ( undefined, arguments ) );

          }

          throw error;

        });

      });

    } as T;

  };

};

const retryifySync = <T extends FN> ( fn: T, isRetriableError: FN<[Exception], boolean | void> ): FN<[number], T> => {

  return function ( timestamp: number ) {

    return function attempt () {

      try {

        return fn.apply ( undefined, arguments );

      } catch ( error ) {

        if ( Date.now () > timestamp ) throw error;

        if ( isRetriableError ( error ) ) return attempt.apply ( undefined, arguments );

        throw error;

      }

    } as T;

  };

};

/* EXPORT */

export {retryifyAsync, retryifySync};

/* IMPORT */

import {LIMIT_FILES_DESCRIPTORS} from '../consts';

/* RETRYIFY QUEUE */

const RetryfyQueue = {

  interval: 25,
  intervalId: <NodeJS.Timeout | undefined> undefined,
  limit: LIMIT_FILES_DESCRIPTORS,
  queueActive: new Set<Function> (),
  queueWaiting: new Set<Function> (),

  init: (): void => {

    if ( RetryfyQueue.intervalId ) return;

    RetryfyQueue.intervalId = setInterval ( RetryfyQueue.tick, RetryfyQueue.interval );

  },

  reset: (): void => {

    if ( !RetryfyQueue.intervalId ) return;

    clearInterval ( RetryfyQueue.intervalId );

    delete RetryfyQueue.intervalId;

  },

  add: ( fn: Function ): void => {

    RetryfyQueue.queueWaiting.add ( fn );

    if ( RetryfyQueue.queueActive.size < ( RetryfyQueue.limit / 2 ) ) { // Active queue not under preassure, executing immediately

      RetryfyQueue.tick ();

    } else {

      RetryfyQueue.init ();

    }

  },

  remove: ( fn: Function ): void => {

    RetryfyQueue.queueWaiting.delete ( fn );

    RetryfyQueue.queueActive.delete ( fn );

  },

  schedule: (): Promise<Function> => {

    return new Promise ( resolve => {

      const cleanup = () => RetryfyQueue.remove ( resolver );

      const resolver = () => resolve ( cleanup );

      RetryfyQueue.add ( resolver );

    });

  },

  tick: (): void => {

    if ( RetryfyQueue.queueActive.size >= RetryfyQueue.limit ) return;

    if ( !RetryfyQueue.queueWaiting.size ) return RetryfyQueue.reset ();

    for ( const fn of RetryfyQueue.queueWaiting ) {

      if ( RetryfyQueue.queueActive.size >= RetryfyQueue.limit ) break;

      RetryfyQueue.queueWaiting.delete ( fn );
      RetryfyQueue.queueActive.add ( fn );

      fn ();

    }

  }

};

/* EXPORT */

export default RetryfyQueue;

/* IMPORT */

import {Disposer} from '../types';

/* VARIABLES */

const Queues: Record<string, Function[] | undefined> = {};

/* SCHEDULER */

//TODO: Maybe publish this as a standalone package

const Scheduler = {

  next: ( id: string ): void => {

    const queue = Queues[id];

    if ( !queue ) return;

    queue.shift ();

    const job = queue[0];

    if ( job ) {

      job ( () => Scheduler.next ( id ) );

    } else {

      delete Queues[id];

    }

  },

  schedule: ( id: string ): Promise<Disposer> => {

    return new Promise ( resolve => {

      let queue = Queues[id];

      if ( !queue ) queue = Queues[id] = [];

      queue.push ( resolve );

      if ( queue.length > 1 ) return;

      resolve ( () => Scheduler.next ( id ) );

    });

  }

};

/* EXPORT */

export default Scheduler;

/* IMPORT */

import * as path from 'path';
import {LIMIT_BASENAME_LENGTH} from '../consts';
import {Disposer} from '../types';
import FS from './fs';

/* TEMP */

//TODO: Maybe publish this as a standalone package

const Temp = {

  store: <Record<string, boolean>> {}, // filePath => purge

  create: ( filePath: string ): string => {

    const randomness = `000000${Math.floor ( Math.random () * 16777215 ).toString ( 16 )}`.slice ( -6 ), // 6 random-enough hex characters
          timestamp = Date.now ().toString ().slice ( -10 ), // 10 precise timestamp digits
          prefix = 'tmp-',
          suffix = `.${prefix}${timestamp}${randomness}`,
          tempPath = `${filePath}${suffix}`;

    return tempPath;

  },

  get: ( filePath: string, creator: ( filePath: string ) => string, purge: boolean = true ): [string, Disposer] => {

    const tempPath = Temp.truncate ( creator ( filePath ) );

    if ( tempPath in Temp.store ) return Temp.get ( filePath, creator, purge ); // Collision found, try again

    Temp.store[tempPath] = purge;

    const disposer = () => delete Temp.store[tempPath];

    return [tempPath, disposer];

  },

  purge: ( filePath: string ): void => {

    if ( !Temp.store[filePath] ) return;

    delete Temp.store[filePath];

    FS.unlinkAttempt ( filePath );

  },

  purgeSync: ( filePath: string ): void => {

    if ( !Temp.store[filePath] ) return;

    delete Temp.store[filePath];

    FS.unlinkSyncAttempt ( filePath );

  },

  purgeSyncAll: (): void => {

    for ( const filePath in Temp.store ) {

      Temp.purgeSync ( filePath );

    }

  },

  truncate: ( filePath: string ): string => { // Truncating paths to avoid getting an "ENAMETOOLONG" error //FIXME: This doesn't really always work, the actual filesystem limits must be detected for this to be implemented correctly

    const basename = path.basename ( filePath );

    if ( basename.length <= LIMIT_BASENAME_LENGTH ) return filePath; //FIXME: Rough and quick attempt at detecting ok lengths

    const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec ( basename );

    if ( !truncable ) return filePath; //FIXME: No truncable part detected, can't really do much without also changing the parent path, which is unsafe, hoping for the best here

    const truncationLength = basename.length - LIMIT_BASENAME_LENGTH;

    return `${filePath.slice ( 0, - basename.length )}${truncable[1]}${truncable[2].slice ( 0, - truncationLength )}${truncable[3]}`; //FIXME: The truncable part might be shorter than needed here

  }

};

/* INIT */

process.on ( 'exit', Temp.purgeSyncAll ); // Ensuring purgeable temp files are purged on exit

/* EXPORT */

export default Temp;
"use strict";
/* CONSTS */
Object.defineProperty(exports, "__esModule", { value: true });
exports.NOOP = exports.LIMIT_FILES_DESCRIPTORS = exports.LIMIT_BASENAME_LENGTH = exports.IS_USER_ROOT = exports.IS_POSIX = exports.DEFAULT_TIMEOUT_SYNC = exports.DEFAULT_TIMEOUT_ASYNC = exports.DEFAULT_WRITE_OPTIONS = exports.DEFAULT_READ_OPTIONS = exports.DEFAULT_FOLDER_MODE = exports.DEFAULT_FILE_MODE = exports.DEFAULT_ENCODING = void 0;
const DEFAULT_ENCODING = 'utf8';
exports.DEFAULT_ENCODING = DEFAULT_ENCODING;
const DEFAULT_FILE_MODE = 0o666;
exports.DEFAULT_FILE_MODE = DEFAULT_FILE_MODE;
const DEFAULT_FOLDER_MODE = 0o777;
exports.DEFAULT_FOLDER_MODE = DEFAULT_FOLDER_MODE;
const DEFAULT_READ_OPTIONS = {};
exports.DEFAULT_READ_OPTIONS = DEFAULT_READ_OPTIONS;
const DEFAULT_WRITE_OPTIONS = {};
exports.DEFAULT_WRITE_OPTIONS = DEFAULT_WRITE_OPTIONS;
const DEFAULT_TIMEOUT_ASYNC = 5000;
exports.DEFAULT_TIMEOUT_ASYNC = DEFAULT_TIMEOUT_ASYNC;
const DEFAULT_TIMEOUT_SYNC = 100;
exports.DEFAULT_TIMEOUT_SYNC = DEFAULT_TIMEOUT_SYNC;
const IS_POSIX = !!process.getuid;
exports.IS_POSIX = IS_POSIX;
const IS_USER_ROOT = process.getuid ? !process.getuid() : false;
exports.IS_USER_ROOT = IS_USER_ROOT;
const LIMIT_BASENAME_LENGTH = 128; //TODO: fetch the real limit from the filesystem //TODO: fetch the whole-path length limit too
exports.LIMIT_BASENAME_LENGTH = LIMIT_BASENAME_LENGTH;
const LIMIT_FILES_DESCRIPTORS = 10000; //TODO: fetch the real limit from the filesystem
exports.LIMIT_FILES_DESCRIPTORS = LIMIT_FILES_DESCRIPTORS;
const NOOP = () => { };
exports.NOOP = NOOP;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeFileSync = exports.writeFile = exports.readFileSync = exports.readFile = void 0;
const path = require("path");
const consts_1 = require("./consts");
const fs_1 = require("./utils/fs");
const lang_1 = require("./utils/lang");
const scheduler_1 = require("./utils/scheduler");
const temp_1 = require("./utils/temp");
function readFile(filePath, options = consts_1.DEFAULT_READ_OPTIONS) {
    var _a;
    if (lang_1.default.isString(options))
        return readFile(filePath, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_ASYNC);
    return fs_1.default.readFileRetry(timeout)(filePath, options);
}
exports.readFile = readFile;
;
function readFileSync(filePath, options = consts_1.DEFAULT_READ_OPTIONS) {
    var _a;
    if (lang_1.default.isString(options))
        return readFileSync(filePath, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_SYNC);
    return fs_1.default.readFileSyncRetry(timeout)(filePath, options);
}
exports.readFileSync = readFileSync;
;
const writeFile = (filePath, data, options, callback) => {
    if (lang_1.default.isFunction(options))
        return writeFile(filePath, data, consts_1.DEFAULT_WRITE_OPTIONS, options);
    const promise = writeFileAsync(filePath, data, options);
    if (callback)
        promise.then(callback, callback);
    return promise;
};
exports.writeFile = writeFile;
const writeFileAsync = async (filePath, data, options = consts_1.DEFAULT_WRITE_OPTIONS) => {
    var _a;
    if (lang_1.default.isString(options))
        return writeFileAsync(filePath, data, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_ASYNC);
    let schedulerCustomDisposer = null, schedulerDisposer = null, tempDisposer = null, tempPath = null, fd = null;
    try {
        if (options.schedule)
            schedulerCustomDisposer = await options.schedule(filePath);
        schedulerDisposer = await scheduler_1.default.schedule(filePath);
        filePath = await fs_1.default.realpathAttempt(filePath) || filePath;
        [tempPath, tempDisposer] = temp_1.default.get(filePath, options.tmpCreate || temp_1.default.create, !(options.tmpPurge === false));
        const useStatChown = consts_1.IS_POSIX && lang_1.default.isUndefined(options.chown), useStatMode = lang_1.default.isUndefined(options.mode);
        if (useStatChown || useStatMode) {
            const stat = await fs_1.default.statAttempt(filePath);
            if (stat) {
                options = { ...options };
                if (useStatChown)
                    options.chown = { uid: stat.uid, gid: stat.gid };
                if (useStatMode)
                    options.mode = stat.mode;
            }
        }
        const parentPath = path.dirname(filePath);
        await fs_1.default.mkdirAttempt(parentPath, {
            mode: consts_1.DEFAULT_FOLDER_MODE,
            recursive: true
        });
        fd = await fs_1.default.openRetry(timeout)(tempPath, 'w', options.mode || consts_1.DEFAULT_FILE_MODE);
        if (options.tmpCreated)
            options.tmpCreated(tempPath);
        if (lang_1.default.isString(data)) {
            await fs_1.default.writeRetry(timeout)(fd, data, 0, options.encoding || consts_1.DEFAULT_ENCODING);
        }
        else if (!lang_1.default.isUndefined(data)) {
            await fs_1.default.writeRetry(timeout)(fd, data, 0, data.length, 0);
        }
        if (options.fsync !== false) {
            if (options.fsyncWait !== false) {
                await fs_1.default.fsyncRetry(timeout)(fd);
            }
            else {
                fs_1.default.fsyncAttempt(fd);
            }
        }
        await fs_1.default.closeRetry(timeout)(fd);
        fd = null;
        if (options.chown)
            await fs_1.default.chownAttempt(tempPath, options.chown.uid, options.chown.gid);
        if (options.mode)
            await fs_1.default.chmodAttempt(tempPath, options.mode);
        try {
            await fs_1.default.renameRetry(timeout)(tempPath, filePath);
        }
        catch (error) {
            if (error.code !== 'ENAMETOOLONG')
                throw error;
            await fs_1.default.renameRetry(timeout)(tempPath, temp_1.default.truncate(filePath));
        }
        tempDisposer();
        tempPath = null;
    }
    finally {
        if (fd)
            await fs_1.default.closeAttempt(fd);
        if (tempPath)
            temp_1.default.purge(tempPath);
        if (schedulerCustomDisposer)
            schedulerCustomDisposer();
        if (schedulerDisposer)
            schedulerDisposer();
    }
};
const writeFileSync = (filePath, data, options = consts_1.DEFAULT_WRITE_OPTIONS) => {
    var _a;
    if (lang_1.default.isString(options))
        return writeFileSync(filePath, data, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_SYNC);
    let tempDisposer = null, tempPath = null, fd = null;
    try {
        filePath = fs_1.default.realpathSyncAttempt(filePath) || filePath;
        [tempPath, tempDisposer] = temp_1.default.get(filePath, options.tmpCreate || temp_1.default.create, !(options.tmpPurge === false));
        const useStatChown = consts_1.IS_POSIX && lang_1.default.isUndefined(options.chown), useStatMode = lang_1.default.isUndefined(options.mode);
        if (useStatChown || useStatMode) {
            const stat = fs_1.default.statSyncAttempt(filePath);
            if (stat) {
                options = { ...options };
                if (useStatChown)
                    options.chown = { uid: stat.uid, gid: stat.gid };
                if (useStatMode)
                    options.mode = stat.mode;
            }
        }
        const parentPath = path.dirname(filePath);
        fs_1.default.mkdirSyncAttempt(parentPath, {
            mode: consts_1.DEFAULT_FOLDER_MODE,
            recursive: true
        });
        fd = fs_1.default.openSyncRetry(timeout)(tempPath, 'w', options.mode || consts_1.DEFAULT_FILE_MODE);
        if (options.tmpCreated)
            options.tmpCreated(tempPath);
        if (lang_1.default.isString(data)) {
            fs_1.default.writeSyncRetry(timeout)(fd, data, 0, options.encoding || consts_1.DEFAULT_ENCODING);
        }
        else if (!lang_1.default.isUndefined(data)) {
            fs_1.default.writeSyncRetry(timeout)(fd, data, 0, data.length, 0);
        }
        if (options.fsync !== false) {
            if (options.fsyncWait !== false) {
                fs_1.default.fsyncSyncRetry(timeout)(fd);
            }
            else {
                fs_1.default.fsyncAttempt(fd);
            }
        }
        fs_1.default.closeSyncRetry(timeout)(fd);
        fd = null;
        if (options.chown)
            fs_1.default.chownSyncAttempt(tempPath, options.chown.uid, options.chown.gid);
        if (options.mode)
            fs_1.default.chmodSyncAttempt(tempPath, options.mode);
        try {
            fs_1.default.renameSyncRetry(timeout)(tempPath, filePath);
        }
        catch (error) {
            if (error.code !== 'ENAMETOOLONG')
                throw error;
            fs_1.default.renameSyncRetry(timeout)(tempPath, temp_1.default.truncate(filePath));
        }
        tempDisposer();
        tempPath = null;
    }
    finally {
        if (fd)
            fs_1.default.closeSyncAttempt(fd);
        if (tempPath)
            temp_1.default.purge(tempPath);
    }
};
exports.writeFileSync = writeFileSync;
"use strict";
/* TYPES */
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.attemptifySync = exports.attemptifyAsync = void 0;
const consts_1 = require("../consts");
/* ATTEMPTIFY */
//TODO: Maybe publish this as a standalone package
//FIXME: The type castings here aren't exactly correct
const attemptifyAsync = (fn, onError = consts_1.NOOP) => {
    return function () {
        return fn.apply(undefined, arguments).catch(onError);
    };
};
exports.attemptifyAsync = attemptifyAsync;
const attemptifySync = (fn, onError = consts_1.NOOP) => {
    return function () {
        try {
            return fn.apply(undefined, arguments);
        }
        catch (error) {
            return onError(error);
        }
    };
};
exports.attemptifySync = attemptifySync;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const util_1 = require("util");
const attemptify_1 = require("./attemptify");
const fs_handlers_1 = require("./fs_handlers");
const retryify_1 = require("./retryify");
/* FS */
const FS = {
    chmodAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.chmod), fs_handlers_1.default.onChangeError),
    chownAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.chown), fs_handlers_1.default.onChangeError),
    closeAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.close)),
    fsyncAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.fsync)),
    mkdirAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.mkdir)),
    realpathAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.realpath)),
    statAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.stat)),
    unlinkAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.unlink)),
    closeRetry: retryify_1.retryifyAsync(util_1.promisify(fs.close), fs_handlers_1.default.isRetriableError),
    fsyncRetry: retryify_1.retryifyAsync(util_1.promisify(fs.fsync), fs_handlers_1.default.isRetriableError),
    openRetry: retryify_1.retryifyAsync(util_1.promisify(fs.open), fs_handlers_1.default.isRetriableError),
    readFileRetry: retryify_1.retryifyAsync(util_1.promisify(fs.readFile), fs_handlers_1.default.isRetriableError),
    renameRetry: retryify_1.retryifyAsync(util_1.promisify(fs.rename), fs_handlers_1.default.isRetriableError),
    statRetry: retryify_1.retryifyAsync(util_1.promisify(fs.stat), fs_handlers_1.default.isRetriableError),
    writeRetry: retryify_1.retryifyAsync(util_1.promisify(fs.write), fs_handlers_1.default.isRetriableError),
    chmodSyncAttempt: attemptify_1.attemptifySync(fs.chmodSync, fs_handlers_1.default.onChangeError),
    chownSyncAttempt: attemptify_1.attemptifySync(fs.chownSync, fs_handlers_1.default.onChangeError),
    closeSyncAttempt: attemptify_1.attemptifySync(fs.closeSync),
    mkdirSyncAttempt: attemptify_1.attemptifySync(fs.mkdirSync),
    realpathSyncAttempt: attemptify_1.attemptifySync(fs.realpathSync),
    statSyncAttempt: attemptify_1.attemptifySync(fs.statSync),
    unlinkSyncAttempt: attemptify_1.attemptifySync(fs.unlinkSync),
    closeSyncRetry: retryify_1.retryifySync(fs.closeSync, fs_handlers_1.default.isRetriableError),
    fsyncSyncRetry: retryify_1.retryifySync(fs.fsyncSync, fs_handlers_1.default.isRetriableError),
    openSyncRetry: retryify_1.retryifySync(fs.openSync, fs_handlers_1.default.isRetriableError),
    readFileSyncRetry: retryify_1.retryifySync(fs.readFileSync, fs_handlers_1.default.isRetriableError),
    renameSyncRetry: retryify_1.retryifySync(fs.renameSync, fs_handlers_1.default.isRetriableError),
    statSyncRetry: retryify_1.retryifySync(fs.statSync, fs_handlers_1.default.isRetriableError),
    writeSyncRetry: retryify_1.retryifySync(fs.writeSync, fs_handlers_1.default.isRetriableError)
};
/* EXPORT */
exports.default = FS;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const consts_1 = require("../consts");
/* FS HANDLERS */
const Handlers = {
    isChangeErrorOk: (error) => {
        const { code } = error;
        if (code === 'ENOSYS')
            return true;
        if (!consts_1.IS_USER_ROOT && (code === 'EINVAL' || code === 'EPERM'))
            return true;
        return false;
    },
    isRetriableError: (error) => {
        const { code } = error;
        if (code === 'EMFILE' || code === 'ENFILE' || code === 'EAGAIN' || code === 'EBUSY' || code === 'EACCESS' || code === 'EACCS' || code === 'EPERM')
            return true;
        return false;
    },
    onChangeError: (error) => {
        if (Handlers.isChangeErrorOk(error))
            return;
        throw error;
    }
};
/* EXPORT */
exports.default = Handlers;
"use strict";
/* LANG */
Object.defineProperty(exports, "__esModule", { value: true });
const Lang = {
    isFunction: (x) => {
        return typeof x === 'function';
    },
    isString: (x) => {
        return typeof x === 'string';
    },
    isUndefined: (x) => {
        return typeof x === 'undefined';
    }
};
/* EXPORT */
exports.default = Lang;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryifySync = exports.retryifyAsync = void 0;
const retryify_queue_1 = require("./retryify_queue");
/* RETRYIFY */
const retryifyAsync = (fn, isRetriableError) => {
    return function (timestamp) {
        return function attempt() {
            return retryify_queue_1.default.schedule().then(cleanup => {
                return fn.apply(undefined, arguments).then(result => {
                    cleanup();
                    return result;
                }, error => {
                    cleanup();
                    if (Date.now() >= timestamp)
                        throw error;
                    if (isRetriableError(error)) {
                        const delay = Math.round(100 + (400 * Math.random())), delayPromise = new Promise(resolve => setTimeout(resolve, delay));
                        return delayPromise.then(() => attempt.apply(undefined, arguments));
                    }
                    throw error;
                });
            });
        };
    };
};
exports.retryifyAsync = retryifyAsync;
const retryifySync = (fn, isRetriableError) => {
    return function (timestamp) {
        return function attempt() {
            try {
                return fn.apply(undefined, arguments);
            }
            catch (error) {
                if (Date.now() > timestamp)
                    throw error;
                if (isRetriableError(error))
                    return attempt.apply(undefined, arguments);
                throw error;
            }
        };
    };
};
exports.retryifySync = retryifySync;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const consts_1 = require("../consts");
/* RETRYIFY QUEUE */
const RetryfyQueue = {
    interval: 25,
    intervalId: undefined,
    limit: consts_1.LIMIT_FILES_DESCRIPTORS,
    queueActive: new Set(),
    queueWaiting: new Set(),
    init: () => {
        if (RetryfyQueue.intervalId)
            return;
        RetryfyQueue.intervalId = setInterval(RetryfyQueue.tick, RetryfyQueue.interval);
    },
    reset: () => {
        if (!RetryfyQueue.intervalId)
            return;
        clearInterval(RetryfyQueue.intervalId);
        delete RetryfyQueue.intervalId;
    },
    add: (fn) => {
        RetryfyQueue.queueWaiting.add(fn);
        if (RetryfyQueue.queueActive.size < (RetryfyQueue.limit / 2)) { // Active queue not under preassure, executing immediately
            RetryfyQueue.tick();
        }
        else {
            RetryfyQueue.init();
        }
    },
    remove: (fn) => {
        RetryfyQueue.queueWaiting.delete(fn);
        RetryfyQueue.queueActive.delete(fn);
    },
    schedule: () => {
        return new Promise(resolve => {
            const cleanup = () => RetryfyQueue.remove(resolver);
            const resolver = () => resolve(cleanup);
            RetryfyQueue.add(resolver);
        });
    },
    tick: () => {
        if (RetryfyQueue.queueActive.size >= RetryfyQueue.limit)
            return;
        if (!RetryfyQueue.queueWaiting.size)
            return RetryfyQueue.reset();
        for (const fn of RetryfyQueue.queueWaiting) {
            if (RetryfyQueue.queueActive.size >= RetryfyQueue.limit)
                break;
            RetryfyQueue.queueWaiting.delete(fn);
            RetryfyQueue.queueActive.add(fn);
            fn();
        }
    }
};
/* EXPORT */
exports.default = RetryfyQueue;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
/* VARIABLES */
const Queues = {};
/* SCHEDULER */
//TODO: Maybe publish this as a standalone package
const Scheduler = {
    next: (id) => {
        const queue = Queues[id];
        if (!queue)
            return;
        queue.shift();
        const job = queue[0];
        if (job) {
            job(() => Scheduler.next(id));
        }
        else {
            delete Queues[id];
        }
    },
    schedule: (id) => {
        return new Promise(resolve => {
            let queue = Queues[id];
            if (!queue)
                queue = Queues[id] = [];
            queue.push(resolve);
            if (queue.length > 1)
                return;
            resolve(() => Scheduler.next(id));
        });
    }
};
/* EXPORT */
exports.default = Scheduler;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const consts_1 = require("../consts");
const fs_1 = require("./fs");
/* TEMP */
//TODO: Maybe publish this as a standalone package
const Temp = {
    store: {},
    create: (filePath) => {
        const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6), // 6 random-enough hex characters
        timestamp = Date.now().toString().slice(-10), // 10 precise timestamp digits
        prefix = 'tmp-', suffix = `.${prefix}${timestamp}${randomness}`, tempPath = `${filePath}${suffix}`;
        return tempPath;
    },
    get: (filePath, creator, purge = true) => {
        const tempPath = Temp.truncate(creator(filePath));
        if (tempPath in Temp.store)
            return Temp.get(filePath, creator, purge); // Collision found, try again
        Temp.store[tempPath] = purge;
        const disposer = () => delete Temp.store[tempPath];
        return [tempPath, disposer];
    },
    purge: (filePath) => {
        if (!Temp.store[filePath])
            return;
        delete Temp.store[filePath];
        fs_1.default.unlinkAttempt(filePath);
    },
    purgeSync: (filePath) => {
        if (!Temp.store[filePath])
            return;
        delete Temp.store[filePath];
        fs_1.default.unlinkSyncAttempt(filePath);
    },
    purgeSyncAll: () => {
        for (const filePath in Temp.store) {
            Temp.purgeSync(filePath);
        }
    },
    truncate: (filePath) => {
        const basename = path.basename(filePath);
        if (basename.length <= consts_1.LIMIT_BASENAME_LENGTH)
            return filePath; //FIXME: Rough and quick attempt at detecting ok lengths
        const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename);
        if (!truncable)
            return filePath; //FIXME: No truncable part detected, can't really do much without also changing the parent path, which is unsafe, hoping for the best here
        const truncationLength = basename.length - consts_1.LIMIT_BASENAME_LENGTH;
        return `${filePath.slice(0, -basename.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`; //FIXME: The truncable part might be shorter than needed here
    }
};
/* INIT */
process.on('exit', Temp.purgeSyncAll); // Ensuring purgeable temp files are purged on exit
/* EXPORT */
exports.default = Temp;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "conf",
  "version": "10.2.0",
  "description": "Simple config handling for your app or module",
  "license": "MIT",
  "repository": "sindresorhus/conf",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "main": "dist/source",
  "engines": {
    "node": ">=12"
  },
  "files": [
    "dist/source"
  ],
  "dependencies": {
    "ajv": "^8.6.3",
    "ajv-formats": "^2.1.1",
    "atomically": "^1.7.0",
    "debounce-fn": "^4.0.0",
    "dot-prop": "^6.0.1",
    "env-paths": "^2.2.1",
    "json-schema-typed": "^7.0.3",
    "onetime": "^5.1.2",
    "pkg-up": "^3.1.0",
    "semver": "^7.3.5"
  },
  "devDependencies": {
    "@ava/typescript": "^1.1.1",
    "@sindresorhus/tsconfig": "^0.7.0",
    "@types/node": "^14.14.41",
    "@types/semver": "^7.3.4",
    "@types/write-file-atomic": "^3.0.1",
    "ava": "^3.15.0",
    "clear-module": "^4.1.1",
    "del": "^6.0.0",
    "del-cli": "^3.0.1",
    "delay": "^5.0.0",
    "nyc": "^15.1.0",
    "p-event": "^4.2.0",
    "tempy": "^1.0.1",
    "tsd": "^0.14.0",
    "typescript": "^4.4.3",
    "xo": "^0.38.2"
  },
  "types": "dist/source"
}"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _a, _b;
var _Conf_validator, _Conf_encryptionKey, _Conf_options, _Conf_defaultValues;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("util");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const assert = require("assert");
const events_1 = require("events");
const dotProp = require("dot-prop");
const pkgUp = require("pkg-up");
const envPaths = require("env-paths");
const atomically = require("atomically");
const ajv_1 = require("ajv");
const ajv_formats_1 = require("ajv-formats");
const debounceFn = require("debounce-fn");
const semver = require("semver");
const onetime = require("onetime");
const encryptionAlgorithm = 'aes-256-cbc';
const createPlainObject = () => {
    return Object.create(null);
};
const isExist = (data) => {
    return data !== undefined && data !== null;
};
let parentDir = '';
try {
    // Prevent caching of this module so module.parent is always accurate.
    // Note: This trick won't work with ESM or inside a webworker
    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
    delete require.cache[__filename];
    parentDir = path.dirname((_b = (_a = module.parent) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : '.');
}
catch (_c) { }
const checkValueType = (key, value) => {
    const nonJsonTypes = new Set([
        'undefined',
        'symbol',
        'function'
    ]);
    const type = typeof value;
    if (nonJsonTypes.has(type)) {
        throw new TypeError(`Setting a value of type \`${type}\` for key \`${key}\` is not allowed as it's not supported by JSON`);
    }
};
const INTERNAL_KEY = '__internal__';
const MIGRATION_KEY = `${INTERNAL_KEY}.migrations.version`;
class Conf {
    constructor(partialOptions = {}) {
        var _a;
        _Conf_validator.set(this, void 0);
        _Conf_encryptionKey.set(this, void 0);
        _Conf_options.set(this, void 0);
        _Conf_defaultValues.set(this, {});
        this._deserialize = value => JSON.parse(value);
        this._serialize = value => JSON.stringify(value, undefined, '\t');
        const options = {
            configName: 'config',
            fileExtension: 'json',
            projectSuffix: 'nodejs',
            clearInvalidConfig: false,
            accessPropertiesByDotNotation: true,
            configFileMode: 0o666,
            ...partialOptions
        };
        const getPackageData = onetime(() => {
            const packagePath = pkgUp.sync({ cwd: parentDir });
            // Can't use `require` because of Webpack being annoying:
            // https://github.com/webpack/webpack/issues/196
            const packageData = packagePath && JSON.parse(fs.readFileSync(packagePath, 'utf8'));
            return packageData !== null && packageData !== void 0 ? packageData : {};
        });
        if (!options.cwd) {
            if (!options.projectName) {
                options.projectName = getPackageData().name;
            }
            if (!options.projectName) {
                throw new Error('Project name could not be inferred. Please specify the `projectName` option.');
            }
            options.cwd = envPaths(options.projectName, { suffix: options.projectSuffix }).config;
        }
        __classPrivateFieldSet(this, _Conf_options, options, "f");
        if (options.schema) {
            if (typeof options.schema !== 'object') {
                throw new TypeError('The `schema` option must be an object.');
            }
            const ajv = new ajv_1.default({
                allErrors: true,
                useDefaults: true
            });
            (0, ajv_formats_1.default)(ajv);
            const schema = {
                type: 'object',
                properties: options.schema
            };
            __classPrivateFieldSet(this, _Conf_validator, ajv.compile(schema), "f");
            for (const [key, value] of Object.entries(options.schema)) {
                if (value === null || value === void 0 ? void 0 : value.default) {
                    __classPrivateFieldGet(this, _Conf_defaultValues, "f")[key] = value.default;
                }
            }
        }
        if (options.defaults) {
            __classPrivateFieldSet(this, _Conf_defaultValues, {
                ...__classPrivateFieldGet(this, _Conf_defaultValues, "f"),
                ...options.defaults
            }, "f");
        }
        if (options.serialize) {
            this._serialize = options.serialize;
        }
        if (options.deserialize) {
            this._deserialize = options.deserialize;
        }
        this.events = new events_1.EventEmitter();
        __classPrivateFieldSet(this, _Conf_encryptionKey, options.encryptionKey, "f");
        const fileExtension = options.fileExtension ? `.${options.fileExtension}` : '';
        this.path = path.resolve(options.cwd, `${(_a = options.configName) !== null && _a !== void 0 ? _a : 'config'}${fileExtension}`);
        const fileStore = this.store;
        const store = Object.assign(createPlainObject(), options.defaults, fileStore);
        this._validate(store);
        try {
            assert.deepEqual(fileStore, store);
        }
        catch (_b) {
            this.store = store;
        }
        if (options.watch) {
            this._watch();
        }
        if (options.migrations) {
            if (!options.projectVersion) {
                options.projectVersion = getPackageData().version;
            }
            if (!options.projectVersion) {
                throw new Error('Project version could not be inferred. Please specify the `projectVersion` option.');
            }
            this._migrate(options.migrations, options.projectVersion, options.beforeEachMigration);
        }
    }
    get(key, defaultValue) {
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            return this._get(key, defaultValue);
        }
        const { store } = this;
        return key in store ? store[key] : defaultValue;
    }
    set(key, value) {
        if (typeof key !== 'string' && typeof key !== 'object') {
            throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof key}`);
        }
        if (typeof key !== 'object' && value === undefined) {
            throw new TypeError('Use `delete()` to clear values');
        }
        if (this._containsReservedKey(key)) {
            throw new TypeError(`Please don't use the ${INTERNAL_KEY} key, as it's used to manage this module internal operations.`);
        }
        const { store } = this;
        const set = (key, value) => {
            checkValueType(key, value);
            if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
                dotProp.set(store, key, value);
            }
            else {
                store[key] = value;
            }
        };
        if (typeof key === 'object') {
            const object = key;
            for (const [key, value] of Object.entries(object)) {
                set(key, value);
            }
        }
        else {
            set(key, value);
        }
        this.store = store;
    }
    /**
    Check if an item exists.

    @param key - The key of the item to check.
    */
    has(key) {
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            return dotProp.has(this.store, key);
        }
        return key in this.store;
    }
    /**
    Reset items to their default values, as defined by the `defaults` or `schema` option.

    @see `clear()` to reset all items.

    @param keys - The keys of the items to reset.
    */
    reset(...keys) {
        for (const key of keys) {
            if (isExist(__classPrivateFieldGet(this, _Conf_defaultValues, "f")[key])) {
                this.set(key, __classPrivateFieldGet(this, _Conf_defaultValues, "f")[key]);
            }
        }
    }
    /**
    Delete an item.

    @param key - The key of the item to delete.
    */
    delete(key) {
        const { store } = this;
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            dotProp.delete(store, key);
        }
        else {
            // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
            delete store[key];
        }
        this.store = store;
    }
    /**
    Delete all items.

    This resets known items to their default values, if defined by the `defaults` or `schema` option.
    */
    clear() {
        this.store = createPlainObject();
        for (const key of Object.keys(__classPrivateFieldGet(this, _Conf_defaultValues, "f"))) {
            this.reset(key);
        }
    }
    /**
    Watches the given `key`, calling `callback` on any changes.

    @param key - The key wo watch.
    @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
    @returns A function, that when called, will unsubscribe.
    */
    onDidChange(key, callback) {
        if (typeof key !== 'string') {
            throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof key}`);
        }
        if (typeof callback !== 'function') {
            throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
        }
        return this._handleChange(() => this.get(key), callback);
    }
    /**
    Watches the whole config object, calling `callback` on any changes.

    @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
    @returns A function, that when called, will unsubscribe.
    */
    onDidAnyChange(callback) {
        if (typeof callback !== 'function') {
            throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
        }
        return this._handleChange(() => this.store, callback);
    }
    get size() {
        return Object.keys(this.store).length;
    }
    get store() {
        try {
            const data = fs.readFileSync(this.path, __classPrivateFieldGet(this, _Conf_encryptionKey, "f") ? null : 'utf8');
            const dataString = this._encryptData(data);
            const deserializedData = this._deserialize(dataString);
            this._validate(deserializedData);
            return Object.assign(createPlainObject(), deserializedData);
        }
        catch (error) {
            if ((error === null || error === void 0 ? void 0 : error.code) === 'ENOENT') {
                this._ensureDirectory();
                return createPlainObject();
            }
            if (__classPrivateFieldGet(this, _Conf_options, "f").clearInvalidConfig && error.name === 'SyntaxError') {
                return createPlainObject();
            }
            throw error;
        }
    }
    set store(value) {
        this._ensureDirectory();
        this._validate(value);
        this._write(value);
        this.events.emit('change');
    }
    *[(_Conf_validator = new WeakMap(), _Conf_encryptionKey = new WeakMap(), _Conf_options = new WeakMap(), _Conf_defaultValues = new WeakMap(), Symbol.iterator)]() {
        for (const [key, value] of Object.entries(this.store)) {
            yield [key, value];
        }
    }
    _encryptData(data) {
        if (!__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
            return data.toString();
        }
        try {
            // Check if an initialization vector has been used to encrypt the data
            if (__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
                try {
                    if (data.slice(16, 17).toString() === ':') {
                        const initializationVector = data.slice(0, 16);
                        const password = crypto.pbkdf2Sync(__classPrivateFieldGet(this, _Conf_encryptionKey, "f"), initializationVector.toString(), 10000, 32, 'sha512');
                        const decipher = crypto.createDecipheriv(encryptionAlgorithm, password, initializationVector);
                        data = Buffer.concat([decipher.update(Buffer.from(data.slice(17))), decipher.final()]).toString('utf8');
                    }
                    else {
                        // TODO: Remove this in the next major version.
                        const decipher = crypto.createDecipher(encryptionAlgorithm, __classPrivateFieldGet(this, _Conf_encryptionKey, "f"));
                        data = Buffer.concat([decipher.update(Buffer.from(data)), decipher.final()]).toString('utf8');
                    }
                }
                catch (_a) { }
            }
        }
        catch (_b) { }
        return data.toString();
    }
    _handleChange(getter, callback) {
        let currentValue = getter();
        const onChange = () => {
            const oldValue = currentValue;
            const newValue = getter();
            if ((0, util_1.isDeepStrictEqual)(newValue, oldValue)) {
                return;
            }
            currentValue = newValue;
            callback.call(this, newValue, oldValue);
        };
        this.events.on('change', onChange);
        return () => this.events.removeListener('change', onChange);
    }
    _validate(data) {
        if (!__classPrivateFieldGet(this, _Conf_validator, "f")) {
            return;
        }
        const valid = __classPrivateFieldGet(this, _Conf_validator, "f").call(this, data);
        if (valid || !__classPrivateFieldGet(this, _Conf_validator, "f").errors) {
            return;
        }
        const errors = __classPrivateFieldGet(this, _Conf_validator, "f").errors
            .map(({ instancePath, message = '' }) => `\`${instancePath.slice(1)}\` ${message}`);
        throw new Error('Config schema violation: ' + errors.join('; '));
    }
    _ensureDirectory() {
        // Ensure the directory exists as it could have been deleted in the meantime.
        fs.mkdirSync(path.dirname(this.path), { recursive: true });
    }
    _write(value) {
        let data = this._serialize(value);
        if (__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
            const initializationVector = crypto.randomBytes(16);
            const password = crypto.pbkdf2Sync(__classPrivateFieldGet(this, _Conf_encryptionKey, "f"), initializationVector.toString(), 10000, 32, 'sha512');
            const cipher = crypto.createCipheriv(encryptionAlgorithm, password, initializationVector);
            data = Buffer.concat([initializationVector, Buffer.from(':'), cipher.update(Buffer.from(data)), cipher.final()]);
        }
        // Temporary workaround for Conf being packaged in a Ubuntu Snap app.
        // See https://github.com/sindresorhus/conf/pull/82
        if (process.env.SNAP) {
            fs.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
        }
        else {
            try {
                atomically.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
            }
            catch (error) {
                // Fix for https://github.com/sindresorhus/electron-store/issues/106
                // Sometimes on Windows, we will get an EXDEV error when atomic writing
                // (even though to the same directory), so we fall back to non atomic write
                if ((error === null || error === void 0 ? void 0 : error.code) === 'EXDEV') {
                    fs.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
                    return;
                }
                throw error;
            }
        }
    }
    _watch() {
        this._ensureDirectory();
        if (!fs.existsSync(this.path)) {
            this._write(createPlainObject());
        }
        if (process.platform === 'win32') {
            fs.watch(this.path, { persistent: false }, debounceFn(() => {
                // On Linux and Windows, writing to the config file emits a `rename` event, so we skip checking the event type.
                this.events.emit('change');
            }, { wait: 100 }));
        }
        else {
            fs.watchFile(this.path, { persistent: false }, debounceFn(() => {
                this.events.emit('change');
            }, { wait: 5000 }));
        }
    }
    _migrate(migrations, versionToMigrate, beforeEachMigration) {
        let previousMigratedVersion = this._get(MIGRATION_KEY, '0.0.0');
        const newerVersions = Object.keys(migrations)
            .filter(candidateVersion => this._shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate));
        let storeBackup = { ...this.store };
        for (const version of newerVersions) {
            try {
                if (beforeEachMigration) {
                    beforeEachMigration(this, {
                        fromVersion: previousMigratedVersion,
                        toVersion: version,
                        finalVersion: versionToMigrate,
                        versions: newerVersions
                    });
                }
                const migration = migrations[version];
                migration(this);
                this._set(MIGRATION_KEY, version);
                previousMigratedVersion = version;
                storeBackup = { ...this.store };
            }
            catch (error) {
                this.store = storeBackup;
                throw new Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${error}`);
            }
        }
        if (this._isVersionInRangeFormat(previousMigratedVersion) || !semver.eq(previousMigratedVersion, versionToMigrate)) {
            this._set(MIGRATION_KEY, versionToMigrate);
        }
    }
    _containsReservedKey(key) {
        if (typeof key === 'object') {
            const firsKey = Object.keys(key)[0];
            if (firsKey === INTERNAL_KEY) {
                return true;
            }
        }
        if (typeof key !== 'string') {
            return false;
        }
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            if (key.startsWith(`${INTERNAL_KEY}.`)) {
                return true;
            }
            return false;
        }
        return false;
    }
    _isVersionInRangeFormat(version) {
        return semver.clean(version) === null;
    }
    _shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate) {
        if (this._isVersionInRangeFormat(candidateVersion)) {
            if (previousMigratedVersion !== '0.0.0' && semver.satisfies(previousMigratedVersion, candidateVersion)) {
                return false;
            }
            return semver.satisfies(versionToMigrate, candidateVersion);
        }
        if (semver.lte(candidateVersion, previousMigratedVersion)) {
            return false;
        }
        if (semver.gt(candidateVersion, versionToMigrate)) {
            return false;
        }
        return true;
    }
    _get(key, defaultValue) {
        return dotProp.get(this.store, key, defaultValue);
    }
    _set(key, value) {
        const { store } = this;
        dotProp.set(store, key, value);
        this.store = store;
    }
}
exports.default = Conf;
// For CommonJS default export support
module.exports = Conf;
module.exports.default = Conf;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
const mimicFn = require('mimic-fn');

module.exports = (inputFunction, options = {}) => {
	if (typeof inputFunction !== 'function') {
		throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``);
	}

	const {
		wait = 0,
		before = false,
		after = true
	} = options;

	if (!before && !after) {
		throw new Error('Both `before` and `after` are false, function wouldn\'t be called.');
	}

	let timeout;
	let result;

	const debouncedFunction = function (...arguments_) {
		const context = this;

		const later = () => {
			timeout = undefined;

			if (after) {
				result = inputFunction.apply(context, arguments_);
			}
		};

		const shouldCallNow = before && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);

		if (shouldCallNow) {
			result = inputFunction.apply(context, arguments_);
		}

		return result;
	};

	mimicFn(debouncedFunction, inputFunction);

	debouncedFunction.cancel = () => {
		if (timeout) {
			clearTimeout(timeout);
			timeout = undefined;
		}
	};

	return debouncedFunction;
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "debounce-fn",
  "version": "4.0.0",
  "description": "Debounce a function",
  "license": "MIT",
  "repository": "sindresorhus/debounce-fn",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "engines": {
    "node": ">=10"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "mimic-fn": "^3.0.0"
  },
  "devDependencies": {
    "ava": "^1.4.1",
    "delay": "^4.2.0",
    "tsd": "^0.11.0",
    "xo": "^0.26.1"
  }
}'use strict';
const isObj = require('is-obj');

const disallowedKeys = new Set([
	'__proto__',
	'prototype',
	'constructor'
]);

const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.has(segment));

function getPathSegments(path) {
	const pathArray = path.split('.');
	const parts = [];

	for (let i = 0; i < pathArray.length; i++) {
		let p = pathArray[i];

		while (p[p.length - 1] === '\\' && pathArray[i + 1] !== undefined) {
			p = p.slice(0, -1) + '.';
			p += pathArray[++i];
		}

		parts.push(p);
	}

	if (!isValidPath(parts)) {
		return [];
	}

	return parts;
}

module.exports = {
	get(object, path, value) {
		if (!isObj(object) || typeof path !== 'string') {
			return value === undefined ? object : value;
		}

		const pathArray = getPathSegments(path);
		if (pathArray.length === 0) {
			return;
		}

		for (let i = 0; i < pathArray.length; i++) {
			object = object[pathArray[i]];

			if (object === undefined || object === null) {
				// `object` is either `undefined` or `null` so we want to stop the loop, and
				// if this is not the last bit of the path, and
				// if it did't return `undefined`
				// it would return `null` if `object` is `null`
				// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
				if (i !== pathArray.length - 1) {
					return value;
				}

				break;
			}
		}

		return object === undefined ? value : object;
	},

	set(object, path, value) {
		if (!isObj(object) || typeof path !== 'string') {
			return object;
		}

		const root = object;
		const pathArray = getPathSegments(path);

		for (let i = 0; i < pathArray.length; i++) {
			const p = pathArray[i];

			if (!isObj(object[p])) {
				object[p] = {};
			}

			if (i === pathArray.length - 1) {
				object[p] = value;
			}

			object = object[p];
		}

		return root;
	},

	delete(object, path) {
		if (!isObj(object) || typeof path !== 'string') {
			return false;
		}

		const pathArray = getPathSegments(path);

		for (let i = 0; i < pathArray.length; i++) {
			const p = pathArray[i];

			if (i === pathArray.length - 1) {
				delete object[p];
				return true;
			}

			object = object[p];

			if (!isObj(object)) {
				return false;
			}
		}
	},

	has(object, path) {
		if (!isObj(object) || typeof path !== 'string') {
			return false;
		}

		const pathArray = getPathSegments(path);
		if (pathArray.length === 0) {
			return false;
		}

		// eslint-disable-next-line unicorn/no-for-loop
		for (let i = 0; i < pathArray.length; i++) {
			if (isObj(object)) {
				if (!(pathArray[i] in object)) {
					return false;
				}

				object = object[pathArray[i]];
			} else {
				return false;
			}
		}

		return true;
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "dot-prop",
  "version": "6.0.1",
  "description": "Get, set, or delete a property from a nested object using a dot path",
  "license": "MIT",
  "repository": "sindresorhus/dot-prop",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "engines": {
    "node": ">=10"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "is-obj": "^2.0.0"
  },
  "devDependencies": {
    "ava": "^2.1.0",
    "benchmark": "^2.1.4",
    "tsd": "^0.13.1",
    "xo": "^0.33.1"
  }
}'use strict';
const path = require('path');
const {app, ipcMain, ipcRenderer, shell} = require('electron');
const Conf = require('conf');

let isInitialized = false;

// Set up the `ipcMain` handler for communication between renderer and main process.
const initDataListener = () => {
	if (!ipcMain || !app) {
		throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
	}

	const appData = {
		defaultCwd: app.getPath('userData'),
		appVersion: app.getVersion()
	};

	if (isInitialized) {
		return appData;
	}

	ipcMain.on('electron-store-get-data', event => {
		event.returnValue = appData;
	});

	isInitialized = true;

	return appData;
};

class ElectronStore extends Conf {
	constructor(options) {
		let defaultCwd;
		let appVersion;

		// If we are in the renderer process, we communicate with the main process
		// to get the required data for the module otherwise, we pull from the main process.
		if (ipcRenderer) {
			const appData = ipcRenderer.sendSync('electron-store-get-data');

			if (!appData) {
				throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
			}

			({defaultCwd, appVersion} = appData);
		} else if (ipcMain && app) {
			({defaultCwd, appVersion} = initDataListener());
		}

		options = {
			name: 'config',
			...options
		};

		if (!options.projectVersion) {
			options.projectVersion = appVersion;
		}

		if (options.cwd) {
			options.cwd = path.isAbsolute(options.cwd) ? options.cwd : path.join(defaultCwd, options.cwd);
		} else {
			options.cwd = defaultCwd;
		}

		options.configName = options.name;
		delete options.name;

		super(options);
	}

	static initRenderer() {
		initDataListener();
	}

	async openInEditor() {
		const error = await shell.openPath(this.path);

		if (error) {
			throw new Error(error);
		}
	}
}

module.exports = ElectronStore;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "electron-store",
  "version": "8.2.0",
  "description": "Simple data persistence for your Electron app or module - Save and load user settings, app state, cache, etc",
  "license": "MIT",
  "repository": "sindresorhus/electron-store",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "sideEffects": false,
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "conf": "^10.2.0",
    "type-fest": "^2.17.0"
  },
  "devDependencies": {
    "ava": "^2.4.0",
    "electron": "^12.0.4",
    "execa": "^5.0.0",
    "tsd": "^0.14.0",
    "xo": "^0.38.2"
  }
}'use strict';
const path = require('path');
const os = require('os');

const homedir = os.homedir();
const tmpdir = os.tmpdir();
const {env} = process;

const macos = name => {
	const library = path.join(homedir, 'Library');

	return {
		data: path.join(library, 'Application Support', name),
		config: path.join(library, 'Preferences', name),
		cache: path.join(library, 'Caches', name),
		log: path.join(library, 'Logs', name),
		temp: path.join(tmpdir, name)
	};
};

const windows = name => {
	const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
	const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');

	return {
		// Data/config/cache/log are invented by me as Windows isn't opinionated about this
		data: path.join(localAppData, name, 'Data'),
		config: path.join(appData, name, 'Config'),
		cache: path.join(localAppData, name, 'Cache'),
		log: path.join(localAppData, name, 'Log'),
		temp: path.join(tmpdir, name)
	};
};

// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
const linux = name => {
	const username = path.basename(homedir);

	return {
		data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
		config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
		cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
		// https://wiki.debian.org/XDGBaseDirectorySpecification#state
		log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
		temp: path.join(tmpdir, username, name)
	};
};

const envPaths = (name, options) => {
	if (typeof name !== 'string') {
		throw new TypeError(`Expected string, got ${typeof name}`);
	}

	options = Object.assign({suffix: 'nodejs'}, options);

	if (options.suffix) {
		// Add suffix to prevent possible conflict with native apps
		name += `-${options.suffix}`;
	}

	if (process.platform === 'darwin') {
		return macos(name);
	}

	if (process.platform === 'win32') {
		return windows(name);
	}

	return linux(name);
};

module.exports = envPaths;
// TODO: Remove this for the next major release
module.exports.default = envPaths;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "env-paths",
  "version": "2.2.1",
  "description": "Get paths for storing things like data, config, cache, etc",
  "license": "MIT",
  "repository": "sindresorhus/env-paths",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.1",
    "xo": "^0.24.0"
  }
}MIT License

Copyright (c) 2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

// do not edit .js files directly - edit src/index.jst



module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }



    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};
{
  "name": "fast-deep-equal",
  "version": "3.1.3",
  "description": "Fast deep equal",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/epoberezkin/fast-deep-equal.git"
  },
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://github.com/epoberezkin/fast-deep-equal#readme",
  "devDependencies": {
    "coveralls": "^3.1.0",
    "dot": "^1.1.2",
    "eslint": "^7.2.0",
    "mocha": "^7.2.0",
    "nyc": "^15.1.0",
    "pre-commit": "^1.2.2",
    "react": "^16.12.0",
    "react-test-renderer": "^16.12.0",
    "sinon": "^9.0.2",
    "typescript": "^3.9.5"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "react.js",
    "react.d.ts",
    "es6/"
  ],
  "types": "index.d.ts"
}'use strict';

// do not edit .js files directly - edit src/index.jst



module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }



    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (key === '_owner' && a.$$typeof) {
        // React-specific: avoid traversing React elements' _owner.
        //  _owner contains circular references
        // and is not needed when comparing the actual elements (and not their owners)
        continue;
      }

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};
'use strict';

// do not edit .js files directly - edit src/index.jst


  var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';


module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }


    if ((a instanceof Map) && (b instanceof Map)) {
      if (a.size !== b.size) return false;
      for (i of a.entries())
        if (!b.has(i[0])) return false;
      for (i of a.entries())
        if (!equal(i[1], b.get(i[0]))) return false;
      return true;
    }

    if ((a instanceof Set) && (b instanceof Set)) {
      if (a.size !== b.size) return false;
      for (i of a.entries())
        if (!b.has(i[0])) return false;
      return true;
    }

    if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (a[i] !== b[i]) return false;
      return true;
    }


    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};
'use strict';

// do not edit .js files directly - edit src/index.jst


  var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';


module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }


    if ((a instanceof Map) && (b instanceof Map)) {
      if (a.size !== b.size) return false;
      for (i of a.entries())
        if (!b.has(i[0])) return false;
      for (i of a.entries())
        if (!equal(i[1], b.get(i[0]))) return false;
      return true;
    }

    if ((a instanceof Set) && (b instanceof Set)) {
      if (a.size !== b.size) return false;
      for (i of a.entries())
        if (!b.has(i[0])) return false;
      return true;
    }

    if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (a[i] !== b[i]) return false;
      return true;
    }


    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (key === '_owner' && a.$$typeof) {
        // React-specific: avoid traversing React elements' _owner.
        //  _owner contains circular references
        // and is not needed when comparing the actual elements (and not their owners)
        continue;
      }

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};
Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae
Copyright (c) 2021-present The Fastify team <https://github.com/fastify/fastify#team>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * The names of any contributors may not be used to endorse or promote
      products derived from this software without specific prior written
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

                                  *   *   *

The complete list of contributors can be found at:
- https://github.com/garycourt/uri-js/graphs/contributors'use strict'

module.exports = require('neostandard')({
  ignores: require('neostandard').resolveIgnoresFromGitignore(),
  ts: true
})
'use strict'

const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')
const { SCHEMES, getSchemeHandler } = require('./lib/schemes')

const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u
const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.'

/**
 * @param {string} scheme
 * @returns {string}
 */
function decodeValidScheme (scheme) {
  const decodedScheme = unescape(String(scheme))
  if (!VALID_SCHEME.test(decodedScheme)) {
    throw new TypeError(MALFORMED_SCHEME_ERROR)
  }
  return decodedScheme
}

/**
 * @template {import('./types/index').URIComponent|string} T
 * @param {T} uri
 * @param {import('./types/index').Options} [options]
 * @returns {T}
 */
function normalize (uri, options) {
  if (typeof uri === 'string') {
    uri = /** @type {T} */ (normalizeString(uri, options))
  } else if (typeof uri === 'object') {
    uri = /** @type {T} */ (parse(serialize(uri, options), options))
  }
  return uri
}

/**
 * @param {string} baseURI
 * @param {string} relativeURI
 * @param {import('./types/index').Options} [options]
 * @returns {string}
 */
function resolve (baseURI, relativeURI, options) {
  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }
  const {
    parsed: baseParsed,
    malformedAuthorityOrPort: baseMalformed,
    malformedPercentEncoding: baseMalformedPercentEncoding,
    malformedSchemeSpecific: baseMalformedSchemeSpecific,
    malformedHost: baseMalformedHost,
    malformedScheme: baseMalformedScheme
  } = parseWithStatus(baseURI, schemelessOptions)
  const {
    parsed: relativeParsed,
    malformedAuthorityOrPort: relativeMalformed,
    malformedPercentEncoding: relativeMalformedPercentEncoding,
    malformedSchemeSpecific: relativeMalformedSchemeSpecific,
    malformedHost: relativeMalformedHost,
    malformedScheme: relativeMalformedScheme
  } = parseWithStatus(relativeURI, schemelessOptions)
  if (
    baseMalformed ||
    relativeMalformed ||
    baseMalformedPercentEncoding ||
    relativeMalformedPercentEncoding ||
    baseMalformedSchemeSpecific ||
    relativeMalformedSchemeSpecific ||
    baseMalformedHost ||
    relativeMalformedHost ||
    baseMalformedScheme ||
    relativeMalformedScheme
  ) {
    throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
  }
  const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true)
  const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme)
  const resolvedHost = resolved.host
  const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&
    (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6)
  canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)
  // Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname
  // parser can reject them even though fast-uri preserves them safely as RFC
  // 3986 data. A raw non-ASCII host must still fail closed if conversion fails.
  const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&
    !/\P{ASCII}/u.test(resolvedHost)
  if (resolved.error && !encodedASCIIHost) {
    throw new Error(resolved.error)
  }
  schemelessOptions.skipEscape = true
  return serialize(resolved, schemelessOptions)
}

/**
 * @param {import ('./types/index').URIComponent} base
 * @param {import ('./types/index').URIComponent} relative
 * @param {import('./types/index').Options} [options]
 * @param {boolean} [skipNormalization=false]
 * @returns {import ('./types/index').URIComponent}
 */
function resolveComponent (base, relative, options, skipNormalization) {
  /** @type {import('./types/index').URIComponent} */
  const target = {}
  if (!skipNormalization) {
    base = parse(serialize(base, options), options) // normalize base component
    relative = parse(serialize(relative, options), options) // normalize relative component
  }
  options = options || {}

  if (!options.tolerant && relative.scheme) {
    target.scheme = relative.scheme
    // target.authority = relative.authority;
    target.userinfo = relative.userinfo
    target.host = relative.host
    target.port = relative.port
    target.path = removeDotSegments(relative.path || '')
    target.query = relative.query
  } else {
    if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
      // target.authority = relative.authority;
      target.userinfo = relative.userinfo
      target.host = relative.host
      target.port = relative.port
      target.path = removeDotSegments(relative.path || '')
      target.query = relative.query
    } else {
      if (!relative.path) {
        target.path = base.path
        if (relative.query !== undefined) {
          target.query = relative.query
        } else {
          target.query = base.query
        }
      } else {
        if (relative.path[0] === '/') {
          target.path = removeDotSegments(relative.path)
        } else {
          if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
            target.path = '/' + relative.path
          } else if (!base.path) {
            target.path = relative.path
          } else {
            target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
          }
          target.path = removeDotSegments(target.path)
        }
        target.query = relative.query
      }
      // target.authority = base.authority;
      target.userinfo = base.userinfo
      target.host = base.host
      target.port = base.port
    }
    target.scheme = base.scheme
  }

  target.fragment = relative.fragment

  return target
}

/**
 * @param {import ('./types/index').URIComponent|string} uriA
 * @param {import ('./types/index').URIComponent|string} uriB
 * @param {import ('./types/index').Options} options
 * @returns {boolean}
 */
function equal (uriA, uriB, options) {
  const normalizedA = normalizeComparableURI(uriA, options)
  const normalizedB = normalizeComparableURI(uriB, options)

  return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB
}

/**
 * @param {Readonly<import('./types/index').URIComponent>} cmpts
 * @param {import('./types/index').Options} [opts]
 * @returns {string}
 */
function serialize (cmpts, opts) {
  const component = {
    host: cmpts.host,
    scheme: cmpts.scheme,
    userinfo: cmpts.userinfo,
    port: cmpts.port,
    path: cmpts.path,
    query: cmpts.query,
    nid: cmpts.nid,
    nss: cmpts.nss,
    uuid: cmpts.uuid,
    fragment: cmpts.fragment,
    reference: cmpts.reference,
    resourceName: cmpts.resourceName,
    secure: cmpts.secure,
    error: ''
  }
  const options = Object.assign({}, opts)
  const uriTokens = []

  if (component.scheme) {
    component.scheme = decodeValidScheme(component.scheme)
  }

  // find scheme handler
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme)

  // perform scheme specific serialization
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)

  const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined
  const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority

  if (component.path !== undefined) {
    if (!options.skipEscape) {
      component.path = serializePathEncoding(component.path, pathNoScheme)
    } else {
      component.path = normalizePercentEncoding(component.path)
    }
  }

  if (options.reference !== 'suffix' && component.scheme) {
    // Scheme handlers may replace the scheme during serialization.
    component.scheme = decodeValidScheme(component.scheme)
    uriTokens.push(component.scheme, ':')
  }

  const authority = recomposeAuthority(component)
  if (authority !== undefined) {
    if (options.reference !== 'suffix') {
      uriTokens.push('//')
    }

    uriTokens.push(authority)

    if (component.path && component.path[0] !== '/') {
      uriTokens.push('/')
    }
  }
  if (component.path !== undefined) {
    let s = component.path

    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
      s = removeDotSegments(s)
    }

    // Dot-segment removal can expose a colon that was not originally in the
    // first segment (for example, "./a:b"). Reapply path-noscheme encoding so
    // the serialized relative reference cannot be reparsed as a URI scheme.
    if (pathNoScheme) {
      s = serializePathEncoding(s, true)
    }

    if (
      authority === undefined &&
      s[0] === '/' &&
      s[1] === '/'
    ) {
      // don't allow the path to start with "//"
      s = '/%2F' + s.slice(2)
    }

    uriTokens.push(s)
  }

  if (component.query !== undefined) {
    uriTokens.push('?', encodeQuery(component.query))
  }

  if (component.fragment !== undefined) {
    uriTokens.push('#', encodeFragment(component.fragment))
  }
  return uriTokens.join('')
}

const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u

// Captures the authority component (between "//" and the next "/", "?" or "#"),
// with or without a scheme prefix, for the literal-backslash rejection below.
const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/

// Captures the leading authority-introducer region after an optional scheme: a
// run of forward slashes, backslashes, and the characters the WHATWG URL parser
// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
// is exactly "//". Node treats "\" as "/" on special schemes and strips those
// characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
// "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
// the path group (host confusion / SSRF / redirect bypass).
const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/

/**
 * @param {import('./types/index').URIComponent} parsed
 * @param {RegExpMatchArray} matches
 * @returns {string|undefined}
 */
function getParseError (parsed, matches) {
  if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {
    return 'URI path must start with "/" when authority is present.'
  }

  if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {
    return 'URI port is malformed.'
  }

  return undefined
}

/**
 * Checks percent syntax without decoding the represented octets. RFC 3986
 * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
 * though they are not independently valid UTF-8.
 *
 * @param {string|undefined} component
 * @returns {boolean}
 */
function hasMalformedPercentEncoding (component) {
  if (component === undefined) return false

  let percent = component.indexOf('%')
  while (percent !== -1) {
    if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
      return true
    }
    percent = component.indexOf('%', percent + 3)
  }

  return false
}

/**
 * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
 * An unterminated `[` is not a literal, so it must still be validated as a
 * reg-name instead of being waved through as an IP.
 *
 * @param {string} host
 * @returns {boolean}
 */
function isIPLiteral (host) {
  return host[0] === '[' && host[host.length - 1] === ']'
}

/**
 * @param {RegExpMatchArray} matches
 * @returns {boolean}
 */
function hasMalformedComponentPercentEncoding (matches) {
  // Bracketed IP literals use a raw "%" as the zone separator for historical
  // compatibility. Their parsing is intentionally left to normalizeIPv6.
  const host = matches[4]
  return hasMalformedPercentEncoding(matches[3]) ||
    (host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||
    hasMalformedPercentEncoding(matches[6]) ||
    hasMalformedPercentEncoding(matches[7]) ||
    hasMalformedPercentEncoding(matches[8])
}

/**
 * @param {import('./types/index').URIComponent} parsed
 * @param {import('./types/index').Options} options
 * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
 * @param {boolean} isIP
 * @returns {boolean} whether host conversion failed
 */
function canonicalizeHost (parsed, options, schemeHandler, isIP) {
  if (
    !options.unicodeSupport &&
    (!schemeHandler || !schemeHandler.unicodeSupport) &&
    parsed.host &&
    !isIPLiteral(parsed.host) &&
    (options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
    isIP === false &&
    nonSimpleDomain(parsed.host)
  ) {
    try {
      parsed.host = new URL('http://' + parsed.host).hostname
    } catch (e) {
      parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
      return true
    }
  }
  return false
}

/**
 * @param {string} uri
 * @param {import('./types/index').Options} [opts]
 * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
 */
function parseWithStatus (uri, opts) {
  const options = Object.assign({}, opts)
  /** @type {import('./types/index').URIComponent} */
  const parsed = {
    scheme: undefined,
    userinfo: undefined,
    host: '',
    port: undefined,
    path: '',
    query: undefined,
    fragment: undefined
  }

  let malformedAuthorityOrPort = false
  let malformedPercentEncoding = false
  let malformedSchemeSpecific = false
  let malformedHost = false
  let malformedIPLiteral = false
  let malformedScheme = false

  let isIP = false
  if (options.reference === 'suffix') {
    if (options.scheme) {
      uri = options.scheme + ':' + uri
    } else {
      uri = '//' + uri
    }
  }

  // A literal backslash (U+005C) is not a valid RFC 3986 URI character and is
  // not an authority delimiter. Reject it in the authority rather than
  // rewriting it: normalizing "\" -> "/" (WHATWG error recovery) could silently
  // change the resource identified by an otherwise-invalid input, and lets "\"
  // act as a host delimiter here while Node's native URL parses a different
  // host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is
  // untouched and remains valid encoded data.
  const authorityMatch = uri.match(AUTHORITY_PREFIX)
  if (authorityMatch !== null && authorityMatch[1].indexOf('\\') !== -1) {
    parsed.error = 'URI authority must not contain a literal backslash.'
    malformedAuthorityOrPort = true
  }

  // Reject a malformed or whitespace-smuggled authority introducer. fast-uri
  // only recognizes a literal "//"; anything else in the leading separator run
  // (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
  // Node strips) means the authority fast-uri parses differs from the one Node's
  // URL resolves. Reject rather than rewrite, mirroring the literal-backslash
  // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
  const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)
  if (introducerMatch !== null) {
    const region = introducerMatch[1]
    const normalizedRegion = region.replace(/[\t\n\r]/g, '')
    // Two or more leading separators introduce an authority.
    if (normalizedRegion.length >= 2) {
      if (normalizedRegion.slice(0, 2) !== '//') {
        parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'
        malformedAuthorityOrPort = true
      } else if (region.length !== normalizedRegion.length) {
        parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'
        malformedAuthorityOrPort = true
      }
    }
  }

  const matches = uri.match(URI_PARSE)

  if (matches) {
    // store each component
    parsed.scheme = matches[1]
    parsed.userinfo = matches[3]
    parsed.host = matches[4]
    parsed.port = parseInt(matches[5], 10)
    parsed.path = matches[6] || ''
    parsed.query = matches[7]
    parsed.fragment = matches[8]

    if (parsed.scheme !== undefined) {
      const decodedScheme = unescape(parsed.scheme)
      if (VALID_SCHEME.test(decodedScheme)) {
        parsed.scheme = decodedScheme.toLowerCase()
      } else {
        parsed.error = parsed.error || MALFORMED_SCHEME_ERROR
        malformedScheme = true
      }
    }

    malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches)
    if (malformedPercentEncoding) {
      parsed.error = parsed.error || 'URI contains malformed percent-encoding.'
    }

    // fix port number
    if (isNaN(parsed.port)) {
      parsed.port = matches[5]
    }

    const parseError = getParseError(parsed, matches)
    if (parseError !== undefined) {
      parsed.error = parsed.error || parseError
      malformedAuthorityOrPort = true
    }

    if (parsed.host) {
      const ipv4result = isIPv4(parsed.host)
      if (ipv4result === false) {
        const bracketedIPLiteral = isIPLiteral(parsed.host)
        const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1
        const ipv6result = normalizeIPv6(parsed.host)
        isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true
        malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true)
        parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase()

        if (malformedIPLiteral) {
          parsed.error = parsed.error || 'URI host is malformed.'
          malformedAuthorityOrPort = true
        }
      } else {
        isIP = true
      }
    }
    if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
      parsed.reference = 'same-document'
    } else if (parsed.scheme === undefined) {
      parsed.reference = 'relative'
    } else if (parsed.fragment === undefined) {
      parsed.reference = 'absolute'
    } else {
      parsed.reference = 'uri'
    }

    // check for reference errors
    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
    }

    // find scheme handler
    const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)

    // convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts
    if (!malformedIPLiteral) {
      malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP)
    }

    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
      if (uri.indexOf('%') !== -1) {
        if (parsed.host !== undefined && !malformedIPLiteral) {
          const host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true)
          parsed.host = reescapeHostDelimiters(host, isIP)
        }
      }
      if (parsed.path) {
        parsed.path = normalizePathEncoding(parsed.path)
      }
      if (parsed.query) {
        parsed.query = normalizeQueryFragmentEncoding(parsed.query)
      }
      if (parsed.fragment) {
        parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment)
      }
    }

    // perform scheme specific parsing
    if (schemeHandler && schemeHandler.parse) {
      schemeHandler.parse(parsed, options)
      if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {
        malformedSchemeSpecific = true
      }
    }
  } else {
    parsed.error = parsed.error || 'URI can not be parsed.'
  }
  return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }
}

/**
 * @param {string} uri
 * @param {import('./types/index').Options} [opts]
 * @returns
 */
function parse (uri, opts) {
  return parseWithStatus(uri, opts).parsed
}

/**
 * @param {string} uri
 * @param {import('./types/index').Options} [opts]
 * @returns {string}
 */
function normalizeString (uri, opts) {
  return normalizeStringWithStatus(uri, opts).normalized
}

/**
 * @param {string} uri
 * @param {import('./types/index').Options} [opts]
 * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
 */
function normalizeStringWithStatus (uri, opts) {
  const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts)
  return {
    normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
    malformedAuthorityOrPort,
    malformedPercentEncoding,
    malformedSchemeSpecific,
    malformedHost,
    malformedScheme
  }
}

/**
 * @param {import ('./types/index').URIComponent|string} uri
 * @param {import('./types/index').Options} [opts]
 * @returns {string|undefined}
 */
function normalizeComparableURI (uri, opts) {
  if (typeof uri !== 'string' && typeof uri !== 'object') {
    return undefined
  }

  let value
  try {
    value = typeof uri === 'string' ? uri : serialize(uri, opts)
  } catch {
    return undefined
  }
  const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts)
  return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized
}

const fastUri = {
  SCHEMES,
  normalize,
  resolve,
  resolveComponent,
  equal,
  serialize,
  parse
}

module.exports = fastUri
module.exports.default = fastUri
module.exports.fastUri = fastUri
{
  "name": "fast-uri",
  "description": "Dependency-free RFC 3986 URI toolbox",
  "version": "3.1.7",
  "main": "index.js",
  "type": "commonjs",
  "types": "types/index.d.ts",
  "license": "BSD-3-Clause",
  "author": "Vincent Le Goff <vince.legoff@gmail.com> (https://github.com/zekth)",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/fastify/fast-uri.git"
  },
  "homepage": "https://github.com/fastify/fast-uri",
  "funding": [
    {
      "type": "github",
      "url": "https://github.com/sponsors/fastify"
    },
    {
      "type": "opencollective",
      "url": "https://opencollective.com/fastify"
    }
  ],
  "devDependencies": {
    "ajv": "^8.16.0",
    "eslint": "^9.17.0",
    "neostandard": "^0.13.0",
    "playwright-test": "^14.1.12",
    "tape": "^5.8.1",
    "tsd": "^0.33.0"
  }
}{
    "compilerOptions": {
        "allowJs": true,
        "checkJs": true,
        "strict": true,
        "noImplicitAny": true,
        "target": "es2015"
    }
}import uri, { URIComponents, URIComponent, Options, options } from '..'
import { expectDeprecated, expectType } from 'tsd'

const parsed = uri.parse('foo')
expectType<URIComponents>(parsed)
const parsed2 = uri.parse('foo', {
  domainHost: true,
  scheme: 'https',
  unicodeSupport: false
})
expectType<URIComponents>(parsed2)

expectType<URIComponent>({} as URIComponents)
expectDeprecated({} as URIComponents)

expectType<Options>({} as options)
expectDeprecated({} as options)
'use strict'

const { isUUID } = require('./utils')
const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu

const supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',
  'wss', 'urn', 'urn:uuid'])

/** @typedef {supportedSchemeNames[number]} SchemeName */

/**
 * @param {string} name
 * @returns {name is SchemeName}
 */
function isValidSchemeName (name) {
  return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1
}

/**
 * @callback SchemeFn
 * @param {import('../types/index').URIComponent} component
 * @param {import('../types/index').Options} options
 * @returns {import('../types/index').URIComponent}
 */

/**
 * @typedef {Object} SchemeHandler
 * @property {SchemeName} scheme - The scheme name.
 * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.
 * @property {SchemeFn} parse - Function to parse the URI component for this scheme.
 * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.
 * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.
 * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.
 * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.
 */

/**
 * @param {import('../types/index').URIComponent} wsComponent
 * @returns {boolean}
 */
function wsIsSecure (wsComponent) {
  if (wsComponent.secure === true) {
    return true
  } else if (wsComponent.secure === false) {
    return false
  } else if (wsComponent.scheme) {
    return (
      wsComponent.scheme.length === 3 &&
      (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&
      (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&
      (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')
    )
  } else {
    return false
  }
}

/** @type {SchemeFn} */
function httpParse (component) {
  if (!component.host) {
    component.error = component.error || 'HTTP URIs must have a host.'
  }

  return component
}

/** @type {SchemeFn} */
function httpSerialize (component) {
  const secure = String(component.scheme).toLowerCase() === 'https'

  // normalize the default port
  if (component.port === (secure ? 443 : 80) || component.port === '') {
    component.port = undefined
  }

  // normalize the empty path
  if (!component.path) {
    component.path = '/'
  }

  // NOTE: We do not parse query strings for HTTP URIs
  // as WWW Form Url Encoded query strings are part of the HTML4+ spec,
  // and not the HTTP spec.

  return component
}

/** @type {SchemeFn} */
function wsParse (wsComponent) {
// indicate if the secure flag is set
  wsComponent.secure = wsIsSecure(wsComponent)

  // construct resouce name
  wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')
  wsComponent.path = undefined
  wsComponent.query = undefined

  return wsComponent
}

/** @type {SchemeFn} */
function wsSerialize (wsComponent) {
// normalize the default port
  if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {
    wsComponent.port = undefined
  }

  // ensure scheme matches secure flag
  if (typeof wsComponent.secure === 'boolean') {
    wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')
    wsComponent.secure = undefined
  }

  // reconstruct path from resource name
  if (wsComponent.resourceName) {
    const queryIndex = wsComponent.resourceName.indexOf('?')
    const path = queryIndex === -1
      ? wsComponent.resourceName
      : wsComponent.resourceName.slice(0, queryIndex)
    wsComponent.path = (path && path !== '/' ? path : undefined)
    wsComponent.query = queryIndex === -1
      ? undefined
      : wsComponent.resourceName.slice(queryIndex + 1)
    wsComponent.resourceName = undefined
  }

  // forbid fragment component
  wsComponent.fragment = undefined

  return wsComponent
}

/** @type {SchemeFn} */
function urnParse (urnComponent, options) {
  if (!urnComponent.path) {
    urnComponent.error = 'URN can not be parsed'
    return urnComponent
  }
  const matches = urnComponent.path.match(URN_REG)
  if (matches && matches[0] === urnComponent.path) {
    const scheme = options.scheme || urnComponent.scheme || 'urn'
    urnComponent.nid = matches[1].toLowerCase()
    urnComponent.nss = matches[2]
    const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`
    const schemeHandler = getSchemeHandler(urnScheme)
    urnComponent.path = undefined

    if (schemeHandler) {
      urnComponent = schemeHandler.parse(urnComponent, options)
    }
  } else {
    urnComponent.error = urnComponent.error || 'URN can not be parsed.'
  }

  return urnComponent
}

/** @type {SchemeFn} */
function urnSerialize (urnComponent, options) {
  if (urnComponent.nid === undefined) {
    throw new Error('URN without nid cannot be serialized')
  }
  const scheme = options.scheme || urnComponent.scheme || 'urn'
  const nid = urnComponent.nid.toLowerCase()
  const urnScheme = `${scheme}:${options.nid || nid}`
  const schemeHandler = getSchemeHandler(urnScheme)

  if (schemeHandler) {
    urnComponent = schemeHandler.serialize(urnComponent, options)
  }

  const uriComponent = urnComponent
  const nss = urnComponent.nss
  uriComponent.path = `${nid || options.nid}:${nss}`

  options.skipEscape = true
  return uriComponent
}

/** @type {SchemeFn} */
function urnuuidParse (urnComponent, options) {
  const uuidComponent = urnComponent
  uuidComponent.uuid = uuidComponent.nss
  uuidComponent.nss = undefined

  if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
    uuidComponent.error = uuidComponent.error || 'UUID is not valid.'
  }

  return uuidComponent
}

/** @type {SchemeFn} */
function urnuuidSerialize (uuidComponent) {
  const urnComponent = uuidComponent
  // normalize UUID
  urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()
  return urnComponent
}

const http = /** @type {SchemeHandler} */ ({
  scheme: 'http',
  domainHost: true,
  parse: httpParse,
  serialize: httpSerialize
})

const https = /** @type {SchemeHandler} */ ({
  scheme: 'https',
  domainHost: http.domainHost,
  parse: httpParse,
  serialize: httpSerialize
})

const ws = /** @type {SchemeHandler} */ ({
  scheme: 'ws',
  domainHost: true,
  parse: wsParse,
  serialize: wsSerialize
})

const wss = /** @type {SchemeHandler} */ ({
  scheme: 'wss',
  domainHost: ws.domainHost,
  parse: ws.parse,
  serialize: ws.serialize
})

const urn = /** @type {SchemeHandler} */ ({
  scheme: 'urn',
  parse: urnParse,
  serialize: urnSerialize,
  skipNormalize: true
})

const urnuuid = /** @type {SchemeHandler} */ ({
  scheme: 'urn:uuid',
  parse: urnuuidParse,
  serialize: urnuuidSerialize,
  skipNormalize: true
})

const SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({
  http,
  https,
  ws,
  wss,
  urn,
  'urn:uuid': urnuuid
})

Object.setPrototypeOf(SCHEMES, null)

/**
 * @param {string|undefined} scheme
 * @returns {SchemeHandler|undefined}
 */
function getSchemeHandler (scheme) {
  return (
    scheme && (
      SCHEMES[/** @type {SchemeName} */ (scheme)] ||
      SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])
  ) ||
    undefined
}

module.exports = {
  wsIsSecure,
  SCHEMES,
  isValidSchemeName,
  getSchemeHandler,
}
'use strict'

/** @type {(value: string) => boolean} */
const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu)

/** @type {(value: string) => boolean} */
const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u)

/** @type {(value: string) => boolean} */
const isPort = RegExp.prototype.test.bind(/^\d*$/u)

/** @type {(value: string) => boolean} */
const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu)

/** @type {(value: string) => boolean} */
const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu)

/** @type {(value: string) => boolean} */
const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u)

/** @type {(value: string) => boolean} */
const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u)

/** @type {(value: string) => boolean} */
const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u)

const BYTE_HEX = new Array(256)
{
  const HEX_DIGITS = '0123456789ABCDEF'
  for (let i = 0; i < 256; i++) {
    BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF]
  }
}
function percentEncodeNonAscii (cp) {
  if (cp < 0x800) {
    return BYTE_HEX[0xC0 | (cp >> 6)] +
           BYTE_HEX[0x80 | (cp & 0x3F)]
  }
  if (cp < 0x10000) {
    return BYTE_HEX[0xE0 | (cp >> 12)] +
           BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
           BYTE_HEX[0x80 | (cp & 0x3F)]
  }
  return BYTE_HEX[0xF0 | (cp >> 18)] +
         BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +
         BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
         BYTE_HEX[0x80 | (cp & 0x3F)]
}

/**
 * @param {Array<string>} input
 * @returns {string}
 */
function stringArrayToHexStripped (input) {
  let acc = ''
  let code = 0
  let i = 0

  for (i = 0; i < input.length; i++) {
    code = input[i].charCodeAt(0)
    if (code === 48) {
      continue
    }
    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
      return ''
    }
    acc += input[i]
    break
  }

  for (i += 1; i < input.length; i++) {
    code = input[i].charCodeAt(0)
    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
      return ''
    }
    acc += input[i]
  }
  return acc
}

/** @type {(value: string) => boolean} */
const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/)

/** @type {(value: string) => boolean} */
const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/)

/** @type {(value: string) => boolean} */
const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/)

/**
 * @param {string} value
 * @returns {boolean}
 */
const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u)

/**
 * @param {string} zone
 * @returns {boolean}
 */
function isZoneIdentifier (zone) {
  if (zone.length === 0) return false

  for (let i = 0; i < zone.length; i++) {
    if (isZoneCharacter(zone[i])) continue
    if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
      i += 2
      continue
    }
    return false
  }

  return true
}

/**
 * Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a
 * single zero hextet is left uncompressed. On ties the leftmost run wins.
 *
 * @param {string[]} hextets
 * @returns {string}
 */
function compressIPv6ZeroRun (hextets) {
  let bestStart = -1
  let bestLength = 0
  let runStart = -1
  let runLength = 0
  for (let i = 0; i < hextets.length; i++) {
    if (hextets[i] === '0') {
      if (runStart === -1) runStart = i
      runLength++
      if (runLength > bestLength) {
        bestLength = runLength
        bestStart = runStart
      }
    } else {
      runStart = -1
      runLength = 0
    }
  }

  if (bestLength < 2) return hextets.join(':')

  const head = hextets.slice(0, bestStart).join(':')
  const tail = hextets.slice(bestStart + bestLength).join(':')
  return head + '::' + tail
}

/**
 * Validates an IPv6 address against the alternatives in RFC 3986 section
 * 3.2.2 and returns the same address with leading hextet zeroes removed.
 * An embedded IPv4 address counts as two hextets and is only valid at the end.
 *
 * @param {string} input
 * @returns {string|undefined}
 */
function normalizeIPv6Address (input) {
  const compression = input.indexOf('::')
  if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined

  const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':')
  const right = compression === -1 ? [] : input.slice(compression + 2).split(':')
  if (compression !== -1) {
    if (left.length === 1 && left[0] === '') left.length = 0
    if (right.length === 1 && right[0] === '') right.length = 0
  }

  const parts = left.concat(right)
  let hextetCount = 0
  for (let i = 0; i < parts.length; i++) {
    const part = parts[i]
    if (part === '') return undefined

    if (part.indexOf('.') !== -1) {
      if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4(part)) return undefined
      hextetCount += 2
      continue
    }

    if (!isHextet(part)) return undefined
    parts[i] = parseInt(part, 16).toString(16)
    hextetCount++
  }

  if (compression === -1) {
    if (hextetCount !== 8) return undefined
    return compressIPv6ZeroRun(parts)
  }
  if (hextetCount >= 8) return undefined

  // expand "::" then re-compress the longest run for a canonical result
  const expanded = parts.slice(0, left.length)
  for (let i = hextetCount; i < 8; i++) expanded.push('0')
  for (let i = left.length; i < parts.length; i++) expanded.push(parts[i])
  return compressIPv6ZeroRun(expanded)
}

/**
 * @typedef {Object} NormalizeIPv6Result
 * @property {string} host - The normalized host.
 * @property {string} [escapedHost] - The escaped host.
 * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
 * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.
 * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.
 */

/**
 * Validates and normalizes a bracketed IP literal. Raw zone separators remain
 * accepted for backwards compatibility, while encoded separators and zone
 * contents follow RFC 6874.
 *
 * @param {string} host
 * @returns {NormalizeIPv6Result}
 */
function normalizeIPv6 (host) {
  const bracketed = host[0] === '[' && host[host.length - 1] === ']'
  const hasBracket = host[0] === '[' || host[host.length - 1] === ']'
  if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }

  let input = bracketed ? host.slice(1, -1) : host
  if (bracketed && isIPvFuture(input)) {
    input = input.toLowerCase()
    return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }
  }

  if (findToken(input, ':') < 2) {
    return { host, isIPV6: false, error: bracketed }
  }

  let zoneIdentifier = ''
  const zoneSeparator = input.indexOf('%')
  if (zoneSeparator !== -1) {
    const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1
    zoneIdentifier = input.slice(zoneSeparator + separatorLength)
    if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }
    input = input.slice(0, zoneSeparator)
  }

  const address = normalizeIPv6Address(input)
  if (address === undefined) return { host, isIPV6: false, error: true }

  return {
    host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),
    escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),
    isIPV6: true
  }
}

/**
 * @param {string} str
 * @param {string} token
 * @returns {number}
 */
function findToken (str, token) {
  let ind = 0
  for (let i = 0; i < str.length; i++) {
    if (str[i] === token) ind++
  }
  return ind
}

/**
 * @param {string} path
 * @returns {string}
 *
 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
 */
function removeDotSegments (path) {
  let input = path
  const output = []
  let nextSlash = -1
  let len = 0

  // eslint-disable-next-line no-cond-assign
  while (len = input.length) {
    if (len === 1) {
      if (input === '.') {
        break
      } else if (input === '/') {
        output.push('/')
        break
      } else {
        output.push(input)
        break
      }
    } else if (len === 2) {
      if (input[0] === '.') {
        if (input[1] === '.') {
          break
        } else if (input[1] === '/') {
          input = input.slice(2)
          continue
        }
      } else if (input[0] === '/') {
        if (input[1] === '.' || input[1] === '/') {
          output.push('/')
          break
        }
      }
    } else if (len === 3) {
      if (input === '/..') {
        if (output.length !== 0) {
          output.pop()
        }
        output.push('/')
        break
      }
    }
    if (input[0] === '.') {
      if (input[1] === '.') {
        if (input[2] === '/') {
          input = input.slice(3)
          continue
        }
      } else if (input[1] === '/') {
        input = input.slice(2)
        continue
      }
    } else if (input[0] === '/') {
      if (input[1] === '.') {
        if (input[2] === '/') {
          input = input.slice(2)
          continue
        } else if (input[2] === '.') {
          if (input[3] === '/') {
            input = input.slice(3)
            if (output.length !== 0) {
              output.pop()
            }
            continue
          }
        }
      }
    }

    // Rule 2E: Move normal path segment to output
    if ((nextSlash = input.indexOf('/', 1)) === -1) {
      output.push(input)
      break
    } else {
      output.push(input.slice(0, nextSlash))
      input = input.slice(nextSlash)
    }
  }

  return output.join('')
}

/**
 * Re-escape RFC 3986 gen-delims that must not appear literally in the host.
 * After the URI regex parses, these characters cannot be literal in the host
 * field, so any that appear after decoding came from percent-encoding and
 * must be restored to prevent authority structure changes.
 *
 * @param {string} host
 * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)
 * @returns {string}
 */
const HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }
const HOST_DELIM_RE = /[@/?#:]/g
const HOST_DELIM_NO_COLON_RE = /[@/?#]/g

function reescapeHostDelimiters (host, isIP) {
  const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE
  re.lastIndex = 0
  return host.replace(re, (ch) => HOST_DELIMS[ch])
}

/**
 * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.
 * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.
 *
 * @param {string} input
 * @param {boolean} [decodeUnreserved=false]
 * @returns {string}
 */
function normalizePercentEncoding (input, decodeUnreserved = false) {
  if (input.indexOf('%') === -1) {
    return input
  }

  let output = ''

  for (let i = 0; i < input.length; i++) {
    if (input[i] === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        const normalizedHex = hex.toUpperCase()
        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))

        if (decodeUnreserved && isUnreserved(decoded)) {
          output += decoded
        } else {
          output += '%' + normalizedHex
        }

        i += 2
        continue
      }
    }

    output += input[i]
  }

  return output
}

/**
 * Normalizes path data without turning reserved escapes into live path syntax.
 * Valid escapes are uppercased, raw unsafe characters are escaped, and only
 * unreserved bytes that are not `.` are decoded.
 *
 * @param {string} input
 * @returns {string}
 */
function normalizePathEncoding (input) {
  let output = ''

  for (let i = 0; i < input.length; i++) {
    const ch = input[i]
    if (ch === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        const normalizedHex = hex.toUpperCase()
        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))

        if (decoded !== '.' && isUnreserved(decoded)) {
          output += decoded
        } else {
          output += '%' + normalizedHex
        }

        i += 2
        continue
      }
    }

    if (isPathCharacter(ch)) {
      output += ch
    } else {
      const code = input.charCodeAt(i)
      if (code < 0x80) {
        output += isEscapeSafe(code) ? ch : BYTE_HEX[code]
      } else if (code < 0xD800 || code > 0xDFFF) {
        output += percentEncodeNonAscii(code)
      } else if (code <= 0xDBFF && i + 1 < input.length) {
        const low = input.charCodeAt(i + 1)
        if (low >= 0xDC00 && low <= 0xDFFF) {
          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
          i++
        } else {
          output += percentEncodeNonAscii(0xFFFD)
        }
      } else {
        output += percentEncodeNonAscii(0xFFFD)
      }
    }
  }

  return output
}

/**
 * Serializes a path without rewriting reserved data. Raw RFC 3986 path
 * characters remain literal, valid escapes are preserved and uppercased, and
 * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the
 * first segment must be escaped so the result cannot be parsed as a scheme.
 *
 * @param {string} input
 * @param {boolean} [pathNoScheme=false]
 * @returns {string}
 */
function serializePathEncoding (input, pathNoScheme = false) {
  let output = ''
  let firstSegment = pathNoScheme && input[0] !== '/'

  for (let i = 0; i < input.length; i++) {
    const ch = input[i]
    if (ch === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        output += '%' + hex.toUpperCase()
        i += 2
        continue
      }
    }

    if (ch === '/') {
      firstSegment = false
    }

    if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {
      output += ch
    } else {
      const code = input.charCodeAt(i)
      if (code < 0x80) {
        output += BYTE_HEX[code]
      } else if (code < 0xD800 || code > 0xDFFF) {
        output += percentEncodeNonAscii(code)
      } else if (code <= 0xDBFF && i + 1 < input.length) {
        const low = input.charCodeAt(i + 1)
        if (low >= 0xDC00 && low <= 0xDFFF) {
          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
          i++
        } else {
          output += percentEncodeNonAscii(0xFFFD)
        }
      } else {
        output += percentEncodeNonAscii(0xFFFD)
      }
    }
  }

  return output
}

/**
 * Percent-encodes a URI component using its RFC 3986 literal character set.
 * Existing valid escapes are preserved and normalized to uppercase hex.
 *
 * @param {string} input
 * @param {(value: string) => boolean} isAllowed
 * @returns {string}
 */
function encodeComponent (input, isAllowed) {
  let output = ''

  for (let i = 0; i < input.length; i++) {
    const ch = input[i]
    if (ch === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        output += '%' + hex.toUpperCase()
        i += 2
        continue
      }
    }

    if (isAllowed(ch)) {
      output += ch
    } else {
      const code = input.charCodeAt(i)
      if (code < 0x80) {
        output += BYTE_HEX[code]
      } else if (code < 0xD800 || code > 0xDFFF) {
        output += percentEncodeNonAscii(code)
      } else if (code <= 0xDBFF && i + 1 < input.length) {
        const low = input.charCodeAt(i + 1)
        if (low >= 0xDC00 && low <= 0xDFFF) {
          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
          i++
        } else {
          output += percentEncodeNonAscii(0xFFFD)
        }
      } else {
        output += percentEncodeNonAscii(0xFFFD)
      }
    }
  }

  return output
}

/**
 * Encodes userinfo while preserving its RFC 3986 Â§3.2.1 literal characters.
 * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.
 *
 * @param {string} input
 * @returns {string}
 */
function encodeUserinfo (input) {
  return encodeComponent(input, isUserinfoCharacter)
}

/**
 * Encodes query data using the RFC 3986 Â§3.4 grammar. A literal `#` must be
 * escaped because it would otherwise begin the fragment component.
 *
 * @param {string} input
 * @returns {string}
 */
function encodeQuery (input) {
  return encodeComponent(input, isQueryFragmentCharacter)
}

/**
 * Encodes fragment data using the RFC 3986 Â§3.5 grammar.
 *
 * @param {string} input
 * @returns {string}
 */
function encodeFragment (input) {
  return encodeComponent(input, isQueryFragmentCharacter)
}

function isEscapeSafe (cp) {
  return (
    (cp >= 0x30 && cp <= 0x39) ||
    (cp >= 0x41 && cp <= 0x5A) ||
    (cp >= 0x61 && cp <= 0x7A) ||
    cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||
    cp === 0x2F || cp === 0x40 || cp === 0x5F
  )
}

/**
 * Normalizes the percent-encoding of a query or fragment component.
 *
 * Like `normalizePathEncoding`, but uses the query/fragment character set
 * (which additionally allows `?`) and decodes `.` since it has no dot-segment
 * meaning outside of a path.
 *
 * @param {string} input
 * @returns {string}
 */
function normalizeQueryFragmentEncoding (input) {
  let output = ''

  for (let i = 0; i < input.length; i++) {
    const ch = input[i]
    if (ch === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        const normalizedHex = hex.toUpperCase()
        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))

        if (isUnreserved(decoded)) {
          output += decoded
        } else {
          output += '%' + normalizedHex
        }

        i += 2
        continue
      }
    }

    if (isQueryFragmentCharacter(ch)) {
      output += ch
    } else {
      const code = input.charCodeAt(i)
      if (code < 0x80) {
        output += isEscapeSafe(code) ? ch : BYTE_HEX[code]
      } else if (code < 0xD800 || code > 0xDFFF) {
        output += percentEncodeNonAscii(code)
      } else if (code <= 0xDBFF && i + 1 < input.length) {
        const low = input.charCodeAt(i + 1)
        if (low >= 0xDC00 && low <= 0xDFFF) {
          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
          i++
        } else {
          output += percentEncodeNonAscii(0xFFFD)
        }
      } else {
        output += percentEncodeNonAscii(0xFFFD)
      }
    }
  }

  return output
}

/**
 * Escapes a component while preserving existing valid percent escapes.
 *
 * @param {string} input
 * @returns {string}
 */
function escapePreservingEscapes (input) {
  let output = ''

  for (let i = 0; i < input.length; i++) {
    if (input[i] === '%' && i + 2 < input.length) {
      const hex = input.slice(i + 1, i + 3)
      if (isHexPair(hex)) {
        output += '%' + hex.toUpperCase()
        i += 2
        continue
      }
    }

    output += escape(input[i])
  }

  return output
}

/**
 * @param {import('../types/index').URIComponent} component
 * @returns {string|undefined}
 */
function recomposeAuthority (component) {
  const uriTokens = []

  if (component.userinfo !== undefined) {
    uriTokens.push(encodeUserinfo(component.userinfo))
    uriTokens.push('@')
  }

  if (component.host !== undefined) {
    let host = component.host
    if (!isIPv4(host)) {
      let ipV6res = normalizeIPv6(host)
      if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
        // Decode only unreserved bytes, once. In particular, keep %25 encoded
        // so it cannot introduce a second escape during recomposition.
        host = normalizePercentEncoding(host, true)
        ipV6res = normalizeIPv6(host)
      }
      if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
        host = `[${ipV6res.escapedHost}]`
      } else {
        host = reescapeHostDelimiters(host, false)
      }
    }
    uriTokens.push(host)
  }

  if (typeof component.port === 'number' || typeof component.port === 'string') {
    const port = String(component.port)
    if (!isPort(port)) {
      throw new TypeError('URI port is malformed.')
    }
    uriTokens.push(':')
    uriTokens.push(port)
  }

  return uriTokens.length ? uriTokens.join('') : undefined
};

module.exports = {
  nonSimpleDomain,
  recomposeAuthority,
  reescapeHostDelimiters,
  normalizePercentEncoding,
  normalizePathEncoding,
  serializePathEncoding,
  normalizeQueryFragmentEncoding,
  encodeUserinfo,
  encodeQuery,
  encodeFragment,
  escapePreservingEscapes,
  removeDotSegments,
  isIPv4,
  isUUID,
  normalizeIPv6,
  stringArrayToHexStripped
}
import { Bench } from 'tinybench'
import { fastUri } from '../index.js'
import { parse as uriJsParse, serialize as uriJsSerialize, resolve as uriJsResolve, equal as uriJsEqual } from 'uri-js'

const base = 'uri://a/b/c/d;p?q'

const domain = 'https://example.com/foo#bar$fiz'
const ipv4 = '//10.10.10.10'
const ipv6 = '//[2001:db8::7]'
const urn = 'urn:foo:a123,456'
const urnuuid = 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6'

const urnuuidComponent = {
  scheme: 'urn',
  nid: 'uuid',
  uuid: 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6'
}

const {
  parse: fastUriParse,
  serialize: fastUriSerialize,
  resolve: fastUriResolve,
  equal: fastUriEqual,
} = fastUri

// Initialization as there is a lot to parse at first
// eg: regexes
fastUriParse(domain)
uriJsParse(domain)

const benchFastUri = new Bench({ name: 'fast-uri benchmark' })
const benchUriJs = new Bench({ name: 'uri-js benchmark' })
const benchWHATWG = new Bench({ name: 'WHATWG URL benchmark' })

benchFastUri.add('fast-uri: parse domain', function () {
  fastUriParse(domain)
})
benchUriJs.add('urijs: parse domain', function () {
  uriJsParse(domain)
})
benchWHATWG.add('WHATWG URL: parse domain', function () {
  // eslint-disable-next-line
  new URL(domain)
})
benchFastUri.add('fast-uri: parse IPv4', function () {
  fastUriParse(ipv4)
})
benchUriJs.add('urijs: parse IPv4', function () {
  uriJsParse(ipv4)
})
benchFastUri.add('fast-uri: parse IPv6', function () {
  fastUriParse(ipv6)
})
benchUriJs.add('urijs: parse IPv6', function () {
  uriJsParse(ipv6)
})
benchFastUri.add('fast-uri: parse URN', function () {
  fastUriParse(urn)
})
benchUriJs.add('urijs: parse URN', function () {
  uriJsParse(urn)
})
benchWHATWG.add('WHATWG URL: parse URN', function () {
  // eslint-disable-next-line
  new URL(urn)
})
benchFastUri.add('fast-uri: parse URN uuid', function () {
  fastUriParse(urnuuid)
})
benchUriJs.add('urijs: parse URN uuid', function () {
  uriJsParse(urnuuid)
})
benchFastUri.add('fast-uri: serialize URN uuid', function () {
  fastUriSerialize(urnuuidComponent)
})
benchUriJs.add('uri-js: serialize URN uuid', function () {
  uriJsSerialize(urnuuidComponent)
})
benchFastUri.add('fast-uri: serialize uri', function () {
  fastUriSerialize({
    scheme: 'uri',
    userinfo: 'foo:bar',
    host: 'example.com',
    port: 1,
    path: 'path',
    query: 'query',
    fragment: 'fragment'
  })
})
benchUriJs.add('urijs: serialize uri', function () {
  uriJsSerialize({
    scheme: 'uri',
    userinfo: 'foo:bar',
    host: 'example.com',
    port: 1,
    path: 'path',
    query: 'query',
    fragment: 'fragment'
  })
})
benchFastUri.add('fast-uri: serialize long uri with dots', function () {
  fastUriSerialize({
    scheme: 'uri',
    userinfo: 'foo:bar',
    host: 'example.com',
    port: 1,
    path: './a/./b/c/../.././d/../e/f/.././/',
    query: 'query',
    fragment: 'fragment'
  })
})
benchUriJs.add('urijs: serialize long uri with dots', function () {
  uriJsSerialize({
    scheme: 'uri',
    userinfo: 'foo:bar',
    host: 'example.com',
    port: 1,
    path: './a/./b/c/../.././d/../e/f/.././/',
    query: 'query',
    fragment: 'fragment'
  })
})
benchFastUri.add('fast-uri: serialize IPv6', function () {
  fastUriSerialize({ host: '2606:2800:220:1:248:1893:25c8:1946' })
})
benchUriJs.add('urijs: serialize IPv6', function () {
  uriJsSerialize({ host: '2606:2800:220:1:248:1893:25c8:1946' })
})
benchFastUri.add('fast-uri: serialize ws', function () {
  fastUriSerialize({ scheme: 'ws', host: 'example.com', resourceName: '/foo?bar', secure: true })
})
benchUriJs.add('urijs: serialize ws', function () {
  uriJsSerialize({ scheme: 'ws', host: 'example.com', resourceName: '/foo?bar', secure: true })
})
benchFastUri.add('fast-uri: resolve', function () {
  fastUriResolve(base, '../../../g')
})
benchUriJs.add('urijs: resolve', function () {
  uriJsResolve(base, '../../../g')
})

benchFastUri.add('fast-uri: equal', function () {
  fastUriEqual('example://a/b/c/%7Bfoo%7D', 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d')
})
benchUriJs.add('urijs: equal', function () {
  uriJsEqual('example://a/b/c/%7Bfoo%7D', 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d')
})

await benchFastUri.run()
console.log(benchFastUri.name)
console.table(benchFastUri.table())

await benchUriJs.run()
console.log(benchUriJs.name)
console.table(benchUriJs.table())

await benchWHATWG.run()
console.log(benchWHATWG.name)
console.table(benchWHATWG.table())
import { Bench } from 'tinybench'
import { fastUri } from '../index.js'

const {
  equal: fastUriEqual,
  parse: fastUriParse,
} = fastUri

const stringA = 'example://a/b/c/%7Bfoo%7D'
const stringB = 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d'

const componentA = fastUriParse(stringA)
const componentB = fastUriParse(stringB)

const benchFastUri = new Bench({ name: 'fast-uri equal' })

benchFastUri.add('equal string with string', function () {
  fastUriEqual(stringA, stringA)
})

benchFastUri.add('equal component with component', function () {
  fastUriEqual(componentA, componentA)
})

benchFastUri.add('equal component with string', function () {
  fastUriEqual(componentA, stringA)
})

benchFastUri.add('equal string with component', function () {
  fastUriEqual(stringA, componentA)
})

benchFastUri.add('not equal string with string', function () {
  fastUriEqual(stringA, stringB)
})

benchFastUri.add('not equal component with component', function () {
  fastUriEqual(componentA, componentB)
})

benchFastUri.add('not equal component with string', function () {
  fastUriEqual(componentA, stringB)
})

benchFastUri.add('not equal string with component', function () {
  fastUriEqual(stringA, componentB)
})

await benchFastUri.run()
console.log(benchFastUri.name)
console.table(benchFastUri.table())
import { Bench } from 'tinybench'
import { nonSimpleDomain } from '../lib/utils.js'

const benchNonSimpleDomain = new Bench({ name: 'nonSimpleDomain' })

const exampleCom = 'example.com'
const exaumlmpleCom = 'exÃ¤mple.com'
const longDomain = 'abc'.repeat(100) + '.com'

console.assert(nonSimpleDomain(exampleCom) === false, 'example.com should be a simple domain')
console.assert(nonSimpleDomain(exaumlmpleCom) === true, 'exÃ¤mple.com should not be a simple domain')
console.assert(nonSimpleDomain(longDomain) === false, `${longDomain} should be a simple domain?`)

benchNonSimpleDomain.add('nonSimpleDomain', function () {
  nonSimpleDomain(exampleCom)
  nonSimpleDomain(exaumlmpleCom)
  nonSimpleDomain(longDomain)
})

await benchNonSimpleDomain.run()
console.log(benchNonSimpleDomain.name)
console.table(benchNonSimpleDomain.table())
{
  "name": "benchmark",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "private": true,
  "author": "",
  "license": "ISC",
  "dependencies": {
    "tinybench": "^5.0.0",
    "uri-js": "^4.4.1"
  }
}import { Bench } from 'tinybench'
import { stringArrayToHexStripped } from '../lib/utils.js'

const benchStringArrayToHexStripped = new Bench({ name: 'stringArrayToHexStripped' })

const case1 = ['0', '0', '0', '0']
const case2 = ['0', '0', '0', '1']
const case3 = ['0', '0', '1', '0']
const case4 = ['0', '1', '0', '0']
const case5 = ['1', '0', '0', '0']
const case6 = ['1', '0', '0', '1']

benchStringArrayToHexStripped.add('stringArrayToHexStripped', function () {
  stringArrayToHexStripped(case1)
  stringArrayToHexStripped(case2)
  stringArrayToHexStripped(case3)
  stringArrayToHexStripped(case4)
  stringArrayToHexStripped(case5)
  stringArrayToHexStripped(case6)
})

await benchStringArrayToHexStripped.run()
console.log(benchStringArrayToHexStripped.name)
console.table(benchStringArrayToHexStripped.table())
import { Bench } from 'tinybench'
import { wsIsSecure } from '../lib/schemes.js'

const benchWsIsSecure = new Bench({ name: 'wsIsSecure' })

const wsComponentAttributeSecureTrue = {
  scheme: 'ws',
  secure: true,
}

const wsComponentAttributeSecureFalse = {
  scheme: 'ws',
  secure: false,
}

const wssComponent = {
  scheme: 'wss',
}

const wssComponentMixedCase = {
  scheme: 'Wss',
}

const wssComponentUpperCase = {
  scheme: 'WSS',
}

const httpComponent = {
  scheme: 'http',
}

console.assert(wsIsSecure(wsComponentAttributeSecureTrue) === true, 'wsComponentAttributeSecureTrue should be secure')
console.assert(wsIsSecure(wsComponentAttributeSecureFalse) === false, 'wsComponentAttributeSecureFalse should not be secure')
console.assert(wsIsSecure(wssComponent) === true, 'wssComponent should be secure')
console.assert(wsIsSecure(wssComponentMixedCase) === true, 'wssComponentMixedCase should be secure')
console.assert(wsIsSecure(wssComponentUpperCase) === true, 'wssComponentUpperCase should be secure')
console.assert(wsIsSecure(httpComponent) === false, 'httpComponent should not be secure')

benchWsIsSecure.add(JSON.stringify(wsComponentAttributeSecureFalse), function () {
  wsIsSecure(wsComponentAttributeSecureFalse)
})

benchWsIsSecure.add(JSON.stringify(wsComponentAttributeSecureTrue), function () {
  wsIsSecure(wsComponentAttributeSecureTrue)
})

benchWsIsSecure.add(JSON.stringify(wssComponent), function () {
  wsIsSecure(wssComponent)
})

benchWsIsSecure.add(JSON.stringify(wssComponentMixedCase), function () {
  wsIsSecure(wssComponentMixedCase)
})

benchWsIsSecure.add(JSON.stringify(wssComponentUpperCase), function () {
  wsIsSecure(wssComponentUpperCase)
})

benchWsIsSecure.add(JSON.stringify(httpComponent), function () {
  wsIsSecure(httpComponent)
})

await benchWsIsSecure.run()
console.log(benchWsIsSecure.name)
console.table(benchWsIsSecure.table())
'use strict';

module.exports = value => {
	const type = typeof value;
	return value !== null && (type === 'object' || type === 'function');
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "is-obj",
  "version": "2.0.0",
  "description": "Check if a value is an object",
  "license": "MIT",
  "repository": "sindresorhus/is-obj",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=8"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.2",
    "xo": "^0.24.0"
  }
}The MIT License (MIT)

Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
// License: MIT. (See LICENSE.)

Object.defineProperty(exports, "__esModule", {
  value: true
})

// This regex comes from regex.coffee, and is inserted here by generate-index.js
// (run `npm run build`).
exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g

exports.matchToToken = function(match) {
  var token = {type: "invalid", value: match[0], closed: undefined}
       if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4])
  else if (match[ 5]) token.type = "comment"
  else if (match[ 6]) token.type = "comment", token.closed = !!match[7]
  else if (match[ 8]) token.type = "regex"
  else if (match[ 9]) token.type = "number"
  else if (match[10]) token.type = "name"
  else if (match[11]) token.type = "punctuator"
  else if (match[12]) token.type = "whitespace"
  return token
}
{
  "name": "js-tokens",
  "version": "4.0.0",
  "author": "Simon Lydell",
  "license": "MIT",
  "description": "A regex that tokenizes JavaScript.",
  "files": [
    "index.js"
  ],
  "repository": "lydell/js-tokens",
  "devDependencies": {
    "coffeescript": "2.1.1",
    "esprima": "4.0.0",
    "everything.js": "1.0.3",
    "mocha": "5.0.0"
  }
}BSD-2-Clause License

Copyright (c) 2018 IETF Trust, Austin Wright, Henry Andrews, Geraint Luff,
and Cloudflare, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

{
  "name": "json-schema-typed",
  "description": "JSONSchema TypeScript definitions.",
  "version": "7.0.3",
  "license": "BSD-2-Clause",
  "files": [
    "dist-*/",
    "bin/"
  ],
  "pika": true,
  "sideEffects": false,
  "homepage": "https://github.com/typeslick/json-schema-typed",
  "repository": {
    "type": "git",
    "url": "https://github.com/typeslick/json-schema-typed.git"
  },
  "dependencies": {},
  "devDependencies": {
    "@babel/cli": "7.6.4",
    "@babel/core": "7.6.4",
    "@babel/runtime-corejs2": "7.6.3",
    "@loomble/cspell-dictionary": "1.0.0",
    "@microsoft/api-extractor": "7.3.4",
    "@pika/pack": "0.5.0",
    "@pika/plugin-build-node": "0.7.1",
    "@pika/plugin-build-types": "0.7.1",
    "@pika/plugin-build-web": "0.7.1",
    "@pika/plugin-standard-pkg": "0.7.1",
    "@types/babel__core": "7.1.3",
    "@types/jest": "24.0.20",
    "@types/jest-diff": "20.0.1",
    "@types/node": "12.11.7",
    "babel-core": "6.26.3",
    "babel-jest": "24.9.0",
    "babel-preset-slick": "7.0.4",
    "core-js": "3.3.4",
    "cspell": "4.0.31",
    "deep-sort-object": "1.0.2",
    "jest": "24.9.0",
    "jest-serializer-path": "0.1.15",
    "prettier": "1.18.2",
    "tsconfig-slick": "3.0.2",
    "tslint": "5.20.0",
    "tslint-slick": "5.0.0",
    "typedoc": "0.15.0",
    "typedoc-plugin-markdown": "2.2.11",
    "typescript": "3.6.4",
    "typescript-tslint-plugin": "0.5.4"
  },
  "esnext": "dist-src/index.js",
  "main": "dist-node/index.js",
  "module": "dist-web/index.js",
  "types": "dist-types/index.d.ts"
}let JSONSchemaFormat;

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(JSONSchemaFormat || (JSONSchemaFormat = {}));

let JSONSchemaType;

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(JSONSchemaType || (JSONSchemaType = {}));

let JSONSchemaContentEncoding;

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));

const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];

export { JSONSchemaContentEncoding, JSONSchemaFormat, JSONSchemaKeys, JSONSchemaType };
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["\"use strict\";\n\nexport let JSONSchemaFormat;\n\n(function (JSONSchemaFormat) {\n  JSONSchemaFormat[\"Date\"] = \"date\";\n  JSONSchemaFormat[\"DateTime\"] = \"date-time\";\n  JSONSchemaFormat[\"Email\"] = \"email\";\n  JSONSchemaFormat[\"Hostname\"] = \"hostname\";\n  JSONSchemaFormat[\"IDNEmail\"] = \"idn-email\";\n  JSONSchemaFormat[\"IDNHostname\"] = \"idn-hostname\";\n  JSONSchemaFormat[\"IPv4\"] = \"ipv4\";\n  JSONSchemaFormat[\"IPv6\"] = \"ipv6\";\n  JSONSchemaFormat[\"IRI\"] = \"iri\";\n  JSONSchemaFormat[\"IRIReference\"] = \"iri-reference\";\n  JSONSchemaFormat[\"JSONPointer\"] = \"json-pointer\";\n  JSONSchemaFormat[\"JSONPointerURIFragment\"] = \"json-pointer-uri-fragment\";\n  JSONSchemaFormat[\"RegEx\"] = \"regex\";\n  JSONSchemaFormat[\"RelativeJSONPointer\"] = \"relative-json-pointer\";\n  JSONSchemaFormat[\"Time\"] = \"time\";\n  JSONSchemaFormat[\"URI\"] = \"uri\";\n  JSONSchemaFormat[\"URIReference\"] = \"uri-reference\";\n  JSONSchemaFormat[\"URITemplate\"] = \"uri-template\";\n  JSONSchemaFormat[\"UUID\"] = \"uuid\";\n})(JSONSchemaFormat || (JSONSchemaFormat = {}));\n\nexport let JSONSchemaType;\n\n(function (JSONSchemaType) {\n  JSONSchemaType[\"Array\"] = \"array\";\n  JSONSchemaType[\"Boolean\"] = \"boolean\";\n  JSONSchemaType[\"Integer\"] = \"integer\";\n  JSONSchemaType[\"Null\"] = \"null\";\n  JSONSchemaType[\"Number\"] = \"number\";\n  JSONSchemaType[\"Object\"] = \"object\";\n  JSONSchemaType[\"String\"] = \"string\";\n})(JSONSchemaType || (JSONSchemaType = {}));\n\nexport let JSONSchemaContentEncoding;\n\n(function (JSONSchemaContentEncoding) {\n  JSONSchemaContentEncoding[\"7bit\"] = \"7bit\";\n  JSONSchemaContentEncoding[\"8bit\"] = \"8bit\";\n  JSONSchemaContentEncoding[\"Binary\"] = \"binary\";\n  JSONSchemaContentEncoding[\"QuotedPrintable\"] = \"quoted-printable\";\n  JSONSchemaContentEncoding[\"Base64\"] = \"base64\";\n  JSONSchemaContentEncoding[\"IETFToken\"] = \"ietf-token\";\n  JSONSchemaContentEncoding[\"XToken\"] = \"x-token\";\n})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));\n\nexport const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];"],"names":[],"mappings":"AAEU,IAAC,gBAAgB,CAAC;;AAE5B,CAAC,UAAU,gBAAgB,EAAE;EAC3B,gBAAgB,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;EAClC,gBAAgB,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;EAC3C,gBAAgB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;EACpC,gBAAgB,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;EAC1C,gBAAgB,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;EAC3C,gBAAgB,CAAC,aAAa,CAAC,GAAG,cAAc,CAAC;EACjD,gBAAgB,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;EAClC,gBAAgB,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;EAClC,gBAAgB,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;EAChC,gBAAgB,CAAC,cAAc,CAAC,GAAG,eAAe,CAAC;EACnD,gBAAgB,CAAC,aAAa,CAAC,GAAG,cAAc,CAAC;EACjD,gBAAgB,C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C,QAAQ,CAAC,GAAG,QAAQ,CAAC;EAC/C,yBAAyB,CAAC,WAAW,CAAC,GAAG,YAAY,CAAC;EACtD,yBAAyB,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC;CACjD,EAAE,yBAAyB,KAAK,yBAAyB,GAAG,EAAE,CAAC,CAAC,CAAC;;AAElE,AAAY,MAAC,cAAc,GAAG,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,SAAS,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,YAAY,EAAE,eAAe,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC;;;;"}"use strict";

export let JSONSchemaFormat;

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(JSONSchemaFormat || (JSONSchemaFormat = {}));

export let JSONSchemaType;

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(JSONSchemaType || (JSONSchemaType = {}));

export let JSONSchemaContentEncoding;

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));

export const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(exports.JSONSchemaFormat || (exports.JSONSchemaFormat = {}));

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(exports.JSONSchemaType || (exports.JSONSchemaType = {}));

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(exports.JSONSchemaContentEncoding || (exports.JSONSchemaContentEncoding = {}));

const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];

exports.JSONSchemaKeys = JSONSchemaKeys;
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["\"use strict\";\n\nexport let JSONSchemaFormat;\n\n(function (JSONSchemaFormat) {\n  JSONSchemaFormat[\"Date\"] = \"date\";\n  JSONSchemaFormat[\"DateTime\"] = \"date-time\";\n  JSONSchemaFormat[\"Email\"] = \"email\";\n  JSONSchemaFormat[\"Hostname\"] = \"hostname\";\n  JSONSchemaFormat[\"IDNEmail\"] = \"idn-email\";\n  JSONSchemaFormat[\"IDNHostname\"] = \"idn-hostname\";\n  JSONSchemaFormat[\"IPv4\"] = \"ipv4\";\n  JSONSchemaFormat[\"IPv6\"] = \"ipv6\";\n  JSONSchemaFormat[\"IRI\"] = \"iri\";\n  JSONSchemaFormat[\"IRIReference\"] = \"iri-reference\";\n  JSONSchemaFormat[\"JSONPointer\"] = \"json-pointer\";\n  JSONSchemaFormat[\"JSONPointerURIFragment\"] = \"json-pointer-uri-fragment\";\n  JSONSchemaFormat[\"RegEx\"] = \"regex\";\n  JSONSchemaFormat[\"RelativeJSONPointer\"] = \"relative-json-pointer\";\n  JSONSchemaFormat[\"Time\"] = \"time\";\n  JSONSchemaFormat[\"URI\"] = \"uri\";\n  JSONSchemaFormat[\"URIReference\"] = \"uri-reference\";\n  JSONSchemaFormat[\"URITemplate\"] = \"uri-template\";\n  JSONSchemaFormat[\"UUID\"] = \"uuid\";\n})(JSONSchemaFormat || (JSONSchemaFormat = {}));\n\nexport let JSONSchemaType;\n\n(function (JSONSchemaType) {\n  JSONSchemaType[\"Array\"] = \"array\";\n  JSONSchemaType[\"Boolean\"] = \"boolean\";\n  JSONSchemaType[\"Integer\"] = \"integer\";\n  JSONSchemaType[\"Null\"] = \"null\";\n  JSONSchemaType[\"Number\"] = \"number\";\n  JSONSchemaType[\"Object\"] = \"object\";\n  JSONSchemaType[\"String\"] = \"string\";\n})(JSONSchemaType || (JSONSchemaType = {}));\n\nexport let JSONSchemaContentEncoding;\n\n(function (JSONSchemaContentEncoding) {\n  JSONSchemaContentEncoding[\"7bit\"] = \"7bit\";\n  JSONSchemaContentEncoding[\"8bit\"] = \"8bit\";\n  JSONSchemaContentEncoding[\"Binary\"] = \"binary\";\n  JSONSchemaContentEncoding[\"QuotedPrintable\"] = \"quoted-printable\";\n  JSONSchemaContentEncoding[\"Base64\"] = \"base64\";\n  JSONSchemaContentEncoding[\"IETFToken\"] = \"ietf-token\";\n  JSONSchemaContentEncoding[\"XToken\"] = \"x-token\";\n})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));\n\nexport const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];"],"names":["JSONSchemaFormat","JSONSchemaType","JSONSchemaContentEncoding","JSONSchemaKeys"],"mappings":";;;;AAIA,CAAC,UAAUA,gBAAV,EAA4B;EAC3BA,gBAAgB,CAAC,MAAD,CAAhB,GAA2B,MAA3B;EACAA,gBAAgB,CA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The MIT License (MIT)

Copyright (c) 2015 Andres Suarez <zertosh@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#!/usr/bin/env node
'use strict';

var looseEnvify = require('./');
var fs = require('fs');

if (process.argv[2]) {
  fs.createReadStream(process.argv[2], {encoding: 'utf8'})
    .pipe(looseEnvify(process.argv[2]))
    .pipe(process.stdout);
} else {
  process.stdin.resume()
  process.stdin
    .pipe(looseEnvify(__filename))
    .pipe(process.stdout);
}
// envify compatibility
'use strict';

module.exports = require('./loose-envify');
'use strict';

module.exports = require('./loose-envify')(process.env);
'use strict';

var stream = require('stream');
var util = require('util');
var replace = require('./replace');

var jsonExtRe = /\.json$/;

module.exports = function(rootEnv) {
  rootEnv = rootEnv || process.env;
  return function (file, trOpts) {
    if (jsonExtRe.test(file)) {
      return stream.PassThrough();
    }
    var envs = trOpts ? [rootEnv, trOpts] : [rootEnv];
    return new LooseEnvify(envs);
  };
};

function LooseEnvify(envs) {
  stream.Transform.call(this);
  this._data = '';
  this._envs = envs;
}
util.inherits(LooseEnvify, stream.Transform);

LooseEnvify.prototype._transform = function(buf, enc, cb) {
  this._data += buf;
  cb();
};

LooseEnvify.prototype._flush = function(cb) {
  var replaced = replace(this._data, this._envs);
  this.push(replaced);
  cb();
};
{
  "name": "loose-envify",
  "version": "1.4.0",
  "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST",
  "homepage": "https://github.com/zertosh/loose-envify",
  "license": "MIT",
  "author": "Andres Suarez <zertosh@gmail.com>",
  "main": "index.js",
  "bin": {
    "loose-envify": "cli.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/zertosh/loose-envify.git"
  },
  "dependencies": {
    "js-tokens": "^3.0.0 || ^4.0.0"
  },
  "devDependencies": {
    "browserify": "^13.1.1",
    "envify": "^3.4.0",
    "tap": "^8.0.0"
  }
}'use strict';

var jsTokens = require('js-tokens').default;

var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/;
var spaceOrCommentRe = /^(?:\s|\/[/*])/;

function replace(src, envs) {
  if (!processEnvRe.test(src)) {
    return src;
  }

  var out = [];
  var purge = envs.some(function(env) {
    return env._ && env._.indexOf('purge') !== -1;
  });

  jsTokens.lastIndex = 0
  var parts = src.match(jsTokens);

  for (var i = 0; i < parts.length; i++) {
    if (parts[i    ] === 'process' &&
        parts[i + 1] === '.' &&
        parts[i + 2] === 'env' &&
        parts[i + 3] === '.') {
      var prevCodeToken = getAdjacentCodeToken(-1, parts, i);
      var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4);
      var replacement = getReplacementString(envs, parts[i + 4], purge);
      if (prevCodeToken !== '.' &&
          nextCodeToken !== '.' &&
          nextCodeToken !== '=' &&
          typeof replacement === 'string') {
        out.push(replacement);
        i += 4;
        continue;
      }
    }
    out.push(parts[i]);
  }

  return out.join('');
}

function getAdjacentCodeToken(dir, parts, i) {
  while (true) {
    var part = parts[i += dir];
    if (!spaceOrCommentRe.test(part)) {
      return part;
    }
  }
}

function getReplacementString(envs, name, purge) {
  for (var j = 0; j < envs.length; j++) {
    var env = envs[j];
    if (typeof env[name] !== 'undefined') {
      return JSON.stringify(env[name]);
    }
  }
  if (purge) {
    return 'undefined';
  }
}

module.exports = replace;
'use strict';

const copyProperty = (to, from, property, ignoreNonConfigurable) => {
	// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
	// `Function#prototype` is non-writable and non-configurable so can never be modified.
	if (property === 'length' || property === 'prototype') {
		return;
	}

	// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
	if (property === 'arguments' || property === 'caller') {
		return;
	}

	const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
	const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);

	if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
		return;
	}

	Object.defineProperty(to, property, fromDescriptor);
};

// `Object.defineProperty()` throws if the property exists, is not configurable and either:
//  - one its descriptors is changed
//  - it is non-writable and its value is changed
const canCopyProperty = function (toDescriptor, fromDescriptor) {
	return toDescriptor === undefined || toDescriptor.configurable || (
		toDescriptor.writable === fromDescriptor.writable &&
		toDescriptor.enumerable === fromDescriptor.enumerable &&
		toDescriptor.configurable === fromDescriptor.configurable &&
		(toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
	);
};

const changePrototype = (to, from) => {
	const fromPrototype = Object.getPrototypeOf(from);
	if (fromPrototype === Object.getPrototypeOf(to)) {
		return;
	}

	Object.setPrototypeOf(to, fromPrototype);
};

const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;

const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');

// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
// We use `bind()` instead of a closure for the same reason.
// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
const changeToString = (to, from, name) => {
	const withName = name === '' ? '' : `with ${name.trim()}() `;
	const newToString = wrappedToString.bind(null, withName, from.toString());
	// Ensure `to.toString.toString` is non-enumerable and has the same `same`
	Object.defineProperty(newToString, 'name', toStringName);
	Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
};

const mimicFn = (to, from, {ignoreNonConfigurable = false} = {}) => {
	const {name} = to;

	for (const property of Reflect.ownKeys(from)) {
		copyProperty(to, from, property, ignoreNonConfigurable);
	}

	changePrototype(to, from);
	changeToString(to, from, name);

	return to;
};

module.exports = mimicFn;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "mimic-fn",
  "version": "3.1.0",
  "description": "Make a function mimic another one",
  "license": "MIT",
  "repository": "sindresorhus/mimic-fn",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=8"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "ava": "^2.1.0",
    "tsd": "^0.7.1",
    "xo": "^0.24.0"
  }
}'use strict';
const mimicFn = require('mimic-fn');

const calledFunctions = new WeakMap();

const onetime = (function_, options = {}) => {
	if (typeof function_ !== 'function') {
		throw new TypeError('Expected a function');
	}

	let returnValue;
	let callCount = 0;
	const functionName = function_.displayName || function_.name || '<anonymous>';

	const onetime = function (...arguments_) {
		calledFunctions.set(onetime, ++callCount);

		if (callCount === 1) {
			returnValue = function_.apply(this, arguments_);
			function_ = null;
		} else if (options.throw === true) {
			throw new Error(`Function \`${functionName}\` can only be called once`);
		}

		return returnValue;
	};

	mimicFn(onetime, function_);
	calledFunctions.set(onetime, callCount);

	return onetime;
};

module.exports = onetime;
// TODO: Remove this for the next major release
module.exports.default = onetime;

module.exports.callCount = function_ => {
	if (!calledFunctions.has(function_)) {
		throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
	}

	return calledFunctions.get(function_);
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "onetime",
  "version": "5.1.2",
  "description": "Ensure a function is only called once",
  "license": "MIT",
  "repository": "sindresorhus/onetime",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "mimic-fn": "^2.1.0"
  },
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.1",
    "xo": "^0.24.0"
  }
}'use strict';

const pTry = (fn, ...arguments_) => new Promise(resolve => {
	resolve(fn(...arguments_));
});

module.exports = pTry;
// TODO: remove this in the next major version
module.exports.default = pTry;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "p-try",
  "version": "2.2.0",
  "description": "`Start a promise chain",
  "license": "MIT",
  "repository": "sindresorhus/p-try",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.1",
    "xo": "^0.24.0"
  }
}'use strict';
const findUp = require('find-up');

module.exports = async ({cwd} = {}) => findUp('package.json', {cwd});
module.exports.sync = ({cwd} = {}) => findUp.sync('package.json', {cwd});
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "pkg-up",
  "version": "3.1.0",
  "description": "Find the closest package.json file",
  "license": "MIT",
  "repository": "sindresorhus/pkg-up",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=8"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "find-up": "^3.0.0"
  },
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.2",
    "xo": "^0.24.0"
  }
}MIT License

Copyright (c) Facebook, Inc. and its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react.production.min.js');
} else {
  module.exports = require('./cjs/react.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react-jsx-dev-runtime.production.min.js');
} else {
  module.exports = require('./cjs/react-jsx-dev-runtime.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react-jsx-runtime.production.min.js');
} else {
  module.exports = require('./cjs/react-jsx-runtime.development.js');
}
{
  "name": "react",
  "description": "React is a JavaScript library for building user interfaces.",
  "version": "18.3.1",
  "homepage": "https://reactjs.org/",
  "license": "MIT",
  "files": [
    "LICENSE",
    "README.md",
    "index.js",
    "cjs/",
    "umd/",
    "jsx-runtime.js",
    "jsx-dev-runtime.js",
    "react.shared-subset.js"
  ],
  "main": "index.js",
  "exports": {
    ".": {
      "react-server": "./react.shared-subset.js",
      "default": "./index.js"
    },
    "./package.json": "./package.json",
    "./jsx-runtime": "./jsx-runtime.js",
    "./jsx-dev-runtime": "./jsx-dev-runtime.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/facebook/react.git",
    "directory": "packages/react"
  },
  "engines": {
    "node": ">=0.10.0"
  },
  "dependencies": {
    "loose-envify": "^1.1.0"
  },
  "browserify": {
    "transform": [
      "loose-envify"
    ]
  }
}'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react.shared-subset.production.min.js');
} else {
  module.exports = require('./cjs/react.shared-subset.development.js');
}
/**
 * @license React
 * react.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict';

  var ReactVersion = '18.3.1';

  // ATTENTION
  // When adding new symbols to this file,
  // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  // The Symbol used to tag the ReactElement-like types.
  var REACT_ELEMENT_TYPE = Symbol.for('react.element');
  var REACT_PORTAL_TYPE = Symbol.for('react.portal');
  var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
  var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
  var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
  var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
  var REACT_CONTEXT_TYPE = Symbol.for('react.context');
  var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
  var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
  var REACT_MEMO_TYPE = Symbol.for('react.memo');
  var REACT_LAZY_TYPE = Symbol.for('react.lazy');
  var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
  var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';
  function getIteratorFn(maybeIterable) {
    if (maybeIterable === null || typeof maybeIterable !== 'object') {
      return null;
    }

    var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

    if (typeof maybeIterator === 'function') {
      return maybeIterator;
    }

    return null;
  }

  /**
   * Keeps track of the current dispatcher.
   */
  var ReactCurrentDispatcher = {
    /**
     * @internal
     * @type {ReactComponent}
     */
    current: null
  };

  /**
   * Keeps track of the current batch's configuration such as how long an update
   * should suspend for if it needs to.
   */
  var ReactCurrentBatchConfig = {
    transition: null
  };

  var ReactCurrentActQueue = {
    current: null,
    // Used to reproduce behavior of `batchedUpdates` in legacy mode.
    isBatchingLegacy: false,
    didScheduleLegacyUpdate: false
  };

  /**
   * Keeps track of the current owner.
   *
   * The current owner is the component who should own any components that are
   * currently being constructed.
   */
  var ReactCurrentOwner = {
    /**
     * @internal
     * @type {ReactComponent}
     */
    current: null
  };

  var ReactDebugCurrentFrame = {};
  var currentExtraStackFrame = null;
  function setExtraStackFrame(stack) {
    {
      currentExtraStackFrame = stack;
    }
  }

  {
    ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
      {
        currentExtraStackFrame = stack;
      }
    }; // Stack implementation injected by the current renderer.


    ReactDebugCurrentFrame.getCurrentStack = null;

    ReactDebugCurrentFrame.getStackAddendum = function () {
      var stack = ''; // Add an extra top frame while an element is being validated

      if (currentExtraStackFrame) {
        stack += currentExtraStackFrame;
      } // Delegate to the injected renderer-specific implementation


      var impl = ReactDebugCurrentFrame.getCurrentStack;

      if (impl) {
        stack += impl() || '';
      }

      return stack;
    };
  }

  // -----------------------------------------------------------------------------

  var enableScopeAPI = false; // Experimental Create Event Handle API.
  var enableCacheElement = false;
  var enableTransitionTracing = false; // No known bugs, but needs performance testing

  var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
  // stuff. Intended to enable React core members to more easily debug scheduling
  // issues in DEV builds.

  var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

  var ReactSharedInternals = {
    ReactCurrentDispatcher: ReactCurrentDispatcher,
    ReactCurrentBatchConfig: ReactCurrentBatchConfig,
    ReactCurrentOwner: ReactCurrentOwner
  };

  {
    ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
    ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
  }

  // by calls to these methods by a Babel plugin.
  //
  // In PROD (or in packages without access to React internals),
  // they are left as they are instead.

  function warn(format) {
    {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }
  }
  function error(format) {
    {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }
  }

  function printWarning(level, format, args) {
    // When changing this logic, you might want to also
    // update consoleWithStackDev.www.js as well.
    {
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var stack = ReactDebugCurrentFrame.getStackAddendum();

      if (stack !== '') {
        format += '%s';
        args = args.concat([stack]);
      } // eslint-disable-next-line react-internal/safe-string-coercion


      var argsWithFormat = args.map(function (item) {
        return String(item);
      }); // Careful: RN currently depends on this prefix

      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
      // breaks IE9: https://github.com/facebook/react/issues/13610
      // eslint-disable-next-line react-internal/no-production-logging

      Function.prototype.apply.call(console[level], console, argsWithFormat);
    }
  }

  var didWarnStateUpdateForUnmountedComponent = {};

  function warnNoop(publicInstance, callerName) {
    {
      var _constructor = publicInstance.constructor;
      var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
      var warningKey = componentName + "." + callerName;

      if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
        return;
      }

      error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);

      didWarnStateUpdateForUnmountedComponent[warningKey] = true;
    }
  }
  /**
   * This is the abstract API for an update queue.
   */


  var ReactNoopUpdateQueue = {
    /**
     * Checks whether or not this composite component is mounted.
     * @param {ReactClass} publicInstance The instance we want to test.
     * @return {boolean} True if mounted, false otherwise.
     * @protected
     * @final
     */
    isMounted: function (publicInstance) {
      return false;
    },

    /**
     * Forces an update. This should only be invoked when it is known with
     * certainty that we are **not** in a DOM transaction.
     *
     * You may want to call this when you know that some deeper aspect of the
     * component's state has changed but `setState` was not called.
     *
     * This will not invoke `shouldComponentUpdate`, but it will invoke
     * `componentWillUpdate` and `componentDidUpdate`.
     *
     * @param {ReactClass} publicInstance The instance that should rerender.
     * @param {?function} callback Called after component is updated.
     * @param {?string} callerName name of the calling function in the public API.
     * @internal
     */
    enqueueForceUpdate: function (publicInstance, callback, callerName) {
      warnNoop(publicInstance, 'forceUpdate');
    },

    /**
     * Replaces all of the state. Always use this or `setState` to mutate state.
     * You should treat `this.state` as immutable.
     *
     * There is no guarantee that `this.state` will be immediately updated, so
     * accessing `this.state` after calling this method may return the old value.
     *
     * @param {ReactClass} publicInstance The instance that should rerender.
     * @param {object} completeState Next state.
     * @param {?function} callback Called after component is updated.
     * @param {?string} callerName name of the calling function in the public API.
     * @internal
     */
    enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
      warnNoop(publicInstance, 'replaceState');
    },

    /**
     * Sets a subset of the state. This only exists because _pendingState is
     * internal. This provides a merging strategy that is not available to deep
     * properties which is confusing. TODO: Expose pendingState or don't use it
     * during the merge.
     *
     * @param {ReactClass} publicInstance The instance that should rerender.
     * @param {object} partialState Next partial state to be merged with state.
     * @param {?function} callback Called after component is updated.
     * @param {?string} Name of the calling function in the public API.
     * @internal
     */
    enqueueSetState: function (publicInstance, partialState, callback, callerName) {
      warnNoop(publicInstance, 'setState');
    }
  };

  var assign = Object.assign;

  var emptyObject = {};

  {
    Object.freeze(emptyObject);
  }
  /**
   * Base class helpers for the updating state of a component.
   */


  function Component(props, context, updater) {
    this.props = props;
    this.context = context; // If a component has string refs, we will assign a different object later.

    this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
    // renderer.

    this.updater = updater || ReactNoopUpdateQueue;
  }

  Component.prototype.isReactComponent = {};
  /**
   * Sets a subset of the state. Always use this to mutate
   * state. You should treat `this.state` as immutable.
   *
   * There is no guarantee that `this.state` will be immediately updated, so
   * accessing `this.state` after calling this method may return the old value.
   *
   * There is no guarantee that calls to `setState` will run synchronously,
   * as they may eventually be batched together.  You can provide an optional
   * callback that will be executed when the call to setState is actually
   * completed.
   *
   * When a function is provided to setState, it will be called at some point in
   * the future (not synchronously). It will be called with the up to date
   * component arguments (state, props, context). These values can be different
   * from this.* because your function may be called after receiveProps but before
   * shouldComponentUpdate, and this new state, props, and context will not yet be
   * assigned to this.
   *
   * @param {object|function} partialState Next partial state or function to
   *        produce next partial state to be merged with current state.
   * @param {?function} callback Called after state is updated.
   * @final
   * @protected
   */

  Component.prototype.setState = function (partialState, callback) {
    if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
      throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
    }

    this.updater.enqueueSetState(this, partialState, callback, 'setState');
  };
  /**
   * Forces an update. This should only be invoked when it is known with
   * certainty that we are **not** in a DOM transaction.
   *
   * You may want to call this when you know that some deeper aspect of the
   * component's state has changed but `setState` was not called.
   *
   * This will not invoke `shouldComponentUpdate`, but it will invoke
   * `componentWillUpdate` and `componentDidUpdate`.
   *
   * @param {?function} callback Called after update is complete.
   * @final
   * @protected
   */


  Component.prototype.forceUpdate = function (callback) {
    this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
  };
  /**
   * Deprecated APIs. These APIs used to exist on classic React classes but since
   * we would like to deprecate them, we're not going to move them over to this
   * modern base class. Instead, we define a getter that warns if it's accessed.
   */


  {
    var deprecatedAPIs = {
      isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
      replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
    };

    var defineDeprecationWarning = function (methodName, info) {
      Object.defineProperty(Component.prototype, methodName, {
        get: function () {
          warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);

          return undefined;
        }
      });
    };

    for (var fnName in deprecatedAPIs) {
      if (deprecatedAPIs.hasOwnProperty(fnName)) {
        defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
      }
    }
  }

  function ComponentDummy() {}

  ComponentDummy.prototype = Component.prototype;
  /**
   * Convenience component with default shallow equality check for sCU.
   */

  function PureComponent(props, context, updater) {
    this.props = props;
    this.context = context; // If a component has string refs, we will assign a different object later.

    this.refs = emptyObject;
    this.updater = updater || ReactNoopUpdateQueue;
  }

  var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
  pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.

  assign(pureComponentPrototype, Component.prototype);
  pureComponentPrototype.isPureReactComponent = true;

  // an immutable object with a single mutable value
  function createRef() {
    var refObject = {
      current: null
    };

    {
      Object.seal(refObject);
    }

    return refObject;
  }

  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

  function isArray(a) {
    return isArrayImpl(a);
  }

  /*
   * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
   * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
   *
   * The functions in this module will throw an easier-to-understand,
   * easier-to-debug exception with a clear errors message message explaining the
   * problem. (Instead of a confusing exception thrown inside the implementation
   * of the `value` object).
   */
  // $FlowFixMe only called in DEV, so void return is not possible.
  function typeName(value) {
    {
      // toStringTag is needed for namespaced types like Temporal.Instant
      var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
      var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
      return type;
    }
  } // $FlowFixMe only called in DEV, so void return is not possible.


  function willCoercionThrow(value) {
    {
      try {
        testStringCoercion(value);
        return false;
      } catch (e) {
        return true;
      }
    }
  }

  function testStringCoercion(value) {
    // If you ended up here by following an exception call stack, here's what's
    // happened: you supplied an object or symbol value to React (as a prop, key,
    // DOM attribute, CSS property, string ref, etc.) and when React tried to
    // coerce it to a string using `'' + value`, an exception was thrown.
    //
    // The most common types that will cause this exception are `Symbol` instances
    // and Temporal objects like `Temporal.Instant`. But any object that has a
    // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
    // exception. (Library authors do this to prevent users from using built-in
    // numeric operators like `+` or comparison operators like `>=` because custom
    // methods are needed to perform accurate arithmetic or comparison.)
    //
    // To fix the problem, coerce this object or symbol value to a string before
    // passing it to React. The most reliable way is usually `String(value)`.
    //
    // To find which value is throwing, check the browser or debugger console.
    // Before this exception was thrown, there should be `console.error` output
    // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
    // problem and how that type was used: key, atrribute, input value prop, etc.
    // In most cases, this console output also shows the component and its
    // ancestor components where the exception happened.
    //
    // eslint-disable-next-line react-internal/safe-string-coercion
    return '' + value;
  }
  function checkKeyStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }

  function getWrappedName(outerType, innerType, wrapperName) {
    var displayName = outerType.displayName;

    if (displayName) {
      return displayName;
    }

    var functionName = innerType.displayName || innerType.name || '';
    return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
  } // Keep in sync with react-reconciler/getComponentNameFromFiber


  function getContextName(type) {
    return type.displayName || 'Context';
  } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


  function getComponentNameFromType(type) {
    if (type == null) {
      // Host root, text node or just invalid type.
      return null;
    }

    {
      if (typeof type.tag === 'number') {
        error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
      }
    }

    if (typeof type === 'function') {
      return type.displayName || type.name || null;
    }

    if (typeof type === 'string') {
      return type;
    }

    switch (type) {
      case REACT_FRAGMENT_TYPE:
        return 'Fragment';

      case REACT_PORTAL_TYPE:
        return 'Portal';

      case REACT_PROFILER_TYPE:
        return 'Profiler';

      case REACT_STRICT_MODE_TYPE:
        return 'StrictMode';

      case REACT_SUSPENSE_TYPE:
        return 'Suspense';

      case REACT_SUSPENSE_LIST_TYPE:
        return 'SuspenseList';

    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_CONTEXT_TYPE:
          var context = type;
          return getContextName(context) + '.Consumer';

        case REACT_PROVIDER_TYPE:
          var provider = type;
          return getContextName(provider._context) + '.Provider';

        case REACT_FORWARD_REF_TYPE:
          return getWrappedName(type, type.render, 'ForwardRef');

        case REACT_MEMO_TYPE:
          var outerName = type.displayName || null;

          if (outerName !== null) {
            return outerName;
          }

          return getComponentNameFromType(type.type) || 'Memo';

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              return getComponentNameFromType(init(payload));
            } catch (x) {
              return null;
            }
          }

        // eslint-disable-next-line no-fallthrough
      }
    }

    return null;
  }

  var hasOwnProperty = Object.prototype.hasOwnProperty;

  var RESERVED_PROPS = {
    key: true,
    ref: true,
    __self: true,
    __source: true
  };
  var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;

  {
    didWarnAboutStringRefs = {};
  }

  function hasValidRef(config) {
    {
      if (hasOwnProperty.call(config, 'ref')) {
        var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;

        if (getter && getter.isReactWarning) {
          return false;
        }
      }
    }

    return config.ref !== undefined;
  }

  function hasValidKey(config) {
    {
      if (hasOwnProperty.call(config, 'key')) {
        var getter = Object.getOwnPropertyDescriptor(config, 'key').get;

        if (getter && getter.isReactWarning) {
          return false;
        }
      }
    }

    return config.key !== undefined;
  }

  function defineKeyPropWarningGetter(props, displayName) {
    var warnAboutAccessingKey = function () {
      {
        if (!specialPropKeyWarningShown) {
          specialPropKeyWarningShown = true;

          error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
        }
      }
    };

    warnAboutAccessingKey.isReactWarning = true;
    Object.defineProperty(props, 'key', {
      get: warnAboutAccessingKey,
      configurable: true
    });
  }

  function defineRefPropWarningGetter(props, displayName) {
    var warnAboutAccessingRef = function () {
      {
        if (!specialPropRefWarningShown) {
          specialPropRefWarningShown = true;

          error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
        }
      }
    };

    warnAboutAccessingRef.isReactWarning = true;
    Object.defineProperty(props, 'ref', {
      get: warnAboutAccessingRef,
      configurable: true
    });
  }

  function warnIfStringRefCannotBeAutoConverted(config) {
    {
      if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
        var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);

        if (!didWarnAboutStringRefs[componentName]) {
          error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);

          didWarnAboutStringRefs[componentName] = true;
        }
      }
    }
  }
  /**
   * Factory method to create a new React element. This no longer adheres to
   * the class pattern, so do not use new to call it. Also, instanceof check
   * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
   * if something is a React Element.
   *
   * @param {*} type
   * @param {*} props
   * @param {*} key
   * @param {string|object} ref
   * @param {*} owner
   * @param {*} self A *temporary* helper to detect places where `this` is
   * different from the `owner` when React.createElement is called, so that we
   * can warn. We want to get rid of owner and replace string `ref`s with arrow
   * functions, and as long as `this` and owner are the same, there will be no
   * change in behavior.
   * @param {*} source An annotation object (added by a transpiler or otherwise)
   * indicating filename, line number, and/or other information.
   * @internal
   */


  var ReactElement = function (type, key, ref, self, source, owner, props) {
    var element = {
      // This tag allows us to uniquely identify this as a React Element
      $$typeof: REACT_ELEMENT_TYPE,
      // Built-in properties that belong on the element
      type: type,
      key: key,
      ref: ref,
      props: props,
      // Record the component responsible for creating this element.
      _owner: owner
    };

    {
      // The validation flag is currently mutative. We put it on
      // an external backing store so that we can freeze the whole object.
      // This can be replaced with a WeakMap once they are implemented in
      // commonly used development environments.
      element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
      // the validation flag non-enumerable (where possible, which should
      // include every environment we run tests in), so the test framework
      // ignores it.

      Object.defineProperty(element._store, 'validated', {
        configurable: false,
        enumerable: false,
        writable: true,
        value: false
      }); // self and source are DEV only properties.

      Object.defineProperty(element, '_self', {
        configurable: false,
        enumerable: false,
        writable: false,
        value: self
      }); // Two elements created in two different places should be considered
      // equal for testing purposes and therefore we hide it from enumeration.

      Object.defineProperty(element, '_source', {
        configurable: false,
        enumerable: false,
        writable: false,
        value: source
      });

      if (Object.freeze) {
        Object.freeze(element.props);
        Object.freeze(element);
      }
    }

    return element;
  };
  /**
   * Create and return a new ReactElement of the given type.
   * See https://reactjs.org/docs/react-api.html#createelement
   */

  function createElement(type, config, children) {
    var propName; // Reserved names are extracted

    var props = {};
    var key = null;
    var ref = null;
    var self = null;
    var source = null;

    if (config != null) {
      if (hasValidRef(config)) {
        ref = config.ref;

        {
          warnIfStringRefCannotBeAutoConverted(config);
        }
      }

      if (hasValidKey(config)) {
        {
          checkKeyStringCoercion(config.key);
        }

        key = '' + config.key;
      }

      self = config.__self === undefined ? null : config.__self;
      source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object

      for (propName in config) {
        if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
          props[propName] = config[propName];
        }
      }
    } // Children can be more than one argument, and those are transferred onto
    // the newly allocated props object.


    var childrenLength = arguments.length - 2;

    if (childrenLength === 1) {
      props.children = children;
    } else if (childrenLength > 1) {
      var childArray = Array(childrenLength);

      for (var i = 0; i < childrenLength; i++) {
        childArray[i] = arguments[i + 2];
      }

      {
        if (Object.freeze) {
          Object.freeze(childArray);
        }
      }

      props.children = childArray;
    } // Resolve default props


    if (type && type.defaultProps) {
      var defaultProps = type.defaultProps;

      for (propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }
    }

    {
      if (key || ref) {
        var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

        if (key) {
          defineKeyPropWarningGetter(props, displayName);
        }

        if (ref) {
          defineRefPropWarningGetter(props, displayName);
        }
      }
    }

    return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
  }
  function cloneAndReplaceKey(oldElement, newKey) {
    var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
    return newElement;
  }
  /**
   * Clone and return a new ReactElement using element as the starting point.
   * See https://reactjs.org/docs/react-api.html#cloneelement
   */

  function cloneElement(element, config, children) {
    if (element === null || element === undefined) {
      throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
    }

    var propName; // Original props are copied

    var props = assign({}, element.props); // Reserved names are extracted

    var key = element.key;
    var ref = element.ref; // Self is preserved since the owner is preserved.

    var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
    // transpiler, and the original source is probably a better indicator of the
    // true owner.

    var source = element._source; // Owner will be preserved, unless ref is overridden

    var owner = element._owner;

    if (config != null) {
      if (hasValidRef(config)) {
        // Silently steal the ref from the parent.
        ref = config.ref;
        owner = ReactCurrentOwner.current;
      }

      if (hasValidKey(config)) {
        {
          checkKeyStringCoercion(config.key);
        }

        key = '' + config.key;
      } // Remaining properties override existing props


      var defaultProps;

      if (element.type && element.type.defaultProps) {
        defaultProps = element.type.defaultProps;
      }

      for (propName in config) {
        if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
          if (config[propName] === undefined && defaultProps !== undefined) {
            // Resolve default props
            props[propName] = defaultProps[propName];
          } else {
            props[propName] = config[propName];
          }
        }
      }
    } // Children can be more than one argument, and those are transferred onto
    // the newly allocated props object.


    var childrenLength = arguments.length - 2;

    if (childrenLength === 1) {
      props.children = children;
    } else if (childrenLength > 1) {
      var childArray = Array(childrenLength);

      for (var i = 0; i < childrenLength; i++) {
        childArray[i] = arguments[i + 2];
      }

      props.children = childArray;
    }

    return ReactElement(element.type, key, ref, self, source, owner, props);
  }
  /**
   * Verifies the object is a ReactElement.
   * See https://reactjs.org/docs/react-api.html#isvalidelement
   * @param {?object} object
   * @return {boolean} True if `object` is a ReactElement.
   * @final
   */

  function isValidElement(object) {
    return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
  }

  var SEPARATOR = '.';
  var SUBSEPARATOR = ':';
  /**
   * Escape and wrap key so it is safe to use as a reactid
   *
   * @param {string} key to be escaped.
   * @return {string} the escaped key.
   */

  function escape(key) {
    var escapeRegex = /[=:]/g;
    var escaperLookup = {
      '=': '=0',
      ':': '=2'
    };
    var escapedString = key.replace(escapeRegex, function (match) {
      return escaperLookup[match];
    });
    return '$' + escapedString;
  }
  /**
   * TODO: Test that a single child and an array with one item have the same key
   * pattern.
   */


  var didWarnAboutMaps = false;
  var userProvidedKeyEscapeRegex = /\/+/g;

  function escapeUserProvidedKey(text) {
    return text.replace(userProvidedKeyEscapeRegex, '$&/');
  }
  /**
   * Generate a key string that identifies a element within a set.
   *
   * @param {*} element A element that could contain a manual key.
   * @param {number} index Index that is used if a manual key is not provided.
   * @return {string}
   */


  function getElementKey(element, index) {
    // Do some typechecking here since we call this blindly. We want to ensure
    // that we don't block potential future ES APIs.
    if (typeof element === 'object' && element !== null && element.key != null) {
      // Explicit key
      {
        checkKeyStringCoercion(element.key);
      }

      return escape('' + element.key);
    } // Implicit key determined by the index in the set


    return index.toString(36);
  }

  function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
    var type = typeof children;

    if (type === 'undefined' || type === 'boolean') {
      // All of the above are perceived as null.
      children = null;
    }

    var invokeCallback = false;

    if (children === null) {
      invokeCallback = true;
    } else {
      switch (type) {
        case 'string':
        case 'number':
          invokeCallback = true;
          break;

        case 'object':
          switch (children.$$typeof) {
            case REACT_ELEMENT_TYPE:
            case REACT_PORTAL_TYPE:
              invokeCallback = true;
          }

      }
    }

    if (invokeCallback) {
      var _child = children;
      var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
      // so that it's consistent if the number of children grows:

      var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;

      if (isArray(mappedChild)) {
        var escapedChildKey = '';

        if (childKey != null) {
          escapedChildKey = escapeUserProvidedKey(childKey) + '/';
        }

        mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
          return c;
        });
      } else if (mappedChild != null) {
        if (isValidElement(mappedChild)) {
          {
            // The `if` statement here prevents auto-disabling of the safe
            // coercion ESLint rule, so we must manually disable it below.
            // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
            if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
              checkKeyStringCoercion(mappedChild.key);
            }
          }

          mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
          // traverseAllChildren used to do for objects as children
          escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
          mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
          // eslint-disable-next-line react-internal/safe-string-coercion
          escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
        }

        array.push(mappedChild);
      }

      return 1;
    }

    var child;
    var nextName;
    var subtreeCount = 0; // Count of children found in the current subtree.

    var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;

    if (isArray(children)) {
      for (var i = 0; i < children.length; i++) {
        child = children[i];
        nextName = nextNamePrefix + getElementKey(child, i);
        subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
      }
    } else {
      var iteratorFn = getIteratorFn(children);

      if (typeof iteratorFn === 'function') {
        var iterableChildren = children;

        {
          // Warn about using Maps as children
          if (iteratorFn === iterableChildren.entries) {
            if (!didWarnAboutMaps) {
              warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
            }

            didWarnAboutMaps = true;
          }
        }

        var iterator = iteratorFn.call(iterableChildren);
        var step;
        var ii = 0;

        while (!(step = iterator.next()).done) {
          child = step.value;
          nextName = nextNamePrefix + getElementKey(child, ii++);
          subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
        }
      } else if (type === 'object') {
        // eslint-disable-next-line react-internal/safe-string-coercion
        var childrenString = String(children);
        throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
      }
    }

    return subtreeCount;
  }

  /**
   * Maps children that are typically specified as `props.children`.
   *
   * See https://reactjs.org/docs/react-api.html#reactchildrenmap
   *
   * The provided mapFunction(child, index) will be called for each
   * leaf child.
   *
   * @param {?*} children Children tree container.
   * @param {function(*, int)} func The map function.
   * @param {*} context Context for mapFunction.
   * @return {object} Object containing the ordered map of results.
   */
  function mapChildren(children, func, context) {
    if (children == null) {
      return children;
    }

    var result = [];
    var count = 0;
    mapIntoArray(children, result, '', '', function (child) {
      return func.call(context, child, count++);
    });
    return result;
  }
  /**
   * Count the number of children that are typically specified as
   * `props.children`.
   *
   * See https://reactjs.org/docs/react-api.html#reactchildrencount
   *
   * @param {?*} children Children tree container.
   * @return {number} The number of children.
   */


  function countChildren(children) {
    var n = 0;
    mapChildren(children, function () {
      n++; // Don't return anything
    });
    return n;
  }

  /**
   * Iterates through children that are typically specified as `props.children`.
   *
   * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
   *
   * The provided forEachFunc(child, index) will be called for each
   * leaf child.
   *
   * @param {?*} children Children tree container.
   * @param {function(*, int)} forEachFunc
   * @param {*} forEachContext Context for forEachContext.
   */
  function forEachChildren(children, forEachFunc, forEachContext) {
    mapChildren(children, function () {
      forEachFunc.apply(this, arguments); // Don't return anything.
    }, forEachContext);
  }
  /**
   * Flatten a children object (typically specified as `props.children`) and
   * return an array with appropriately re-keyed children.
   *
   * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
   */


  function toArray(children) {
    return mapChildren(children, function (child) {
      return child;
    }) || [];
  }
  /**
   * Returns the first child in a collection of children and verifies that there
   * is only one child in the collection.
   *
   * See https://reactjs.org/docs/react-api.html#reactchildrenonly
   *
   * The current implementation of this function assumes that a single child gets
   * passed without a wrapper, but the purpose of this helper function is to
   * abstract away the particular structure of children.
   *
   * @param {?object} children Child collection structure.
   * @return {ReactElement} The first and only `ReactElement` contained in the
   * structure.
   */


  function onlyChild(children) {
    if (!isValidElement(children)) {
      throw new Error('React.Children.only expected to receive a single React element child.');
    }

    return children;
  }

  function createContext(defaultValue) {
    // TODO: Second argument used to be an optional `calculateChangedBits`
    // function. Warn to reserve for future use?
    var context = {
      $$typeof: REACT_CONTEXT_TYPE,
      // As a workaround to support multiple concurrent renderers, we categorize
      // some renderers as primary and others as secondary. We only expect
      // there to be two concurrent renderers at most: React Native (primary) and
      // Fabric (secondary); React DOM (primary) and React ART (secondary).
      // Secondary renderers store their context values on separate fields.
      _currentValue: defaultValue,
      _currentValue2: defaultValue,
      // Used to track how many concurrent renderers this context currently
      // supports within in a single renderer. Such as parallel server rendering.
      _threadCount: 0,
      // These are circular
      Provider: null,
      Consumer: null,
      // Add these to use same hidden class in VM as ServerContext
      _defaultValue: null,
      _globalName: null
    };
    context.Provider = {
      $$typeof: REACT_PROVIDER_TYPE,
      _context: context
    };
    var hasWarnedAboutUsingNestedContextConsumers = false;
    var hasWarnedAboutUsingConsumerProvider = false;
    var hasWarnedAboutDisplayNameOnConsumer = false;

    {
      // A separate object, but proxies back to the original context object for
      // backwards compatibility. It has a different $$typeof, so we can properly
      // warn for the incorrect usage of Context as a Consumer.
      var Consumer = {
        $$typeof: REACT_CONTEXT_TYPE,
        _context: context
      }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here

      Object.defineProperties(Consumer, {
        Provider: {
          get: function () {
            if (!hasWarnedAboutUsingConsumerProvider) {
              hasWarnedAboutUsingConsumerProvider = true;

              error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
            }

            return context.Provider;
          },
          set: function (_Provider) {
            context.Provider = _Provider;
          }
        },
        _currentValue: {
          get: function () {
            return context._currentValue;
          },
          set: function (_currentValue) {
            context._currentValue = _currentValue;
          }
        },
        _currentValue2: {
          get: function () {
            return context._currentValue2;
          },
          set: function (_currentValue2) {
            context._currentValue2 = _currentValue2;
          }
        },
        _threadCount: {
          get: function () {
            return context._threadCount;
          },
          set: function (_threadCount) {
            context._threadCount = _threadCount;
          }
        },
        Consumer: {
          get: function () {
            if (!hasWarnedAboutUsingNestedContextConsumers) {
              hasWarnedAboutUsingNestedContextConsumers = true;

              error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
            }

            return context.Consumer;
          }
        },
        displayName: {
          get: function () {
            return context.displayName;
          },
          set: function (displayName) {
            if (!hasWarnedAboutDisplayNameOnConsumer) {
              warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);

              hasWarnedAboutDisplayNameOnConsumer = true;
            }
          }
        }
      }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty

      context.Consumer = Consumer;
    }

    {
      context._currentRenderer = null;
      context._currentRenderer2 = null;
    }

    return context;
  }

  var Uninitialized = -1;
  var Pending = 0;
  var Resolved = 1;
  var Rejected = 2;

  function lazyInitializer(payload) {
    if (payload._status === Uninitialized) {
      var ctor = payload._result;
      var thenable = ctor(); // Transition to the next state.
      // This might throw either because it's missing or throws. If so, we treat it
      // as still uninitialized and try again next time. Which is the same as what
      // happens if the ctor or any wrappers processing the ctor throws. This might
      // end up fixing it if the resolution was a concurrency bug.

      thenable.then(function (moduleObject) {
        if (payload._status === Pending || payload._status === Uninitialized) {
          // Transition to the next state.
          var resolved = payload;
          resolved._status = Resolved;
          resolved._result = moduleObject;
        }
      }, function (error) {
        if (payload._status === Pending || payload._status === Uninitialized) {
          // Transition to the next state.
          var rejected = payload;
          rejected._status = Rejected;
          rejected._result = error;
        }
      });

      if (payload._status === Uninitialized) {
        // In case, we're still uninitialized, then we're waiting for the thenable
        // to resolve. Set it as pending in the meantime.
        var pending = payload;
        pending._status = Pending;
        pending._result = thenable;
      }
    }

    if (payload._status === Resolved) {
      var moduleObject = payload._result;

      {
        if (moduleObject === undefined) {
          error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + // Break up imports to avoid accidentally parsing them as dependencies.
          'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
        }
      }

      {
        if (!('default' in moduleObject)) {
          error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + // Break up imports to avoid accidentally parsing them as dependencies.
          'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
        }
      }

      return moduleObject.default;
    } else {
      throw payload._result;
    }
  }

  function lazy(ctor) {
    var payload = {
      // We use these fields to store the result.
      _status: Uninitialized,
      _result: ctor
    };
    var lazyType = {
      $$typeof: REACT_LAZY_TYPE,
      _payload: payload,
      _init: lazyInitializer
    };

    {
      // In production, this would just set it on the object.
      var defaultProps;
      var propTypes; // $FlowFixMe

      Object.defineProperties(lazyType, {
        defaultProps: {
          configurable: true,
          get: function () {
            return defaultProps;
          },
          set: function (newDefaultProps) {
            error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');

            defaultProps = newDefaultProps; // Match production behavior more closely:
            // $FlowFixMe

            Object.defineProperty(lazyType, 'defaultProps', {
              enumerable: true
            });
          }
        },
        propTypes: {
          configurable: true,
          get: function () {
            return propTypes;
          },
          set: function (newPropTypes) {
            error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');

            propTypes = newPropTypes; // Match production behavior more closely:
            // $FlowFixMe

            Object.defineProperty(lazyType, 'propTypes', {
              enumerable: true
            });
          }
        }
      });
    }

    return lazyType;
  }

  function forwardRef(render) {
    {
      if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
        error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
      } else if (typeof render !== 'function') {
        error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
      } else {
        if (render.length !== 0 && render.length !== 2) {
          error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
        }
      }

      if (render != null) {
        if (render.defaultProps != null || render.propTypes != null) {
          error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
        }
      }
    }

    var elementType = {
      $$typeof: REACT_FORWARD_REF_TYPE,
      render: render
    };

    {
      var ownName;
      Object.defineProperty(elementType, 'displayName', {
        enumerable: false,
        configurable: true,
        get: function () {
          return ownName;
        },
        set: function (name) {
          ownName = name; // The inner component shouldn't inherit this display name in most cases,
          // because the component may be used elsewhere.
          // But it's nice for anonymous functions to inherit the name,
          // so that our component-stack generation logic will display their frames.
          // An anonymous function generally suggests a pattern like:
          //   React.forwardRef((props, ref) => {...});
          // This kind of inner function is not used elsewhere so the side effect is okay.

          if (!render.name && !render.displayName) {
            render.displayName = name;
          }
        }
      });
    }

    return elementType;
  }

  var REACT_MODULE_REFERENCE;

  {
    REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
  }

  function isValidElementType(type) {
    if (typeof type === 'string' || typeof type === 'function') {
      return true;
    } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).


    if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing  || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden  || type === REACT_OFFSCREEN_TYPE || enableScopeAPI  || enableCacheElement  || enableTransitionTracing ) {
      return true;
    }

    if (typeof type === 'object' && type !== null) {
      if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
      // types supported by any Flight configuration anywhere since
      // we don't know which Flight build this will end up being used
      // with.
      type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
        return true;
      }
    }

    return false;
  }

  function memo(type, compare) {
    {
      if (!isValidElementType(type)) {
        error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
      }
    }

    var elementType = {
      $$typeof: REACT_MEMO_TYPE,
      type: type,
      compare: compare === undefined ? null : compare
    };

    {
      var ownName;
      Object.defineProperty(elementType, 'displayName', {
        enumerable: false,
        configurable: true,
        get: function () {
          return ownName;
        },
        set: function (name) {
          ownName = name; // The inner component shouldn't inherit this display name in most cases,
          // because the component may be used elsewhere.
          // But it's nice for anonymous functions to inherit the name,
          // so that our component-stack generation logic will display their frames.
          // An anonymous function generally suggests a pattern like:
          //   React.memo((props) => {...});
          // This kind of inner function is not used elsewhere so the side effect is okay.

          if (!type.name && !type.displayName) {
            type.displayName = name;
          }
        }
      });
    }

    return elementType;
  }

  function resolveDispatcher() {
    var dispatcher = ReactCurrentDispatcher.current;

    {
      if (dispatcher === null) {
        error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
      }
    } // Will result in a null access error if accessed outside render phase. We
    // intentionally don't throw our own error because this is in a hot path.
    // Also helps ensure this is inlined.


    return dispatcher;
  }
  function useContext(Context) {
    var dispatcher = resolveDispatcher();

    {
      // TODO: add a more generic warning for invalid values.
      if (Context._context !== undefined) {
        var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
        // and nobody should be using this in existing code.

        if (realContext.Consumer === Context) {
          error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
        } else if (realContext.Provider === Context) {
          error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
        }
      }
    }

    return dispatcher.useContext(Context);
  }
  function useState(initialState) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useState(initialState);
  }
  function useReducer(reducer, initialArg, init) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useReducer(reducer, initialArg, init);
  }
  function useRef(initialValue) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useRef(initialValue);
  }
  function useEffect(create, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useEffect(create, deps);
  }
  function useInsertionEffect(create, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useInsertionEffect(create, deps);
  }
  function useLayoutEffect(create, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useLayoutEffect(create, deps);
  }
  function useCallback(callback, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useCallback(callback, deps);
  }
  function useMemo(create, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useMemo(create, deps);
  }
  function useImperativeHandle(ref, create, deps) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useImperativeHandle(ref, create, deps);
  }
  function useDebugValue(value, formatterFn) {
    {
      var dispatcher = resolveDispatcher();
      return dispatcher.useDebugValue(value, formatterFn);
    }
  }
  function useTransition() {
    var dispatcher = resolveDispatcher();
    return dispatcher.useTransition();
  }
  function useDeferredValue(value) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useDeferredValue(value);
  }
  function useId() {
    var dispatcher = resolveDispatcher();
    return dispatcher.useId();
  }
  function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    var dispatcher = resolveDispatcher();
    return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
  }

  // Helpers to patch console.logs to avoid logging during side-effect free
  // replaying on render function. This currently only patches the object
  // lazily which won't cover if the log function was extracted eagerly.
  // We could also eagerly patch the method.
  var disabledDepth = 0;
  var prevLog;
  var prevInfo;
  var prevWarn;
  var prevError;
  var prevGroup;
  var prevGroupCollapsed;
  var prevGroupEnd;

  function disabledLog() {}

  disabledLog.__reactDisabledLog = true;
  function disableLogs() {
    {
      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      disabledDepth++;
    }
  }
  function reenableLogs() {
    {
      disabledDepth--;

      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        var props = {
          configurable: true,
          enumerable: true,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          log: assign({}, props, {
            value: prevLog
          }),
          info: assign({}, props, {
            value: prevInfo
          }),
          warn: assign({}, props, {
            value: prevWarn
          }),
          error: assign({}, props, {
            value: prevError
          }),
          group: assign({}, props, {
            value: prevGroup
          }),
          groupCollapsed: assign({}, props, {
            value: prevGroupCollapsed
          }),
          groupEnd: assign({}, props, {
            value: prevGroupEnd
          })
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      if (disabledDepth < 0) {
        error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
      }
    }
  }

  var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
  var prefix;
  function describeBuiltInComponentFrame(name, source, ownerFn) {
    {
      if (prefix === undefined) {
        // Extract the VM specific prefix used by each line.
        try {
          throw Error();
        } catch (x) {
          var match = x.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || '';
        }
      } // We use the prefix to ensure our stacks line up with native stack frames.


      return '\n' + prefix + name;
    }
  }
  var reentry = false;
  var componentFrameCache;

  {
    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
    componentFrameCache = new PossiblyWeakMap();
  }

  function describeNativeComponentFrame(fn, construct) {
    // If something asked for a stack inside a fake render, it should get ignored.
    if ( !fn || reentry) {
      return '';
    }

    {
      var frame = componentFrameCache.get(fn);

      if (frame !== undefined) {
        return frame;
      }
    }

    var control;
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

    Error.prepareStackTrace = undefined;
    var previousDispatcher;

    {
      previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
      // for warnings.

      ReactCurrentDispatcher$1.current = null;
      disableLogs();
    }

    try {
      // This should throw.
      if (construct) {
        // Something should be setting the props in the constructor.
        var Fake = function () {
          throw Error();
        }; // $FlowFixMe


        Object.defineProperty(Fake.prototype, 'props', {
          set: function () {
            // We use a throwing setter instead of frozen or non-writable props
            // because that won't throw in a non-strict mode function.
            throw Error();
          }
        });

        if (typeof Reflect === 'object' && Reflect.construct) {
          // We construct a different control for this case to include any extra
          // frames added by the construct call.
          try {
            Reflect.construct(Fake, []);
          } catch (x) {
            control = x;
          }

          Reflect.construct(fn, [], Fake);
        } else {
          try {
            Fake.call();
          } catch (x) {
            control = x;
          }

          fn.call(Fake.prototype);
        }
      } else {
        try {
          throw Error();
        } catch (x) {
          control = x;
        }

        fn();
      }
    } catch (sample) {
      // This is inlined manually because closure doesn't do it for us.
      if (sample && control && typeof sample.stack === 'string') {
        // This extracts the first frame from the sample that isn't also in the control.
        // Skipping one frame that we assume is the frame that calls the two.
        var sampleLines = sample.stack.split('\n');
        var controlLines = control.stack.split('\n');
        var s = sampleLines.length - 1;
        var c = controlLines.length - 1;

        while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
          // We expect at least one stack frame to be shared.
          // Typically this will be the root most one. However, stack frames may be
          // cut off due to maximum stack limits. In this case, one maybe cut off
          // earlier than the other. We assume that the sample is longer or the same
          // and there for cut off earlier. So we should find the root most frame in
          // the sample somewhere in the control.
          c--;
        }

        for (; s >= 1 && c >= 0; s--, c--) {
          // Next we find the first one that isn't the same which should be the
          // frame that called our sample function and the control.
          if (sampleLines[s] !== controlLines[c]) {
            // In V8, the first line is describing the message but other VMs don't.
            // If we're about to return the first line, and the control is also on the same
            // line, that's a pretty good indicator that our sample threw at same line as
            // the control. I.e. before we entered the sample frame. So we ignore this result.
            // This can happen if you passed a class to function component, or non-function.
            if (s !== 1 || c !== 1) {
              do {
                s--;
                c--; // We may still have similar intermediate frames from the construct call.
                // The next one that isn't the same should be our match though.

                if (c < 0 || sampleLines[s] !== controlLines[c]) {
                  // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                  var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                  // but we have a user-provided "displayName"
                  // splice it in to make the stack more readable.


                  if (fn.displayName && _frame.includes('<anonymous>')) {
                    _frame = _frame.replace('<anonymous>', fn.displayName);
                  }

                  {
                    if (typeof fn === 'function') {
                      componentFrameCache.set(fn, _frame);
                    }
                  } // Return the line we found.


                  return _frame;
                }
              } while (s >= 1 && c >= 0);
            }

            break;
          }
        }
      }
    } finally {
      reentry = false;

      {
        ReactCurrentDispatcher$1.current = previousDispatcher;
        reenableLogs();
      }

      Error.prepareStackTrace = previousPrepareStackTrace;
    } // Fallback to just using the name if we couldn't make it throw.


    var name = fn ? fn.displayName || fn.name : '';
    var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

    {
      if (typeof fn === 'function') {
        componentFrameCache.set(fn, syntheticFrame);
      }
    }

    return syntheticFrame;
  }
  function describeFunctionComponentFrame(fn, source, ownerFn) {
    {
      return describeNativeComponentFrame(fn, false);
    }
  }

  function shouldConstruct(Component) {
    var prototype = Component.prototype;
    return !!(prototype && prototype.isReactComponent);
  }

  function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

    if (type == null) {
      return '';
    }

    if (typeof type === 'function') {
      {
        return describeNativeComponentFrame(type, shouldConstruct(type));
      }
    }

    if (typeof type === 'string') {
      return describeBuiltInComponentFrame(type);
    }

    switch (type) {
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame('Suspense');

      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame('SuspenseList');
    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeFunctionComponentFrame(type.render);

        case REACT_MEMO_TYPE:
          // Memo may contain any component type so we recursively resolve it.
          return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              // Lazy may contain any component type so we recursively resolve it.
              return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
            } catch (x) {}
          }
      }
    }

    return '';
  }

  var loggedTypeFailures = {};
  var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

  function setCurrentlyValidatingElement(element) {
    {
      if (element) {
        var owner = element._owner;
        var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
        ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
      } else {
        ReactDebugCurrentFrame$1.setExtraStackFrame(null);
      }
    }
  }

  function checkPropTypes(typeSpecs, values, location, componentName, element) {
    {
      // $FlowFixMe This is okay but Flow doesn't know it.
      var has = Function.call.bind(hasOwnProperty);

      for (var typeSpecName in typeSpecs) {
        if (has(typeSpecs, typeSpecName)) {
          var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
          // fail the render phase where it didn't fail before. So we log it.
          // After these have been cleaned up, we'll let them throw.

          try {
            // This is intentionally an invariant that gets caught. It's the same
            // behavior as without this statement except with a better message.
            if (typeof typeSpecs[typeSpecName] !== 'function') {
              // eslint-disable-next-line react-internal/prod-error-codes
              var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
              err.name = 'Invariant Violation';
              throw err;
            }

            error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
          } catch (ex) {
            error$1 = ex;
          }

          if (error$1 && !(error$1 instanceof Error)) {
            setCurrentlyValidatingElement(element);

            error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

            setCurrentlyValidatingElement(null);
          }

          if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
            // Only monitor this failure once because there tends to be a lot of the
            // same error.
            loggedTypeFailures[error$1.message] = true;
            setCurrentlyValidatingElement(element);

            error('Failed %s type: %s', location, error$1.message);

            setCurrentlyValidatingElement(null);
          }
        }
      }
    }
  }

  function setCurrentlyValidatingElement$1(element) {
    {
      if (element) {
        var owner = element._owner;
        var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
        setExtraStackFrame(stack);
      } else {
        setExtraStackFrame(null);
      }
    }
  }

  var propTypesMisspellWarningShown;

  {
    propTypesMisspellWarningShown = false;
  }

  function getDeclarationErrorAddendum() {
    if (ReactCurrentOwner.current) {
      var name = getComponentNameFromType(ReactCurrentOwner.current.type);

      if (name) {
        return '\n\nCheck the render method of `' + name + '`.';
      }
    }

    return '';
  }

  function getSourceInfoErrorAddendum(source) {
    if (source !== undefined) {
      var fileName = source.fileName.replace(/^.*[\\\/]/, '');
      var lineNumber = source.lineNumber;
      return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
    }

    return '';
  }

  function getSourceInfoErrorAddendumForProps(elementProps) {
    if (elementProps !== null && elementProps !== undefined) {
      return getSourceInfoErrorAddendum(elementProps.__source);
    }

    return '';
  }
  /**
   * Warn if there's no key explicitly set on dynamic arrays of children or
   * object keys are not valid. This allows us to keep track of children between
   * updates.
   */


  var ownerHasKeyUseWarning = {};

  function getCurrentComponentErrorInfo(parentType) {
    var info = getDeclarationErrorAddendum();

    if (!info) {
      var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;

      if (parentName) {
        info = "\n\nCheck the top-level render call using <" + parentName + ">.";
      }
    }

    return info;
  }
  /**
   * Warn if the element doesn't have an explicit key assigned to it.
   * This element is in an array. The array could grow and shrink or be
   * reordered. All children that haven't already been validated are required to
   * have a "key" property assigned to it. Error statuses are cached so a warning
   * will only be shown once.
   *
   * @internal
   * @param {ReactElement} element Element that requires a key.
   * @param {*} parentType element's parent's type.
   */


  function validateExplicitKey(element, parentType) {
    if (!element._store || element._store.validated || element.key != null) {
      return;
    }

    element._store.validated = true;
    var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);

    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
      return;
    }

    ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
    // property, it may be the creator of the child that's responsible for
    // assigning it a key.

    var childOwner = '';

    if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
      // Give the component that originally created this child.
      childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
    }

    {
      setCurrentlyValidatingElement$1(element);

      error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);

      setCurrentlyValidatingElement$1(null);
    }
  }
  /**
   * Ensure that every element either is passed in a static location, in an
   * array with an explicit keys property defined, or in an object literal
   * with valid key property.
   *
   * @internal
   * @param {ReactNode} node Statically passed child of any type.
   * @param {*} parentType node's parent's type.
   */


  function validateChildKeys(node, parentType) {
    if (typeof node !== 'object') {
      return;
    }

    if (isArray(node)) {
      for (var i = 0; i < node.length; i++) {
        var child = node[i];

        if (isValidElement(child)) {
          validateExplicitKey(child, parentType);
        }
      }
    } else if (isValidElement(node)) {
      // This element was passed in a valid location.
      if (node._store) {
        node._store.validated = true;
      }
    } else if (node) {
      var iteratorFn = getIteratorFn(node);

      if (typeof iteratorFn === 'function') {
        // Entry iterators used to provide implicit keys,
        // but now we print a separate warning for them later.
        if (iteratorFn !== node.entries) {
          var iterator = iteratorFn.call(node);
          var step;

          while (!(step = iterator.next()).done) {
            if (isValidElement(step.value)) {
              validateExplicitKey(step.value, parentType);
            }
          }
        }
      }
    }
  }
  /**
   * Given an element, validate that its props follow the propTypes definition,
   * provided by the type.
   *
   * @param {ReactElement} element
   */


  function validatePropTypes(element) {
    {
      var type = element.type;

      if (type === null || type === undefined || typeof type === 'string') {
        return;
      }

      var propTypes;

      if (typeof type === 'function') {
        propTypes = type.propTypes;
      } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
      // Inner props are checked in the reconciler.
      type.$$typeof === REACT_MEMO_TYPE)) {
        propTypes = type.propTypes;
      } else {
        return;
      }

      if (propTypes) {
        // Intentionally inside to avoid triggering lazy initializers:
        var name = getComponentNameFromType(type);
        checkPropTypes(propTypes, element.props, 'prop', name, element);
      } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
        propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

        var _name = getComponentNameFromType(type);

        error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
      }

      if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
        error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
      }
    }
  }
  /**
   * Given a fragment, validate that it can only be provided with fragment props
   * @param {ReactElement} fragment
   */


  function validateFragmentProps(fragment) {
    {
      var keys = Object.keys(fragment.props);

      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (key !== 'children' && key !== 'key') {
          setCurrentlyValidatingElement$1(fragment);

          error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);

          setCurrentlyValidatingElement$1(null);
          break;
        }
      }

      if (fragment.ref !== null) {
        setCurrentlyValidatingElement$1(fragment);

        error('Invalid attribute `ref` supplied to `React.Fragment`.');

        setCurrentlyValidatingElement$1(null);
      }
    }
  }
  function createElementWithValidation(type, props, children) {
    var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
    // succeed and there will likely be errors in render.

    if (!validType) {
      var info = '';

      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
        info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
      }

      var sourceInfo = getSourceInfoErrorAddendumForProps(props);

      if (sourceInfo) {
        info += sourceInfo;
      } else {
        info += getDeclarationErrorAddendum();
      }

      var typeString;

      if (type === null) {
        typeString = 'null';
      } else if (isArray(type)) {
        typeString = 'array';
      } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
        typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
        info = ' Did you accidentally export a JSX literal instead of a component?';
      } else {
        typeString = typeof type;
      }

      {
        error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
      }
    }

    var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
    // TODO: Drop this when these are no longer allowed as the type argument.

    if (element == null) {
      return element;
    } // Skip key warning if the type isn't valid since our key validation logic
    // doesn't expect a non-string/function type and can throw confusing errors.
    // We don't want exception behavior to differ between dev and prod.
    // (Rendering will throw with a helpful message and as soon as the type is
    // fixed, the key warnings will appear.)


    if (validType) {
      for (var i = 2; i < arguments.length; i++) {
        validateChildKeys(arguments[i], type);
      }
    }

    if (type === REACT_FRAGMENT_TYPE) {
      validateFragmentProps(element);
    } else {
      validatePropTypes(element);
    }

    return element;
  }
  var didWarnAboutDeprecatedCreateFactory = false;
  function createFactoryWithValidation(type) {
    var validatedFactory = createElementWithValidation.bind(null, type);
    validatedFactory.type = type;

    {
      if (!didWarnAboutDeprecatedCreateFactory) {
        didWarnAboutDeprecatedCreateFactory = true;

        warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
      } // Legacy hook: remove it


      Object.defineProperty(validatedFactory, 'type', {
        enumerable: false,
        get: function () {
          warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');

          Object.defineProperty(this, 'type', {
            value: type
          });
          return type;
        }
      });
    }

    return validatedFactory;
  }
  function cloneElementWithValidation(element, props, children) {
    var newElement = cloneElement.apply(this, arguments);

    for (var i = 2; i < arguments.length; i++) {
      validateChildKeys(arguments[i], newElement.type);
    }

    validatePropTypes(newElement);
    return newElement;
  }

  var enableSchedulerDebugging = false;
  var enableProfiling = false;
  var frameYieldMs = 5;

  function push(heap, node) {
    var index = heap.length;
    heap.push(node);
    siftUp(heap, node, index);
  }
  function peek(heap) {
    return heap.length === 0 ? null : heap[0];
  }
  function pop(heap) {
    if (heap.length === 0) {
      return null;
    }

    var first = heap[0];
    var last = heap.pop();

    if (last !== first) {
      heap[0] = last;
      siftDown(heap, last, 0);
    }

    return first;
  }

  function siftUp(heap, node, i) {
    var index = i;

    while (index > 0) {
      var parentIndex = index - 1 >>> 1;
      var parent = heap[parentIndex];

      if (compare(parent, node) > 0) {
        // The parent is larger. Swap positions.
        heap[parentIndex] = node;
        heap[index] = parent;
        index = parentIndex;
      } else {
        // The parent is smaller. Exit.
        return;
      }
    }
  }

  function siftDown(heap, node, i) {
    var index = i;
    var length = heap.length;
    var halfLength = length >>> 1;

    while (index < halfLength) {
      var leftIndex = (index + 1) * 2 - 1;
      var left = heap[leftIndex];
      var rightIndex = leftIndex + 1;
      var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

      if (compare(left, node) < 0) {
        if (rightIndex < length && compare(right, left) < 0) {
          heap[index] = right;
          heap[rightIndex] = node;
          index = rightIndex;
        } else {
          heap[index] = left;
          heap[leftIndex] = node;
          index = leftIndex;
        }
      } else if (rightIndex < length && compare(right, node) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        // Neither child is smaller. Exit.
        return;
      }
    }
  }

  function compare(a, b) {
    // Compare sort index first, then task id.
    var diff = a.sortIndex - b.sortIndex;
    return diff !== 0 ? diff : a.id - b.id;
  }

  // TODO: Use symbols?
  var ImmediatePriority = 1;
  var UserBlockingPriority = 2;
  var NormalPriority = 3;
  var LowPriority = 4;
  var IdlePriority = 5;

  function markTaskErrored(task, ms) {
  }

  /* eslint-disable no-var */
  var getCurrentTime;
  var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';

  if (hasPerformanceNow) {
    var localPerformance = performance;

    getCurrentTime = function () {
      return localPerformance.now();
    };
  } else {
    var localDate = Date;
    var initialTime = localDate.now();

    getCurrentTime = function () {
      return localDate.now() - initialTime;
    };
  } // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
  // Math.pow(2, 30) - 1
  // 0b111111111111111111111111111111


  var maxSigned31BitInt = 1073741823; // Times out immediately

  var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

  var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
  var NORMAL_PRIORITY_TIMEOUT = 5000;
  var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

  var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

  var taskQueue = [];
  var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

  var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
  var currentTask = null;
  var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.

  var isPerformingWork = false;
  var isHostCallbackScheduled = false;
  var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.

  var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
  var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
  var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom

  var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;

  function advanceTimers(currentTime) {
    // Check for tasks that are no longer delayed and add them to the queue.
    var timer = peek(timerQueue);

    while (timer !== null) {
      if (timer.callback === null) {
        // Timer was cancelled.
        pop(timerQueue);
      } else if (timer.startTime <= currentTime) {
        // Timer fired. Transfer to the task queue.
        pop(timerQueue);
        timer.sortIndex = timer.expirationTime;
        push(taskQueue, timer);
      } else {
        // Remaining timers are pending.
        return;
      }

      timer = peek(timerQueue);
    }
  }

  function handleTimeout(currentTime) {
    isHostTimeoutScheduled = false;
    advanceTimers(currentTime);

    if (!isHostCallbackScheduled) {
      if (peek(taskQueue) !== null) {
        isHostCallbackScheduled = true;
        requestHostCallback(flushWork);
      } else {
        var firstTimer = peek(timerQueue);

        if (firstTimer !== null) {
          requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
      }
    }
  }

  function flushWork(hasTimeRemaining, initialTime) {


    isHostCallbackScheduled = false;

    if (isHostTimeoutScheduled) {
      // We scheduled a timeout but it's no longer needed. Cancel it.
      isHostTimeoutScheduled = false;
      cancelHostTimeout();
    }

    isPerformingWork = true;
    var previousPriorityLevel = currentPriorityLevel;

    try {
      if (enableProfiling) {
        try {
          return workLoop(hasTimeRemaining, initialTime);
        } catch (error) {
          if (currentTask !== null) {
            var currentTime = getCurrentTime();
            markTaskErrored(currentTask, currentTime);
            currentTask.isQueued = false;
          }

          throw error;
        }
      } else {
        // No catch in prod code path.
        return workLoop(hasTimeRemaining, initialTime);
      }
    } finally {
      currentTask = null;
      currentPriorityLevel = previousPriorityLevel;
      isPerformingWork = false;
    }
  }

  function workLoop(hasTimeRemaining, initialTime) {
    var currentTime = initialTime;
    advanceTimers(currentTime);
    currentTask = peek(taskQueue);

    while (currentTask !== null && !(enableSchedulerDebugging )) {
      if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
        // This currentTask hasn't expired, and we've reached the deadline.
        break;
      }

      var callback = currentTask.callback;

      if (typeof callback === 'function') {
        currentTask.callback = null;
        currentPriorityLevel = currentTask.priorityLevel;
        var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;

        var continuationCallback = callback(didUserCallbackTimeout);
        currentTime = getCurrentTime();

        if (typeof continuationCallback === 'function') {
          currentTask.callback = continuationCallback;
        } else {

          if (currentTask === peek(taskQueue)) {
            pop(taskQueue);
          }
        }

        advanceTimers(currentTime);
      } else {
        pop(taskQueue);
      }

      currentTask = peek(taskQueue);
    } // Return whether there's additional work


    if (currentTask !== null) {
      return true;
    } else {
      var firstTimer = peek(timerQueue);

      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }

      return false;
    }
  }

  function unstable_runWithPriority(priorityLevel, eventHandler) {
    switch (priorityLevel) {
      case ImmediatePriority:
      case UserBlockingPriority:
      case NormalPriority:
      case LowPriority:
      case IdlePriority:
        break;

      default:
        priorityLevel = NormalPriority;
    }

    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = priorityLevel;

    try {
      return eventHandler();
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  }

  function unstable_next(eventHandler) {
    var priorityLevel;

    switch (currentPriorityLevel) {
      case ImmediatePriority:
      case UserBlockingPriority:
      case NormalPriority:
        // Shift down to normal priority
        priorityLevel = NormalPriority;
        break;

      default:
        // Anything lower than normal priority should remain at the current level.
        priorityLevel = currentPriorityLevel;
        break;
    }

    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = priorityLevel;

    try {
      return eventHandler();
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  }

  function unstable_wrapCallback(callback) {
    var parentPriorityLevel = currentPriorityLevel;
    return function () {
      // This is a fork of runWithPriority, inlined for performance.
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = parentPriorityLevel;

      try {
        return callback.apply(this, arguments);
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
  }

  function unstable_scheduleCallback(priorityLevel, callback, options) {
    var currentTime = getCurrentTime();
    var startTime;

    if (typeof options === 'object' && options !== null) {
      var delay = options.delay;

      if (typeof delay === 'number' && delay > 0) {
        startTime = currentTime + delay;
      } else {
        startTime = currentTime;
      }
    } else {
      startTime = currentTime;
    }

    var timeout;

    switch (priorityLevel) {
      case ImmediatePriority:
        timeout = IMMEDIATE_PRIORITY_TIMEOUT;
        break;

      case UserBlockingPriority:
        timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
        break;

      case IdlePriority:
        timeout = IDLE_PRIORITY_TIMEOUT;
        break;

      case LowPriority:
        timeout = LOW_PRIORITY_TIMEOUT;
        break;

      case NormalPriority:
      default:
        timeout = NORMAL_PRIORITY_TIMEOUT;
        break;
    }

    var expirationTime = startTime + timeout;
    var newTask = {
      id: taskIdCounter++,
      callback: callback,
      priorityLevel: priorityLevel,
      startTime: startTime,
      expirationTime: expirationTime,
      sortIndex: -1
    };

    if (startTime > currentTime) {
      // This is a delayed task.
      newTask.sortIndex = startTime;
      push(timerQueue, newTask);

      if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
        // All tasks are delayed, and this is the task with the earliest delay.
        if (isHostTimeoutScheduled) {
          // Cancel an existing timeout.
          cancelHostTimeout();
        } else {
          isHostTimeoutScheduled = true;
        } // Schedule a timeout.


        requestHostTimeout(handleTimeout, startTime - currentTime);
      }
    } else {
      newTask.sortIndex = expirationTime;
      push(taskQueue, newTask);
      // wait until the next time we yield.


      if (!isHostCallbackScheduled && !isPerformingWork) {
        isHostCallbackScheduled = true;
        requestHostCallback(flushWork);
      }
    }

    return newTask;
  }

  function unstable_pauseExecution() {
  }

  function unstable_continueExecution() {

    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  function unstable_getFirstCallbackNode() {
    return peek(taskQueue);
  }

  function unstable_cancelCallback(task) {
    // remove from the queue because you can't remove arbitrary nodes from an
    // array based heap, only the first one.)


    task.callback = null;
  }

  function unstable_getCurrentPriorityLevel() {
    return currentPriorityLevel;
  }

  var isMessageLoopRunning = false;
  var scheduledHostCallback = null;
  var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
  // thread, like user events. By default, it yields multiple times per frame.
  // It does not attempt to align with frame boundaries, since most tasks don't
  // need to be frame aligned; for those that do, use requestAnimationFrame.

  var frameInterval = frameYieldMs;
  var startTime = -1;

  function shouldYieldToHost() {
    var timeElapsed = getCurrentTime() - startTime;

    if (timeElapsed < frameInterval) {
      // The main thread has only been blocked for a really short amount of time;
      // smaller than a single frame. Don't yield yet.
      return false;
    } // The main thread has been blocked for a non-negligible amount of time. We


    return true;
  }

  function requestPaint() {

  }

  function forceFrameRate(fps) {
    if (fps < 0 || fps > 125) {
      // Using console['error'] to evade Babel and ESLint
      console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
      return;
    }

    if (fps > 0) {
      frameInterval = Math.floor(1000 / fps);
    } else {
      // reset the framerate
      frameInterval = frameYieldMs;
    }
  }

  var performWorkUntilDeadline = function () {
    if (scheduledHostCallback !== null) {
      var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread
      // has been blocked.

      startTime = currentTime;
      var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
      // error can be observed.
      //
      // Intentionally not using a try-catch, since that makes some debugging
      // techniques harder. Instead, if `scheduledHostCallback` errors, then
      // `hasMoreWork` will remain true, and we'll continue the work loop.

      var hasMoreWork = true;

      try {
        hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
      } finally {
        if (hasMoreWork) {
          // If there's more work, schedule the next message event at the end
          // of the preceding one.
          schedulePerformWorkUntilDeadline();
        } else {
          isMessageLoopRunning = false;
          scheduledHostCallback = null;
        }
      }
    } else {
      isMessageLoopRunning = false;
    } // Yielding to the browser will give it a chance to paint, so we can
  };

  var schedulePerformWorkUntilDeadline;

  if (typeof localSetImmediate === 'function') {
    // Node.js and old IE.
    // There's a few reasons for why we prefer setImmediate.
    //
    // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
    // (Even though this is a DOM fork of the Scheduler, you could get here
    // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
    // https://github.com/facebook/react/issues/20756
    //
    // But also, it runs earlier which is the semantic we want.
    // If other browsers ever implement it, it's better to use it.
    // Although both of these would be inferior to native scheduling.
    schedulePerformWorkUntilDeadline = function () {
      localSetImmediate(performWorkUntilDeadline);
    };
  } else if (typeof MessageChannel !== 'undefined') {
    // DOM and Worker environments.
    // We prefer MessageChannel because of the 4ms setTimeout clamping.
    var channel = new MessageChannel();
    var port = channel.port2;
    channel.port1.onmessage = performWorkUntilDeadline;

    schedulePerformWorkUntilDeadline = function () {
      port.postMessage(null);
    };
  } else {
    // We should only fallback here in non-browser environments.
    schedulePerformWorkUntilDeadline = function () {
      localSetTimeout(performWorkUntilDeadline, 0);
    };
  }

  function requestHostCallback(callback) {
    scheduledHostCallback = callback;

    if (!isMessageLoopRunning) {
      isMessageLoopRunning = true;
      schedulePerformWorkUntilDeadline();
    }
  }

  function requestHostTimeout(callback, ms) {
    taskTimeoutID = localSetTimeout(function () {
      callback(getCurrentTime());
    }, ms);
  }

  function cancelHostTimeout() {
    localClearTimeout(taskTimeoutID);
    taskTimeoutID = -1;
  }

  var unstable_requestPaint = requestPaint;
  var unstable_Profiling =  null;



  var Scheduler = /*#__PURE__*/Object.freeze({
    __proto__: null,
    unstable_ImmediatePriority: ImmediatePriority,
    unstable_UserBlockingPriority: UserBlockingPriority,
    unstable_NormalPriority: NormalPriority,
    unstable_IdlePriority: IdlePriority,
    unstable_LowPriority: LowPriority,
    unstable_runWithPriority: unstable_runWithPriority,
    unstable_next: unstable_next,
    unstable_scheduleCallback: unstable_scheduleCallback,
    unstable_cancelCallback: unstable_cancelCallback,
    unstable_wrapCallback: unstable_wrapCallback,
    unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
    unstable_shouldYield: shouldYieldToHost,
    unstable_requestPaint: unstable_requestPaint,
    unstable_continueExecution: unstable_continueExecution,
    unstable_pauseExecution: unstable_pauseExecution,
    unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
    get unstable_now () { return getCurrentTime; },
    unstable_forceFrameRate: forceFrameRate,
    unstable_Profiling: unstable_Profiling
  });

  var ReactSharedInternals$1 = {
    ReactCurrentDispatcher: ReactCurrentDispatcher,
    ReactCurrentOwner: ReactCurrentOwner,
    ReactCurrentBatchConfig: ReactCurrentBatchConfig,
    // Re-export the schedule API(s) for UMD bundles.
    // This avoids introducing a dependency on a new UMD global in a minor update,
    // Since that would be a breaking change (e.g. for all existing CodeSandboxes).
    // This re-export is only required for UMD bundles;
    // CJS bundles use the shared NPM package.
    Scheduler: Scheduler
  };

  {
    ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue;
    ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
  }

  function startTransition(scope, options) {
    var prevTransition = ReactCurrentBatchConfig.transition;
    ReactCurrentBatchConfig.transition = {};
    var currentTransition = ReactCurrentBatchConfig.transition;

    {
      ReactCurrentBatchConfig.transition._updatedFibers = new Set();
    }

    try {
      scope();
    } finally {
      ReactCurrentBatchConfig.transition = prevTransition;

      {
        if (prevTransition === null && currentTransition._updatedFibers) {
          var updatedFibersCount = currentTransition._updatedFibers.size;

          if (updatedFibersCount > 10) {
            warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
          }

          currentTransition._updatedFibers.clear();
        }
      }
    }
  }

  var didWarnAboutMessageChannel = false;
  var enqueueTaskImpl = null;
  function enqueueTask(task) {
    if (enqueueTaskImpl === null) {
      try {
        // read require off the module object to get around the bundlers.
        // we don't want them to detect a require and bundle a Node polyfill.
        var requireString = ('require' + Math.random()).slice(0, 7);
        var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
        // version of setImmediate, bypassing fake timers if any.

        enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
      } catch (_err) {
        // we're in a browser
        // we can't use regular timers because they may still be faked
        // so we try MessageChannel+postMessage instead
        enqueueTaskImpl = function (callback) {
          {
            if (didWarnAboutMessageChannel === false) {
              didWarnAboutMessageChannel = true;

              if (typeof MessageChannel === 'undefined') {
                error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
              }
            }
          }

          var channel = new MessageChannel();
          channel.port1.onmessage = callback;
          channel.port2.postMessage(undefined);
        };
      }
    }

    return enqueueTaskImpl(task);
  }

  var actScopeDepth = 0;
  var didWarnNoAwaitAct = false;
  function act(callback) {
    {
      // `act` calls can be nested, so we track the depth. This represents the
      // number of `act` scopes on the stack.
      var prevActScopeDepth = actScopeDepth;
      actScopeDepth++;

      if (ReactCurrentActQueue.current === null) {
        // This is the outermost `act` scope. Initialize the queue. The reconciler
        // will detect the queue and use it instead of Scheduler.
        ReactCurrentActQueue.current = [];
      }

      var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
      var result;

      try {
        // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
        // set to `true` while the given callback is executed, not for updates
        // triggered during an async event, because this is how the legacy
        // implementation of `act` behaved.
        ReactCurrentActQueue.isBatchingLegacy = true;
        result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
        // which flushed updates immediately after the scope function exits, even
        // if it's an async function.

        if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
          var queue = ReactCurrentActQueue.current;

          if (queue !== null) {
            ReactCurrentActQueue.didScheduleLegacyUpdate = false;
            flushActQueue(queue);
          }
        }
      } catch (error) {
        popActScope(prevActScopeDepth);
        throw error;
      } finally {
        ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
      }

      if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
        var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
        // for it to resolve before exiting the current scope.

        var wasAwaited = false;
        var thenable = {
          then: function (resolve, reject) {
            wasAwaited = true;
            thenableResult.then(function (returnValue) {
              popActScope(prevActScopeDepth);

              if (actScopeDepth === 0) {
                // We've exited the outermost act scope. Recursively flush the
                // queue until there's no remaining work.
                recursivelyFlushAsyncActWork(returnValue, resolve, reject);
              } else {
                resolve(returnValue);
              }
            }, function (error) {
              // The callback threw an error.
              popActScope(prevActScopeDepth);
              reject(error);
            });
          }
        };

        {
          if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
            // eslint-disable-next-line no-undef
            Promise.resolve().then(function () {}).then(function () {
              if (!wasAwaited) {
                didWarnNoAwaitAct = true;

                error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
              }
            });
          }
        }

        return thenable;
      } else {
        var returnValue = result; // The callback is not an async function. Exit the current scope
        // immediately, without awaiting.

        popActScope(prevActScopeDepth);

        if (actScopeDepth === 0) {
          // Exiting the outermost act scope. Flush the queue.
          var _queue = ReactCurrentActQueue.current;

          if (_queue !== null) {
            flushActQueue(_queue);
            ReactCurrentActQueue.current = null;
          } // Return a thenable. If the user awaits it, we'll flush again in
          // case additional work was scheduled by a microtask.


          var _thenable = {
            then: function (resolve, reject) {
              // Confirm we haven't re-entered another `act` scope, in case
              // the user does something weird like await the thenable
              // multiple times.
              if (ReactCurrentActQueue.current === null) {
                // Recursively flush the queue until there's no remaining work.
                ReactCurrentActQueue.current = [];
                recursivelyFlushAsyncActWork(returnValue, resolve, reject);
              } else {
                resolve(returnValue);
              }
            }
          };
          return _thenable;
        } else {
          // Since we're inside a nested `act` scope, the returned thenable
          // immediately resolves. The outer scope will flush the queue.
          var _thenable2 = {
            then: function (resolve, reject) {
              resolve(returnValue);
            }
          };
          return _thenable2;
        }
      }
    }
  }

  function popActScope(prevActScopeDepth) {
    {
      if (prevActScopeDepth !== actScopeDepth - 1) {
        error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
      }

      actScopeDepth = prevActScopeDepth;
    }
  }

  function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
    {
      var queue = ReactCurrentActQueue.current;

      if (queue !== null) {
        try {
          flushActQueue(queue);
          enqueueTask(function () {
            if (queue.length === 0) {
              // No additional work was scheduled. Finish.
              ReactCurrentActQueue.current = null;
              resolve(returnValue);
            } else {
              // Keep flushing work until there's none left.
              recursivelyFlushAsyncActWork(returnValue, resolve, reject);
            }
          });
        } catch (error) {
          reject(error);
        }
      } else {
        resolve(returnValue);
      }
    }
  }

  var isFlushing = false;

  function flushActQueue(queue) {
    {
      if (!isFlushing) {
        // Prevent re-entrance.
        isFlushing = true;
        var i = 0;

        try {
          for (; i < queue.length; i++) {
            var callback = queue[i];

            do {
              callback = callback(true);
            } while (callback !== null);
          }

          queue.length = 0;
        } catch (error) {
          // If something throws, leave the remaining callbacks on the queue.
          queue = queue.slice(i + 1);
          throw error;
        } finally {
          isFlushing = false;
        }
      }
    }
  }

  var createElement$1 =  createElementWithValidation ;
  var cloneElement$1 =  cloneElementWithValidation ;
  var createFactory =  createFactoryWithValidation ;
  var Children = {
    map: mapChildren,
    forEach: forEachChildren,
    count: countChildren,
    toArray: toArray,
    only: onlyChild
  };

  exports.Children = Children;
  exports.Component = Component;
  exports.Fragment = REACT_FRAGMENT_TYPE;
  exports.Profiler = REACT_PROFILER_TYPE;
  exports.PureComponent = PureComponent;
  exports.StrictMode = REACT_STRICT_MODE_TYPE;
  exports.Suspense = REACT_SUSPENSE_TYPE;
  exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
  exports.act = act;
  exports.cloneElement = cloneElement$1;
  exports.createContext = createContext;
  exports.createElement = createElement$1;
  exports.createFactory = createFactory;
  exports.createRef = createRef;
  exports.forwardRef = forwardRef;
  exports.isValidElement = isValidElement;
  exports.lazy = lazy;
  exports.memo = memo;
  exports.startTransition = startTransition;
  exports.unstable_act = act;
  exports.useCallback = useCallback;
  exports.useContext = useContext;
  exports.useDebugValue = useDebugValue;
  exports.useDeferredValue = useDeferredValue;
  exports.useEffect = useEffect;
  exports.useId = useId;
  exports.useImperativeHandle = useImperativeHandle;
  exports.useInsertionEffect = useInsertionEffect;
  exports.useLayoutEffect = useLayoutEffect;
  exports.useMemo = useMemo;
  exports.useReducer = useReducer;
  exports.useRef = useRef;
  exports.useState = useState;
  exports.useSyncExternalStore = useSyncExternalStore;
  exports.useTransition = useTransition;
  exports.version = ReactVersion;

})));
/**
 * @license React
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(c,x){"object"===typeof exports&&"undefined"!==typeof module?x(exports):"function"===typeof define&&define.amd?define(["exports"],x):(c=c||self,x(c.React={}))})(this,function(c){function x(a){if(null===a||"object"!==typeof a)return null;a=V&&a[V]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Y(){}function K(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Z(a,b,
e){var m,d={},c=null,h=null;if(null!=b)for(m in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(c=""+b.key),b)aa.call(b,m)&&!ba.hasOwnProperty(m)&&(d[m]=b[m]);var l=arguments.length-2;if(1===l)d.children=e;else if(1<l){for(var f=Array(l),k=0;k<l;k++)f[k]=arguments[k+2];d.children=f}if(a&&a.defaultProps)for(m in l=a.defaultProps,l)void 0===d[m]&&(d[m]=l[m]);return{$$typeof:y,type:a,key:c,ref:h,props:d,_owner:L.current}}function oa(a,b){return{$$typeof:y,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}
function M(a){return"object"===typeof a&&null!==a&&a.$$typeof===y}function pa(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}function N(a,b){return"object"===typeof a&&null!==a&&null!=a.key?pa(""+a.key):b.toString(36)}function B(a,b,e,m,d){var c=typeof a;if("undefined"===c||"boolean"===c)a=null;var h=!1;if(null===a)h=!0;else switch(c){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case y:case qa:h=!0}}if(h)return h=a,d=d(h),a=""===m?"."+
N(h,0):m,ca(d)?(e="",null!=a&&(e=a.replace(da,"$&/")+"/"),B(d,b,e,"",function(a){return a})):null!=d&&(M(d)&&(d=oa(d,e+(!d.key||h&&h.key===d.key?"":(""+d.key).replace(da,"$&/")+"/")+a)),b.push(d)),1;h=0;m=""===m?".":m+":";if(ca(a))for(var l=0;l<a.length;l++){c=a[l];var f=m+N(c,l);h+=B(c,b,e,f,d)}else if(f=x(a),"function"===typeof f)for(a=f.call(a),l=0;!(c=a.next()).done;)c=c.value,f=m+N(c,l++),h+=B(c,b,e,f,d);else if("object"===c)throw b=String(a),Error("Objects are not valid as a React child (found: "+
("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}function C(a,b,e){if(null==a)return a;var c=[],d=0;B(a,c,"","",function(a){return b.call(e,a,d++)});return c}function ra(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=
0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}function O(a,b){var e=a.length;a.push(b);a:for(;0<e;){var c=e-1>>>1,d=a[c];if(0<D(d,b))a[c]=b,a[e]=d,e=c;else break a}}function p(a){return 0===a.length?null:a[0]}function E(a){if(0===a.length)return null;var b=a[0],e=a.pop();if(e!==b){a[0]=e;a:for(var c=0,d=a.length,k=d>>>1;c<k;){var h=2*(c+1)-1,l=a[h],f=h+1,g=a[f];if(0>D(l,e))f<d&&0>D(g,l)?(a[c]=g,a[f]=e,c=f):(a[c]=l,a[h]=e,c=h);else if(f<d&&0>D(g,e))a[c]=g,a[f]=e,c=f;else break a}}return b}
function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=p(r);null!==b;){if(null===b.callback)E(r);else if(b.startTime<=a)E(r),b.sortIndex=b.expirationTime,O(q,b);else break;b=p(r)}}function Q(a){z=!1;P(a);if(!u)if(null!==p(q))u=!0,R(S);else{var b=p(r);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ea(A),A=-1);F=!0;var c=k;try{P(b);for(n=p(q);null!==n&&(!(n.expirationTime>b)||a&&!fa());){var m=n.callback;if("function"===typeof m){n.callback=null;
k=n.priorityLevel;var d=m(n.expirationTime<=b);b=v();"function"===typeof d?n.callback=d:n===p(q)&&E(q);P(b)}else E(q);n=p(q)}if(null!==n)var g=!0;else{var h=p(r);null!==h&&T(Q,h.startTime-b);g=!1}return g}finally{n=null,k=c,F=!1}}function fa(){return v()-ha<ia?!1:!0}function R(a){G=a;H||(H=!0,I())}function T(a,b){A=ja(function(){a(v())},b)}function ka(a){throw Error("act(...) is not supported in production builds of React.");}var y=Symbol.for("react.element"),qa=Symbol.for("react.portal"),sa=Symbol.for("react.fragment"),
ta=Symbol.for("react.strict_mode"),ua=Symbol.for("react.profiler"),va=Symbol.for("react.provider"),wa=Symbol.for("react.context"),xa=Symbol.for("react.forward_ref"),ya=Symbol.for("react.suspense"),za=Symbol.for("react.memo"),Aa=Symbol.for("react.lazy"),V=Symbol.iterator,X={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a,b,c,m){},enqueueSetState:function(a,b,c,m){}},la=Object.assign,W={};w.prototype.isReactComponent={};w.prototype.setState=function(a,
b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};Y.prototype=w.prototype;var t=K.prototype=new Y;t.constructor=K;la(t,w.prototype);t.isPureReactComponent=!0;var ca=Array.isArray,aa=Object.prototype.hasOwnProperty,L={current:null},
ba={key:!0,ref:!0,__self:!0,__source:!0},da=/\/+/g,g={current:null},J={transition:null};if("object"===typeof performance&&"function"===typeof performance.now){var Ba=performance;var v=function(){return Ba.now()}}else{var ma=Date,Ca=ma.now();v=function(){return ma.now()-Ca}}var q=[],r=[],Da=1,n=null,k=3,F=!1,u=!1,z=!1,ja="function"===typeof setTimeout?setTimeout:null,ea="function"===typeof clearTimeout?clearTimeout:null,na="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&&
void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var H=!1,G=null,A=-1,ia=5,ha=-1,U=function(){if(null!==G){var a=v();ha=a;var b=!0;try{b=G(!0,a)}finally{b?I():(H=!1,G=null)}}else H=!1};if("function"===typeof na)var I=function(){na(U)};else if("undefined"!==typeof MessageChannel){t=new MessageChannel;var Ea=t.port2;t.port1.onmessage=U;I=function(){Ea.postMessage(null)}}else I=function(){ja(U,0)};t={ReactCurrentDispatcher:g,
ReactCurrentOwner:L,ReactCurrentBatchConfig:J,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=k;k=a;try{return b()}finally{k=c}},unstable_next:function(a){switch(k){case 1:case 2:case 3:var b=3;break;default:b=k}var c=k;k=b;try{return a()}finally{k=c}},unstable_scheduleCallback:function(a,
b,c){var e=v();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?e+c:e):c=e;switch(a){case 1:var d=-1;break;case 2:d=250;break;case 5:d=1073741823;break;case 4:d=1E4;break;default:d=5E3}d=c+d;a={id:Da++,callback:b,priorityLevel:a,startTime:c,expirationTime:d,sortIndex:-1};c>e?(a.sortIndex=c,O(r,a),null===p(q)&&a===p(r)&&(z?(ea(A),A=-1):z=!0,T(Q,c-e))):(a.sortIndex=d,O(q,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b=
k;return function(){var c=k;k=b;try{return a.apply(this,arguments)}finally{k=c}}},unstable_getCurrentPriorityLevel:function(){return k},unstable_shouldYield:fa,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return p(q)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):
ia=0<a?Math.floor(1E3/a):5},unstable_Profiling:null}};c.Children={map:C,forEach:function(a,b,c){C(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;C(a,function(){b++});return b},toArray:function(a){return C(a,function(a){return a})||[]},only:function(a){if(!M(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};c.Component=w;c.Fragment=sa;c.Profiler=ua;c.PureComponent=K;c.StrictMode=ta;c.Suspense=ya;c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=
t;c.act=ka;c.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var e=la({},a.props),d=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=L.current);void 0!==b.key&&(d=""+b.key);if(a.type&&a.type.defaultProps)var l=a.type.defaultProps;for(f in b)aa.call(b,f)&&!ba.hasOwnProperty(f)&&(e[f]=void 0===b[f]&&void 0!==l?l[f]:b[f])}var f=arguments.length-2;if(1===f)e.children=c;else if(1<f){l=
Array(f);for(var g=0;g<f;g++)l[g]=arguments[g+2];e.children=l}return{$$typeof:y,type:a.type,key:d,ref:k,props:e,_owner:h}};c.createContext=function(a){a={$$typeof:wa,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:va,_context:a};return a.Consumer=a};c.createElement=Z;c.createFactory=function(a){var b=Z.bind(null,a);b.type=a;return b};c.createRef=function(){return{current:null}};c.forwardRef=function(a){return{$$typeof:xa,
render:a}};c.isValidElement=M;c.lazy=function(a){return{$$typeof:Aa,_payload:{_status:-1,_result:a},_init:ra}};c.memo=function(a,b){return{$$typeof:za,type:a,compare:void 0===b?null:b}};c.startTransition=function(a,b){b=J.transition;J.transition={};try{a()}finally{J.transition=b}};c.unstable_act=ka;c.useCallback=function(a,b){return g.current.useCallback(a,b)};c.useContext=function(a){return g.current.useContext(a)};c.useDebugValue=function(a,b){};c.useDeferredValue=function(a){return g.current.useDeferredValue(a)};
c.useEffect=function(a,b){return g.current.useEffect(a,b)};c.useId=function(){return g.current.useId()};c.useImperativeHandle=function(a,b,c){return g.current.useImperativeHandle(a,b,c)};c.useInsertionEffect=function(a,b){return g.current.useInsertionEffect(a,b)};c.useLayoutEffect=function(a,b){return g.current.useLayoutEffect(a,b)};c.useMemo=function(a,b){return g.current.useMemo(a,b)};c.useReducer=function(a,b,c){return g.current.useReducer(a,b,c)};c.useRef=function(a){return g.current.useRef(a)};
c.useState=function(a){return g.current.useState(a)};c.useSyncExternalStore=function(a,b,c){return g.current.useSyncExternalStore(a,b,c)};c.useTransition=function(){return g.current.useTransition()};c.version="18.3.1"});
})();
/**
 * @license React
 * react.profiling.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(c,x){"object"===typeof exports&&"undefined"!==typeof module?x(exports):"function"===typeof define&&define.amd?define(["exports"],x):(c=c||self,x(c.React={}))})(this,function(c){function x(a){if(null===a||"object"!==typeof a)return null;a=V&&a[V]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Y(){}function K(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Z(a,b,
e){var m,d={},c=null,h=null;if(null!=b)for(m in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(c=""+b.key),b)aa.call(b,m)&&!ba.hasOwnProperty(m)&&(d[m]=b[m]);var l=arguments.length-2;if(1===l)d.children=e;else if(1<l){for(var f=Array(l),k=0;k<l;k++)f[k]=arguments[k+2];d.children=f}if(a&&a.defaultProps)for(m in l=a.defaultProps,l)void 0===d[m]&&(d[m]=l[m]);return{$$typeof:y,type:a,key:c,ref:h,props:d,_owner:L.current}}function oa(a,b){return{$$typeof:y,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}
function M(a){return"object"===typeof a&&null!==a&&a.$$typeof===y}function pa(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}function N(a,b){return"object"===typeof a&&null!==a&&null!=a.key?pa(""+a.key):b.toString(36)}function B(a,b,e,m,d){var c=typeof a;if("undefined"===c||"boolean"===c)a=null;var h=!1;if(null===a)h=!0;else switch(c){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case y:case qa:h=!0}}if(h)return h=a,d=d(h),a=""===m?"."+
N(h,0):m,ca(d)?(e="",null!=a&&(e=a.replace(da,"$&/")+"/"),B(d,b,e,"",function(a){return a})):null!=d&&(M(d)&&(d=oa(d,e+(!d.key||h&&h.key===d.key?"":(""+d.key).replace(da,"$&/")+"/")+a)),b.push(d)),1;h=0;m=""===m?".":m+":";if(ca(a))for(var l=0;l<a.length;l++){c=a[l];var f=m+N(c,l);h+=B(c,b,e,f,d)}else if(f=x(a),"function"===typeof f)for(a=f.call(a),l=0;!(c=a.next()).done;)c=c.value,f=m+N(c,l++),h+=B(c,b,e,f,d);else if("object"===c)throw b=String(a),Error("Objects are not valid as a React child (found: "+
("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}function C(a,b,e){if(null==a)return a;var c=[],d=0;B(a,c,"","",function(a){return b.call(e,a,d++)});return c}function ra(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=
0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}function O(a,b){var e=a.length;a.push(b);a:for(;0<e;){var c=e-1>>>1,d=a[c];if(0<D(d,b))a[c]=b,a[e]=d,e=c;else break a}}function p(a){return 0===a.length?null:a[0]}function E(a){if(0===a.length)return null;var b=a[0],e=a.pop();if(e!==b){a[0]=e;a:for(var c=0,d=a.length,k=d>>>1;c<k;){var h=2*(c+1)-1,l=a[h],f=h+1,g=a[f];if(0>D(l,e))f<d&&0>D(g,l)?(a[c]=g,a[f]=e,c=f):(a[c]=l,a[h]=e,c=h);else if(f<d&&0>D(g,e))a[c]=g,a[f]=e,c=f;else break a}}return b}
function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=p(r);null!==b;){if(null===b.callback)E(r);else if(b.startTime<=a)E(r),b.sortIndex=b.expirationTime,O(q,b);else break;b=p(r)}}function Q(a){z=!1;P(a);if(!u)if(null!==p(q))u=!0,R(S);else{var b=p(r);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ea(A),A=-1);F=!0;var c=k;try{P(b);for(n=p(q);null!==n&&(!(n.expirationTime>b)||a&&!fa());){var m=n.callback;if("function"===typeof m){n.callback=null;
k=n.priorityLevel;var d=m(n.expirationTime<=b);b=v();"function"===typeof d?n.callback=d:n===p(q)&&E(q);P(b)}else E(q);n=p(q)}if(null!==n)var g=!0;else{var h=p(r);null!==h&&T(Q,h.startTime-b);g=!1}return g}finally{n=null,k=c,F=!1}}function fa(){return v()-ha<ia?!1:!0}function R(a){G=a;H||(H=!0,I())}function T(a,b){A=ja(function(){a(v())},b)}function ka(a){throw Error("act(...) is not supported in production builds of React.");}var y=Symbol.for("react.element"),qa=Symbol.for("react.portal"),sa=Symbol.for("react.fragment"),
ta=Symbol.for("react.strict_mode"),ua=Symbol.for("react.profiler"),va=Symbol.for("react.provider"),wa=Symbol.for("react.context"),xa=Symbol.for("react.forward_ref"),ya=Symbol.for("react.suspense"),za=Symbol.for("react.memo"),Aa=Symbol.for("react.lazy"),V=Symbol.iterator,X={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a,b,c,m){},enqueueSetState:function(a,b,c,m){}},la=Object.assign,W={};w.prototype.isReactComponent={};w.prototype.setState=function(a,
b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};Y.prototype=w.prototype;var t=K.prototype=new Y;t.constructor=K;la(t,w.prototype);t.isPureReactComponent=!0;var ca=Array.isArray,aa=Object.prototype.hasOwnProperty,L={current:null},
ba={key:!0,ref:!0,__self:!0,__source:!0},da=/\/+/g,g={current:null},J={transition:null};if("object"===typeof performance&&"function"===typeof performance.now){var Ba=performance;var v=function(){return Ba.now()}}else{var ma=Date,Ca=ma.now();v=function(){return ma.now()-Ca}}var q=[],r=[],Da=1,n=null,k=3,F=!1,u=!1,z=!1,ja="function"===typeof setTimeout?setTimeout:null,ea="function"===typeof clearTimeout?clearTimeout:null,na="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&&
void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var H=!1,G=null,A=-1,ia=5,ha=-1,U=function(){if(null!==G){var a=v();ha=a;var b=!0;try{b=G(!0,a)}finally{b?I():(H=!1,G=null)}}else H=!1};if("function"===typeof na)var I=function(){na(U)};else if("undefined"!==typeof MessageChannel){t=new MessageChannel;var Ea=t.port2;t.port1.onmessage=U;I=function(){Ea.postMessage(null)}}else I=function(){ja(U,0)};t={ReactCurrentDispatcher:g,
ReactCurrentOwner:L,ReactCurrentBatchConfig:J,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=k;k=a;try{return b()}finally{k=c}},unstable_next:function(a){switch(k){case 1:case 2:case 3:var b=3;break;default:b=k}var c=k;k=b;try{return a()}finally{k=c}},unstable_scheduleCallback:function(a,
b,c){var e=v();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?e+c:e):c=e;switch(a){case 1:var d=-1;break;case 2:d=250;break;case 5:d=1073741823;break;case 4:d=1E4;break;default:d=5E3}d=c+d;a={id:Da++,callback:b,priorityLevel:a,startTime:c,expirationTime:d,sortIndex:-1};c>e?(a.sortIndex=c,O(r,a),null===p(q)&&a===p(r)&&(z?(ea(A),A=-1):z=!0,T(Q,c-e))):(a.sortIndex=d,O(q,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b=
k;return function(){var c=k;k=b;try{return a.apply(this,arguments)}finally{k=c}}},unstable_getCurrentPriorityLevel:function(){return k},unstable_shouldYield:fa,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return p(q)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):
ia=0<a?Math.floor(1E3/a):5},unstable_Profiling:null}};c.Children={map:C,forEach:function(a,b,c){C(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;C(a,function(){b++});return b},toArray:function(a){return C(a,function(a){return a})||[]},only:function(a){if(!M(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};c.Component=w;c.Fragment=sa;c.Profiler=ua;c.PureComponent=K;c.StrictMode=ta;c.Suspense=ya;c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=
t;c.act=ka;c.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var e=la({},a.props),d=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=L.current);void 0!==b.key&&(d=""+b.key);if(a.type&&a.type.defaultProps)var l=a.type.defaultProps;for(f in b)aa.call(b,f)&&!ba.hasOwnProperty(f)&&(e[f]=void 0===b[f]&&void 0!==l?l[f]:b[f])}var f=arguments.length-2;if(1===f)e.children=c;else if(1<f){l=
Array(f);for(var g=0;g<f;g++)l[g]=arguments[g+2];e.children=l}return{$$typeof:y,type:a.type,key:d,ref:k,props:e,_owner:h}};c.createContext=function(a){a={$$typeof:wa,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:va,_context:a};return a.Consumer=a};c.createElement=Z;c.createFactory=function(a){var b=Z.bind(null,a);b.type=a;return b};c.createRef=function(){return{current:null}};c.forwardRef=function(a){return{$$typeof:xa,
render:a}};c.isValidElement=M;c.lazy=function(a){return{$$typeof:Aa,_payload:{_status:-1,_result:a},_init:ra}};c.memo=function(a,b){return{$$typeof:za,type:a,compare:void 0===b?null:b}};c.startTransition=function(a,b){b=J.transition;J.transition={};try{a()}finally{J.transition=b}};c.unstable_act=ka;c.useCallback=function(a,b){return g.current.useCallback(a,b)};c.useContext=function(a){return g.current.useContext(a)};c.useDebugValue=function(a,b){};c.useDeferredValue=function(a){return g.current.useDeferredValue(a)};
c.useEffect=function(a,b){return g.current.useEffect(a,b)};c.useId=function(){return g.current.useId()};c.useImperativeHandle=function(a,b,c){return g.current.useImperativeHandle(a,b,c)};c.useInsertionEffect=function(a,b){return g.current.useInsertionEffect(a,b)};c.useLayoutEffect=function(a,b){return g.current.useLayoutEffect(a,b)};c.useMemo=function(a,b){return g.current.useMemo(a,b)};c.useReducer=function(a,b,c){return g.current.useReducer(a,b,c)};c.useRef=function(a){return g.current.useRef(a)};
c.useState=function(a){return g.current.useState(a)};c.useSyncExternalStore=function(a,b,c){return g.current.useSyncExternalStore(a,b,c)};c.useTransition=function(){return g.current.useTransition()};c.version="18.3.1"});
})();
/**
 * @license React
 * react-jsx-dev-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

// -----------------------------------------------------------------------------

var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing

var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.

var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

var REACT_MODULE_REFERENCE;

{
  REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}

function isValidElementType(type) {
  if (typeof type === 'string' || typeof type === 'function') {
    return true;
  } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).


  if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing  || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden  || type === REACT_OFFSCREEN_TYPE || enableScopeAPI  || enableCacheElement  || enableTransitionTracing ) {
    return true;
  }

  if (typeof type === 'object' && type !== null) {
    if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
    // types supported by any Flight configuration anywhere since
    // we don't know which Flight build this will end up being used
    // with.
    type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
      return true;
    }
  }

  return false;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

var assign = Object.assign;

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}
function checkKeyStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
var RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true
};
var specialPropKeyWarningShown;
var specialPropRefWarningShown;
var didWarnAboutStringRefs;

{
  didWarnAboutStringRefs = {};
}

function hasValidRef(config) {
  {
    if (hasOwnProperty.call(config, 'ref')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.ref !== undefined;
}

function hasValidKey(config) {
  {
    if (hasOwnProperty.call(config, 'key')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.key !== undefined;
}

function warnIfStringRefCannotBeAutoConverted(config, self) {
  {
    if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
      var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);

      if (!didWarnAboutStringRefs[componentName]) {
        error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);

        didWarnAboutStringRefs[componentName] = true;
      }
    }
  }
}

function defineKeyPropWarningGetter(props, displayName) {
  {
    var warnAboutAccessingKey = function () {
      if (!specialPropKeyWarningShown) {
        specialPropKeyWarningShown = true;

        error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    };

    warnAboutAccessingKey.isReactWarning = true;
    Object.defineProperty(props, 'key', {
      get: warnAboutAccessingKey,
      configurable: true
    });
  }
}

function defineRefPropWarningGetter(props, displayName) {
  {
    var warnAboutAccessingRef = function () {
      if (!specialPropRefWarningShown) {
        specialPropRefWarningShown = true;

        error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    };

    warnAboutAccessingRef.isReactWarning = true;
    Object.defineProperty(props, 'ref', {
      get: warnAboutAccessingRef,
      configurable: true
    });
  }
}
/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, instanceof check
 * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @param {*} type
 * @param {*} props
 * @param {*} key
 * @param {string|object} ref
 * @param {*} owner
 * @param {*} self A *temporary* helper to detect places where `this` is
 * different from the `owner` when React.createElement is called, so that we
 * can warn. We want to get rid of owner and replace string `ref`s with arrow
 * functions, and as long as `this` and owner are the same, there will be no
 * change in behavior.
 * @param {*} source An annotation object (added by a transpiler or otherwise)
 * indicating filename, line number, and/or other information.
 * @internal
 */


var ReactElement = function (type, key, ref, self, source, owner, props) {
  var element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,
    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,
    // Record the component responsible for creating this element.
    _owner: owner
  };

  {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.

    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false
    }); // self and source are DEV only properties.

    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self
    }); // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.

    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source
    });

    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};
/**
 * https://github.com/reactjs/rfcs/pull/107
 * @param {*} type
 * @param {object} props
 * @param {string} key
 */

function jsxDEV(type, config, maybeKey, source, self) {
  {
    var propName; // Reserved names are extracted

    var props = {};
    var key = null;
    var ref = null; // Currently, key can be spread in as a prop. This causes a potential
    // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
    // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
    // but as an intermediary step, we will use jsxDEV for everything except
    // <div {...props} key="Hi" />, because we aren't currently able to tell if
    // key is explicitly declared to be undefined or not.

    if (maybeKey !== undefined) {
      {
        checkKeyStringCoercion(maybeKey);
      }

      key = '' + maybeKey;
    }

    if (hasValidKey(config)) {
      {
        checkKeyStringCoercion(config.key);
      }

      key = '' + config.key;
    }

    if (hasValidRef(config)) {
      ref = config.ref;
      warnIfStringRefCannotBeAutoConverted(config, self);
    } // Remaining properties are added to a new props object


    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        props[propName] = config[propName];
      }
    } // Resolve default props


    if (type && type.defaultProps) {
      var defaultProps = type.defaultProps;

      for (propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }
    }

    if (key || ref) {
      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

      if (key) {
        defineKeyPropWarningGetter(props, displayName);
      }

      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }

    return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
  }
}

var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement$1(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame$1.setExtraStackFrame(null);
    }
  }
}

var propTypesMisspellWarningShown;

{
  propTypesMisspellWarningShown = false;
}
/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a ReactElement.
 * @final
 */


function isValidElement(object) {
  {
    return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
  }
}

function getDeclarationErrorAddendum() {
  {
    if (ReactCurrentOwner$1.current) {
      var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);

      if (name) {
        return '\n\nCheck the render method of `' + name + '`.';
      }
    }

    return '';
  }
}

function getSourceInfoErrorAddendum(source) {
  {
    if (source !== undefined) {
      var fileName = source.fileName.replace(/^.*[\\\/]/, '');
      var lineNumber = source.lineNumber;
      return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
    }

    return '';
  }
}
/**
 * Warn if there's no key explicitly set on dynamic arrays of children or
 * object keys are not valid. This allows us to keep track of children between
 * updates.
 */


var ownerHasKeyUseWarning = {};

function getCurrentComponentErrorInfo(parentType) {
  {
    var info = getDeclarationErrorAddendum();

    if (!info) {
      var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;

      if (parentName) {
        info = "\n\nCheck the top-level render call using <" + parentName + ">.";
      }
    }

    return info;
  }
}
/**
 * Warn if the element doesn't have an explicit key assigned to it.
 * This element is in an array. The array could grow and shrink or be
 * reordered. All children that haven't already been validated are required to
 * have a "key" property assigned to it. Error statuses are cached so a warning
 * will only be shown once.
 *
 * @internal
 * @param {ReactElement} element Element that requires a key.
 * @param {*} parentType element's parent's type.
 */


function validateExplicitKey(element, parentType) {
  {
    if (!element._store || element._store.validated || element.key != null) {
      return;
    }

    element._store.validated = true;
    var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);

    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
      return;
    }

    ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
    // property, it may be the creator of the child that's responsible for
    // assigning it a key.

    var childOwner = '';

    if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
      // Give the component that originally created this child.
      childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
    }

    setCurrentlyValidatingElement$1(element);

    error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);

    setCurrentlyValidatingElement$1(null);
  }
}
/**
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */


function validateChildKeys(node, parentType) {
  {
    if (typeof node !== 'object') {
      return;
    }

    if (isArray(node)) {
      for (var i = 0; i < node.length; i++) {
        var child = node[i];

        if (isValidElement(child)) {
          validateExplicitKey(child, parentType);
        }
      }
    } else if (isValidElement(node)) {
      // This element was passed in a valid location.
      if (node._store) {
        node._store.validated = true;
      }
    } else if (node) {
      var iteratorFn = getIteratorFn(node);

      if (typeof iteratorFn === 'function') {
        // Entry iterators used to provide implicit keys,
        // but now we print a separate warning for them later.
        if (iteratorFn !== node.entries) {
          var iterator = iteratorFn.call(node);
          var step;

          while (!(step = iterator.next()).done) {
            if (isValidElement(step.value)) {
              validateExplicitKey(step.value, parentType);
            }
          }
        }
      }
    }
  }
}
/**
 * Given an element, validate that its props follow the propTypes definition,
 * provided by the type.
 *
 * @param {ReactElement} element
 */


function validatePropTypes(element) {
  {
    var type = element.type;

    if (type === null || type === undefined || typeof type === 'string') {
      return;
    }

    var propTypes;

    if (typeof type === 'function') {
      propTypes = type.propTypes;
    } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
    // Inner props are checked in the reconciler.
    type.$$typeof === REACT_MEMO_TYPE)) {
      propTypes = type.propTypes;
    } else {
      return;
    }

    if (propTypes) {
      // Intentionally inside to avoid triggering lazy initializers:
      var name = getComponentNameFromType(type);
      checkPropTypes(propTypes, element.props, 'prop', name, element);
    } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
      propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

      var _name = getComponentNameFromType(type);

      error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
    }

    if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
    }
  }
}
/**
 * Given a fragment, validate that it can only be provided with fragment props
 * @param {ReactElement} fragment
 */


function validateFragmentProps(fragment) {
  {
    var keys = Object.keys(fragment.props);

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];

      if (key !== 'children' && key !== 'key') {
        setCurrentlyValidatingElement$1(fragment);

        error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);

        setCurrentlyValidatingElement$1(null);
        break;
      }
    }

    if (fragment.ref !== null) {
      setCurrentlyValidatingElement$1(fragment);

      error('Invalid attribute `ref` supplied to `React.Fragment`.');

      setCurrentlyValidatingElement$1(null);
    }
  }
}

var didWarnAboutKeySpread = {};
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
  {
    var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
    // succeed and there will likely be errors in render.

    if (!validType) {
      var info = '';

      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
        info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
      }

      var sourceInfo = getSourceInfoErrorAddendum(source);

      if (sourceInfo) {
        info += sourceInfo;
      } else {
        info += getDeclarationErrorAddendum();
      }

      var typeString;

      if (type === null) {
        typeString = 'null';
      } else if (isArray(type)) {
        typeString = 'array';
      } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
        typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
        info = ' Did you accidentally export a JSX literal instead of a component?';
      } else {
        typeString = typeof type;
      }

      error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
    }

    var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
    // TODO: Drop this when these are no longer allowed as the type argument.

    if (element == null) {
      return element;
    } // Skip key warning if the type isn't valid since our key validation logic
    // doesn't expect a non-string/function type and can throw confusing errors.
    // We don't want exception behavior to differ between dev and prod.
    // (Rendering will throw with a helpful message and as soon as the type is
    // fixed, the key warnings will appear.)


    if (validType) {
      var children = props.children;

      if (children !== undefined) {
        if (isStaticChildren) {
          if (isArray(children)) {
            for (var i = 0; i < children.length; i++) {
              validateChildKeys(children[i], type);
            }

            if (Object.freeze) {
              Object.freeze(children);
            }
          } else {
            error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
          }
        } else {
          validateChildKeys(children, type);
        }
      }
    }

    {
      if (hasOwnProperty.call(props, 'key')) {
        var componentName = getComponentNameFromType(type);
        var keys = Object.keys(props).filter(function (k) {
          return k !== 'key';
        });
        var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';

        if (!didWarnAboutKeySpread[componentName + beforeExample]) {
          var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';

          error('A props object containing a "key" prop is being spread into JSX:\n' + '  let props = %s;\n' + '  <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + '  let props = %s;\n' + '  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);

          didWarnAboutKeySpread[componentName + beforeExample] = true;
        }
      }
    }

    if (type === REACT_FRAGMENT_TYPE) {
      validateFragmentProps(element);
    } else {
      validatePropTypes(element);
    }

    return element;
  }
} // These two functions exist to still get child warnings in dev

var jsxDEV$1 =  jsxWithValidation ;

exports.Fragment = REACT_FRAGMENT_TYPE;
exports.jsxDEV = jsxDEV$1;
  })();
}
/**
 * @license React
 * react-jsx-dev-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var a=Symbol.for("react.fragment");exports.Fragment=a;exports.jsxDEV=void 0;
/**
 * @license React
 * react-jsx-dev-runtime.profiling.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var a=Symbol.for("react.fragment");exports.Fragment=a;exports.jsxDEV=void 0;
/**
 * @license React
 * react-jsx-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

// -----------------------------------------------------------------------------

var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing

var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.

var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

var REACT_MODULE_REFERENCE;

{
  REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}

function isValidElementType(type) {
  if (typeof type === 'string' || typeof type === 'function') {
    return true;
  } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).


  if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing  || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden  || type === REACT_OFFSCREEN_TYPE || enableScopeAPI  || enableCacheElement  || enableTransitionTracing ) {
    return true;
  }

  if (typeof type === 'object' && type !== null) {
    if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
    // types supported by any Flight configuration anywhere since
    // we don't know which Flight build this will end up being used
    // with.
    type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
      return true;
    }
  }

  return false;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

var assign = Object.assign;

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}
function checkKeyStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
var RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true
};
var specialPropKeyWarningShown;
var specialPropRefWarningShown;
var didWarnAboutStringRefs;

{
  didWarnAboutStringRefs = {};
}

function hasValidRef(config) {
  {
    if (hasOwnProperty.call(config, 'ref')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.ref !== undefined;
}

function hasValidKey(config) {
  {
    if (hasOwnProperty.call(config, 'key')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.key !== undefined;
}

function warnIfStringRefCannotBeAutoConverted(config, self) {
  {
    if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
      var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);

      if (!didWarnAboutStringRefs[componentName]) {
        error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);

        didWarnAboutStringRefs[componentName] = true;
      }
    }
  }
}

function defineKeyPropWarningGetter(props, displayName) {
  {
    var warnAboutAccessingKey = function () {
      if (!specialPropKeyWarningShown) {
        specialPropKeyWarningShown = true;

        error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    };

    warnAboutAccessingKey.isReactWarning = true;
    Object.defineProperty(props, 'key', {
      get: warnAboutAccessingKey,
      configurable: true
    });
  }
}

function defineRefPropWarningGetter(props, displayName) {
  {
    var warnAboutAccessingRef = function () {
      if (!specialPropRefWarningShown) {
        specialPropRefWarningShown = true;

        error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    };

    warnAboutAccessingRef.isReactWarning = true;
    Object.defineProperty(props, 'ref', {
      get: warnAboutAccessingRef,
      configurable: true
    });
  }
}
/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, instanceof check
 * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @param {*} type
 * @param {*} props
 * @param {*} key
 * @param {string|object} ref
 * @param {*} owner
 * @param {*} self A *temporary* helper to detect places where `this` is
 * different from the `owner` when React.createElement is called, so that we
 * can warn. We want to get rid of owner and replace string `ref`s with arrow
 * functions, and as long as `this` and owner are the same, there will be no
 * change in behavior.
 * @param {*} source An annotation object (added by a transpiler or otherwise)
 * indicating filename, line number, and/or other information.
 * @internal
 */


var ReactElement = function (type, key, ref, self, source, owner, props) {
  var element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,
    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,
    // Record the component responsible for creating this element.
    _owner: owner
  };

  {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.

    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false
    }); // self and source are DEV only properties.

    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self
    }); // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.

    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source
    });

    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};
/**
 * https://github.com/reactjs/rfcs/pull/107
 * @param {*} type
 * @param {object} props
 * @param {string} key
 */

function jsxDEV(type, config, maybeKey, source, self) {
  {
    var propName; // Reserved names are extracted

    var props = {};
    var key = null;
    var ref = null; // Currently, key can be spread in as a prop. This causes a potential
    // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
    // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
    // but as an intermediary step, we will use jsxDEV for everything except
    // <div {...props} key="Hi" />, because we aren't currently able to tell if
    // key is explicitly declared to be undefined or not.

    if (maybeKey !== undefined) {
      {
        checkKeyStringCoercion(maybeKey);
      }

      key = '' + maybeKey;
    }

    if (hasValidKey(config)) {
      {
        checkKeyStringCoercion(config.key);
      }

      key = '' + config.key;
    }

    if (hasValidRef(config)) {
      ref = config.ref;
      warnIfStringRefCannotBeAutoConverted(config, self);
    } // Remaining properties are added to a new props object


    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        props[propName] = config[propName];
      }
    } // Resolve default props


    if (type && type.defaultProps) {
      var defaultProps = type.defaultProps;

      for (propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }
    }

    if (key || ref) {
      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

      if (key) {
        defineKeyPropWarningGetter(props, displayName);
      }

      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }

    return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
  }
}

var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement$1(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame$1.setExtraStackFrame(null);
    }
  }
}

var propTypesMisspellWarningShown;

{
  propTypesMisspellWarningShown = false;
}
/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a ReactElement.
 * @final
 */


function isValidElement(object) {
  {
    return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
  }
}

function getDeclarationErrorAddendum() {
  {
    if (ReactCurrentOwner$1.current) {
      var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);

      if (name) {
        return '\n\nCheck the render method of `' + name + '`.';
      }
    }

    return '';
  }
}

function getSourceInfoErrorAddendum(source) {
  {
    if (source !== undefined) {
      var fileName = source.fileName.replace(/^.*[\\\/]/, '');
      var lineNumber = source.lineNumber;
      return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
    }

    return '';
  }
}
/**
 * Warn if there's no key explicitly set on dynamic arrays of children or
 * object keys are not valid. This allows us to keep track of children between
 * updates.
 */


var ownerHasKeyUseWarning = {};

function getCurrentComponentErrorInfo(parentType) {
  {
    var info = getDeclarationErrorAddendum();

    if (!info) {
      var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;

      if (parentName) {
        info = "\n\nCheck the top-level render call using <" + parentName + ">.";
      }
    }

    return info;
  }
}
/**
 * Warn if the element doesn't have an explicit key assigned to it.
 * This element is in an array. The array could grow and shrink or be
 * reordered. All children that haven't already been validated are required to
 * have a "key" property assigned to it. Error statuses are cached so a warning
 * will only be shown once.
 *
 * @internal
 * @param {ReactElement} element Element that requires a key.
 * @param {*} parentType element's parent's type.
 */


function validateExplicitKey(element, parentType) {
  {
    if (!element._store || element._store.validated || element.key != null) {
      return;
    }

    element._store.validated = true;
    var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);

    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
      return;
    }

    ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
    // property, it may be the creator of the child that's responsible for
    // assigning it a key.

    var childOwner = '';

    if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
      // Give the component that originally created this child.
      childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
    }

    setCurrentlyValidatingElement$1(element);

    error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);

    setCurrentlyValidatingElement$1(null);
  }
}
/**
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */


function validateChildKeys(node, parentType) {
  {
    if (typeof node !== 'object') {
      return;
    }

    if (isArray(node)) {
      for (var i = 0; i < node.length; i++) {
        var child = node[i];

        if (isValidElement(child)) {
          validateExplicitKey(child, parentType);
        }
      }
    } else if (isValidElement(node)) {
      // This element was passed in a valid location.
      if (node._store) {
        node._store.validated = true;
      }
    } else if (node) {
      var iteratorFn = getIteratorFn(node);

      if (typeof iteratorFn === 'function') {
        // Entry iterators used to provide implicit keys,
        // but now we print a separate warning for them later.
        if (iteratorFn !== node.entries) {
          var iterator = iteratorFn.call(node);
          var step;

          while (!(step = iterator.next()).done) {
            if (isValidElement(step.value)) {
              validateExplicitKey(step.value, parentType);
            }
          }
        }
      }
    }
  }
}
/**
 * Given an element, validate that its props follow the propTypes definition,
 * provided by the type.
 *
 * @param {ReactElement} element
 */


function validatePropTypes(element) {
  {
    var type = element.type;

    if (type === null || type === undefined || typeof type === 'string') {
      return;
    }

    var propTypes;

    if (typeof type === 'function') {
      propTypes = type.propTypes;
    } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
    // Inner props are checked in the reconciler.
    type.$$typeof === REACT_MEMO_TYPE)) {
      propTypes = type.propTypes;
    } else {
      return;
    }

    if (propTypes) {
      // Intentionally inside to avoid triggering lazy initializers:
      var name = getComponentNameFromType(type);
      checkPropTypes(propTypes, element.props, 'prop', name, element);
    } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
      propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

      var _name = getComponentNameFromType(type);

      error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
    }

    if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
    }
  }
}
/**
 * Given a fragment, validate that it can only be provided with fragment props
 * @param {ReactElement} fragment
 */


function validateFragmentProps(fragment) {
  {
    var keys = Object.keys(fragment.props);

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];

      if (key !== 'children' && key !== 'key') {
        setCurrentlyValidatingElement$1(fragment);

        error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);

        setCurrentlyValidatingElement$1(null);
        break;
      }
    }

    if (fragment.ref !== null) {
      setCurrentlyValidatingElement$1(fragment);

      error('Invalid attribute `ref` supplied to `React.Fragment`.');

      setCurrentlyValidatingElement$1(null);
    }
  }
}

var didWarnAboutKeySpread = {};
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
  {
    var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
    // succeed and there will likely be errors in render.

    if (!validType) {
      var info = '';

      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
        info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
      }

      var sourceInfo = getSourceInfoErrorAddendum(source);

      if (sourceInfo) {
        info += sourceInfo;
      } else {
        info += getDeclarationErrorAddendum();
      }

      var typeString;

      if (type === null) {
        typeString = 'null';
      } else if (isArray(type)) {
        typeString = 'array';
      } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
        typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
        info = ' Did you accidentally export a JSX literal instead of a component?';
      } else {
        typeString = typeof type;
      }

      error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
    }

    var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
    // TODO: Drop this when these are no longer allowed as the type argument.

    if (element == null) {
      return element;
    } // Skip key warning if the type isn't valid since our key validation logic
    // doesn't expect a non-string/function type and can throw confusing errors.
    // We don't want exception behavior to differ between dev and prod.
    // (Rendering will throw with a helpful message and as soon as the type is
    // fixed, the key warnings will appear.)


    if (validType) {
      var children = props.children;

      if (children !== undefined) {
        if (isStaticChildren) {
          if (isArray(children)) {
            for (var i = 0; i < children.length; i++) {
              validateChildKeys(children[i], type);
            }

            if (Object.freeze) {
              Object.freeze(children);
            }
          } else {
            error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
          }
        } else {
          validateChildKeys(children, type);
        }
      }
    }

    {
      if (hasOwnProperty.call(props, 'key')) {
        var componentName = getComponentNameFromType(type);
        var keys = Object.keys(props).filter(function (k) {
          return k !== 'key';
        });
        var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';

        if (!didWarnAboutKeySpread[componentName + beforeExample]) {
          var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';

          error('A props object containing a "key" prop is being spread into JSX:\n' + '  let props = %s;\n' + '  <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + '  let props = %s;\n' + '  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);

          didWarnAboutKeySpread[componentName + beforeExample] = true;
        }
      }
    }

    if (type === REACT_FRAGMENT_TYPE) {
      validateFragmentProps(element);
    } else {
      validatePropTypes(element);
    }

    return element;
  }
} // These two functions exist to still get child warnings in dev
// even with the prod transform. This means that jsxDEV is purely
// opt-in behavior for better messages but that we won't stop
// giving you warnings if you use production apis.

function jsxWithValidationStatic(type, props, key) {
  {
    return jsxWithValidation(type, props, key, true);
  }
}
function jsxWithValidationDynamic(type, props, key) {
  {
    return jsxWithValidation(type, props, key, false);
  }
}

var jsx =  jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
// for now we can ship identical prod functions

var jsxs =  jsxWithValidationStatic ;

exports.Fragment = REACT_FRAGMENT_TYPE;
exports.jsx = jsx;
exports.jsxs = jsxs;
  })();
}
/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var f=require("react"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;
/**
 * @license React
 * react-jsx-runtime.profiling.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var f=require("react"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;
/**
 * @license React
 * react.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {

          'use strict';

/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
}
          var ReactVersion = '18.3.1';

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

/**
 * Keeps track of the current dispatcher.
 */
var ReactCurrentDispatcher = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: null
};

/**
 * Keeps track of the current batch's configuration such as how long an update
 * should suspend for if it needs to.
 */
var ReactCurrentBatchConfig = {
  transition: null
};

var ReactCurrentActQueue = {
  current: null,
  // Used to reproduce behavior of `batchedUpdates` in legacy mode.
  isBatchingLegacy: false,
  didScheduleLegacyUpdate: false
};

/**
 * Keeps track of the current owner.
 *
 * The current owner is the component who should own any components that are
 * currently being constructed.
 */
var ReactCurrentOwner = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: null
};

var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
  {
    currentExtraStackFrame = stack;
  }
}

{
  ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
    {
      currentExtraStackFrame = stack;
    }
  }; // Stack implementation injected by the current renderer.


  ReactDebugCurrentFrame.getCurrentStack = null;

  ReactDebugCurrentFrame.getStackAddendum = function () {
    var stack = ''; // Add an extra top frame while an element is being validated

    if (currentExtraStackFrame) {
      stack += currentExtraStackFrame;
    } // Delegate to the injected renderer-specific implementation


    var impl = ReactDebugCurrentFrame.getCurrentStack;

    if (impl) {
      stack += impl() || '';
    }

    return stack;
  };
}

// -----------------------------------------------------------------------------

var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing

var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.

var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

var ReactSharedInternals = {
  ReactCurrentDispatcher: ReactCurrentDispatcher,
  ReactCurrentBatchConfig: ReactCurrentBatchConfig,
  ReactCurrentOwner: ReactCurrentOwner
};

{
  ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
  ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

var didWarnStateUpdateForUnmountedComponent = {};

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
    var warningKey = componentName + "." + callerName;

    if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
      return;
    }

    error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);

    didWarnStateUpdateForUnmountedComponent[warningKey] = true;
  }
}
/**
 * This is the abstract API for an update queue.
 */


var ReactNoopUpdateQueue = {
  /**
   * Checks whether or not this composite component is mounted.
   * @param {ReactClass} publicInstance The instance we want to test.
   * @return {boolean} True if mounted, false otherwise.
   * @protected
   * @final
   */
  isMounted: function (publicInstance) {
    return false;
  },

  /**
   * Forces an update. This should only be invoked when it is known with
   * certainty that we are **not** in a DOM transaction.
   *
   * You may want to call this when you know that some deeper aspect of the
   * component's state has changed but `setState` was not called.
   *
   * This will not invoke `shouldComponentUpdate`, but it will invoke
   * `componentWillUpdate` and `componentDidUpdate`.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {?function} callback Called after component is updated.
   * @param {?string} callerName name of the calling function in the public API.
   * @internal
   */
  enqueueForceUpdate: function (publicInstance, callback, callerName) {
    warnNoop(publicInstance, 'forceUpdate');
  },

  /**
   * Replaces all of the state. Always use this or `setState` to mutate state.
   * You should treat `this.state` as immutable.
   *
   * There is no guarantee that `this.state` will be immediately updated, so
   * accessing `this.state` after calling this method may return the old value.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {object} completeState Next state.
   * @param {?function} callback Called after component is updated.
   * @param {?string} callerName name of the calling function in the public API.
   * @internal
   */
  enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
    warnNoop(publicInstance, 'replaceState');
  },

  /**
   * Sets a subset of the state. This only exists because _pendingState is
   * internal. This provides a merging strategy that is not available to deep
   * properties which is confusing. TODO: Expose pendingState or don't use it
   * during the merge.
   *
   * @param {ReactClass} publicInstance The instance that should rerender.
   * @param {object} partialState Next partial state to be merged with state.
   * @param {?function} callback Called after component is updated.
   * @param {?string} Name of the calling function in the public API.
   * @internal
   */
  enqueueSetState: function (publicInstance, partialState, callback, callerName) {
    warnNoop(publicInstance, 'setState');
  }
};

var assign = Object.assign;

var emptyObject = {};

{
  Object.freeze(emptyObject);
}
/**
 * Base class helpers for the updating state of a component.
 */


function Component(props, context, updater) {
  this.props = props;
  this.context = context; // If a component has string refs, we will assign a different object later.

  this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
  // renderer.

  this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.isReactComponent = {};
/**
 * Sets a subset of the state. Always use this to mutate
 * state. You should treat `this.state` as immutable.
 *
 * There is no guarantee that `this.state` will be immediately updated, so
 * accessing `this.state` after calling this method may return the old value.
 *
 * There is no guarantee that calls to `setState` will run synchronously,
 * as they may eventually be batched together.  You can provide an optional
 * callback that will be executed when the call to setState is actually
 * completed.
 *
 * When a function is provided to setState, it will be called at some point in
 * the future (not synchronously). It will be called with the up to date
 * component arguments (state, props, context). These values can be different
 * from this.* because your function may be called after receiveProps but before
 * shouldComponentUpdate, and this new state, props, and context will not yet be
 * assigned to this.
 *
 * @param {object|function} partialState Next partial state or function to
 *        produce next partial state to be merged with current state.
 * @param {?function} callback Called after state is updated.
 * @final
 * @protected
 */

Component.prototype.setState = function (partialState, callback) {
  if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
    throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
  }

  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
 * Forces an update. This should only be invoked when it is known with
 * certainty that we are **not** in a DOM transaction.
 *
 * You may want to call this when you know that some deeper aspect of the
 * component's state has changed but `setState` was not called.
 *
 * This will not invoke `shouldComponentUpdate`, but it will invoke
 * `componentWillUpdate` and `componentDidUpdate`.
 *
 * @param {?function} callback Called after update is complete.
 * @final
 * @protected
 */


Component.prototype.forceUpdate = function (callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
 * Deprecated APIs. These APIs used to exist on classic React classes but since
 * we would like to deprecate them, we're not going to move them over to this
 * modern base class. Instead, we define a getter that warns if it's accessed.
 */


{
  var deprecatedAPIs = {
    isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
    replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
  };

  var defineDeprecationWarning = function (methodName, info) {
    Object.defineProperty(Component.prototype, methodName, {
      get: function () {
        warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);

        return undefined;
      }
    });
  };

  for (var fnName in deprecatedAPIs) {
    if (deprecatedAPIs.hasOwnProperty(fnName)) {
      defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
    }
  }
}

function ComponentDummy() {}

ComponentDummy.prototype = Component.prototype;
/**
 * Convenience component with default shallow equality check for sCU.
 */

function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context; // If a component has string refs, we will assign a different object later.

  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.

assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

// an immutable object with a single mutable value
function createRef() {
  var refObject = {
    current: null
  };

  {
    Object.seal(refObject);
  }

  return refObject;
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}
function checkKeyStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

var RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;

{
  didWarnAboutStringRefs = {};
}

function hasValidRef(config) {
  {
    if (hasOwnProperty.call(config, 'ref')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.ref !== undefined;
}

function hasValidKey(config) {
  {
    if (hasOwnProperty.call(config, 'key')) {
      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;

      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }

  return config.key !== undefined;
}

function defineKeyPropWarningGetter(props, displayName) {
  var warnAboutAccessingKey = function () {
    {
      if (!specialPropKeyWarningShown) {
        specialPropKeyWarningShown = true;

        error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    }
  };

  warnAboutAccessingKey.isReactWarning = true;
  Object.defineProperty(props, 'key', {
    get: warnAboutAccessingKey,
    configurable: true
  });
}

function defineRefPropWarningGetter(props, displayName) {
  var warnAboutAccessingRef = function () {
    {
      if (!specialPropRefWarningShown) {
        specialPropRefWarningShown = true;

        error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
      }
    }
  };

  warnAboutAccessingRef.isReactWarning = true;
  Object.defineProperty(props, 'ref', {
    get: warnAboutAccessingRef,
    configurable: true
  });
}

function warnIfStringRefCannotBeAutoConverted(config) {
  {
    if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
      var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);

      if (!didWarnAboutStringRefs[componentName]) {
        error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);

        didWarnAboutStringRefs[componentName] = true;
      }
    }
  }
}
/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, instanceof check
 * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @param {*} type
 * @param {*} props
 * @param {*} key
 * @param {string|object} ref
 * @param {*} owner
 * @param {*} self A *temporary* helper to detect places where `this` is
 * different from the `owner` when React.createElement is called, so that we
 * can warn. We want to get rid of owner and replace string `ref`s with arrow
 * functions, and as long as `this` and owner are the same, there will be no
 * change in behavior.
 * @param {*} source An annotation object (added by a transpiler or otherwise)
 * indicating filename, line number, and/or other information.
 * @internal
 */


var ReactElement = function (type, key, ref, self, source, owner, props) {
  var element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,
    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,
    // Record the component responsible for creating this element.
    _owner: owner
  };

  {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.

    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false
    }); // self and source are DEV only properties.

    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self
    }); // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.

    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source
    });

    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};
/**
 * Create and return a new ReactElement of the given type.
 * See https://reactjs.org/docs/react-api.html#createelement
 */

function createElement(type, config, children) {
  var propName; // Reserved names are extracted

  var props = {};
  var key = null;
  var ref = null;
  var self = null;
  var source = null;

  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;

      {
        warnIfStringRefCannotBeAutoConverted(config);
      }
    }

    if (hasValidKey(config)) {
      {
        checkKeyStringCoercion(config.key);
      }

      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object

    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        props[propName] = config[propName];
      }
    }
  } // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.


  var childrenLength = arguments.length - 2;

  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);

    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }

    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }

    props.children = childArray;
  } // Resolve default props


  if (type && type.defaultProps) {
    var defaultProps = type.defaultProps;

    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }

  {
    if (key || ref) {
      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

      if (key) {
        defineKeyPropWarningGetter(props, displayName);
      }

      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }
  }

  return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
  var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
  return newElement;
}
/**
 * Clone and return a new ReactElement using element as the starting point.
 * See https://reactjs.org/docs/react-api.html#cloneelement
 */

function cloneElement(element, config, children) {
  if (element === null || element === undefined) {
    throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
  }

  var propName; // Original props are copied

  var props = assign({}, element.props); // Reserved names are extracted

  var key = element.key;
  var ref = element.ref; // Self is preserved since the owner is preserved.

  var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
  // transpiler, and the original source is probably a better indicator of the
  // true owner.

  var source = element._source; // Owner will be preserved, unless ref is overridden

  var owner = element._owner;

  if (config != null) {
    if (hasValidRef(config)) {
      // Silently steal the ref from the parent.
      ref = config.ref;
      owner = ReactCurrentOwner.current;
    }

    if (hasValidKey(config)) {
      {
        checkKeyStringCoercion(config.key);
      }

      key = '' + config.key;
    } // Remaining properties override existing props


    var defaultProps;

    if (element.type && element.type.defaultProps) {
      defaultProps = element.type.defaultProps;
    }

    for (propName in config) {
      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
        if (config[propName] === undefined && defaultProps !== undefined) {
          // Resolve default props
          props[propName] = defaultProps[propName];
        } else {
          props[propName] = config[propName];
        }
      }
    }
  } // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.


  var childrenLength = arguments.length - 2;

  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);

    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }

    props.children = childArray;
  }

  return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a ReactElement.
 * @final
 */

function isValidElement(object) {
  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}

var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
 * Escape and wrap key so it is safe to use as a reactid
 *
 * @param {string} key to be escaped.
 * @return {string} the escaped key.
 */

function escape(key) {
  var escapeRegex = /[=:]/g;
  var escaperLookup = {
    '=': '=0',
    ':': '=2'
  };
  var escapedString = key.replace(escapeRegex, function (match) {
    return escaperLookup[match];
  });
  return '$' + escapedString;
}
/**
 * TODO: Test that a single child and an array with one item have the same key
 * pattern.
 */


var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;

function escapeUserProvidedKey(text) {
  return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
 * Generate a key string that identifies a element within a set.
 *
 * @param {*} element A element that could contain a manual key.
 * @param {number} index Index that is used if a manual key is not provided.
 * @return {string}
 */


function getElementKey(element, index) {
  // Do some typechecking here since we call this blindly. We want to ensure
  // that we don't block potential future ES APIs.
  if (typeof element === 'object' && element !== null && element.key != null) {
    // Explicit key
    {
      checkKeyStringCoercion(element.key);
    }

    return escape('' + element.key);
  } // Implicit key determined by the index in the set


  return index.toString(36);
}

function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
  var type = typeof children;

  if (type === 'undefined' || type === 'boolean') {
    // All of the above are perceived as null.
    children = null;
  }

  var invokeCallback = false;

  if (children === null) {
    invokeCallback = true;
  } else {
    switch (type) {
      case 'string':
      case 'number':
        invokeCallback = true;
        break;

      case 'object':
        switch (children.$$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            invokeCallback = true;
        }

    }
  }

  if (invokeCallback) {
    var _child = children;
    var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
    // so that it's consistent if the number of children grows:

    var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;

    if (isArray(mappedChild)) {
      var escapedChildKey = '';

      if (childKey != null) {
        escapedChildKey = escapeUserProvidedKey(childKey) + '/';
      }

      mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
        return c;
      });
    } else if (mappedChild != null) {
      if (isValidElement(mappedChild)) {
        {
          // The `if` statement here prevents auto-disabling of the safe
          // coercion ESLint rule, so we must manually disable it below.
          // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
          if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
            checkKeyStringCoercion(mappedChild.key);
          }
        }

        mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
        // traverseAllChildren used to do for objects as children
        escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
        mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
        // eslint-disable-next-line react-internal/safe-string-coercion
        escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
      }

      array.push(mappedChild);
    }

    return 1;
  }

  var child;
  var nextName;
  var subtreeCount = 0; // Count of children found in the current subtree.

  var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;

  if (isArray(children)) {
    for (var i = 0; i < children.length; i++) {
      child = children[i];
      nextName = nextNamePrefix + getElementKey(child, i);
      subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
    }
  } else {
    var iteratorFn = getIteratorFn(children);

    if (typeof iteratorFn === 'function') {
      var iterableChildren = children;

      {
        // Warn about using Maps as children
        if (iteratorFn === iterableChildren.entries) {
          if (!didWarnAboutMaps) {
            warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
          }

          didWarnAboutMaps = true;
        }
      }

      var iterator = iteratorFn.call(iterableChildren);
      var step;
      var ii = 0;

      while (!(step = iterator.next()).done) {
        child = step.value;
        nextName = nextNamePrefix + getElementKey(child, ii++);
        subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
      }
    } else if (type === 'object') {
      // eslint-disable-next-line react-internal/safe-string-coercion
      var childrenString = String(children);
      throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
    }
  }

  return subtreeCount;
}

/**
 * Maps children that are typically specified as `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenmap
 *
 * The provided mapFunction(child, index) will be called for each
 * leaf child.
 *
 * @param {?*} children Children tree container.
 * @param {function(*, int)} func The map function.
 * @param {*} context Context for mapFunction.
 * @return {object} Object containing the ordered map of results.
 */
function mapChildren(children, func, context) {
  if (children == null) {
    return children;
  }

  var result = [];
  var count = 0;
  mapIntoArray(children, result, '', '', function (child) {
    return func.call(context, child, count++);
  });
  return result;
}
/**
 * Count the number of children that are typically specified as
 * `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrencount
 *
 * @param {?*} children Children tree container.
 * @return {number} The number of children.
 */


function countChildren(children) {
  var n = 0;
  mapChildren(children, function () {
    n++; // Don't return anything
  });
  return n;
}

/**
 * Iterates through children that are typically specified as `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
 *
 * The provided forEachFunc(child, index) will be called for each
 * leaf child.
 *
 * @param {?*} children Children tree container.
 * @param {function(*, int)} forEachFunc
 * @param {*} forEachContext Context for forEachContext.
 */
function forEachChildren(children, forEachFunc, forEachContext) {
  mapChildren(children, function () {
    forEachFunc.apply(this, arguments); // Don't return anything.
  }, forEachContext);
}
/**
 * Flatten a children object (typically specified as `props.children`) and
 * return an array with appropriately re-keyed children.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
 */


function toArray(children) {
  return mapChildren(children, function (child) {
    return child;
  }) || [];
}
/**
 * Returns the first child in a collection of children and verifies that there
 * is only one child in the collection.
 *
 * See https://reactjs.org/docs/react-api.html#reactchildrenonly
 *
 * The current implementation of this function assumes that a single child gets
 * passed without a wrapper, but the purpose of this helper function is to
 * abstract away the particular structure of children.
 *
 * @param {?object} children Child collection structure.
 * @return {ReactElement} The first and only `ReactElement` contained in the
 * structure.
 */


function onlyChild(children) {
  if (!isValidElement(children)) {
    throw new Error('React.Children.only expected to receive a single React element child.');
  }

  return children;
}

function createContext(defaultValue) {
  // TODO: Second argument used to be an optional `calculateChangedBits`
  // function. Warn to reserve for future use?
  var context = {
    $$typeof: REACT_CONTEXT_TYPE,
    // As a workaround to support multiple concurrent renderers, we categorize
    // some renderers as primary and others as secondary. We only expect
    // there to be two concurrent renderers at most: React Native (primary) and
    // Fabric (secondary); React DOM (primary) and React ART (secondary).
    // Secondary renderers store their context values on separate fields.
    _currentValue: defaultValue,
    _currentValue2: defaultValue,
    // Used to track how many concurrent renderers this context currently
    // supports within in a single renderer. Such as parallel server rendering.
    _threadCount: 0,
    // These are circular
    Provider: null,
    Consumer: null,
    // Add these to use same hidden class in VM as ServerContext
    _defaultValue: null,
    _globalName: null
  };
  context.Provider = {
    $$typeof: REACT_PROVIDER_TYPE,
    _context: context
  };
  var hasWarnedAboutUsingNestedContextConsumers = false;
  var hasWarnedAboutUsingConsumerProvider = false;
  var hasWarnedAboutDisplayNameOnConsumer = false;

  {
    // A separate object, but proxies back to the original context object for
    // backwards compatibility. It has a different $$typeof, so we can properly
    // warn for the incorrect usage of Context as a Consumer.
    var Consumer = {
      $$typeof: REACT_CONTEXT_TYPE,
      _context: context
    }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here

    Object.defineProperties(Consumer, {
      Provider: {
        get: function () {
          if (!hasWarnedAboutUsingConsumerProvider) {
            hasWarnedAboutUsingConsumerProvider = true;

            error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
          }

          return context.Provider;
        },
        set: function (_Provider) {
          context.Provider = _Provider;
        }
      },
      _currentValue: {
        get: function () {
          return context._currentValue;
        },
        set: function (_currentValue) {
          context._currentValue = _currentValue;
        }
      },
      _currentValue2: {
        get: function () {
          return context._currentValue2;
        },
        set: function (_currentValue2) {
          context._currentValue2 = _currentValue2;
        }
      },
      _threadCount: {
        get: function () {
          return context._threadCount;
        },
        set: function (_threadCount) {
          context._threadCount = _threadCount;
        }
      },
      Consumer: {
        get: function () {
          if (!hasWarnedAboutUsingNestedContextConsumers) {
            hasWarnedAboutUsingNestedContextConsumers = true;

            error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
          }

          return context.Consumer;
        }
      },
      displayName: {
        get: function () {
          return context.displayName;
        },
        set: function (displayName) {
          if (!hasWarnedAboutDisplayNameOnConsumer) {
            warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);

            hasWarnedAboutDisplayNameOnConsumer = true;
          }
        }
      }
    }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty

    context.Consumer = Consumer;
  }

  {
    context._currentRenderer = null;
    context._currentRenderer2 = null;
  }

  return context;
}

var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;

function lazyInitializer(payload) {
  if (payload._status === Uninitialized) {
    var ctor = payload._result;
    var thenable = ctor(); // Transition to the next state.
    // This might throw either because it's missing or throws. If so, we treat it
    // as still uninitialized and try again next time. Which is the same as what
    // happens if the ctor or any wrappers processing the ctor throws. This might
    // end up fixing it if the resolution was a concurrency bug.

    thenable.then(function (moduleObject) {
      if (payload._status === Pending || payload._status === Uninitialized) {
        // Transition to the next state.
        var resolved = payload;
        resolved._status = Resolved;
        resolved._result = moduleObject;
      }
    }, function (error) {
      if (payload._status === Pending || payload._status === Uninitialized) {
        // Transition to the next state.
        var rejected = payload;
        rejected._status = Rejected;
        rejected._result = error;
      }
    });

    if (payload._status === Uninitialized) {
      // In case, we're still uninitialized, then we're waiting for the thenable
      // to resolve. Set it as pending in the meantime.
      var pending = payload;
      pending._status = Pending;
      pending._result = thenable;
    }
  }

  if (payload._status === Resolved) {
    var moduleObject = payload._result;

    {
      if (moduleObject === undefined) {
        error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + // Break up imports to avoid accidentally parsing them as dependencies.
        'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
      }
    }

    {
      if (!('default' in moduleObject)) {
        error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + // Break up imports to avoid accidentally parsing them as dependencies.
        'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
      }
    }

    return moduleObject.default;
  } else {
    throw payload._result;
  }
}

function lazy(ctor) {
  var payload = {
    // We use these fields to store the result.
    _status: Uninitialized,
    _result: ctor
  };
  var lazyType = {
    $$typeof: REACT_LAZY_TYPE,
    _payload: payload,
    _init: lazyInitializer
  };

  {
    // In production, this would just set it on the object.
    var defaultProps;
    var propTypes; // $FlowFixMe

    Object.defineProperties(lazyType, {
      defaultProps: {
        configurable: true,
        get: function () {
          return defaultProps;
        },
        set: function (newDefaultProps) {
          error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');

          defaultProps = newDefaultProps; // Match production behavior more closely:
          // $FlowFixMe

          Object.defineProperty(lazyType, 'defaultProps', {
            enumerable: true
          });
        }
      },
      propTypes: {
        configurable: true,
        get: function () {
          return propTypes;
        },
        set: function (newPropTypes) {
          error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');

          propTypes = newPropTypes; // Match production behavior more closely:
          // $FlowFixMe

          Object.defineProperty(lazyType, 'propTypes', {
            enumerable: true
          });
        }
      }
    });
  }

  return lazyType;
}

function forwardRef(render) {
  {
    if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
      error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
    } else if (typeof render !== 'function') {
      error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
    } else {
      if (render.length !== 0 && render.length !== 2) {
        error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
      }
    }

    if (render != null) {
      if (render.defaultProps != null || render.propTypes != null) {
        error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
      }
    }
  }

  var elementType = {
    $$typeof: REACT_FORWARD_REF_TYPE,
    render: render
  };

  {
    var ownName;
    Object.defineProperty(elementType, 'displayName', {
      enumerable: false,
      configurable: true,
      get: function () {
        return ownName;
      },
      set: function (name) {
        ownName = name; // The inner component shouldn't inherit this display name in most cases,
        // because the component may be used elsewhere.
        // But it's nice for anonymous functions to inherit the name,
        // so that our component-stack generation logic will display their frames.
        // An anonymous function generally suggests a pattern like:
        //   React.forwardRef((props, ref) => {...});
        // This kind of inner function is not used elsewhere so the side effect is okay.

        if (!render.name && !render.displayName) {
          render.displayName = name;
        }
      }
    });
  }

  return elementType;
}

var REACT_MODULE_REFERENCE;

{
  REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}

function isValidElementType(type) {
  if (typeof type === 'string' || typeof type === 'function') {
    return true;
  } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).


  if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing  || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden  || type === REACT_OFFSCREEN_TYPE || enableScopeAPI  || enableCacheElement  || enableTransitionTracing ) {
    return true;
  }

  if (typeof type === 'object' && type !== null) {
    if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
    // types supported by any Flight configuration anywhere since
    // we don't know which Flight build this will end up being used
    // with.
    type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
      return true;
    }
  }

  return false;
}

function memo(type, compare) {
  {
    if (!isValidElementType(type)) {
      error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
    }
  }

  var elementType = {
    $$typeof: REACT_MEMO_TYPE,
    type: type,
    compare: compare === undefined ? null : compare
  };

  {
    var ownName;
    Object.defineProperty(elementType, 'displayName', {
      enumerable: false,
      configurable: true,
      get: function () {
        return ownName;
      },
      set: function (name) {
        ownName = name; // The inner component shouldn't inherit this display name in most cases,
        // because the component may be used elsewhere.
        // But it's nice for anonymous functions to inherit the name,
        // so that our component-stack generation logic will display their frames.
        // An anonymous function generally suggests a pattern like:
        //   React.memo((props) => {...});
        // This kind of inner function is not used elsewhere so the side effect is okay.

        if (!type.name && !type.displayName) {
          type.displayName = name;
        }
      }
    });
  }

  return elementType;
}

function resolveDispatcher() {
  var dispatcher = ReactCurrentDispatcher.current;

  {
    if (dispatcher === null) {
      error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
    }
  } // Will result in a null access error if accessed outside render phase. We
  // intentionally don't throw our own error because this is in a hot path.
  // Also helps ensure this is inlined.


  return dispatcher;
}
function useContext(Context) {
  var dispatcher = resolveDispatcher();

  {
    // TODO: add a more generic warning for invalid values.
    if (Context._context !== undefined) {
      var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
      // and nobody should be using this in existing code.

      if (realContext.Consumer === Context) {
        error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
      } else if (realContext.Provider === Context) {
        error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
      }
    }
  }

  return dispatcher.useContext(Context);
}
function useState(initialState) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useEffect(create, deps);
}
function useInsertionEffect(create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useInsertionEffect(create, deps);
}
function useLayoutEffect(create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
  {
    var dispatcher = resolveDispatcher();
    return dispatcher.useDebugValue(value, formatterFn);
  }
}
function useTransition() {
  var dispatcher = resolveDispatcher();
  return dispatcher.useTransition();
}
function useDeferredValue(value) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useDeferredValue(value);
}
function useId() {
  var dispatcher = resolveDispatcher();
  return dispatcher.useId();
}
function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher$1.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher$1.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame$1.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

function setCurrentlyValidatingElement$1(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      setExtraStackFrame(stack);
    } else {
      setExtraStackFrame(null);
    }
  }
}

var propTypesMisspellWarningShown;

{
  propTypesMisspellWarningShown = false;
}

function getDeclarationErrorAddendum() {
  if (ReactCurrentOwner.current) {
    var name = getComponentNameFromType(ReactCurrentOwner.current.type);

    if (name) {
      return '\n\nCheck the render method of `' + name + '`.';
    }
  }

  return '';
}

function getSourceInfoErrorAddendum(source) {
  if (source !== undefined) {
    var fileName = source.fileName.replace(/^.*[\\\/]/, '');
    var lineNumber = source.lineNumber;
    return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
  }

  return '';
}

function getSourceInfoErrorAddendumForProps(elementProps) {
  if (elementProps !== null && elementProps !== undefined) {
    return getSourceInfoErrorAddendum(elementProps.__source);
  }

  return '';
}
/**
 * Warn if there's no key explicitly set on dynamic arrays of children or
 * object keys are not valid. This allows us to keep track of children between
 * updates.
 */


var ownerHasKeyUseWarning = {};

function getCurrentComponentErrorInfo(parentType) {
  var info = getDeclarationErrorAddendum();

  if (!info) {
    var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;

    if (parentName) {
      info = "\n\nCheck the top-level render call using <" + parentName + ">.";
    }
  }

  return info;
}
/**
 * Warn if the element doesn't have an explicit key assigned to it.
 * This element is in an array. The array could grow and shrink or be
 * reordered. All children that haven't already been validated are required to
 * have a "key" property assigned to it. Error statuses are cached so a warning
 * will only be shown once.
 *
 * @internal
 * @param {ReactElement} element Element that requires a key.
 * @param {*} parentType element's parent's type.
 */


function validateExplicitKey(element, parentType) {
  if (!element._store || element._store.validated || element.key != null) {
    return;
  }

  element._store.validated = true;
  var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);

  if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
    return;
  }

  ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
  // property, it may be the creator of the child that's responsible for
  // assigning it a key.

  var childOwner = '';

  if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
    // Give the component that originally created this child.
    childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
  }

  {
    setCurrentlyValidatingElement$1(element);

    error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);

    setCurrentlyValidatingElement$1(null);
  }
}
/**
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */


function validateChildKeys(node, parentType) {
  if (typeof node !== 'object') {
    return;
  }

  if (isArray(node)) {
    for (var i = 0; i < node.length; i++) {
      var child = node[i];

      if (isValidElement(child)) {
        validateExplicitKey(child, parentType);
      }
    }
  } else if (isValidElement(node)) {
    // This element was passed in a valid location.
    if (node._store) {
      node._store.validated = true;
    }
  } else if (node) {
    var iteratorFn = getIteratorFn(node);

    if (typeof iteratorFn === 'function') {
      // Entry iterators used to provide implicit keys,
      // but now we print a separate warning for them later.
      if (iteratorFn !== node.entries) {
        var iterator = iteratorFn.call(node);
        var step;

        while (!(step = iterator.next()).done) {
          if (isValidElement(step.value)) {
            validateExplicitKey(step.value, parentType);
          }
        }
      }
    }
  }
}
/**
 * Given an element, validate that its props follow the propTypes definition,
 * provided by the type.
 *
 * @param {ReactElement} element
 */


function validatePropTypes(element) {
  {
    var type = element.type;

    if (type === null || type === undefined || typeof type === 'string') {
      return;
    }

    var propTypes;

    if (typeof type === 'function') {
      propTypes = type.propTypes;
    } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
    // Inner props are checked in the reconciler.
    type.$$typeof === REACT_MEMO_TYPE)) {
      propTypes = type.propTypes;
    } else {
      return;
    }

    if (propTypes) {
      // Intentionally inside to avoid triggering lazy initializers:
      var name = getComponentNameFromType(type);
      checkPropTypes(propTypes, element.props, 'prop', name, element);
    } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
      propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

      var _name = getComponentNameFromType(type);

      error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
    }

    if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
    }
  }
}
/**
 * Given a fragment, validate that it can only be provided with fragment props
 * @param {ReactElement} fragment
 */


function validateFragmentProps(fragment) {
  {
    var keys = Object.keys(fragment.props);

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];

      if (key !== 'children' && key !== 'key') {
        setCurrentlyValidatingElement$1(fragment);

        error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);

        setCurrentlyValidatingElement$1(null);
        break;
      }
    }

    if (fragment.ref !== null) {
      setCurrentlyValidatingElement$1(fragment);

      error('Invalid attribute `ref` supplied to `React.Fragment`.');

      setCurrentlyValidatingElement$1(null);
    }
  }
}
function createElementWithValidation(type, props, children) {
  var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
  // succeed and there will likely be errors in render.

  if (!validType) {
    var info = '';

    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
    }

    var sourceInfo = getSourceInfoErrorAddendumForProps(props);

    if (sourceInfo) {
      info += sourceInfo;
    } else {
      info += getDeclarationErrorAddendum();
    }

    var typeString;

    if (type === null) {
      typeString = 'null';
    } else if (isArray(type)) {
      typeString = 'array';
    } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
      typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
      info = ' Did you accidentally export a JSX literal instead of a component?';
    } else {
      typeString = typeof type;
    }

    {
      error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
    }
  }

  var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
  // TODO: Drop this when these are no longer allowed as the type argument.

  if (element == null) {
    return element;
  } // Skip key warning if the type isn't valid since our key validation logic
  // doesn't expect a non-string/function type and can throw confusing errors.
  // We don't want exception behavior to differ between dev and prod.
  // (Rendering will throw with a helpful message and as soon as the type is
  // fixed, the key warnings will appear.)


  if (validType) {
    for (var i = 2; i < arguments.length; i++) {
      validateChildKeys(arguments[i], type);
    }
  }

  if (type === REACT_FRAGMENT_TYPE) {
    validateFragmentProps(element);
  } else {
    validatePropTypes(element);
  }

  return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
  var validatedFactory = createElementWithValidation.bind(null, type);
  validatedFactory.type = type;

  {
    if (!didWarnAboutDeprecatedCreateFactory) {
      didWarnAboutDeprecatedCreateFactory = true;

      warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
    } // Legacy hook: remove it


    Object.defineProperty(validatedFactory, 'type', {
      enumerable: false,
      get: function () {
        warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');

        Object.defineProperty(this, 'type', {
          value: type
        });
        return type;
      }
    });
  }

  return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
  var newElement = cloneElement.apply(this, arguments);

  for (var i = 2; i < arguments.length; i++) {
    validateChildKeys(arguments[i], newElement.type);
  }

  validatePropTypes(newElement);
  return newElement;
}

function startTransition(scope, options) {
  var prevTransition = ReactCurrentBatchConfig.transition;
  ReactCurrentBatchConfig.transition = {};
  var currentTransition = ReactCurrentBatchConfig.transition;

  {
    ReactCurrentBatchConfig.transition._updatedFibers = new Set();
  }

  try {
    scope();
  } finally {
    ReactCurrentBatchConfig.transition = prevTransition;

    {
      if (prevTransition === null && currentTransition._updatedFibers) {
        var updatedFibersCount = currentTransition._updatedFibers.size;

        if (updatedFibersCount > 10) {
          warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
        }

        currentTransition._updatedFibers.clear();
      }
    }
  }
}

var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
  if (enqueueTaskImpl === null) {
    try {
      // read require off the module object to get around the bundlers.
      // we don't want them to detect a require and bundle a Node polyfill.
      var requireString = ('require' + Math.random()).slice(0, 7);
      var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
      // version of setImmediate, bypassing fake timers if any.

      enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
    } catch (_err) {
      // we're in a browser
      // we can't use regular timers because they may still be faked
      // so we try MessageChannel+postMessage instead
      enqueueTaskImpl = function (callback) {
        {
          if (didWarnAboutMessageChannel === false) {
            didWarnAboutMessageChannel = true;

            if (typeof MessageChannel === 'undefined') {
              error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
            }
          }
        }

        var channel = new MessageChannel();
        channel.port1.onmessage = callback;
        channel.port2.postMessage(undefined);
      };
    }
  }

  return enqueueTaskImpl(task);
}

var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
  {
    // `act` calls can be nested, so we track the depth. This represents the
    // number of `act` scopes on the stack.
    var prevActScopeDepth = actScopeDepth;
    actScopeDepth++;

    if (ReactCurrentActQueue.current === null) {
      // This is the outermost `act` scope. Initialize the queue. The reconciler
      // will detect the queue and use it instead of Scheduler.
      ReactCurrentActQueue.current = [];
    }

    var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
    var result;

    try {
      // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
      // set to `true` while the given callback is executed, not for updates
      // triggered during an async event, because this is how the legacy
      // implementation of `act` behaved.
      ReactCurrentActQueue.isBatchingLegacy = true;
      result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
      // which flushed updates immediately after the scope function exits, even
      // if it's an async function.

      if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
        var queue = ReactCurrentActQueue.current;

        if (queue !== null) {
          ReactCurrentActQueue.didScheduleLegacyUpdate = false;
          flushActQueue(queue);
        }
      }
    } catch (error) {
      popActScope(prevActScopeDepth);
      throw error;
    } finally {
      ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
    }

    if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
      var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
      // for it to resolve before exiting the current scope.

      var wasAwaited = false;
      var thenable = {
        then: function (resolve, reject) {
          wasAwaited = true;
          thenableResult.then(function (returnValue) {
            popActScope(prevActScopeDepth);

            if (actScopeDepth === 0) {
              // We've exited the outermost act scope. Recursively flush the
              // queue until there's no remaining work.
              recursivelyFlushAsyncActWork(returnValue, resolve, reject);
            } else {
              resolve(returnValue);
            }
          }, function (error) {
            // The callback threw an error.
            popActScope(prevActScopeDepth);
            reject(error);
          });
        }
      };

      {
        if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
          // eslint-disable-next-line no-undef
          Promise.resolve().then(function () {}).then(function () {
            if (!wasAwaited) {
              didWarnNoAwaitAct = true;

              error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
            }
          });
        }
      }

      return thenable;
    } else {
      var returnValue = result; // The callback is not an async function. Exit the current scope
      // immediately, without awaiting.

      popActScope(prevActScopeDepth);

      if (actScopeDepth === 0) {
        // Exiting the outermost act scope. Flush the queue.
        var _queue = ReactCurrentActQueue.current;

        if (_queue !== null) {
          flushActQueue(_queue);
          ReactCurrentActQueue.current = null;
        } // Return a thenable. If the user awaits it, we'll flush again in
        // case additional work was scheduled by a microtask.


        var _thenable = {
          then: function (resolve, reject) {
            // Confirm we haven't re-entered another `act` scope, in case
            // the user does something weird like await the thenable
            // multiple times.
            if (ReactCurrentActQueue.current === null) {
              // Recursively flush the queue until there's no remaining work.
              ReactCurrentActQueue.current = [];
              recursivelyFlushAsyncActWork(returnValue, resolve, reject);
            } else {
              resolve(returnValue);
            }
          }
        };
        return _thenable;
      } else {
        // Since we're inside a nested `act` scope, the returned thenable
        // immediately resolves. The outer scope will flush the queue.
        var _thenable2 = {
          then: function (resolve, reject) {
            resolve(returnValue);
          }
        };
        return _thenable2;
      }
    }
  }
}

function popActScope(prevActScopeDepth) {
  {
    if (prevActScopeDepth !== actScopeDepth - 1) {
      error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
    }

    actScopeDepth = prevActScopeDepth;
  }
}

function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
  {
    var queue = ReactCurrentActQueue.current;

    if (queue !== null) {
      try {
        flushActQueue(queue);
        enqueueTask(function () {
          if (queue.length === 0) {
            // No additional work was scheduled. Finish.
            ReactCurrentActQueue.current = null;
            resolve(returnValue);
          } else {
            // Keep flushing work until there's none left.
            recursivelyFlushAsyncActWork(returnValue, resolve, reject);
          }
        });
      } catch (error) {
        reject(error);
      }
    } else {
      resolve(returnValue);
    }
  }
}

var isFlushing = false;

function flushActQueue(queue) {
  {
    if (!isFlushing) {
      // Prevent re-entrance.
      isFlushing = true;
      var i = 0;

      try {
        for (; i < queue.length; i++) {
          var callback = queue[i];

          do {
            callback = callback(true);
          } while (callback !== null);
        }

        queue.length = 0;
      } catch (error) {
        // If something throws, leave the remaining callbacks on the queue.
        queue = queue.slice(i + 1);
        throw error;
      } finally {
        isFlushing = false;
      }
    }
  }
}

var createElement$1 =  createElementWithValidation ;
var cloneElement$1 =  cloneElementWithValidation ;
var createFactory =  createFactoryWithValidation ;
var Children = {
  map: mapChildren,
  forEach: forEachChildren,
  count: countChildren,
  toArray: toArray,
  only: onlyChild
};

exports.Children = Children;
exports.Component = Component;
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.Profiler = REACT_PROFILER_TYPE;
exports.PureComponent = PureComponent;
exports.StrictMode = REACT_STRICT_MODE_TYPE;
exports.Suspense = REACT_SUSPENSE_TYPE;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
exports.act = act;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useId = useId;
exports.useImperativeHandle = useImperativeHandle;
exports.useInsertionEffect = useInsertionEffect;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useSyncExternalStore = useSyncExternalStore;
exports.useTransition = useTransition;
exports.version = ReactVersion;
          /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
        
  })();
}
/**
 * @license React
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return"function"===typeof a?a:null}
var B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};
E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;
H.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};
function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return{$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
function N(a,b){return{$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return"object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return"object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case l:case n:h=!0}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c)}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}
var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};function X(){throw Error("act(...) is not supported in production builds of React.");}
exports.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments)},e)},count:function(a){var b=0;S(a,function(){b++});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};exports.Component=E;exports.Fragment=p;exports.Profiler=r;exports.PureComponent=G;exports.StrictMode=q;exports.Suspense=w;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;exports.act=X;
exports.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};exports.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};
exports.forwardRef=function(a){return{$$typeof:v,render:a}};exports.isValidElement=O;exports.lazy=function(a){return{$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};exports.memo=function(a,b){return{$$typeof:x,type:a,compare:void 0===b?null:b}};exports.startTransition=function(a){var b=V.transition;V.transition={};try{a()}finally{V.transition=b}};exports.unstable_act=X;exports.useCallback=function(a,b){return U.current.useCallback(a,b)};exports.useContext=function(a){return U.current.useContext(a)};
exports.useDebugValue=function(){};exports.useDeferredValue=function(a){return U.current.useDeferredValue(a)};exports.useEffect=function(a,b){return U.current.useEffect(a,b)};exports.useId=function(){return U.current.useId()};exports.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};exports.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};exports.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};
exports.useMemo=function(a,b){return U.current.useMemo(a,b)};exports.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};exports.useRef=function(a){return U.current.useRef(a)};exports.useState=function(a){return U.current.useState(a)};exports.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};exports.useTransition=function(){return U.current.useTransition()};exports.version="18.3.1";
/**
 * @license React
 * react.shared-subset.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('This entry point is not yet supported outside of experimental channels');
  })();
}
/**
 * @license React
 * react.shared-subset.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';throw Error("This entry point is not yet supported outside of experimental channels");
MIT License

Copyright (c) Facebook, Inc. and its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

var m = require('react-dom');
if (process.env.NODE_ENV === 'production') {
  exports.createRoot = m.createRoot;
  exports.hydrateRoot = m.hydrateRoot;
} else {
  var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  exports.createRoot = function(c, o) {
    i.usingClientEntryPoint = true;
    try {
      return m.createRoot(c, o);
    } finally {
      i.usingClientEntryPoint = false;
    }
  };
  exports.hydrateRoot = function(c, h, o) {
    i.usingClientEntryPoint = true;
    try {
      return m.hydrateRoot(c, h, o);
    } finally {
      i.usingClientEntryPoint = false;
    }
  };
}
'use strict';

function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (process.env.NODE_ENV !== 'production') {
    // This branch is unreachable because this function is only called
    // in production, but the condition is true only in development.
    // Therefore if the branch is still here, dead code elimination wasn't
    // properly applied.
    // Don't change the message. React DevTools relies on it. Also make sure
    // this message doesn't occur elsewhere in this function, or it will cause
    // a false positive.
    throw new Error('^_^');
  }
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (process.env.NODE_ENV === 'production') {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = require('./cjs/react-dom.production.min.js');
} else {
  module.exports = require('./cjs/react-dom.development.js');
}
{
  "name": "react-dom",
  "version": "18.3.1",
  "description": "React package for working with the DOM.",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/facebook/react.git",
    "directory": "packages/react-dom"
  },
  "license": "MIT",
  "homepage": "https://reactjs.org/",
  "dependencies": {
    "loose-envify": "^1.1.0",
    "scheduler": "^0.23.2"
  },
  "peerDependencies": {
    "react": "^18.3.1"
  },
  "files": [
    "LICENSE",
    "README.md",
    "index.js",
    "client.js",
    "profiling.js",
    "server.js",
    "server.browser.js",
    "server.node.js",
    "test-utils.js",
    "cjs/",
    "umd/"
  ],
  "exports": {
    ".": "./index.js",
    "./client": "./client.js",
    "./server": {
      "deno": "./server.browser.js",
      "worker": "./server.browser.js",
      "browser": "./server.browser.js",
      "default": "./server.node.js"
    },
    "./server.browser": "./server.browser.js",
    "./server.node": "./server.node.js",
    "./profiling": "./profiling.js",
    "./test-utils": "./test-utils.js",
    "./package.json": "./package.json"
  },
  "browser": {
    "./server.js": "./server.browser.js"
  },
  "browserify": {
    "transform": [
      "loose-envify"
    ]
  }
}'use strict';

function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (process.env.NODE_ENV !== 'production') {
    // This branch is unreachable because this function is only called
    // in production, but the condition is true only in development.
    // Therefore if the branch is still here, dead code elimination wasn't
    // properly applied.
    // Don't change the message. React DevTools relies on it. Also make sure
    // this message doesn't occur elsewhere in this function, or it will cause
    // a false positive.
    throw new Error('^_^');
  }
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (process.env.NODE_ENV === 'production') {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = require('./cjs/react-dom.profiling.min.js');
} else {
  module.exports = require('./cjs/react-dom.development.js');
}
'use strict';

var l, s;
if (process.env.NODE_ENV === 'production') {
  l = require('./cjs/react-dom-server-legacy.browser.production.min.js');
  s = require('./cjs/react-dom-server.browser.production.min.js');
} else {
  l = require('./cjs/react-dom-server-legacy.browser.development.js');
  s = require('./cjs/react-dom-server.browser.development.js');
}

exports.version = l.version;
exports.renderToString = l.renderToString;
exports.renderToStaticMarkup = l.renderToStaticMarkup;
exports.renderToNodeStream = l.renderToNodeStream;
exports.renderToStaticNodeStream = l.renderToStaticNodeStream;
exports.renderToReadableStream = s.renderToReadableStream;
'use strict';

module.exports = require('./server.node');
'use strict';

var l, s;
if (process.env.NODE_ENV === 'production') {
  l = require('./cjs/react-dom-server-legacy.node.production.min.js');
  s = require('./cjs/react-dom-server.node.production.min.js');
} else {
  l = require('./cjs/react-dom-server-legacy.node.development.js');
  s = require('./cjs/react-dom-server.node.development.js');
}

exports.version = l.version;
exports.renderToString = l.renderToString;
exports.renderToStaticMarkup = l.renderToStaticMarkup;
exports.renderToNodeStream = l.renderToNodeStream;
exports.renderToStaticNodeStream = l.renderToStaticNodeStream;
exports.renderToPipeableStream = s.renderToPipeableStream;
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react-dom-test-utils.production.min.js');
} else {
  module.exports = require('./cjs/react-dom-test-utils.development.js');
}
/**
 * @license React
 * react-dom-server-legacy.browser.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
  (global = global || self, factory(global.ReactDOMServer = {}, global.React));
}(this, (function (exports, React) { 'use strict';

  var ReactVersion = '18.3.1';

  var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

  // by calls to these methods by a Babel plugin.
  //
  // In PROD (or in packages without access to React internals),
  // they are left as they are instead.

  function warn(format) {
    {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }
  }
  function error(format) {
    {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }
  }

  function printWarning(level, format, args) {
    // When changing this logic, you might want to also
    // update consoleWithStackDev.www.js as well.
    {
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var stack = ReactDebugCurrentFrame.getStackAddendum();

      if (stack !== '') {
        format += '%s';
        args = args.concat([stack]);
      } // eslint-disable-next-line react-internal/safe-string-coercion


      var argsWithFormat = args.map(function (item) {
        return String(item);
      }); // Careful: RN currently depends on this prefix

      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
      // breaks IE9: https://github.com/facebook/react/issues/13610
      // eslint-disable-next-line react-internal/no-production-logging

      Function.prototype.apply.call(console[level], console, argsWithFormat);
    }
  }

  function scheduleWork(callback) {
    callback();
  }
  function beginWriting(destination) {}
  function writeChunk(destination, chunk) {
    writeChunkAndReturn(destination, chunk);
  }
  function writeChunkAndReturn(destination, chunk) {
    return destination.push(chunk);
  }
  function completeWriting(destination) {}
  function close(destination) {
    destination.push(null);
  }
  function stringToChunk(content) {
    return content;
  }
  function stringToPrecomputedChunk(content) {
    return content;
  }
  function closeWithError(destination, error) {
    // $FlowFixMe: This is an Error object or the destination accepts other types.
    destination.destroy(error);
  }

  /*
   * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
   * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
   *
   * The functions in this module will throw an easier-to-understand,
   * easier-to-debug exception with a clear errors message message explaining the
   * problem. (Instead of a confusing exception thrown inside the implementation
   * of the `value` object).
   */
  // $FlowFixMe only called in DEV, so void return is not possible.
  function typeName(value) {
    {
      // toStringTag is needed for namespaced types like Temporal.Instant
      var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
      var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
      return type;
    }
  } // $FlowFixMe only called in DEV, so void return is not possible.


  function willCoercionThrow(value) {
    {
      try {
        testStringCoercion(value);
        return false;
      } catch (e) {
        return true;
      }
    }
  }

  function testStringCoercion(value) {
    // If you ended up here by following an exception call stack, here's what's
    // happened: you supplied an object or symbol value to React (as a prop, key,
    // DOM attribute, CSS property, string ref, etc.) and when React tried to
    // coerce it to a string using `'' + value`, an exception was thrown.
    //
    // The most common types that will cause this exception are `Symbol` instances
    // and Temporal objects like `Temporal.Instant`. But any object that has a
    // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
    // exception. (Library authors do this to prevent users from using built-in
    // numeric operators like `+` or comparison operators like `>=` because custom
    // methods are needed to perform accurate arithmetic or comparison.)
    //
    // To fix the problem, coerce this object or symbol value to a string before
    // passing it to React. The most reliable way is usually `String(value)`.
    //
    // To find which value is throwing, check the browser or debugger console.
    // Before this exception was thrown, there should be `console.error` output
    // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
    // problem and how that type was used: key, atrribute, input value prop, etc.
    // In most cases, this console output also shows the component and its
    // ancestor components where the exception happened.
    //
    // eslint-disable-next-line react-internal/safe-string-coercion
    return '' + value;
  }

  function checkAttributeStringCoercion(value, attributeName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkCSSPropertyStringCoercion(value, propName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkHtmlStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }

  var hasOwnProperty = Object.prototype.hasOwnProperty;

  // A reserved attribute.
  // It is handled by React separately and shouldn't be written to the DOM.
  var RESERVED = 0; // A simple string attribute.
  // Attributes that aren't in the filter are presumed to have this type.

  var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
  // "enumerated" attributes with "true" and "false" as possible values.
  // When true, it should be set to a "true" string.
  // When false, it should be set to a "false" string.

  var BOOLEANISH_STRING = 2; // A real boolean attribute.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.

  var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.
  // For any other value, should be present with that value.

  var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
  // When falsy, it should be removed.

  var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
  // When falsy, it should be removed.

  var POSITIVE_NUMERIC = 6;

  /* eslint-disable max-len */
  var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  /* eslint-enable max-len */

  var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
  var illegalAttributeNameCache = {};
  var validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
      return true;
    }

    if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
      return false;
    }

    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
      validatedAttributeNameCache[attributeName] = true;
      return true;
    }

    illegalAttributeNameCache[attributeName] = true;

    {
      error('Invalid attribute name: `%s`', attributeName);
    }

    return false;
  }
  function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
    if (propertyInfo !== null && propertyInfo.type === RESERVED) {
      return false;
    }

    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return true;

      case 'boolean':
        {
          if (isCustomComponentTag) {
            return false;
          }

          if (propertyInfo !== null) {
            return !propertyInfo.acceptsBooleans;
          } else {
            var prefix = name.toLowerCase().slice(0, 5);
            return prefix !== 'data-' && prefix !== 'aria-';
          }
        }

      default:
        return false;
    }
  }
  function getPropertyInfo(name) {
    return properties.hasOwnProperty(name) ? properties[name] : null;
  }

  function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
    this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
    this.attributeName = attributeName;
    this.attributeNamespace = attributeNamespace;
    this.mustUseProperty = mustUseProperty;
    this.propertyName = name;
    this.type = type;
    this.sanitizeURL = sanitizeURL;
    this.removeEmptyString = removeEmptyString;
  } // When adding attributes to this list, be sure to also add them to
  // the `possibleStandardNames` module to ensure casing and incorrect
  // name warnings.


  var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

  var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
  // elements (not just inputs). Now that ReactDOMInput assigns to the
  // defaultValue property -- do we need this?
  'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

  reservedProps.forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // A few React string attributes have a different name.
  // This is a mapping from React prop names to the attribute names.

  [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
    var name = _ref[0],
        attributeName = _ref[1];
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" HTML attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).

  ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" SVG attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).
  // Since these are SVG attributes, their attribute names are case-sensitive.

  ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML boolean attributes.

  ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
  // on the client side because the browsers are inconsistent. Instead we call focus().
  'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
  'itemScope'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are the few React props that we set as DOM properties
  // rather than attributes. These are all booleans.

  ['checked', // Note: `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`. We have special logic for handling this.
  'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that are "overloaded booleans": they behave like
  // booleans, but can also accept a string value.

  ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be positive numbers.

  ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be numbers.

  ['rowSpan', 'start'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  });
  var CAMELIZE = /[\-\:]([a-z])/g;

  var capitalize = function (token) {
    return token[1].toUpperCase();
  }; // This is a list of all SVG attributes that need special casing, namespacing,
  // or boolean value assignment. Regular attributes that just accept strings
  // and have the same names are omitted, just like in the HTML attribute filter.
  // Some of these attributes can be hard to find. This list was created by
  // scraping the MDN documentation.


  ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // String SVG attributes with the xlink namespace.

  ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
    false);
  }); // String SVG attributes with the xml namespace.

  ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
    false);
  }); // These attribute exists both in HTML and SVG.
  // The attribute name is case-sensitive in SVG so we can't just use
  // the React name like we do for attributes that exist only in HTML.

  ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These attributes accept URLs. These must not allow javascript: URLS.
  // These will also need to accept Trusted Types object in the future.

  var xlinkHref = 'xlinkHref';
  properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
  'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
  false);
  ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    true, // sanitizeURL
    true);
  });

  /**
   * CSS properties which accept numbers but are not in units of "px".
   */
  var isUnitlessNumber = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    // SVG-related properties
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  };
  /**
   * @param {string} prefix vendor-specific prefix, eg: Webkit
   * @param {string} key style name, eg: transitionDuration
   * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
   * WebkitTransitionDuration
   */

  function prefixKey(prefix, key) {
    return prefix + key.charAt(0).toUpperCase() + key.substring(1);
  }
  /**
   * Support style names that may come passed in prefixed by adding permutations
   * of vendor prefixes.
   */


  var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
  // infinite loop, because it iterates over the newly added props too.

  Object.keys(isUnitlessNumber).forEach(function (prop) {
    prefixes.forEach(function (prefix) {
      isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
    });
  });

  var hasReadOnlyValue = {
    button: true,
    checkbox: true,
    image: true,
    hidden: true,
    radio: true,
    reset: true,
    submit: true
  };
  function checkControlledValueProps(tagName, props) {
    {
      if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
        error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }

      if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
        error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }
    }
  }

  function isCustomComponent(tagName, props) {
    if (tagName.indexOf('-') === -1) {
      return typeof props.is === 'string';
    }

    switch (tagName) {
      // These are reserved SVG and MathML elements.
      // We don't mind this list too much because we expect it to never grow.
      // The alternative is to track the namespace in a few places which is convoluted.
      // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
      case 'annotation-xml':
      case 'color-profile':
      case 'font-face':
      case 'font-face-src':
      case 'font-face-uri':
      case 'font-face-format':
      case 'font-face-name':
      case 'missing-glyph':
        return false;

      default:
        return true;
    }
  }

  var ariaProperties = {
    'aria-current': 0,
    // state
    'aria-description': 0,
    'aria-details': 0,
    'aria-disabled': 0,
    // state
    'aria-hidden': 0,
    // state
    'aria-invalid': 0,
    // state
    'aria-keyshortcuts': 0,
    'aria-label': 0,
    'aria-roledescription': 0,
    // Widget Attributes
    'aria-autocomplete': 0,
    'aria-checked': 0,
    'aria-expanded': 0,
    'aria-haspopup': 0,
    'aria-level': 0,
    'aria-modal': 0,
    'aria-multiline': 0,
    'aria-multiselectable': 0,
    'aria-orientation': 0,
    'aria-placeholder': 0,
    'aria-pressed': 0,
    'aria-readonly': 0,
    'aria-required': 0,
    'aria-selected': 0,
    'aria-sort': 0,
    'aria-valuemax': 0,
    'aria-valuemin': 0,
    'aria-valuenow': 0,
    'aria-valuetext': 0,
    // Live Region Attributes
    'aria-atomic': 0,
    'aria-busy': 0,
    'aria-live': 0,
    'aria-relevant': 0,
    // Drag-and-Drop Attributes
    'aria-dropeffect': 0,
    'aria-grabbed': 0,
    // Relationship Attributes
    'aria-activedescendant': 0,
    'aria-colcount': 0,
    'aria-colindex': 0,
    'aria-colspan': 0,
    'aria-controls': 0,
    'aria-describedby': 0,
    'aria-errormessage': 0,
    'aria-flowto': 0,
    'aria-labelledby': 0,
    'aria-owns': 0,
    'aria-posinset': 0,
    'aria-rowcount': 0,
    'aria-rowindex': 0,
    'aria-rowspan': 0,
    'aria-setsize': 0
  };

  var warnedProperties = {};
  var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  function validateProperty(tagName, name) {
    {
      if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
        return true;
      }

      if (rARIACamel.test(name)) {
        var ariaName = 'aria-' + name.slice(4).toLowerCase();
        var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (correctName == null) {
          error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

          warnedProperties[name] = true;
          return true;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== correctName) {
          error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

          warnedProperties[name] = true;
          return true;
        }
      }

      if (rARIA.test(name)) {
        var lowerCasedName = name.toLowerCase();
        var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (standardName == null) {
          warnedProperties[name] = true;
          return false;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== standardName) {
          error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties[name] = true;
          return true;
        }
      }
    }

    return true;
  }

  function warnInvalidARIAProps(type, props) {
    {
      var invalidProps = [];

      for (var key in props) {
        var isValid = validateProperty(type, key);

        if (!isValid) {
          invalidProps.push(key);
        }
      }

      var unknownPropString = invalidProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (invalidProps.length === 1) {
        error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      } else if (invalidProps.length > 1) {
        error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      }
    }
  }

  function validateProperties(type, props) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnInvalidARIAProps(type, props);
  }

  var didWarnValueNull = false;
  function validateProperties$1(type, props) {
    {
      if (type !== 'input' && type !== 'textarea' && type !== 'select') {
        return;
      }

      if (props != null && props.value === null && !didWarnValueNull) {
        didWarnValueNull = true;

        if (type === 'select' && props.multiple) {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
        } else {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
        }
      }
    }
  }

  // When adding attributes to the HTML or SVG allowed attribute list, be sure to
  // also add them to this module to ensure casing and incorrect name
  // warnings.
  var possibleStandardNames = {
    // HTML
    accept: 'accept',
    acceptcharset: 'acceptCharset',
    'accept-charset': 'acceptCharset',
    accesskey: 'accessKey',
    action: 'action',
    allowfullscreen: 'allowFullScreen',
    alt: 'alt',
    as: 'as',
    async: 'async',
    autocapitalize: 'autoCapitalize',
    autocomplete: 'autoComplete',
    autocorrect: 'autoCorrect',
    autofocus: 'autoFocus',
    autoplay: 'autoPlay',
    autosave: 'autoSave',
    capture: 'capture',
    cellpadding: 'cellPadding',
    cellspacing: 'cellSpacing',
    challenge: 'challenge',
    charset: 'charSet',
    checked: 'checked',
    children: 'children',
    cite: 'cite',
    class: 'className',
    classid: 'classID',
    classname: 'className',
    cols: 'cols',
    colspan: 'colSpan',
    content: 'content',
    contenteditable: 'contentEditable',
    contextmenu: 'contextMenu',
    controls: 'controls',
    controlslist: 'controlsList',
    coords: 'coords',
    crossorigin: 'crossOrigin',
    dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
    data: 'data',
    datetime: 'dateTime',
    default: 'default',
    defaultchecked: 'defaultChecked',
    defaultvalue: 'defaultValue',
    defer: 'defer',
    dir: 'dir',
    disabled: 'disabled',
    disablepictureinpicture: 'disablePictureInPicture',
    disableremoteplayback: 'disableRemotePlayback',
    download: 'download',
    draggable: 'draggable',
    enctype: 'encType',
    enterkeyhint: 'enterKeyHint',
    for: 'htmlFor',
    form: 'form',
    formmethod: 'formMethod',
    formaction: 'formAction',
    formenctype: 'formEncType',
    formnovalidate: 'formNoValidate',
    formtarget: 'formTarget',
    frameborder: 'frameBorder',
    headers: 'headers',
    height: 'height',
    hidden: 'hidden',
    high: 'high',
    href: 'href',
    hreflang: 'hrefLang',
    htmlfor: 'htmlFor',
    httpequiv: 'httpEquiv',
    'http-equiv': 'httpEquiv',
    icon: 'icon',
    id: 'id',
    imagesizes: 'imageSizes',
    imagesrcset: 'imageSrcSet',
    innerhtml: 'innerHTML',
    inputmode: 'inputMode',
    integrity: 'integrity',
    is: 'is',
    itemid: 'itemID',
    itemprop: 'itemProp',
    itemref: 'itemRef',
    itemscope: 'itemScope',
    itemtype: 'itemType',
    keyparams: 'keyParams',
    keytype: 'keyType',
    kind: 'kind',
    label: 'label',
    lang: 'lang',
    list: 'list',
    loop: 'loop',
    low: 'low',
    manifest: 'manifest',
    marginwidth: 'marginWidth',
    marginheight: 'marginHeight',
    max: 'max',
    maxlength: 'maxLength',
    media: 'media',
    mediagroup: 'mediaGroup',
    method: 'method',
    min: 'min',
    minlength: 'minLength',
    multiple: 'multiple',
    muted: 'muted',
    name: 'name',
    nomodule: 'noModule',
    nonce: 'nonce',
    novalidate: 'noValidate',
    open: 'open',
    optimum: 'optimum',
    pattern: 'pattern',
    placeholder: 'placeholder',
    playsinline: 'playsInline',
    poster: 'poster',
    preload: 'preload',
    profile: 'profile',
    radiogroup: 'radioGroup',
    readonly: 'readOnly',
    referrerpolicy: 'referrerPolicy',
    rel: 'rel',
    required: 'required',
    reversed: 'reversed',
    role: 'role',
    rows: 'rows',
    rowspan: 'rowSpan',
    sandbox: 'sandbox',
    scope: 'scope',
    scoped: 'scoped',
    scrolling: 'scrolling',
    seamless: 'seamless',
    selected: 'selected',
    shape: 'shape',
    size: 'size',
    sizes: 'sizes',
    span: 'span',
    spellcheck: 'spellCheck',
    src: 'src',
    srcdoc: 'srcDoc',
    srclang: 'srcLang',
    srcset: 'srcSet',
    start: 'start',
    step: 'step',
    style: 'style',
    summary: 'summary',
    tabindex: 'tabIndex',
    target: 'target',
    title: 'title',
    type: 'type',
    usemap: 'useMap',
    value: 'value',
    width: 'width',
    wmode: 'wmode',
    wrap: 'wrap',
    // SVG
    about: 'about',
    accentheight: 'accentHeight',
    'accent-height': 'accentHeight',
    accumulate: 'accumulate',
    additive: 'additive',
    alignmentbaseline: 'alignmentBaseline',
    'alignment-baseline': 'alignmentBaseline',
    allowreorder: 'allowReorder',
    alphabetic: 'alphabetic',
    amplitude: 'amplitude',
    arabicform: 'arabicForm',
    'arabic-form': 'arabicForm',
    ascent: 'ascent',
    attributename: 'attributeName',
    attributetype: 'attributeType',
    autoreverse: 'autoReverse',
    azimuth: 'azimuth',
    basefrequency: 'baseFrequency',
    baselineshift: 'baselineShift',
    'baseline-shift': 'baselineShift',
    baseprofile: 'baseProfile',
    bbox: 'bbox',
    begin: 'begin',
    bias: 'bias',
    by: 'by',
    calcmode: 'calcMode',
    capheight: 'capHeight',
    'cap-height': 'capHeight',
    clip: 'clip',
    clippath: 'clipPath',
    'clip-path': 'clipPath',
    clippathunits: 'clipPathUnits',
    cliprule: 'clipRule',
    'clip-rule': 'clipRule',
    color: 'color',
    colorinterpolation: 'colorInterpolation',
    'color-interpolation': 'colorInterpolation',
    colorinterpolationfilters: 'colorInterpolationFilters',
    'color-interpolation-filters': 'colorInterpolationFilters',
    colorprofile: 'colorProfile',
    'color-profile': 'colorProfile',
    colorrendering: 'colorRendering',
    'color-rendering': 'colorRendering',
    contentscripttype: 'contentScriptType',
    contentstyletype: 'contentStyleType',
    cursor: 'cursor',
    cx: 'cx',
    cy: 'cy',
    d: 'd',
    datatype: 'datatype',
    decelerate: 'decelerate',
    descent: 'descent',
    diffuseconstant: 'diffuseConstant',
    direction: 'direction',
    display: 'display',
    divisor: 'divisor',
    dominantbaseline: 'dominantBaseline',
    'dominant-baseline': 'dominantBaseline',
    dur: 'dur',
    dx: 'dx',
    dy: 'dy',
    edgemode: 'edgeMode',
    elevation: 'elevation',
    enablebackground: 'enableBackground',
    'enable-background': 'enableBackground',
    end: 'end',
    exponent: 'exponent',
    externalresourcesrequired: 'externalResourcesRequired',
    fill: 'fill',
    fillopacity: 'fillOpacity',
    'fill-opacity': 'fillOpacity',
    fillrule: 'fillRule',
    'fill-rule': 'fillRule',
    filter: 'filter',
    filterres: 'filterRes',
    filterunits: 'filterUnits',
    floodopacity: 'floodOpacity',
    'flood-opacity': 'floodOpacity',
    floodcolor: 'floodColor',
    'flood-color': 'floodColor',
    focusable: 'focusable',
    fontfamily: 'fontFamily',
    'font-family': 'fontFamily',
    fontsize: 'fontSize',
    'font-size': 'fontSize',
    fontsizeadjust: 'fontSizeAdjust',
    'font-size-adjust': 'fontSizeAdjust',
    fontstretch: 'fontStretch',
    'font-stretch': 'fontStretch',
    fontstyle: 'fontStyle',
    'font-style': 'fontStyle',
    fontvariant: 'fontVariant',
    'font-variant': 'fontVariant',
    fontweight: 'fontWeight',
    'font-weight': 'fontWeight',
    format: 'format',
    from: 'from',
    fx: 'fx',
    fy: 'fy',
    g1: 'g1',
    g2: 'g2',
    glyphname: 'glyphName',
    'glyph-name': 'glyphName',
    glyphorientationhorizontal: 'glyphOrientationHorizontal',
    'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
    glyphorientationvertical: 'glyphOrientationVertical',
    'glyph-orientation-vertical': 'glyphOrientationVertical',
    glyphref: 'glyphRef',
    gradienttransform: 'gradientTransform',
    gradientunits: 'gradientUnits',
    hanging: 'hanging',
    horizadvx: 'horizAdvX',
    'horiz-adv-x': 'horizAdvX',
    horizoriginx: 'horizOriginX',
    'horiz-origin-x': 'horizOriginX',
    ideographic: 'ideographic',
    imagerendering: 'imageRendering',
    'image-rendering': 'imageRendering',
    in2: 'in2',
    in: 'in',
    inlist: 'inlist',
    intercept: 'intercept',
    k1: 'k1',
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
    k: 'k',
    kernelmatrix: 'kernelMatrix',
    kernelunitlength: 'kernelUnitLength',
    kerning: 'kerning',
    keypoints: 'keyPoints',
    keysplines: 'keySplines',
    keytimes: 'keyTimes',
    lengthadjust: 'lengthAdjust',
    letterspacing: 'letterSpacing',
    'letter-spacing': 'letterSpacing',
    lightingcolor: 'lightingColor',
    'lighting-color': 'lightingColor',
    limitingconeangle: 'limitingConeAngle',
    local: 'local',
    markerend: 'markerEnd',
    'marker-end': 'markerEnd',
    markerheight: 'markerHeight',
    markermid: 'markerMid',
    'marker-mid': 'markerMid',
    markerstart: 'markerStart',
    'marker-start': 'markerStart',
    markerunits: 'markerUnits',
    markerwidth: 'markerWidth',
    mask: 'mask',
    maskcontentunits: 'maskContentUnits',
    maskunits: 'maskUnits',
    mathematical: 'mathematical',
    mode: 'mode',
    numoctaves: 'numOctaves',
    offset: 'offset',
    opacity: 'opacity',
    operator: 'operator',
    order: 'order',
    orient: 'orient',
    orientation: 'orientation',
    origin: 'origin',
    overflow: 'overflow',
    overlineposition: 'overlinePosition',
    'overline-position': 'overlinePosition',
    overlinethickness: 'overlineThickness',
    'overline-thickness': 'overlineThickness',
    paintorder: 'paintOrder',
    'paint-order': 'paintOrder',
    panose1: 'panose1',
    'panose-1': 'panose1',
    pathlength: 'pathLength',
    patterncontentunits: 'patternContentUnits',
    patterntransform: 'patternTransform',
    patternunits: 'patternUnits',
    pointerevents: 'pointerEvents',
    'pointer-events': 'pointerEvents',
    points: 'points',
    pointsatx: 'pointsAtX',
    pointsaty: 'pointsAtY',
    pointsatz: 'pointsAtZ',
    prefix: 'prefix',
    preservealpha: 'preserveAlpha',
    preserveaspectratio: 'preserveAspectRatio',
    primitiveunits: 'primitiveUnits',
    property: 'property',
    r: 'r',
    radius: 'radius',
    refx: 'refX',
    refy: 'refY',
    renderingintent: 'renderingIntent',
    'rendering-intent': 'renderingIntent',
    repeatcount: 'repeatCount',
    repeatdur: 'repeatDur',
    requiredextensions: 'requiredExtensions',
    requiredfeatures: 'requiredFeatures',
    resource: 'resource',
    restart: 'restart',
    result: 'result',
    results: 'results',
    rotate: 'rotate',
    rx: 'rx',
    ry: 'ry',
    scale: 'scale',
    security: 'security',
    seed: 'seed',
    shaperendering: 'shapeRendering',
    'shape-rendering': 'shapeRendering',
    slope: 'slope',
    spacing: 'spacing',
    specularconstant: 'specularConstant',
    specularexponent: 'specularExponent',
    speed: 'speed',
    spreadmethod: 'spreadMethod',
    startoffset: 'startOffset',
    stddeviation: 'stdDeviation',
    stemh: 'stemh',
    stemv: 'stemv',
    stitchtiles: 'stitchTiles',
    stopcolor: 'stopColor',
    'stop-color': 'stopColor',
    stopopacity: 'stopOpacity',
    'stop-opacity': 'stopOpacity',
    strikethroughposition: 'strikethroughPosition',
    'strikethrough-position': 'strikethroughPosition',
    strikethroughthickness: 'strikethroughThickness',
    'strikethrough-thickness': 'strikethroughThickness',
    string: 'string',
    stroke: 'stroke',
    strokedasharray: 'strokeDasharray',
    'stroke-dasharray': 'strokeDasharray',
    strokedashoffset: 'strokeDashoffset',
    'stroke-dashoffset': 'strokeDashoffset',
    strokelinecap: 'strokeLinecap',
    'stroke-linecap': 'strokeLinecap',
    strokelinejoin: 'strokeLinejoin',
    'stroke-linejoin': 'strokeLinejoin',
    strokemiterlimit: 'strokeMiterlimit',
    'stroke-miterlimit': 'strokeMiterlimit',
    strokewidth: 'strokeWidth',
    'stroke-width': 'strokeWidth',
    strokeopacity: 'strokeOpacity',
    'stroke-opacity': 'strokeOpacity',
    suppresscontenteditablewarning: 'suppressContentEditableWarning',
    suppresshydrationwarning: 'suppressHydrationWarning',
    surfacescale: 'surfaceScale',
    systemlanguage: 'systemLanguage',
    tablevalues: 'tableValues',
    targetx: 'targetX',
    targety: 'targetY',
    textanchor: 'textAnchor',
    'text-anchor': 'textAnchor',
    textdecoration: 'textDecoration',
    'text-decoration': 'textDecoration',
    textlength: 'textLength',
    textrendering: 'textRendering',
    'text-rendering': 'textRendering',
    to: 'to',
    transform: 'transform',
    typeof: 'typeof',
    u1: 'u1',
    u2: 'u2',
    underlineposition: 'underlinePosition',
    'underline-position': 'underlinePosition',
    underlinethickness: 'underlineThickness',
    'underline-thickness': 'underlineThickness',
    unicode: 'unicode',
    unicodebidi: 'unicodeBidi',
    'unicode-bidi': 'unicodeBidi',
    unicoderange: 'unicodeRange',
    'unicode-range': 'unicodeRange',
    unitsperem: 'unitsPerEm',
    'units-per-em': 'unitsPerEm',
    unselectable: 'unselectable',
    valphabetic: 'vAlphabetic',
    'v-alphabetic': 'vAlphabetic',
    values: 'values',
    vectoreffect: 'vectorEffect',
    'vector-effect': 'vectorEffect',
    version: 'version',
    vertadvy: 'vertAdvY',
    'vert-adv-y': 'vertAdvY',
    vertoriginx: 'vertOriginX',
    'vert-origin-x': 'vertOriginX',
    vertoriginy: 'vertOriginY',
    'vert-origin-y': 'vertOriginY',
    vhanging: 'vHanging',
    'v-hanging': 'vHanging',
    videographic: 'vIdeographic',
    'v-ideographic': 'vIdeographic',
    viewbox: 'viewBox',
    viewtarget: 'viewTarget',
    visibility: 'visibility',
    vmathematical: 'vMathematical',
    'v-mathematical': 'vMathematical',
    vocab: 'vocab',
    widths: 'widths',
    wordspacing: 'wordSpacing',
    'word-spacing': 'wordSpacing',
    writingmode: 'writingMode',
    'writing-mode': 'writingMode',
    x1: 'x1',
    x2: 'x2',
    x: 'x',
    xchannelselector: 'xChannelSelector',
    xheight: 'xHeight',
    'x-height': 'xHeight',
    xlinkactuate: 'xlinkActuate',
    'xlink:actuate': 'xlinkActuate',
    xlinkarcrole: 'xlinkArcrole',
    'xlink:arcrole': 'xlinkArcrole',
    xlinkhref: 'xlinkHref',
    'xlink:href': 'xlinkHref',
    xlinkrole: 'xlinkRole',
    'xlink:role': 'xlinkRole',
    xlinkshow: 'xlinkShow',
    'xlink:show': 'xlinkShow',
    xlinktitle: 'xlinkTitle',
    'xlink:title': 'xlinkTitle',
    xlinktype: 'xlinkType',
    'xlink:type': 'xlinkType',
    xmlbase: 'xmlBase',
    'xml:base': 'xmlBase',
    xmllang: 'xmlLang',
    'xml:lang': 'xmlLang',
    xmlns: 'xmlns',
    'xml:space': 'xmlSpace',
    xmlnsxlink: 'xmlnsXlink',
    'xmlns:xlink': 'xmlnsXlink',
    xmlspace: 'xmlSpace',
    y1: 'y1',
    y2: 'y2',
    y: 'y',
    ychannelselector: 'yChannelSelector',
    z: 'z',
    zoomandpan: 'zoomAndPan'
  };

  var validateProperty$1 = function () {};

  {
    var warnedProperties$1 = {};
    var EVENT_NAME_REGEX = /^on./;
    var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
    var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
    var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

    validateProperty$1 = function (tagName, name, value, eventRegistry) {
      if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
        return true;
      }

      var lowerCasedName = name.toLowerCase();

      if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
        error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

        warnedProperties$1[name] = true;
        return true;
      } // We can't rely on the event system being injected on the server.


      if (eventRegistry != null) {
        var registrationNameDependencies = eventRegistry.registrationNameDependencies,
            possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

        if (registrationNameDependencies.hasOwnProperty(name)) {
          return true;
        }

        var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

        if (registrationName != null) {
          error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

          warnedProperties$1[name] = true;
          return true;
        }

        if (EVENT_NAME_REGEX.test(name)) {
          error('Unknown event handler property `%s`. It will be ignored.', name);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (EVENT_NAME_REGEX.test(name)) {
        // If no event plugins have been injected, we are in a server environment.
        // So we can't tell if the event name is correct for sure, but we can filter
        // out known bad ones like `onclick`. We can't suggest a specific replacement though.
        if (INVALID_EVENT_NAME_REGEX.test(name)) {
          error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Let the ARIA attribute hook validate ARIA attributes


      if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
        return true;
      }

      if (lowerCasedName === 'innerhtml') {
        error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'aria') {
        error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
        error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'number' && isNaN(value)) {
        error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

        warnedProperties$1[name] = true;
        return true;
      }

      var propertyInfo = getPropertyInfo(name);
      var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        var standardName = possibleStandardNames[lowerCasedName];

        if (standardName !== name) {
          error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (!isReserved && name !== lowerCasedName) {
        // Unknown attributes should have lowercase casing since that's how they
        // will be cased anyway with server rendering.
        error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        if (value) {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
        } else {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Now that we've validated casing, do not validate
      // data types for reserved props


      if (isReserved) {
        return true;
      } // Warn when a known attribute is a bad type


      if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        warnedProperties$1[name] = true;
        return false;
      } // Warn when passing the strings 'false' or 'true' into a boolean prop


      if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
        error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

        warnedProperties$1[name] = true;
        return true;
      }

      return true;
    };
  }

  var warnUnknownProperties = function (type, props, eventRegistry) {
    {
      var unknownProps = [];

      for (var key in props) {
        var isValid = validateProperty$1(type, key, props[key], eventRegistry);

        if (!isValid) {
          unknownProps.push(key);
        }
      }

      var unknownPropString = unknownProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (unknownProps.length === 1) {
        error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      } else if (unknownProps.length > 1) {
        error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      }
    }
  };

  function validateProperties$2(type, props, eventRegistry) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnUnknownProperties(type, props, eventRegistry);
  }

  var warnValidStyle = function () {};

  {
    // 'msTransform' is correct, but the other prefixes should be capitalized
    var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
    var msPattern = /^-ms-/;
    var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

    var badStyleValueWithSemicolonPattern = /;\s*$/;
    var warnedStyleNames = {};
    var warnedStyleValues = {};
    var warnedForNaNValue = false;
    var warnedForInfinityValue = false;

    var camelize = function (string) {
      return string.replace(hyphenPattern, function (_, character) {
        return character.toUpperCase();
      });
    };

    var warnHyphenatedStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
      // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
      // is converted to lowercase `ms`.
      camelize(name.replace(msPattern, 'ms-')));
    };

    var warnBadVendoredStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
    };

    var warnStyleValueWithSemicolon = function (name, value) {
      if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
        return;
      }

      warnedStyleValues[value] = true;

      error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
    };

    var warnStyleValueIsNaN = function (name, value) {
      if (warnedForNaNValue) {
        return;
      }

      warnedForNaNValue = true;

      error('`NaN` is an invalid value for the `%s` css style property.', name);
    };

    var warnStyleValueIsInfinity = function (name, value) {
      if (warnedForInfinityValue) {
        return;
      }

      warnedForInfinityValue = true;

      error('`Infinity` is an invalid value for the `%s` css style property.', name);
    };

    warnValidStyle = function (name, value) {
      if (name.indexOf('-') > -1) {
        warnHyphenatedStyleName(name);
      } else if (badVendoredStyleNamePattern.test(name)) {
        warnBadVendoredStyleName(name);
      } else if (badStyleValueWithSemicolonPattern.test(value)) {
        warnStyleValueWithSemicolon(name, value);
      }

      if (typeof value === 'number') {
        if (isNaN(value)) {
          warnStyleValueIsNaN(name, value);
        } else if (!isFinite(value)) {
          warnStyleValueIsInfinity(name, value);
        }
      }
    };
  }

  var warnValidStyle$1 = warnValidStyle;

  // code copied and modified from escape-html
  var matchHtmlRegExp = /["'&<>]/;
  /**
   * Escapes special characters and HTML entities in a given html string.
   *
   * @param  {string} string HTML string to escape for later insertion
   * @return {string}
   * @public
   */

  function escapeHtml(string) {
    {
      checkHtmlStringCoercion(string);
    }

    var str = '' + string;
    var match = matchHtmlRegExp.exec(str);

    if (!match) {
      return str;
    }

    var escape;
    var html = '';
    var index;
    var lastIndex = 0;

    for (index = match.index; index < str.length; index++) {
      switch (str.charCodeAt(index)) {
        case 34:
          // "
          escape = '&quot;';
          break;

        case 38:
          // &
          escape = '&amp;';
          break;

        case 39:
          // '
          escape = '&#x27;'; // modified from escape-html; used to be '&#39'

          break;

        case 60:
          // <
          escape = '&lt;';
          break;

        case 62:
          // >
          escape = '&gt;';
          break;

        default:
          continue;
      }

      if (lastIndex !== index) {
        html += str.substring(lastIndex, index);
      }

      lastIndex = index + 1;
      html += escape;
    }

    return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  } // end code copied and modified from escape-html

  /**
   * Escapes text to prevent scripting attacks.
   *
   * @param {*} text Text value to escape.
   * @return {string} An escaped string.
   */


  function escapeTextForBrowser(text) {
    if (typeof text === 'boolean' || typeof text === 'number') {
      // this shortcircuit helps perf for types that we know will never have
      // special characters, especially given that this function is used often
      // for numeric dom ids.
      return '' + text;
    }

    return escapeHtml(text);
  }

  var uppercasePattern = /([A-Z])/g;
  var msPattern$1 = /^ms-/;
  /**
   * Hyphenates a camelcased CSS property name, for example:
   *
   *   > hyphenateStyleName('backgroundColor')
   *   < "background-color"
   *   > hyphenateStyleName('MozTransition')
   *   < "-moz-transition"
   *   > hyphenateStyleName('msTransition')
   *   < "-ms-transition"
   *
   * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
   * is converted to `-ms-`.
   */

  function hyphenateStyleName(name) {
    return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
  }

  // and any newline or tab are filtered out as if they're not part of the URL.
  // https://url.spec.whatwg.org/#url-parsing
  // Tab or newline are defined as \r\n\t:
  // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  // A C0 control is a code point in the range \u0000 NULL to \u001F
  // INFORMATION SEPARATOR ONE, inclusive:
  // https://infra.spec.whatwg.org/#c0-control-or-space

  /* eslint-disable max-len */

  var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
  var didWarn = false;

  function sanitizeURL(url) {
    {
      if (!didWarn && isJavaScriptProtocol.test(url)) {
        didWarn = true;

        error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
      }
    }
  }

  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

  function isArray(a) {
    return isArrayImpl(a);
  }

  var startInlineScript = stringToPrecomputedChunk('<script>');
  var endInlineScript = stringToPrecomputedChunk('</script>');
  var startScriptSrc = stringToPrecomputedChunk('<script src="');
  var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
  var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
  /**
   * This escaping function is designed to work with bootstrapScriptContent only.
   * because we know we are escaping the entire script. We can avoid for instance
   * escaping html comment string sequences that are valid javascript as well because
   * if there are no sebsequent <script sequences the html parser will never enter
   * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
   *
   * While untrusted script content should be made safe before using this api it will
   * ensure that the script cannot be early terminated or never terminated state
   */

  function escapeBootstrapScriptContent(scriptText) {
    {
      checkHtmlStringCoercion(scriptText);
    }

    return ('' + scriptText).replace(scriptRegex, scriptReplacer);
  }

  var scriptRegex = /(<\/|<)(s)(cript)/gi;

  var scriptReplacer = function (match, prefix, s, suffix) {
    return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
  }; // Allows us to keep track of what we've already written so we can refer back to it.


  function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
    var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
    var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
    var bootstrapChunks = [];

    if (bootstrapScriptContent !== undefined) {
      bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
    }

    if (bootstrapScripts !== undefined) {
      for (var i = 0; i < bootstrapScripts.length; i++) {
        bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
      }
    }

    if (bootstrapModules !== undefined) {
      for (var _i = 0; _i < bootstrapModules.length; _i++) {
        bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
      }
    }

    return {
      bootstrapChunks: bootstrapChunks,
      startInlineScript: inlineScriptWithNonce,
      placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
      segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
      boundaryPrefix: idPrefix + 'B:',
      idPrefix: idPrefix,
      nextSuspenseID: 0,
      sentCompleteSegmentFunction: false,
      sentCompleteBoundaryFunction: false,
      sentClientRenderFunction: false
    };
  } // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
  // modes. We only include the variants as they matter for the sake of our purposes.
  // We don't actually provide the namespace therefore we use constants instead of the string.

  var ROOT_HTML_MODE = 0; // Used for the root most element tag.

  var HTML_MODE = 1;
  var SVG_MODE = 2;
  var MATHML_MODE = 3;
  var HTML_TABLE_MODE = 4;
  var HTML_TABLE_BODY_MODE = 5;
  var HTML_TABLE_ROW_MODE = 6;
  var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
  // still makes sense

  function createFormatContext(insertionMode, selectedValue) {
    return {
      insertionMode: insertionMode,
      selectedValue: selectedValue
    };
  }
  function getChildFormatContext(parentContext, type, props) {
    switch (type) {
      case 'select':
        return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

      case 'svg':
        return createFormatContext(SVG_MODE, null);

      case 'math':
        return createFormatContext(MATHML_MODE, null);

      case 'foreignObject':
        return createFormatContext(HTML_MODE, null);
      // Table parents are special in that their children can only be created at all if they're
      // wrapped in a table parent. So we need to encode that we're entering this mode.

      case 'table':
        return createFormatContext(HTML_TABLE_MODE, null);

      case 'thead':
      case 'tbody':
      case 'tfoot':
        return createFormatContext(HTML_TABLE_BODY_MODE, null);

      case 'colgroup':
        return createFormatContext(HTML_COLGROUP_MODE, null);

      case 'tr':
        return createFormatContext(HTML_TABLE_ROW_MODE, null);
    }

    if (parentContext.insertionMode >= HTML_TABLE_MODE) {
      // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
      // entered plain HTML again.
      return createFormatContext(HTML_MODE, null);
    }

    if (parentContext.insertionMode === ROOT_HTML_MODE) {
      // We've emitted the root and is now in plain HTML mode.
      return createFormatContext(HTML_MODE, null);
    }

    return parentContext;
  }
  var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
  function assignSuspenseBoundaryID(responseState) {
    var generatedID = responseState.nextSuspenseID++;
    return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
  }
  function makeId(responseState, treeId, localId) {
    var idPrefix = responseState.idPrefix;
    var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
    // that represents the position of this useId hook among all the useId
    // hooks for this fiber.

    if (localId > 0) {
      id += 'H' + localId.toString(32);
    }

    return id + ':';
  }

  function encodeHTMLTextNode(text) {
    return escapeTextForBrowser(text);
  }

  var textSeparator = stringToPrecomputedChunk('<!-- -->');
  function pushTextInstance(target, text, responseState, textEmbedded) {
    if (text === '') {
      // Empty text doesn't have a DOM node representation and the hydration is aware of this.
      return textEmbedded;
    }

    if (textEmbedded) {
      target.push(textSeparator);
    }

    target.push(stringToChunk(encodeHTMLTextNode(text)));
    return true;
  } // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
  // emit a text separator when we don't know for sure it is safe to omit

  function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
    if (lastPushedText && textEmbedded) {
      target.push(textSeparator);
    }
  }
  var styleNameCache = new Map();

  function processStyleName(styleName) {
    var chunk = styleNameCache.get(styleName);

    if (chunk !== undefined) {
      return chunk;
    }

    var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
    styleNameCache.set(styleName, result);
    return result;
  }

  var styleAttributeStart = stringToPrecomputedChunk(' style="');
  var styleAssign = stringToPrecomputedChunk(':');
  var styleSeparator = stringToPrecomputedChunk(';');

  function pushStyle(target, responseState, style) {
    if (typeof style !== 'object') {
      throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
    }

    var isFirst = true;

    for (var styleName in style) {
      if (!hasOwnProperty.call(style, styleName)) {
        continue;
      } // If you provide unsafe user data here they can inject arbitrary CSS
      // which may be problematic (I couldn't repro this):
      // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
      // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
      // This is not an XSS hole but instead a potential CSS injection issue
      // which has lead to a greater discussion about how we're going to
      // trust URLs moving forward. See #2115901


      var styleValue = style[styleName];

      if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
        // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
        continue;
      }

      var nameChunk = void 0;
      var valueChunk = void 0;
      var isCustomProperty = styleName.indexOf('--') === 0;

      if (isCustomProperty) {
        nameChunk = stringToChunk(escapeTextForBrowser(styleName));

        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      } else {
        {
          warnValidStyle$1(styleName, styleValue);
        }

        nameChunk = processStyleName(styleName);

        if (typeof styleValue === 'number') {
          if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
            valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
          } else {
            valueChunk = stringToChunk('' + styleValue);
          }
        } else {
          {
            checkCSSPropertyStringCoercion(styleValue, styleName);
          }

          valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
        }
      }

      if (isFirst) {
        isFirst = false; // If it's first, we don't need any separators prefixed.

        target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
      } else {
        target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
      }
    }

    if (!isFirst) {
      target.push(attributeEnd);
    }
  }

  var attributeSeparator = stringToPrecomputedChunk(' ');
  var attributeAssign = stringToPrecomputedChunk('="');
  var attributeEnd = stringToPrecomputedChunk('"');
  var attributeEmptyString = stringToPrecomputedChunk('=""');

  function pushAttribute(target, responseState, name, value) {
    switch (name) {
      case 'style':
        {
          pushStyle(target, responseState, value);
          return;
        }

      case 'defaultValue':
      case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

      case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

      case 'suppressContentEditableWarning':
      case 'suppressHydrationWarning':
        // Ignored. These are built-in to React on the client.
        return;
    }

    if ( // shouldIgnoreAttribute
    // We have already filtered out null/undefined and reserved words.
    name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
      return;
    }

    var propertyInfo = getPropertyInfo(name);

    if (propertyInfo !== null) {
      // shouldRemoveAttribute
      switch (typeof value) {
        case 'function': // $FlowIssue symbol is perfectly valid here

        case 'symbol':
          // eslint-disable-line
          return;

        case 'boolean':
          {
            if (!propertyInfo.acceptsBooleans) {
              return;
            }
          }
      }

      var attributeName = propertyInfo.attributeName;
      var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

      switch (propertyInfo.type) {
        case BOOLEAN:
          if (value) {
            target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
          }

          return;

        case OVERLOADED_BOOLEAN:
          if (value === true) {
            target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
          } else if (value === false) ; else {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          return;

        case NUMERIC:
          if (!isNaN(value)) {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          break;

        case POSITIVE_NUMERIC:
          if (!isNaN(value) && value >= 1) {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          break;

        default:
          if (propertyInfo.sanitizeURL) {
            {
              checkAttributeStringCoercion(value, attributeName);
            }

            value = '' + value;
            sanitizeURL(value);
          }

          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
      }
    } else if (isAttributeNameSafe(name)) {
      // shouldRemoveAttribute
      switch (typeof value) {
        case 'function': // $FlowIssue symbol is perfectly valid here

        case 'symbol':
          // eslint-disable-line
          return;

        case 'boolean':
          {
            var prefix = name.toLowerCase().slice(0, 5);

            if (prefix !== 'data-' && prefix !== 'aria-') {
              return;
            }
          }
      }

      target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  }

  var endOfStartTag = stringToPrecomputedChunk('>');
  var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

  function pushInnerHTML(target, innerHTML, children) {
    if (innerHTML != null) {
      if (children != null) {
        throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      }

      if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
        throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
      }

      var html = innerHTML.__html;

      if (html !== null && html !== undefined) {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  } // TODO: Move these to ResponseState so that we warn for every request.
  // It would help debugging in stateful servers (e.g. service worker).


  var didWarnDefaultInputValue = false;
  var didWarnDefaultChecked = false;
  var didWarnDefaultSelectValue = false;
  var didWarnDefaultTextareaValue = false;
  var didWarnInvalidOptionChildren = false;
  var didWarnInvalidOptionInnerHTML = false;
  var didWarnSelectedSetOnOption = false;

  function checkSelectProp(props, propName) {
    {
      var value = props[propName];

      if (value != null) {
        var array = isArray(value);

        if (props.multiple && !array) {
          error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
        } else if (!props.multiple && array) {
          error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
        }
      }
    }
  }

  function pushStartSelect(target, props, responseState) {
    {
      checkControlledValueProps('select', props);
      checkSelectProp(props, 'value');
      checkSelectProp(props, 'defaultValue');

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
        error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

        didWarnDefaultSelectValue = true;
      }
    }

    target.push(startChunkForTag('select'));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            // TODO: This doesn't really make sense for select since it can't use the controlled
            // value in the innerHTML.
            innerHTML = propValue;
            break;

          case 'defaultValue':
          case 'value':
            // These are set on the Context instead and applied to the nested options.
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  function flattenOptionChildren(children) {
    var content = ''; // Flatten children and warn if they aren't strings or numbers;
    // invalid types are ignored.

    React.Children.forEach(children, function (child) {
      if (child == null) {
        return;
      }

      content += child;

      {
        if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
          didWarnInvalidOptionChildren = true;

          error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
        }
      }
    });
    return content;
  }

  var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

  function pushStartOption(target, props, responseState, formatContext) {
    var selectedValue = formatContext.selectedValue;
    target.push(startChunkForTag('option'));
    var children = null;
    var value = null;
    var selected = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'selected':
            // ignore
            selected = propValue;

            {
              // TODO: Remove support for `selected` in <option>.
              if (!didWarnSelectedSetOnOption) {
                error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

                didWarnSelectedSetOnOption = true;
              }
            }

            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;
          // eslint-disable-next-line-no-fallthrough

          case 'value':
            value = propValue;
          // We intentionally fallthrough to also set the attribute on the node.
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (selectedValue != null) {
      var stringValue;

      if (value !== null) {
        {
          checkAttributeStringCoercion(value, 'value');
        }

        stringValue = '' + value;
      } else {
        {
          if (innerHTML !== null) {
            if (!didWarnInvalidOptionInnerHTML) {
              didWarnInvalidOptionInnerHTML = true;

              error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
            }
          }
        }

        stringValue = flattenOptionChildren(children);
      }

      if (isArray(selectedValue)) {
        // multiple
        for (var i = 0; i < selectedValue.length; i++) {
          {
            checkAttributeStringCoercion(selectedValue[i], 'value');
          }

          var v = '' + selectedValue[i];

          if (v === stringValue) {
            target.push(selectedMarkerAttribute);
            break;
          }
        }
      } else {
        {
          checkAttributeStringCoercion(selectedValue, 'select.value');
        }

        if ('' + selectedValue === stringValue) {
          target.push(selectedMarkerAttribute);
        }
      }
    } else if (selected) {
      target.push(selectedMarkerAttribute);
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  function pushInput(target, props, responseState) {
    {
      checkControlledValueProps('input', props);

      if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
        error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

        didWarnDefaultChecked = true;
      }

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
        error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

        didWarnDefaultInputValue = true;
      }
    }

    target.push(startChunkForTag('input'));
    var value = null;
    var defaultValue = null;
    var checked = null;
    var defaultChecked = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          case 'defaultChecked':
            defaultChecked = propValue;
            break;

          case 'defaultValue':
            defaultValue = propValue;
            break;

          case 'checked':
            checked = propValue;
            break;

          case 'value':
            value = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (checked !== null) {
      pushAttribute(target, responseState, 'checked', checked);
    } else if (defaultChecked !== null) {
      pushAttribute(target, responseState, 'checked', defaultChecked);
    }

    if (value !== null) {
      pushAttribute(target, responseState, 'value', value);
    } else if (defaultValue !== null) {
      pushAttribute(target, responseState, 'value', defaultValue);
    }

    target.push(endOfStartTagSelfClosing);
    return null;
  }

  function pushStartTextArea(target, props, responseState) {
    {
      checkControlledValueProps('textarea', props);

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
        error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

        didWarnDefaultTextareaValue = true;
      }
    }

    target.push(startChunkForTag('textarea'));
    var value = null;
    var defaultValue = null;
    var children = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'value':
            value = propValue;
            break;

          case 'defaultValue':
            defaultValue = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (value === null && defaultValue !== null) {
      value = defaultValue;
    }

    target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

    if (children != null) {
      {
        error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
      }

      if (value != null) {
        throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
      }

      if (isArray(children)) {
        if (children.length > 1) {
          throw new Error('<textarea> can only have at most one child.');
        } // TODO: remove the coercion and the DEV check below because it will
        // always be overwritten by the coercion several lines below it. #22309


        {
          checkHtmlStringCoercion(children[0]);
        }

        value = '' + children[0];
      }

      {
        checkHtmlStringCoercion(children);
      }

      value = '' + children;
    }

    if (typeof value === 'string' && value[0] === '\n') {
      // text/html ignores the first character in these tags if it's a newline
      // Prefer to break application/xml over text/html (for now) by adding
      // a newline specifically to get eaten by the parser. (Alternately for
      // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
      // \r is normalized out by HTMLTextAreaElement#value.)
      // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
      // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
      // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
      // See: Parsing of "textarea" "listing" and "pre" elements
      //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
      target.push(leadingNewline);
    } // ToString and push directly instead of recurse over children.
    // We don't really support complex children in the value anyway.
    // This also currently avoids a trailing comment node which breaks textarea.


    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      target.push(stringToChunk(encodeHTMLTextNode('' + value)));
    }

    return null;
  }

  function pushSelfClosing(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTagSelfClosing);
    return null;
  }

  function pushStartMenuItem(target, props, responseState) {
    target.push(startChunkForTag('menuitem'));

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    return null;
  }

  function pushStartTitle(target, props, responseState) {
    target.push(startChunkForTag('title'));
    var children = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);

    {
      var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

      if (Array.isArray(children) && children.length > 1) {
        error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      } else if (child != null && child.$$typeof != null) {
        error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
        error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      }
    }

    return children;
  }

  function pushStartGenericElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);

    if (typeof children === 'string') {
      // Special case children as a string to avoid the unnecessary comment.
      // TODO: Remove this special case after the general optimization is in place.
      target.push(stringToChunk(encodeHTMLTextNode(children)));
      return null;
    }

    return children;
  }

  function pushStartCustomElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          case 'style':
            pushStyle(target, responseState, propValue);
            break;

          case 'suppressContentEditableWarning':
          case 'suppressHydrationWarning':
            // Ignored. These are built-in to React on the client.
            break;

          default:
            if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
              target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
            }

            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  var leadingNewline = stringToPrecomputedChunk('\n');

  function pushStartPreformattedElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    // TODO: This doesn't deal with the case where the child is an array
    // or component that returns a string.

    if (innerHTML != null) {
      if (children != null) {
        throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      }

      if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
        throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
      }

      var html = innerHTML.__html;

      if (html !== null && html !== undefined) {
        if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
          target.push(leadingNewline, stringToChunk(html));
        } else {
          {
            checkHtmlStringCoercion(html);
          }

          target.push(stringToChunk('' + html));
        }
      }
    }

    if (typeof children === 'string' && children[0] === '\n') {
      target.push(leadingNewline);
    }

    return children;
  } // We accept any tag to be rendered but since this gets injected into arbitrary
  // HTML, we want to make sure that it's a safe tag.
  // http://www.w3.org/TR/REC-xml/#NT-Name


  var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

  var validatedTagCache = new Map();

  function startChunkForTag(tag) {
    var tagStartChunk = validatedTagCache.get(tag);

    if (tagStartChunk === undefined) {
      if (!VALID_TAG_REGEX.test(tag)) {
        throw new Error("Invalid tag: " + tag);
      }

      tagStartChunk = stringToPrecomputedChunk('<' + tag);
      validatedTagCache.set(tag, tagStartChunk);
    }

    return tagStartChunk;
  }

  var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
  function pushStartInstance(target, type, props, responseState, formatContext) {
    {
      validateProperties(type, props);
      validateProperties$1(type, props);
      validateProperties$2(type, props, null);

      if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
        error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
      }

      if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
          error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
        }
      }
    }

    switch (type) {
      // Special tags
      case 'select':
        return pushStartSelect(target, props, responseState);

      case 'option':
        return pushStartOption(target, props, responseState, formatContext);

      case 'textarea':
        return pushStartTextArea(target, props, responseState);

      case 'input':
        return pushInput(target, props, responseState);

      case 'menuitem':
        return pushStartMenuItem(target, props, responseState);

      case 'title':
        return pushStartTitle(target, props, responseState);
      // Newline eating tags

      case 'listing':
      case 'pre':
        {
          return pushStartPreformattedElement(target, props, type, responseState);
        }
      // Omitted close tags

      case 'area':
      case 'base':
      case 'br':
      case 'col':
      case 'embed':
      case 'hr':
      case 'img':
      case 'keygen':
      case 'link':
      case 'meta':
      case 'param':
      case 'source':
      case 'track':
      case 'wbr':
        {
          return pushSelfClosing(target, props, type, responseState);
        }
      // These are reserved SVG and MathML elements, that are never custom elements.
      // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

      case 'annotation-xml':
      case 'color-profile':
      case 'font-face':
      case 'font-face-src':
      case 'font-face-uri':
      case 'font-face-format':
      case 'font-face-name':
      case 'missing-glyph':
        {
          return pushStartGenericElement(target, props, type, responseState);
        }

      case 'html':
        {
          if (formatContext.insertionMode === ROOT_HTML_MODE) {
            // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
            // then we also emit the DOCTYPE as part of the root content as a convenience for
            // rendering the whole document.
            target.push(DOCTYPE);
          }

          return pushStartGenericElement(target, props, type, responseState);
        }

      default:
        {
          if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
            // Generic element
            return pushStartGenericElement(target, props, type, responseState);
          } else {
            // Custom element
            return pushStartCustomElement(target, props, type, responseState);
          }
        }
    }
  }
  var endTag1 = stringToPrecomputedChunk('</');
  var endTag2 = stringToPrecomputedChunk('>');
  function pushEndInstance(target, type, props) {
    switch (type) {
      // Omitted close tags
      // TODO: Instead of repeating this switch we could try to pass a flag from above.
      // That would require returning a tuple. Which might be ok if it gets inlined.
      case 'area':
      case 'base':
      case 'br':
      case 'col':
      case 'embed':
      case 'hr':
      case 'img':
      case 'input':
      case 'keygen':
      case 'link':
      case 'meta':
      case 'param':
      case 'source':
      case 'track':
      case 'wbr':
        {
          // No close tag needed.
          break;
        }

      default:
        {
          target.push(endTag1, stringToChunk(type), endTag2);
        }
    }
  }
  function writeCompletedRoot(destination, responseState) {
    var bootstrapChunks = responseState.bootstrapChunks;
    var i = 0;

    for (; i < bootstrapChunks.length - 1; i++) {
      writeChunk(destination, bootstrapChunks[i]);
    }

    if (i < bootstrapChunks.length) {
      return writeChunkAndReturn(destination, bootstrapChunks[i]);
    }

    return true;
  } // Structural Nodes
  // A placeholder is a node inside a hidden partial tree that can be filled in later, but before
  // display. It's never visible to users. We use the template tag because it can be used in every
  // type of parent. <script> tags also work in every other tag except <colgroup>.

  var placeholder1 = stringToPrecomputedChunk('<template id="');
  var placeholder2 = stringToPrecomputedChunk('"></template>');
  function writePlaceholder(destination, responseState, id) {
    writeChunk(destination, placeholder1);
    writeChunk(destination, responseState.placeholderPrefix);
    var formattedID = stringToChunk(id.toString(16));
    writeChunk(destination, formattedID);
    return writeChunkAndReturn(destination, placeholder2);
  } // Suspense boundaries are encoded as comments.

  var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
  var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
  var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
  var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
  var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
  var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
  var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
  var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
  var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
  var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
  var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
  function writeStartCompletedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
  }
  function writeStartPendingSuspenseBoundary(destination, responseState, id) {
    writeChunk(destination, startPendingSuspenseBoundary1);

    if (id === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    writeChunk(destination, id);
    return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
  }
  function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
    var result;
    result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
    writeChunk(destination, clientRenderedSuspenseBoundaryError1);

    if (errorDigest) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    {
      if (errorMesssage) {
        writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
        writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
        writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
      }

      if (errorComponentStack) {
        writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
        writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
        writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
      }
    }

    result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
    return result;
  }
  function writeEndCompletedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  function writeEndPendingSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
  var startSegmentHTML2 = stringToPrecomputedChunk('">');
  var endSegmentHTML = stringToPrecomputedChunk('</div>');
  var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
  var startSegmentSVG2 = stringToPrecomputedChunk('">');
  var endSegmentSVG = stringToPrecomputedChunk('</svg>');
  var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
  var startSegmentMathML2 = stringToPrecomputedChunk('">');
  var endSegmentMathML = stringToPrecomputedChunk('</math>');
  var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
  var startSegmentTable2 = stringToPrecomputedChunk('">');
  var endSegmentTable = stringToPrecomputedChunk('</table>');
  var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
  var startSegmentTableBody2 = stringToPrecomputedChunk('">');
  var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
  var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
  var startSegmentTableRow2 = stringToPrecomputedChunk('">');
  var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
  var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
  var startSegmentColGroup2 = stringToPrecomputedChunk('">');
  var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
  function writeStartSegment(destination, responseState, formatContext, id) {
    switch (formatContext.insertionMode) {
      case ROOT_HTML_MODE:
      case HTML_MODE:
        {
          writeChunk(destination, startSegmentHTML);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentHTML2);
        }

      case SVG_MODE:
        {
          writeChunk(destination, startSegmentSVG);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentSVG2);
        }

      case MATHML_MODE:
        {
          writeChunk(destination, startSegmentMathML);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentMathML2);
        }

      case HTML_TABLE_MODE:
        {
          writeChunk(destination, startSegmentTable);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTable2);
        }
      // TODO: For the rest of these, there will be extra wrapper nodes that never
      // get deleted from the document. We need to delete the table too as part
      // of the injected scripts. They are invisible though so it's not too terrible
      // and it's kind of an edge case to suspend in a table. Totally supported though.

      case HTML_TABLE_BODY_MODE:
        {
          writeChunk(destination, startSegmentTableBody);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTableBody2);
        }

      case HTML_TABLE_ROW_MODE:
        {
          writeChunk(destination, startSegmentTableRow);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTableRow2);
        }

      case HTML_COLGROUP_MODE:
        {
          writeChunk(destination, startSegmentColGroup);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentColGroup2);
        }

      default:
        {
          throw new Error('Unknown insertion mode. This is a bug in React.');
        }
    }
  }
  function writeEndSegment(destination, formatContext) {
    switch (formatContext.insertionMode) {
      case ROOT_HTML_MODE:
      case HTML_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentHTML);
        }

      case SVG_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentSVG);
        }

      case MATHML_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentMathML);
        }

      case HTML_TABLE_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTable);
        }

      case HTML_TABLE_BODY_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTableBody);
        }

      case HTML_TABLE_ROW_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTableRow);
        }

      case HTML_COLGROUP_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentColGroup);
        }

      default:
        {
          throw new Error('Unknown insertion mode. This is a bug in React.');
        }
    }
  } // Instruction Set
  // The following code is the source scripts that we then minify and inline below,
  // with renamed function names that we hope don't collide:
  // const COMMENT_NODE = 8;
  // const SUSPENSE_START_DATA = '$';
  // const SUSPENSE_END_DATA = '/$';
  // const SUSPENSE_PENDING_START_DATA = '$?';
  // const SUSPENSE_FALLBACK_START_DATA = '$!';
  //
  // function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
  //   // Find the fallback's first element.
  //   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  //   if (!suspenseIdNode) {
  //     // The user must have already navigated away from this tree.
  //     // E.g. because the parent was hydrated.
  //     return;
  //   }
  //   // Find the boundary around the fallback. This is always the previous node.
  //   const suspenseNode = suspenseIdNode.previousSibling;
  //   // Tag it to be client rendered.
  //   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
  //   // assign error metadata to first sibling
  //   let dataset = suspenseIdNode.dataset;
  //   if (errorDigest) dataset.dgst = errorDigest;
  //   if (errorMsg) dataset.msg = errorMsg;
  //   if (errorComponentStack) dataset.stck = errorComponentStack;
  //   // Tell React to retry it if the parent already hydrated.
  //   if (suspenseNode._reactRetry) {
  //     suspenseNode._reactRetry();
  //   }
  // }
  //
  // function completeBoundary(suspenseBoundaryID, contentID) {
  //   // Find the fallback's first element.
  //   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  //   const contentNode = document.getElementById(contentID);
  //   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
  //   // This might also help by not causing recalcing each time we move a child from here to the target.
  //   contentNode.parentNode.removeChild(contentNode);
  //   if (!suspenseIdNode) {
  //     // The user must have already navigated away from this tree.
  //     // E.g. because the parent was hydrated. That's fine there's nothing to do
  //     // but we have to make sure that we already deleted the container node.
  //     return;
  //   }
  //   // Find the boundary around the fallback. This is always the previous node.
  //   const suspenseNode = suspenseIdNode.previousSibling;
  //
  //   // Clear all the existing children. This is complicated because
  //   // there can be embedded Suspense boundaries in the fallback.
  //   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
  //   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
  //   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
  //   const parentInstance = suspenseNode.parentNode;
  //   let node = suspenseNode.nextSibling;
  //   let depth = 0;
  //   do {
  //     if (node && node.nodeType === COMMENT_NODE) {
  //       const data = node.data;
  //       if (data === SUSPENSE_END_DATA) {
  //         if (depth === 0) {
  //           break;
  //         } else {
  //           depth--;
  //         }
  //       } else if (
  //         data === SUSPENSE_START_DATA ||
  //         data === SUSPENSE_PENDING_START_DATA ||
  //         data === SUSPENSE_FALLBACK_START_DATA
  //       ) {
  //         depth++;
  //       }
  //     }
  //
  //     const nextNode = node.nextSibling;
  //     parentInstance.removeChild(node);
  //     node = nextNode;
  //   } while (node);
  //
  //   const endOfBoundary = node;
  //
  //   // Insert all the children from the contentNode between the start and end of suspense boundary.
  //   while (contentNode.firstChild) {
  //     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
  //   }
  //   suspenseNode.data = SUSPENSE_START_DATA;
  //   if (suspenseNode._reactRetry) {
  //     suspenseNode._reactRetry();
  //   }
  // }
  //
  // function completeSegment(containerID, placeholderID) {
  //   const segmentContainer = document.getElementById(containerID);
  //   const placeholderNode = document.getElementById(placeholderID);
  //   // We always expect both nodes to exist here because, while we might
  //   // have navigated away from the main tree, we still expect the detached
  //   // tree to exist.
  //   segmentContainer.parentNode.removeChild(segmentContainer);
  //   while (segmentContainer.firstChild) {
  //     placeholderNode.parentNode.insertBefore(
  //       segmentContainer.firstChild,
  //       placeholderNode,
  //     );
  //   }
  //   placeholderNode.parentNode.removeChild(placeholderNode);
  // }

  var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
  var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
  var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
  var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
  var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
  var completeSegmentScript2 = stringToPrecomputedChunk('","');
  var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
  function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentCompleteSegmentFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentCompleteSegmentFunction = true;
      writeChunk(destination, completeSegmentScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, completeSegmentScript1Partial);
    }

    writeChunk(destination, responseState.segmentPrefix);
    var formattedID = stringToChunk(contentSegmentID.toString(16));
    writeChunk(destination, formattedID);
    writeChunk(destination, completeSegmentScript2);
    writeChunk(destination, responseState.placeholderPrefix);
    writeChunk(destination, formattedID);
    return writeChunkAndReturn(destination, completeSegmentScript3);
  }
  var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
  var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
  var completeBoundaryScript2 = stringToPrecomputedChunk('","');
  var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
  function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentCompleteBoundaryFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentCompleteBoundaryFunction = true;
      writeChunk(destination, completeBoundaryScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, completeBoundaryScript1Partial);
    }

    if (boundaryID === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    var formattedContentID = stringToChunk(contentSegmentID.toString(16));
    writeChunk(destination, boundaryID);
    writeChunk(destination, completeBoundaryScript2);
    writeChunk(destination, responseState.segmentPrefix);
    writeChunk(destination, formattedContentID);
    return writeChunkAndReturn(destination, completeBoundaryScript3);
  }
  var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
  var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
  var clientRenderScript1A = stringToPrecomputedChunk('"');
  var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
  var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
  function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentClientRenderFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentClientRenderFunction = true;
      writeChunk(destination, clientRenderScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, clientRenderScript1Partial);
    }

    if (boundaryID === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    writeChunk(destination, boundaryID);
    writeChunk(destination, clientRenderScript1A);

    if (errorDigest || errorMessage || errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
    }

    if (errorMessage || errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
    }

    return writeChunkAndReturn(destination, clientRenderScript2);
  }
  var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

  function escapeJSStringsForInstructionScripts(input) {
    var escaped = JSON.stringify(input);
    return escaped.replace(regexForJSStringsInScripts, function (match) {
      switch (match) {
        // santizing breaking out of strings and script tags
        case '<':
          return "\\u003c";

        case "\u2028":
          return "\\u2028";

        case "\u2029":
          return "\\u2029";

        default:
          {
            // eslint-disable-next-line react-internal/prod-error-codes
            throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
          }
      }
    });
  }

  function createResponseState$1(generateStaticMarkup, identifierPrefix) {
    var responseState = createResponseState(identifierPrefix, undefined);
    return {
      // Keep this in sync with ReactDOMServerFormatConfig
      bootstrapChunks: responseState.bootstrapChunks,
      startInlineScript: responseState.startInlineScript,
      placeholderPrefix: responseState.placeholderPrefix,
      segmentPrefix: responseState.segmentPrefix,
      boundaryPrefix: responseState.boundaryPrefix,
      idPrefix: responseState.idPrefix,
      nextSuspenseID: responseState.nextSuspenseID,
      sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction,
      sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction,
      sentClientRenderFunction: responseState.sentClientRenderFunction,
      // This is an extra field for the legacy renderer
      generateStaticMarkup: generateStaticMarkup
    };
  }
  function createRootFormatContext() {
    return {
      insertionMode: HTML_MODE,
      // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode.
      selectedValue: null
    };
  }
  function pushTextInstance$1(target, text, responseState, textEmbedded) {
    if (responseState.generateStaticMarkup) {
      target.push(stringToChunk(escapeTextForBrowser(text)));
      return false;
    } else {
      return pushTextInstance(target, text, responseState, textEmbedded);
    }
  }
  function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) {
    if (responseState.generateStaticMarkup) {
      return;
    } else {
      return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded);
    }
  }
  function writeStartCompletedSuspenseBoundary$1(destination, responseState) {
    if (responseState.generateStaticMarkup) {
      // A completed boundary is done and doesn't need a representation in the HTML
      // if we're not going to be hydrating it.
      return true;
    }

    return writeStartCompletedSuspenseBoundary(destination);
  }
  function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format.
  errorDigest, errorMessage, errorComponentStack) {
    if (responseState.generateStaticMarkup) {
      // A client rendered boundary is done and doesn't need a representation in the HTML
      // since we'll never hydrate it. This is arguably an error in static generation.
      return true;
    }

    return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack);
  }
  function writeEndCompletedSuspenseBoundary$1(destination, responseState) {
    if (responseState.generateStaticMarkup) {
      return true;
    }

    return writeEndCompletedSuspenseBoundary(destination);
  }
  function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) {
    if (responseState.generateStaticMarkup) {
      return true;
    }

    return writeEndClientRenderedSuspenseBoundary(destination);
  }

  var assign = Object.assign;

  // ATTENTION
  // When adding new symbols to this file,
  // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  // The Symbol used to tag the ReactElement-like types.
  var REACT_ELEMENT_TYPE = Symbol.for('react.element');
  var REACT_PORTAL_TYPE = Symbol.for('react.portal');
  var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
  var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
  var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
  var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
  var REACT_CONTEXT_TYPE = Symbol.for('react.context');
  var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
  var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
  var REACT_MEMO_TYPE = Symbol.for('react.memo');
  var REACT_LAZY_TYPE = Symbol.for('react.lazy');
  var REACT_SCOPE_TYPE = Symbol.for('react.scope');
  var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
  var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
  var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
  var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';
  function getIteratorFn(maybeIterable) {
    if (maybeIterable === null || typeof maybeIterable !== 'object') {
      return null;
    }

    var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

    if (typeof maybeIterator === 'function') {
      return maybeIterator;
    }

    return null;
  }

  function getWrappedName(outerType, innerType, wrapperName) {
    var displayName = outerType.displayName;

    if (displayName) {
      return displayName;
    }

    var functionName = innerType.displayName || innerType.name || '';
    return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
  } // Keep in sync with react-reconciler/getComponentNameFromFiber


  function getContextName(type) {
    return type.displayName || 'Context';
  } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


  function getComponentNameFromType(type) {
    if (type == null) {
      // Host root, text node or just invalid type.
      return null;
    }

    {
      if (typeof type.tag === 'number') {
        error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
      }
    }

    if (typeof type === 'function') {
      return type.displayName || type.name || null;
    }

    if (typeof type === 'string') {
      return type;
    }

    switch (type) {
      case REACT_FRAGMENT_TYPE:
        return 'Fragment';

      case REACT_PORTAL_TYPE:
        return 'Portal';

      case REACT_PROFILER_TYPE:
        return 'Profiler';

      case REACT_STRICT_MODE_TYPE:
        return 'StrictMode';

      case REACT_SUSPENSE_TYPE:
        return 'Suspense';

      case REACT_SUSPENSE_LIST_TYPE:
        return 'SuspenseList';

    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_CONTEXT_TYPE:
          var context = type;
          return getContextName(context) + '.Consumer';

        case REACT_PROVIDER_TYPE:
          var provider = type;
          return getContextName(provider._context) + '.Provider';

        case REACT_FORWARD_REF_TYPE:
          return getWrappedName(type, type.render, 'ForwardRef');

        case REACT_MEMO_TYPE:
          var outerName = type.displayName || null;

          if (outerName !== null) {
            return outerName;
          }

          return getComponentNameFromType(type.type) || 'Memo';

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              return getComponentNameFromType(init(payload));
            } catch (x) {
              return null;
            }
          }

        // eslint-disable-next-line no-fallthrough
      }
    }

    return null;
  }

  // Helpers to patch console.logs to avoid logging during side-effect free
  // replaying on render function. This currently only patches the object
  // lazily which won't cover if the log function was extracted eagerly.
  // We could also eagerly patch the method.
  var disabledDepth = 0;
  var prevLog;
  var prevInfo;
  var prevWarn;
  var prevError;
  var prevGroup;
  var prevGroupCollapsed;
  var prevGroupEnd;

  function disabledLog() {}

  disabledLog.__reactDisabledLog = true;
  function disableLogs() {
    {
      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      disabledDepth++;
    }
  }
  function reenableLogs() {
    {
      disabledDepth--;

      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        var props = {
          configurable: true,
          enumerable: true,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          log: assign({}, props, {
            value: prevLog
          }),
          info: assign({}, props, {
            value: prevInfo
          }),
          warn: assign({}, props, {
            value: prevWarn
          }),
          error: assign({}, props, {
            value: prevError
          }),
          group: assign({}, props, {
            value: prevGroup
          }),
          groupCollapsed: assign({}, props, {
            value: prevGroupCollapsed
          }),
          groupEnd: assign({}, props, {
            value: prevGroupEnd
          })
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      if (disabledDepth < 0) {
        error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
      }
    }
  }

  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  var prefix;
  function describeBuiltInComponentFrame(name, source, ownerFn) {
    {
      if (prefix === undefined) {
        // Extract the VM specific prefix used by each line.
        try {
          throw Error();
        } catch (x) {
          var match = x.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || '';
        }
      } // We use the prefix to ensure our stacks line up with native stack frames.


      return '\n' + prefix + name;
    }
  }
  var reentry = false;
  var componentFrameCache;

  {
    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
    componentFrameCache = new PossiblyWeakMap();
  }

  function describeNativeComponentFrame(fn, construct) {
    // If something asked for a stack inside a fake render, it should get ignored.
    if ( !fn || reentry) {
      return '';
    }

    {
      var frame = componentFrameCache.get(fn);

      if (frame !== undefined) {
        return frame;
      }
    }

    var control;
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

    Error.prepareStackTrace = undefined;
    var previousDispatcher;

    {
      previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
      // for warnings.

      ReactCurrentDispatcher.current = null;
      disableLogs();
    }

    try {
      // This should throw.
      if (construct) {
        // Something should be setting the props in the constructor.
        var Fake = function () {
          throw Error();
        }; // $FlowFixMe


        Object.defineProperty(Fake.prototype, 'props', {
          set: function () {
            // We use a throwing setter instead of frozen or non-writable props
            // because that won't throw in a non-strict mode function.
            throw Error();
          }
        });

        if (typeof Reflect === 'object' && Reflect.construct) {
          // We construct a different control for this case to include any extra
          // frames added by the construct call.
          try {
            Reflect.construct(Fake, []);
          } catch (x) {
            control = x;
          }

          Reflect.construct(fn, [], Fake);
        } else {
          try {
            Fake.call();
          } catch (x) {
            control = x;
          }

          fn.call(Fake.prototype);
        }
      } else {
        try {
          throw Error();
        } catch (x) {
          control = x;
        }

        fn();
      }
    } catch (sample) {
      // This is inlined manually because closure doesn't do it for us.
      if (sample && control && typeof sample.stack === 'string') {
        // This extracts the first frame from the sample that isn't also in the control.
        // Skipping one frame that we assume is the frame that calls the two.
        var sampleLines = sample.stack.split('\n');
        var controlLines = control.stack.split('\n');
        var s = sampleLines.length - 1;
        var c = controlLines.length - 1;

        while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
          // We expect at least one stack frame to be shared.
          // Typically this will be the root most one. However, stack frames may be
          // cut off due to maximum stack limits. In this case, one maybe cut off
          // earlier than the other. We assume that the sample is longer or the same
          // and there for cut off earlier. So we should find the root most frame in
          // the sample somewhere in the control.
          c--;
        }

        for (; s >= 1 && c >= 0; s--, c--) {
          // Next we find the first one that isn't the same which should be the
          // frame that called our sample function and the control.
          if (sampleLines[s] !== controlLines[c]) {
            // In V8, the first line is describing the message but other VMs don't.
            // If we're about to return the first line, and the control is also on the same
            // line, that's a pretty good indicator that our sample threw at same line as
            // the control. I.e. before we entered the sample frame. So we ignore this result.
            // This can happen if you passed a class to function component, or non-function.
            if (s !== 1 || c !== 1) {
              do {
                s--;
                c--; // We may still have similar intermediate frames from the construct call.
                // The next one that isn't the same should be our match though.

                if (c < 0 || sampleLines[s] !== controlLines[c]) {
                  // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                  var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                  // but we have a user-provided "displayName"
                  // splice it in to make the stack more readable.


                  if (fn.displayName && _frame.includes('<anonymous>')) {
                    _frame = _frame.replace('<anonymous>', fn.displayName);
                  }

                  {
                    if (typeof fn === 'function') {
                      componentFrameCache.set(fn, _frame);
                    }
                  } // Return the line we found.


                  return _frame;
                }
              } while (s >= 1 && c >= 0);
            }

            break;
          }
        }
      }
    } finally {
      reentry = false;

      {
        ReactCurrentDispatcher.current = previousDispatcher;
        reenableLogs();
      }

      Error.prepareStackTrace = previousPrepareStackTrace;
    } // Fallback to just using the name if we couldn't make it throw.


    var name = fn ? fn.displayName || fn.name : '';
    var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

    {
      if (typeof fn === 'function') {
        componentFrameCache.set(fn, syntheticFrame);
      }
    }

    return syntheticFrame;
  }

  function describeClassComponentFrame(ctor, source, ownerFn) {
    {
      return describeNativeComponentFrame(ctor, true);
    }
  }
  function describeFunctionComponentFrame(fn, source, ownerFn) {
    {
      return describeNativeComponentFrame(fn, false);
    }
  }

  function shouldConstruct(Component) {
    var prototype = Component.prototype;
    return !!(prototype && prototype.isReactComponent);
  }

  function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

    if (type == null) {
      return '';
    }

    if (typeof type === 'function') {
      {
        return describeNativeComponentFrame(type, shouldConstruct(type));
      }
    }

    if (typeof type === 'string') {
      return describeBuiltInComponentFrame(type);
    }

    switch (type) {
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame('Suspense');

      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame('SuspenseList');
    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeFunctionComponentFrame(type.render);

        case REACT_MEMO_TYPE:
          // Memo may contain any component type so we recursively resolve it.
          return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              // Lazy may contain any component type so we recursively resolve it.
              return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
            } catch (x) {}
          }
      }
    }

    return '';
  }

  var loggedTypeFailures = {};
  var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

  function setCurrentlyValidatingElement(element) {
    {
      if (element) {
        var owner = element._owner;
        var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
        ReactDebugCurrentFrame.setExtraStackFrame(stack);
      } else {
        ReactDebugCurrentFrame.setExtraStackFrame(null);
      }
    }
  }

  function checkPropTypes(typeSpecs, values, location, componentName, element) {
    {
      // $FlowFixMe This is okay but Flow doesn't know it.
      var has = Function.call.bind(hasOwnProperty);

      for (var typeSpecName in typeSpecs) {
        if (has(typeSpecs, typeSpecName)) {
          var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
          // fail the render phase where it didn't fail before. So we log it.
          // After these have been cleaned up, we'll let them throw.

          try {
            // This is intentionally an invariant that gets caught. It's the same
            // behavior as without this statement except with a better message.
            if (typeof typeSpecs[typeSpecName] !== 'function') {
              // eslint-disable-next-line react-internal/prod-error-codes
              var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
              err.name = 'Invariant Violation';
              throw err;
            }

            error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
          } catch (ex) {
            error$1 = ex;
          }

          if (error$1 && !(error$1 instanceof Error)) {
            setCurrentlyValidatingElement(element);

            error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

            setCurrentlyValidatingElement(null);
          }

          if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
            // Only monitor this failure once because there tends to be a lot of the
            // same error.
            loggedTypeFailures[error$1.message] = true;
            setCurrentlyValidatingElement(element);

            error('Failed %s type: %s', location, error$1.message);

            setCurrentlyValidatingElement(null);
          }
        }
      }
    }
  }

  var warnedAboutMissingGetChildContext;

  {
    warnedAboutMissingGetChildContext = {};
  }

  var emptyContextObject = {};

  {
    Object.freeze(emptyContextObject);
  }

  function getMaskedContext(type, unmaskedContext) {
    {
      var contextTypes = type.contextTypes;

      if (!contextTypes) {
        return emptyContextObject;
      }

      var context = {};

      for (var key in contextTypes) {
        context[key] = unmaskedContext[key];
      }

      {
        var name = getComponentNameFromType(type) || 'Unknown';
        checkPropTypes(contextTypes, context, 'context', name);
      }

      return context;
    }
  }
  function processChildContext(instance, type, parentContext, childContextTypes) {
    {
      // TODO (bvaughn) Replace this behavior with an invariant() in the future.
      // It has only been added in Fiber to match the (unintentional) behavior in Stack.
      if (typeof instance.getChildContext !== 'function') {
        {
          var componentName = getComponentNameFromType(type) || 'Unknown';

          if (!warnedAboutMissingGetChildContext[componentName]) {
            warnedAboutMissingGetChildContext[componentName] = true;

            error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
          }
        }

        return parentContext;
      }

      var childContext = instance.getChildContext();

      for (var contextKey in childContext) {
        if (!(contextKey in childContextTypes)) {
          throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
        }
      }

      {
        var name = getComponentNameFromType(type) || 'Unknown';
        checkPropTypes(childContextTypes, childContext, 'child context', name);
      }

      return assign({}, parentContext, childContext);
    }
  }

  var rendererSigil;

  {
    // Use this to detect multiple renderers using the same context
    rendererSigil = {};
  } // Used to store the parent path of all context overrides in a shared linked list.
  // Forming a reverse tree.


  var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
  // This global (actually thread local) state represents what state all those "current",
  // fields are currently in.

  var currentActiveSnapshot = null;

  function popNode(prev) {
    {
      prev.context._currentValue2 = prev.parentValue;
    }
  }

  function pushNode(next) {
    {
      next.context._currentValue2 = next.value;
    }
  }

  function popToNearestCommonAncestor(prev, next) {
    if (prev === next) ; else {
      popNode(prev);
      var parentPrev = prev.parent;
      var parentNext = next.parent;

      if (parentPrev === null) {
        if (parentNext !== null) {
          throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
        }
      } else {
        if (parentNext === null) {
          throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
        }

        popToNearestCommonAncestor(parentPrev, parentNext);
      } // On the way back, we push the new ones that weren't common.


      pushNode(next);
    }
  }

  function popAllPrevious(prev) {
    popNode(prev);
    var parentPrev = prev.parent;

    if (parentPrev !== null) {
      popAllPrevious(parentPrev);
    }
  }

  function pushAllNext(next) {
    var parentNext = next.parent;

    if (parentNext !== null) {
      pushAllNext(parentNext);
    }

    pushNode(next);
  }

  function popPreviousToCommonLevel(prev, next) {
    popNode(prev);
    var parentPrev = prev.parent;

    if (parentPrev === null) {
      throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
    }

    if (parentPrev.depth === next.depth) {
      // We found the same level. Now we just need to find a shared ancestor.
      popToNearestCommonAncestor(parentPrev, next);
    } else {
      // We must still be deeper.
      popPreviousToCommonLevel(parentPrev, next);
    }
  }

  function popNextToCommonLevel(prev, next) {
    var parentNext = next.parent;

    if (parentNext === null) {
      throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
    }

    if (prev.depth === parentNext.depth) {
      // We found the same level. Now we just need to find a shared ancestor.
      popToNearestCommonAncestor(prev, parentNext);
    } else {
      // We must still be deeper.
      popNextToCommonLevel(prev, parentNext);
    }

    pushNode(next);
  } // Perform context switching to the new snapshot.
  // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
  // updating all the context's current values. That way reads, always just read the current value.
  // At the cost of updating contexts even if they're never read by this subtree.


  function switchContext(newSnapshot) {
    // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
    // We also need to update any new contexts that are now on the stack with the deepest value.
    // The easiest way to update new contexts is to just reapply them in reverse order from the
    // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
    // for that. Therefore this algorithm is recursive.
    // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
    // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
    // 3) Then we reapply new contexts on the way back up the stack.
    var prev = currentActiveSnapshot;
    var next = newSnapshot;

    if (prev !== next) {
      if (prev === null) {
        // $FlowFixMe: This has to be non-null since it's not equal to prev.
        pushAllNext(next);
      } else if (next === null) {
        popAllPrevious(prev);
      } else if (prev.depth === next.depth) {
        popToNearestCommonAncestor(prev, next);
      } else if (prev.depth > next.depth) {
        popPreviousToCommonLevel(prev, next);
      } else {
        popNextToCommonLevel(prev, next);
      }

      currentActiveSnapshot = next;
    }
  }
  function pushProvider(context, nextValue) {
    var prevValue;

    {
      prevValue = context._currentValue2;
      context._currentValue2 = nextValue;

      {
        if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
          error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
        }

        context._currentRenderer2 = rendererSigil;
      }
    }

    var prevNode = currentActiveSnapshot;
    var newNode = {
      parent: prevNode,
      depth: prevNode === null ? 0 : prevNode.depth + 1,
      context: context,
      parentValue: prevValue,
      value: nextValue
    };
    currentActiveSnapshot = newNode;
    return newNode;
  }
  function popProvider(context) {
    var prevSnapshot = currentActiveSnapshot;

    if (prevSnapshot === null) {
      throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
    }

    {
      if (prevSnapshot.context !== context) {
        error('The parent context is not the expected context. This is probably a bug in React.');
      }
    }

    {
      var _value = prevSnapshot.parentValue;

      if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
        prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;
      } else {
        prevSnapshot.context._currentValue2 = _value;
      }

      {
        if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
          error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
        }

        context._currentRenderer2 = rendererSigil;
      }
    }

    return currentActiveSnapshot = prevSnapshot.parent;
  }
  function getActiveContext() {
    return currentActiveSnapshot;
  }
  function readContext(context) {
    var value =  context._currentValue2;
    return value;
  }

  /**
   * `ReactInstanceMap` maintains a mapping from a public facing stateful
   * instance (key) and the internal representation (value). This allows public
   * methods to accept the user facing instance as an argument and map them back
   * to internal methods.
   *
   * Note that this module is currently shared and assumed to be stateless.
   * If this becomes an actual Map, that will break.
   */
  function get(key) {
    return key._reactInternals;
  }
  function set(key, value) {
    key._reactInternals = value;
  }

  var didWarnAboutNoopUpdateForComponent = {};
  var didWarnAboutDeprecatedWillMount = {};
  var didWarnAboutUninitializedState;
  var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
  var didWarnAboutLegacyLifecyclesAndDerivedState;
  var didWarnAboutUndefinedDerivedState;
  var warnOnUndefinedDerivedState;
  var warnOnInvalidCallback;
  var didWarnAboutDirectlyAssigningPropsToState;
  var didWarnAboutContextTypeAndContextTypes;
  var didWarnAboutInvalidateContextType;

  {
    didWarnAboutUninitializedState = new Set();
    didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
    didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
    didWarnAboutDirectlyAssigningPropsToState = new Set();
    didWarnAboutUndefinedDerivedState = new Set();
    didWarnAboutContextTypeAndContextTypes = new Set();
    didWarnAboutInvalidateContextType = new Set();
    var didWarnOnInvalidCallback = new Set();

    warnOnInvalidCallback = function (callback, callerName) {
      if (callback === null || typeof callback === 'function') {
        return;
      }

      var key = callerName + '_' + callback;

      if (!didWarnOnInvalidCallback.has(key)) {
        didWarnOnInvalidCallback.add(key);

        error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
      }
    };

    warnOnUndefinedDerivedState = function (type, partialState) {
      if (partialState === undefined) {
        var componentName = getComponentNameFromType(type) || 'Component';

        if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
          didWarnAboutUndefinedDerivedState.add(componentName);

          error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
        }
      }
    };
  }

  function warnNoop(publicInstance, callerName) {
    {
      var _constructor = publicInstance.constructor;
      var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
      var warningKey = componentName + '.' + callerName;

      if (didWarnAboutNoopUpdateForComponent[warningKey]) {
        return;
      }

      error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

      didWarnAboutNoopUpdateForComponent[warningKey] = true;
    }
  }

  var classComponentUpdater = {
    isMounted: function (inst) {
      return false;
    },
    enqueueSetState: function (inst, payload, callback) {
      var internals = get(inst);

      if (internals.queue === null) {
        warnNoop(inst, 'setState');
      } else {
        internals.queue.push(payload);

        {
          if (callback !== undefined && callback !== null) {
            warnOnInvalidCallback(callback, 'setState');
          }
        }
      }
    },
    enqueueReplaceState: function (inst, payload, callback) {
      var internals = get(inst);
      internals.replace = true;
      internals.queue = [payload];

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    },
    enqueueForceUpdate: function (inst, callback) {
      var internals = get(inst);

      if (internals.queue === null) {
        warnNoop(inst, 'forceUpdate');
      } else {
        {
          if (callback !== undefined && callback !== null) {
            warnOnInvalidCallback(callback, 'setState');
          }
        }
      }
    }
  };

  function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
    var partialState = getDerivedStateFromProps(nextProps, prevState);

    {
      warnOnUndefinedDerivedState(ctor, partialState);
    } // Merge the partial state and the previous state.


    var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
    return newState;
  }

  function constructClassInstance(ctor, props, maskedLegacyContext) {
    var context = emptyContextObject;
    var contextType = ctor.contextType;

    {
      if ('contextType' in ctor) {
        var isValid = // Allow null for conditional declaration
        contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

        if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
          didWarnAboutInvalidateContextType.add(ctor);
          var addendum = '';

          if (contextType === undefined) {
            addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
          } else if (typeof contextType !== 'object') {
            addendum = ' However, it is set to a ' + typeof contextType + '.';
          } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
            addendum = ' Did you accidentally pass the Context.Provider instead?';
          } else if (contextType._context !== undefined) {
            // <Context.Consumer>
            addendum = ' Did you accidentally pass the Context.Consumer instead?';
          } else {
            addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
          }

          error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
        }
      }
    }

    if (typeof contextType === 'object' && contextType !== null) {
      context = readContext(contextType);
    } else {
      context = maskedLegacyContext;
    }

    var instance = new ctor(props, context);

    {
      if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutUninitializedState.has(componentName)) {
          didWarnAboutUninitializedState.add(componentName);

          error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
        }
      } // If new component APIs are defined, "unsafe" lifecycles won't be called.
      // Warn about these lifecycles if they are present.
      // Don't warn about react-lifecycles-compat polyfilled methods though.


      if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
        var foundWillMountName = null;
        var foundWillReceivePropsName = null;
        var foundWillUpdateName = null;

        if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
          foundWillMountName = 'componentWillMount';
        } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
          foundWillMountName = 'UNSAFE_componentWillMount';
        }

        if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
          foundWillReceivePropsName = 'componentWillReceiveProps';
        } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
          foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
        }

        if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
          foundWillUpdateName = 'componentWillUpdate';
        } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
          foundWillUpdateName = 'UNSAFE_componentWillUpdate';
        }

        if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
          var _componentName = getComponentNameFromType(ctor) || 'Component';

          var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

          if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
            didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

            error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
          }
        }
      }
    }

    return instance;
  }

  function checkClassInstance(instance, ctor, newProps) {
    {
      var name = getComponentNameFromType(ctor) || 'Component';
      var renderPresent = instance.render;

      if (!renderPresent) {
        if (ctor.prototype && typeof ctor.prototype.render === 'function') {
          error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
        } else {
          error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
        }
      }

      if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
        error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
      }

      if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
        error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
      }

      if (instance.propTypes) {
        error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
      }

      if (instance.contextType) {
        error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
      }

      {
        if (instance.contextTypes) {
          error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
        }

        if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
          didWarnAboutContextTypeAndContextTypes.add(ctor);

          error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
        }
      }

      if (typeof instance.componentShouldUpdate === 'function') {
        error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
      }

      if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
        error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
      }

      if (typeof instance.componentDidUnmount === 'function') {
        error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
      }

      if (typeof instance.componentDidReceiveProps === 'function') {
        error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
      }

      if (typeof instance.componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
      }

      if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
      }

      var hasMutatedProps = instance.props !== newProps;

      if (instance.props !== undefined && hasMutatedProps) {
        error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
      }

      if (instance.defaultProps) {
        error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
        didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

        error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
      }

      if (typeof instance.getDerivedStateFromProps === 'function') {
        error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof instance.getDerivedStateFromError === 'function') {
        error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
        error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
      }

      var _state = instance.state;

      if (_state && (typeof _state !== 'object' || isArray(_state))) {
        error('%s.state: must be set to an object or null', name);
      }

      if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
        error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
      }
    }
  }

  function callComponentWillMount(type, instance) {
    var oldState = instance.state;

    if (typeof instance.componentWillMount === 'function') {
      {
        if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
          var componentName = getComponentNameFromType(type) || 'Unknown';

          if (!didWarnAboutDeprecatedWillMount[componentName]) {
            warn( // keep this warning in sync with ReactStrictModeWarning.js
            'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

            didWarnAboutDeprecatedWillMount[componentName] = true;
          }
        }
      }

      instance.componentWillMount();
    }

    if (typeof instance.UNSAFE_componentWillMount === 'function') {
      instance.UNSAFE_componentWillMount();
    }

    if (oldState !== instance.state) {
      {
        error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
      }

      classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
    }
  }

  function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
    if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
      var oldQueue = internalInstance.queue;
      var oldReplace = internalInstance.replace;
      internalInstance.queue = null;
      internalInstance.replace = false;

      if (oldReplace && oldQueue.length === 1) {
        inst.state = oldQueue[0];
      } else {
        var nextState = oldReplace ? oldQueue[0] : inst.state;
        var dontMutate = true;

        for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
          var partial = oldQueue[i];
          var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

          if (partialState != null) {
            if (dontMutate) {
              dontMutate = false;
              nextState = assign({}, nextState, partialState);
            } else {
              assign(nextState, partialState);
            }
          }
        }

        inst.state = nextState;
      }
    } else {
      internalInstance.queue = null;
    }
  } // Invokes the mount life-cycles on a previously never rendered instance.


  function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
    {
      checkClassInstance(instance, ctor, newProps);
    }

    var initialState = instance.state !== undefined ? instance.state : null;
    instance.updater = classComponentUpdater;
    instance.props = newProps;
    instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
    // The internal instance will be used to manage updates that happen during this mount.

    var internalInstance = {
      queue: [],
      replace: false
    };
    set(instance, internalInstance);
    var contextType = ctor.contextType;

    if (typeof contextType === 'object' && contextType !== null) {
      instance.context = readContext(contextType);
    } else {
      instance.context = maskedLegacyContext;
    }

    {
      if (instance.state === newProps) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
          didWarnAboutDirectlyAssigningPropsToState.add(componentName);

          error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
        }
      }
    }

    var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

    if (typeof getDerivedStateFromProps === 'function') {
      instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
    } // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.


    if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
      callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
      // process them now.

      processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
    }
  }

  // Ids are base 32 strings whose binary representation corresponds to the
  // position of a node in a tree.
  // Every time the tree forks into multiple children, we add additional bits to
  // the left of the sequence that represent the position of the child within the
  // current level of children.
  //
  //      00101       00010001011010101
  //      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
  //   Fork 5 of 20       Parent id
  //
  // The leading 0s are important. In the above example, you only need 3 bits to
  // represent slot 5. However, you need 5 bits to represent all the forks at
  // the current level, so we must account for the empty bits at the end.
  //
  // For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
  // the zeroth id at a level would be indistinguishable from its parent.
  //
  // If a node has only one child, and does not materialize an id (i.e. does not
  // contain a useId hook), then we don't need to allocate any space in the
  // sequence. It's treated as a transparent indirection. For example, these two
  // trees produce the same ids:
  //
  // <>                          <>
  //   <Indirection>               <A />
  //     <A />                     <B />
  //   </Indirection>            </>
  //   <B />
  // </>
  //
  // However, we cannot skip any node that materializes an id. Otherwise, a parent
  // id that does not fork would be indistinguishable from its child id. For
  // example, this tree does not fork, but the parent and child must have
  // different ids.
  //
  // <Parent>
  //   <Child />
  // </Parent>
  //
  // To handle this scenario, every time we materialize an id, we allocate a
  // new level with a single slot. You can think of this as a fork with only one
  // prong, or an array of children with length 1.
  //
  // It's possible for the size of the sequence to exceed 32 bits, the max
  // size for bitwise operations. When this happens, we make more room by
  // converting the right part of the id to a string and storing it in an overflow
  // variable. We use a base 32 string representation, because 32 is the largest
  // power of 2 that is supported by toString(). We want the base to be large so
  // that the resulting ids are compact, and we want the base to be a power of 2
  // because every log2(base) bits corresponds to a single character, i.e. every
  // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
  // affecting the final result.
  var emptyTreeContext = {
    id: 1,
    overflow: ''
  };
  function getTreeId(context) {
    var overflow = context.overflow;
    var idWithLeadingBit = context.id;
    var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
    return id.toString(32) + overflow;
  }
  function pushTreeContext(baseContext, totalChildren, index) {
    var baseIdWithLeadingBit = baseContext.id;
    var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
    // of the id; we use it to account for leading 0s.

    var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
    var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
    var slot = index + 1;
    var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
    // consideration the leading 1 we use to mark the end of the sequence.

    if (length > 30) {
      // We overflowed the bitwise-safe range. Fall back to slower algorithm.
      // This branch assumes the length of the base id is greater than 5; it won't
      // work for smaller ids, because you need 5 bits per character.
      //
      // We encode the id in multiple steps: first the base id, then the
      // remaining digits.
      //
      // Each 5 bit sequence corresponds to a single base 32 character. So for
      // example, if the current id is 23 bits long, we can convert 20 of those
      // bits into a string of 4 characters, with 3 bits left over.
      //
      // First calculate how many bits in the base id represent a complete
      // sequence of characters.
      var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

      var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

      var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

      var restOfBaseId = baseId >> numberOfOverflowBits;
      var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
      // we made more room, this time it won't overflow.

      var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
      var restOfNewBits = slot << restOfBaseLength;
      var id = restOfNewBits | restOfBaseId;
      var overflow = newOverflow + baseOverflow;
      return {
        id: 1 << restOfLength | id,
        overflow: overflow
      };
    } else {
      // Normal path
      var newBits = slot << baseLength;

      var _id = newBits | baseId;

      var _overflow = baseOverflow;
      return {
        id: 1 << length | _id,
        overflow: _overflow
      };
    }
  }

  function getBitLength(number) {
    return 32 - clz32(number);
  }

  function getLeadingBit(id) {
    return 1 << getBitLength(id) - 1;
  } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
  // Based on:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

  var log = Math.log;
  var LN2 = Math.LN2;

  function clz32Fallback(x) {
    var asUint = x >>> 0;

    if (asUint === 0) {
      return 32;
    }

    return 31 - (log(asUint) / LN2 | 0) | 0;
  }

  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */
  function is(x, y) {
    return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
    ;
  }

  var objectIs = typeof Object.is === 'function' ? Object.is : is;

  var currentlyRenderingComponent = null;
  var currentlyRenderingTask = null;
  var firstWorkInProgressHook = null;
  var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

  var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

  var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

  var localIdCounter = 0; // Lazily created map of render-phase updates

  var renderPhaseUpdates = null; // Counter to prevent infinite loops.

  var numberOfReRenders = 0;
  var RE_RENDER_LIMIT = 25;
  var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

  var currentHookNameInDev;

  function resolveCurrentlyRenderingComponent() {
    if (currentlyRenderingComponent === null) {
      throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
    }

    {
      if (isInHookUserCodeInDev) {
        error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
      }
    }

    return currentlyRenderingComponent;
  }

  function areHookInputsEqual(nextDeps, prevDeps) {
    if (prevDeps === null) {
      {
        error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
      }

      return false;
    }

    {
      // Don't bother comparing lengths in prod because these arrays should be
      // passed inline.
      if (nextDeps.length !== prevDeps.length) {
        error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
      }
    }

    for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
      if (objectIs(nextDeps[i], prevDeps[i])) {
        continue;
      }

      return false;
    }

    return true;
  }

  function createHook() {
    if (numberOfReRenders > 0) {
      throw new Error('Rendered more hooks than during the previous render');
    }

    return {
      memoizedState: null,
      queue: null,
      next: null
    };
  }

  function createWorkInProgressHook() {
    if (workInProgressHook === null) {
      // This is the first hook in the list
      if (firstWorkInProgressHook === null) {
        isReRender = false;
        firstWorkInProgressHook = workInProgressHook = createHook();
      } else {
        // There's already a work-in-progress. Reuse it.
        isReRender = true;
        workInProgressHook = firstWorkInProgressHook;
      }
    } else {
      if (workInProgressHook.next === null) {
        isReRender = false; // Append to the end of the list

        workInProgressHook = workInProgressHook.next = createHook();
      } else {
        // There's already a work-in-progress. Reuse it.
        isReRender = true;
        workInProgressHook = workInProgressHook.next;
      }
    }

    return workInProgressHook;
  }

  function prepareToUseHooks(task, componentIdentity) {
    currentlyRenderingComponent = componentIdentity;
    currentlyRenderingTask = task;

    {
      isInHookUserCodeInDev = false;
    } // The following should have already been reset
    // didScheduleRenderPhaseUpdate = false;
    // localIdCounter = 0;
    // firstWorkInProgressHook = null;
    // numberOfReRenders = 0;
    // renderPhaseUpdates = null;
    // workInProgressHook = null;


    localIdCounter = 0;
  }
  function finishHooks(Component, props, children, refOrContext) {
    // This must be called after every function component to prevent hooks from
    // being used in classes.
    while (didScheduleRenderPhaseUpdate) {
      // Updates were scheduled during the render phase. They are stored in
      // the `renderPhaseUpdates` map. Call the component again, reusing the
      // work-in-progress hooks and applying the additional updates on top. Keep
      // restarting until no more updates are scheduled.
      didScheduleRenderPhaseUpdate = false;
      localIdCounter = 0;
      numberOfReRenders += 1; // Start over from the beginning of the list

      workInProgressHook = null;
      children = Component(props, refOrContext);
    }

    resetHooksState();
    return children;
  }
  function checkDidRenderIdHook() {
    // This should be called immediately after every finishHooks call.
    // Conceptually, it's part of the return value of finishHooks; it's only a
    // separate function to avoid using an array tuple.
    var didRenderIdHook = localIdCounter !== 0;
    return didRenderIdHook;
  } // Reset the internal hooks state if an error occurs while rendering a component

  function resetHooksState() {
    {
      isInHookUserCodeInDev = false;
    }

    currentlyRenderingComponent = null;
    currentlyRenderingTask = null;
    didScheduleRenderPhaseUpdate = false;
    firstWorkInProgressHook = null;
    numberOfReRenders = 0;
    renderPhaseUpdates = null;
    workInProgressHook = null;
  }

  function readContext$1(context) {
    {
      if (isInHookUserCodeInDev) {
        error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
      }
    }

    return readContext(context);
  }

  function useContext(context) {
    {
      currentHookNameInDev = 'useContext';
    }

    resolveCurrentlyRenderingComponent();
    return readContext(context);
  }

  function basicStateReducer(state, action) {
    // $FlowFixMe: Flow doesn't like mixed types
    return typeof action === 'function' ? action(state) : action;
  }

  function useState(initialState) {
    {
      currentHookNameInDev = 'useState';
    }

    return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
    initialState);
  }
  function useReducer(reducer, initialArg, init) {
    {
      if (reducer !== basicStateReducer) {
        currentHookNameInDev = 'useReducer';
      }
    }

    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();

    if (isReRender) {
      // This is a re-render. Apply the new render phase updates to the previous
      // current hook.
      var queue = workInProgressHook.queue;
      var dispatch = queue.dispatch;

      if (renderPhaseUpdates !== null) {
        // Render phase updates are stored in a map of queue -> linked list
        var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

        if (firstRenderPhaseUpdate !== undefined) {
          renderPhaseUpdates.delete(queue);
          var newState = workInProgressHook.memoizedState;
          var update = firstRenderPhaseUpdate;

          do {
            // Process this render phase update. We don't have to check the
            // priority because it will always be the same as the current
            // render's.
            var action = update.action;

            {
              isInHookUserCodeInDev = true;
            }

            newState = reducer(newState, action);

            {
              isInHookUserCodeInDev = false;
            }

            update = update.next;
          } while (update !== null);

          workInProgressHook.memoizedState = newState;
          return [newState, dispatch];
        }
      }

      return [workInProgressHook.memoizedState, dispatch];
    } else {
      {
        isInHookUserCodeInDev = true;
      }

      var initialState;

      if (reducer === basicStateReducer) {
        // Special case for `useState`.
        initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
      } else {
        initialState = init !== undefined ? init(initialArg) : initialArg;
      }

      {
        isInHookUserCodeInDev = false;
      }

      workInProgressHook.memoizedState = initialState;

      var _queue = workInProgressHook.queue = {
        last: null,
        dispatch: null
      };

      var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

      return [workInProgressHook.memoizedState, _dispatch];
    }
  }

  function useMemo(nextCreate, deps) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;

    if (workInProgressHook !== null) {
      var prevState = workInProgressHook.memoizedState;

      if (prevState !== null) {
        if (nextDeps !== null) {
          var prevDeps = prevState[1];

          if (areHookInputsEqual(nextDeps, prevDeps)) {
            return prevState[0];
          }
        }
      }
    }

    {
      isInHookUserCodeInDev = true;
    }

    var nextValue = nextCreate();

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = [nextValue, nextDeps];
    return nextValue;
  }

  function useRef(initialValue) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    var previousRef = workInProgressHook.memoizedState;

    if (previousRef === null) {
      var ref = {
        current: initialValue
      };

      {
        Object.seal(ref);
      }

      workInProgressHook.memoizedState = ref;
      return ref;
    } else {
      return previousRef;
    }
  }

  function useLayoutEffect(create, inputs) {
    {
      currentHookNameInDev = 'useLayoutEffect';

      error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
    }
  }

  function dispatchAction(componentIdentity, queue, action) {
    if (numberOfReRenders >= RE_RENDER_LIMIT) {
      throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
    }

    if (componentIdentity === currentlyRenderingComponent) {
      // This is a render phase update. Stash it in a lazily-created map of
      // queue -> linked list of updates. After this render pass, we'll restart
      // and apply the stashed updates on top of the work-in-progress hook.
      didScheduleRenderPhaseUpdate = true;
      var update = {
        action: action,
        next: null
      };

      if (renderPhaseUpdates === null) {
        renderPhaseUpdates = new Map();
      }

      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate === undefined) {
        renderPhaseUpdates.set(queue, update);
      } else {
        // Append the update to the end of the list.
        var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

        while (lastRenderPhaseUpdate.next !== null) {
          lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        }

        lastRenderPhaseUpdate.next = update;
      }
    }
  }

  function useCallback(callback, deps) {
    return useMemo(function () {
      return callback;
    }, deps);
  } // TODO Decide on how to implement this hook for server rendering.
  // If a mutation occurs during render, consider triggering a Suspense boundary
  // and falling back to client rendering.

  function useMutableSource(source, getSnapshot, subscribe) {
    resolveCurrentlyRenderingComponent();
    return getSnapshot(source._source);
  }

  function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    if (getServerSnapshot === undefined) {
      throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
    }

    return getServerSnapshot();
  }

  function useDeferredValue(value) {
    resolveCurrentlyRenderingComponent();
    return value;
  }

  function unsupportedStartTransition() {
    throw new Error('startTransition cannot be called during server rendering.');
  }

  function useTransition() {
    resolveCurrentlyRenderingComponent();
    return [false, unsupportedStartTransition];
  }

  function useId() {
    var task = currentlyRenderingTask;
    var treeId = getTreeId(task.treeContext);
    var responseState = currentResponseState;

    if (responseState === null) {
      throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
    }

    var localId = localIdCounter++;
    return makeId(responseState, treeId, localId);
  }

  function noop() {}

  var Dispatcher = {
    readContext: readContext$1,
    useContext: useContext,
    useMemo: useMemo,
    useReducer: useReducer,
    useRef: useRef,
    useState: useState,
    useInsertionEffect: noop,
    useLayoutEffect: useLayoutEffect,
    useCallback: useCallback,
    // useImperativeHandle is not run in the server environment
    useImperativeHandle: noop,
    // Effects are not run in the server environment.
    useEffect: noop,
    // Debugging effect
    useDebugValue: noop,
    useDeferredValue: useDeferredValue,
    useTransition: useTransition,
    useId: useId,
    // Subscriptions are not setup in a server environment.
    useMutableSource: useMutableSource,
    useSyncExternalStore: useSyncExternalStore
  };

  var currentResponseState = null;
  function setCurrentResponseState(responseState) {
    currentResponseState = responseState;
  }

  function getStackByComponentStackNode(componentStack) {
    try {
      var info = '';
      var node = componentStack;

      do {
        switch (node.tag) {
          case 0:
            info += describeBuiltInComponentFrame(node.type, null, null);
            break;

          case 1:
            info += describeFunctionComponentFrame(node.type, null, null);
            break;

          case 2:
            info += describeClassComponentFrame(node.type, null, null);
            break;
        }

        node = node.parent;
      } while (node);

      return info;
    } catch (x) {
      return '\nError generating stack: ' + x.message + '\n' + x.stack;
    }
  }

  var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
  var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
  var PENDING = 0;
  var COMPLETED = 1;
  var FLUSHED = 2;
  var ABORTED = 3;
  var ERRORED = 4;
  var OPEN = 0;
  var CLOSING = 1;
  var CLOSED = 2;
  // This is a default heuristic for how to split up the HTML content into progressive
  // loading. Our goal is to be able to display additional new content about every 500ms.
  // Faster than that is unnecessary and should be throttled on the client. It also
  // adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
  // end device but higher end suffer less from the overhead than lower end does from
  // not getting small enough pieces. We error on the side of low end.
  // We base this on low end 3G speeds which is about 500kbits per second. We assume
  // that there can be a reasonable drop off from max bandwidth which leaves you with
  // as little as 80%. We can receive half of that each 500ms - at best. In practice,
  // a little bandwidth is lost to processing and contention - e.g. CSS and images that
  // are downloaded along with the main content. So we estimate about half of that to be
  // the lower end throughput. In other words, we expect that you can at least show
  // about 12.5kb of content per 500ms. Not counting starting latency for the first
  // paint.
  // 500 * 1024 / 8 * .8 * 0.5 / 2
  var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

  function defaultErrorHandler(error) {
    console['error'](error); // Don't transform to our wrapper

    return null;
  }

  function noop$1() {}

  function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
    var pingedTasks = [];
    var abortSet = new Set();
    var request = {
      destination: null,
      responseState: responseState,
      progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
      status: OPEN,
      fatalError: null,
      nextSegmentId: 0,
      allPendingTasks: 0,
      pendingRootTasks: 0,
      completedRootSegment: null,
      abortableTasks: abortSet,
      pingedTasks: pingedTasks,
      clientRenderedBoundaries: [],
      completedBoundaries: [],
      partialBoundaries: [],
      onError: onError === undefined ? defaultErrorHandler : onError,
      onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
      onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
      onShellError: onShellError === undefined ? noop$1 : onShellError,
      onFatalError: onFatalError === undefined ? noop$1 : onFatalError
    }; // This segment represents the root fallback.

    var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
    false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

    rootSegment.parentFlushed = true;
    var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
    pingedTasks.push(rootTask);
    return request;
  }

  function pingTask(request, task) {
    var pingedTasks = request.pingedTasks;
    pingedTasks.push(task);

    if (pingedTasks.length === 1) {
      scheduleWork(function () {
        return performWork(request);
      });
    }
  }

  function createSuspenseBoundary(request, fallbackAbortableTasks) {
    return {
      id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
      rootSegmentID: -1,
      parentFlushed: false,
      pendingTasks: 0,
      forceClientRender: false,
      completedSegments: [],
      byteSize: 0,
      fallbackAbortableTasks: fallbackAbortableTasks,
      errorDigest: null
    };
  }

  function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
    request.allPendingTasks++;

    if (blockedBoundary === null) {
      request.pendingRootTasks++;
    } else {
      blockedBoundary.pendingTasks++;
    }

    var task = {
      node: node,
      ping: function () {
        return pingTask(request, task);
      },
      blockedBoundary: blockedBoundary,
      blockedSegment: blockedSegment,
      abortSet: abortSet,
      legacyContext: legacyContext,
      context: context,
      treeContext: treeContext
    };

    {
      task.componentStack = null;
    }

    abortSet.add(task);
    return task;
  }

  function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
    return {
      status: PENDING,
      id: -1,
      // lazily assigned later
      index: index,
      parentFlushed: false,
      chunks: [],
      children: [],
      formatContext: formatContext,
      boundary: boundary,
      lastPushedText: lastPushedText,
      textEmbedded: textEmbedded
    };
  } // DEV-only global reference to the currently executing task


  var currentTaskInDEV = null;

  function getCurrentStackInDEV() {
    {
      if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
        return '';
      }

      return getStackByComponentStackNode(currentTaskInDEV.componentStack);
    }
  }

  function pushBuiltInComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 0,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function pushFunctionComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 1,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function pushClassComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 2,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function popComponentStackInDEV(task) {
    {
      if (task.componentStack === null) {
        error('Unexpectedly popped too many stack frames. This is a bug in React.');
      } else {
        task.componentStack = task.componentStack.parent;
      }
    }
  } // stash the component stack of an unwinding error until it is processed


  var lastBoundaryErrorComponentStackDev = null;

  function captureBoundaryErrorDetailsDev(boundary, error) {
    {
      var errorMessage;

      if (typeof error === 'string') {
        errorMessage = error;
      } else if (error && typeof error.message === 'string') {
        errorMessage = error.message;
      } else {
        // eslint-disable-next-line react-internal/safe-string-coercion
        errorMessage = String(error);
      }

      var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
      lastBoundaryErrorComponentStackDev = null;
      boundary.errorMessage = errorMessage;
      boundary.errorComponentStack = errorComponentStack;
    }
  }

  function logRecoverableError(request, error) {
    // If this callback errors, we intentionally let that error bubble up to become a fatal error
    // so that someone fixes the error reporting instead of hiding it.
    var errorDigest = request.onError(error);

    if (errorDigest != null && typeof errorDigest !== 'string') {
      // eslint-disable-next-line react-internal/prod-error-codes
      throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
    }

    return errorDigest;
  }

  function fatalError(request, error) {
    // This is called outside error handling code such as if the root errors outside
    // a suspense boundary or if the root suspense boundary's fallback errors.
    // It's also called if React itself or its host configs errors.
    var onShellError = request.onShellError;
    onShellError(error);
    var onFatalError = request.onFatalError;
    onFatalError(error);

    if (request.destination !== null) {
      request.status = CLOSED;
      closeWithError(request.destination, error);
    } else {
      request.status = CLOSING;
      request.fatalError = error;
    }
  }

  function renderSuspenseBoundary(request, task, props) {
    pushBuiltInComponentStackInDEV(task, 'Suspense');
    var parentBoundary = task.blockedBoundary;
    var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
    // the fallback so that we can later replace that segment with the content.
    // This also lets us split out the main content even if it doesn't suspend,
    // in case it ends up generating a large subtree of content.

    var fallback = props.fallback;
    var content = props.children;
    var fallbackAbortSet = new Set();
    var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
    var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

    var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
    false, false);
    parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

    parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

    var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
    false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
    // no parent segment so there's nothing to wait on.

    contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
    // I suspect that there might be some efficiency benefits from not creating the suspended task
    // and instead just using the stack if possible.
    // TODO: Call this directly instead of messing with saving and restoring contexts.
    // We can reuse the current context and task to render the content immediately without
    // context switching. We just need to temporarily switch which boundary and which segment
    // we're writing to. If something suspends, it'll spawn new suspended task with that context.

    task.blockedBoundary = newBoundary;
    task.blockedSegment = contentRootSegment;

    try {
      // We use the safe form because we don't handle suspending here. Only error handling.
      renderNode(request, task, content);
      pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
      contentRootSegment.status = COMPLETED;
      queueCompletedSegment(newBoundary, contentRootSegment);

      if (newBoundary.pendingTasks === 0) {
        // This must have been the last segment we were waiting on. This boundary is now complete.
        // Therefore we won't need the fallback. We early return so that we don't have to create
        // the fallback.
        popComponentStackInDEV(task);
        return;
      }
    } catch (error) {
      contentRootSegment.status = ERRORED;
      newBoundary.forceClientRender = true;
      newBoundary.errorDigest = logRecoverableError(request, error);

      {
        captureBoundaryErrorDetailsDev(newBoundary, error);
      } // We don't need to decrement any task numbers because we didn't spawn any new task.
      // We don't need to schedule any task because we know the parent has written yet.
      // We do need to fallthrough to create the fallback though.

    } finally {
      task.blockedBoundary = parentBoundary;
      task.blockedSegment = parentSegment;
    } // We create suspended task for the fallback because we don't want to actually work
    // on it yet in case we finish the main content, so we queue for later.


    var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

    {
      suspendedFallbackTask.componentStack = task.componentStack;
    } // TODO: This should be queued at a separate lower priority queue so that we only work
    // on preparing fallbacks if we don't have any more main content to task on.


    request.pingedTasks.push(suspendedFallbackTask);
    popComponentStackInDEV(task);
  }

  function renderHostElement(request, task, type, props) {
    pushBuiltInComponentStackInDEV(task, type);
    var segment = task.blockedSegment;
    var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
    segment.lastPushedText = false;
    var prevContext = segment.formatContext;
    segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
    // need to pop back up and finish this subtree of HTML.

    renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
    // the correct context. Therefore this is not in a finally.

    segment.formatContext = prevContext;
    pushEndInstance(segment.chunks, type);
    segment.lastPushedText = false;
    popComponentStackInDEV(task);
  }

  function shouldConstruct$1(Component) {
    return Component.prototype && Component.prototype.isReactComponent;
  }

  function renderWithHooks(request, task, Component, props, secondArg) {
    var componentIdentity = {};
    prepareToUseHooks(task, componentIdentity);
    var result = Component(props, secondArg);
    return finishHooks(Component, props, result, secondArg);
  }

  function finishClassComponent(request, task, instance, Component, props) {
    var nextChildren = instance.render();

    {
      if (instance.props !== props) {
        if (!didWarnAboutReassigningProps) {
          error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
        }

        didWarnAboutReassigningProps = true;
      }
    }

    {
      var childContextTypes = Component.childContextTypes;

      if (childContextTypes !== null && childContextTypes !== undefined) {
        var previousContext = task.legacyContext;
        var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
        task.legacyContext = mergedContext;
        renderNodeDestructive(request, task, nextChildren);
        task.legacyContext = previousContext;
        return;
      }
    }

    renderNodeDestructive(request, task, nextChildren);
  }

  function renderClassComponent(request, task, Component, props) {
    pushClassComponentStackInDEV(task, Component);
    var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
    var instance = constructClassInstance(Component, props, maskedContext);
    mountClassInstance(instance, Component, props, maskedContext);
    finishClassComponent(request, task, instance, Component, props);
    popComponentStackInDEV(task);
  }

  var didWarnAboutBadClass = {};
  var didWarnAboutModulePatternComponent = {};
  var didWarnAboutContextTypeOnFunctionComponent = {};
  var didWarnAboutGetDerivedStateOnFunctionComponent = {};
  var didWarnAboutReassigningProps = false;
  var didWarnAboutDefaultPropsOnFunctionComponent = {};
  var didWarnAboutGenerators = false;
  var didWarnAboutMaps = false;
  var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
  // components for some reason.

  function renderIndeterminateComponent(request, task, Component, props) {
    var legacyContext;

    {
      legacyContext = getMaskedContext(Component, task.legacyContext);
    }

    pushFunctionComponentStackInDEV(task, Component);

    {
      if (Component.prototype && typeof Component.prototype.render === 'function') {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutBadClass[componentName]) {
          error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

          didWarnAboutBadClass[componentName] = true;
        }
      }
    }

    var value = renderWithHooks(request, task, Component, props, legacyContext);
    var hasId = checkDidRenderIdHook();

    {
      // Support for module components is deprecated and is removed behind a flag.
      // Whether or not it would crash later, we want to show a good message in DEV first.
      if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
        var _componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

          didWarnAboutModulePatternComponent[_componentName] = true;
        }
      }
    }

    if ( // Run these checks in production only if the flag is off.
    // Eventually we'll delete this branch altogether.
     typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      {
        var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName2]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

          didWarnAboutModulePatternComponent[_componentName2] = true;
        }
      }

      mountClassInstance(value, Component, props, legacyContext);
      finishClassComponent(request, task, value, Component, props);
    } else {

      {
        validateFunctionComponentInDev(Component);
      } // We're now successfully past this task, and we don't have to pop back to
      // the previous task every again, so we can use the destructive recursive form.


      if (hasId) {
        // This component materialized an id. We treat this as its own level, with
        // a single "child" slot.
        var prevTreeContext = task.treeContext;
        var totalChildren = 1;
        var index = 0;
        task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

        try {
          renderNodeDestructive(request, task, value);
        } finally {
          task.treeContext = prevTreeContext;
        }
      } else {
        renderNodeDestructive(request, task, value);
      }
    }

    popComponentStackInDEV(task);
  }

  function validateFunctionComponentInDev(Component) {
    {
      if (Component) {
        if (Component.childContextTypes) {
          error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
        }
      }

      if ( Component.defaultProps !== undefined) {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
          error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

          didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
        }
      }

      if (typeof Component.getDerivedStateFromProps === 'function') {
        var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
          error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

          didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
        }
      }

      if (typeof Component.contextType === 'object' && Component.contextType !== null) {
        var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
          error('%s: Function components do not support contextType.', _componentName4);

          didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
        }
      }
    }
  }

  function resolveDefaultProps(Component, baseProps) {
    if (Component && Component.defaultProps) {
      // Resolve default props. Taken from ReactElement
      var props = assign({}, baseProps);
      var defaultProps = Component.defaultProps;

      for (var propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }

      return props;
    }

    return baseProps;
  }

  function renderForwardRef(request, task, type, props, ref) {
    pushFunctionComponentStackInDEV(task, type.render);
    var children = renderWithHooks(request, task, type.render, props, ref);
    var hasId = checkDidRenderIdHook();

    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, children);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, children);
    }

    popComponentStackInDEV(task);
  }

  function renderMemo(request, task, type, props, ref) {
    var innerType = type.type;
    var resolvedProps = resolveDefaultProps(innerType, props);
    renderElement(request, task, innerType, resolvedProps, ref);
  }

  function renderContextConsumer(request, task, context, props) {
    // The logic below for Context differs depending on PROD or DEV mode. In
    // DEV mode, we create a separate object for Context.Consumer that acts
    // like a proxy to Context. This proxy object adds unnecessary code in PROD
    // so we use the old behaviour (Context.Consumer references Context) to
    // reduce size and overhead. The separate object references context via
    // a property called "_context", which also gives us the ability to check
    // in DEV mode if this property exists or not and warn if it does not.
    {
      if (context._context === undefined) {
        // This may be because it's a Context (rather than a Consumer).
        // Or it may be because it's older React where they're the same thing.
        // We only want to warn if we're sure it's a new React.
        if (context !== context.Consumer) {
          if (!hasWarnedAboutUsingContextAsConsumer) {
            hasWarnedAboutUsingContextAsConsumer = true;

            error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
          }
        }
      } else {
        context = context._context;
      }
    }

    var render = props.children;

    {
      if (typeof render !== 'function') {
        error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
      }
    }

    var newValue = readContext(context);
    var newChildren = render(newValue);
    renderNodeDestructive(request, task, newChildren);
  }

  function renderContextProvider(request, task, type, props) {
    var context = type._context;
    var value = props.value;
    var children = props.children;
    var prevSnapshot;

    {
      prevSnapshot = task.context;
    }

    task.context = pushProvider(context, value);
    renderNodeDestructive(request, task, children);
    task.context = popProvider(context);

    {
      if (prevSnapshot !== task.context) {
        error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
      }
    }
  }

  function renderLazyComponent(request, task, lazyComponent, props, ref) {
    pushBuiltInComponentStackInDEV(task, 'Lazy');
    var payload = lazyComponent._payload;
    var init = lazyComponent._init;
    var Component = init(payload);
    var resolvedProps = resolveDefaultProps(Component, props);
    renderElement(request, task, Component, resolvedProps, ref);
    popComponentStackInDEV(task);
  }

  function renderElement(request, task, type, props, ref) {
    if (typeof type === 'function') {
      if (shouldConstruct$1(type)) {
        renderClassComponent(request, task, type, props);
        return;
      } else {
        renderIndeterminateComponent(request, task, type, props);
        return;
      }
    }

    if (typeof type === 'string') {
      renderHostElement(request, task, type, props);
      return;
    }

    switch (type) {
      // TODO: LegacyHidden acts the same as a fragment. This only works
      // because we currently assume that every instance of LegacyHidden is
      // accompanied by a host component wrapper. In the hidden mode, the host
      // component is given a `hidden` attribute, which ensures that the
      // initial HTML is not visible. To support the use of LegacyHidden as a
      // true fragment, without an extra DOM node, we would have to hide the
      // initial HTML in some other way.
      // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
      case REACT_LEGACY_HIDDEN_TYPE:
      case REACT_DEBUG_TRACING_MODE_TYPE:
      case REACT_STRICT_MODE_TYPE:
      case REACT_PROFILER_TYPE:
      case REACT_FRAGMENT_TYPE:
        {
          renderNodeDestructive(request, task, props.children);
          return;
        }

      case REACT_SUSPENSE_LIST_TYPE:
        {
          pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

          renderNodeDestructive(request, task, props.children);
          popComponentStackInDEV(task);
          return;
        }

      case REACT_SCOPE_TYPE:
        {

          throw new Error('ReactDOMServer does not yet support scope components.');
        }
      // eslint-disable-next-line-no-fallthrough

      case REACT_SUSPENSE_TYPE:
        {
          {
            renderSuspenseBoundary(request, task, props);
          }

          return;
        }
    }

    if (typeof type === 'object' && type !== null) {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          {
            renderForwardRef(request, task, type, props, ref);
            return;
          }

        case REACT_MEMO_TYPE:
          {
            renderMemo(request, task, type, props, ref);
            return;
          }

        case REACT_PROVIDER_TYPE:
          {
            renderContextProvider(request, task, type, props);
            return;
          }

        case REACT_CONTEXT_TYPE:
          {
            renderContextConsumer(request, task, type, props);
            return;
          }

        case REACT_LAZY_TYPE:
          {
            renderLazyComponent(request, task, type, props);
            return;
          }
      }
    }

    var info = '';

    {
      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
        info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
      }
    }

    throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
  }

  function validateIterable(iterable, iteratorFn) {
    {
      // We don't support rendering Generators because it's a mutation.
      // See https://github.com/facebook/react/issues/12995
      if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
      iterable[Symbol.toStringTag] === 'Generator') {
        if (!didWarnAboutGenerators) {
          error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
        }

        didWarnAboutGenerators = true;
      } // Warn about using Maps as children


      if (iterable.entries === iteratorFn) {
        if (!didWarnAboutMaps) {
          error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
        }

        didWarnAboutMaps = true;
      }
    }
  }

  function renderNodeDestructive(request, task, node) {
    {
      // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
      // a component stack at the right place in the tree. We don't do this in renderNode
      // becuase it is not called at every layer of the tree and we may lose frames
      try {
        return renderNodeDestructiveImpl(request, task, node);
      } catch (x) {
        if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
          // This is an error, stash the component stack if it is null.
          lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
        } // rethrow so normal suspense logic can handle thrown value accordingly


        throw x;
      }
    }
  } // This function by it self renders a node and consumes the task by mutating it
  // to update the current execution state.


  function renderNodeDestructiveImpl(request, task, node) {
    // Stash the node we're working on. We'll pick up from this task in case
    // something suspends.
    task.node = node; // Handle object types

    if (typeof node === 'object' && node !== null) {
      switch (node.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var element = node;
            var type = element.type;
            var props = element.props;
            var ref = element.ref;
            renderElement(request, task, type, props, ref);
            return;
          }

        case REACT_PORTAL_TYPE:
          throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
        // eslint-disable-next-line-no-fallthrough

        case REACT_LAZY_TYPE:
          {
            var lazyNode = node;
            var payload = lazyNode._payload;
            var init = lazyNode._init;
            var resolvedNode;

            {
              try {
                resolvedNode = init(payload);
              } catch (x) {
                if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                  // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                  // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                  // vs Component position. We do not want the frame for Errors so we exclusively do this in
                  // the wakeable branch
                  pushBuiltInComponentStackInDEV(task, 'Lazy');
                }

                throw x;
              }
            }

            renderNodeDestructive(request, task, resolvedNode);
            return;
          }
      }

      if (isArray(node)) {
        renderChildrenArray(request, task, node);
        return;
      }

      var iteratorFn = getIteratorFn(node);

      if (iteratorFn) {
        {
          validateIterable(node, iteratorFn);
        }

        var iterator = iteratorFn.call(node);

        if (iterator) {
          // We need to know how many total children are in this set, so that we
          // can allocate enough id slots to acommodate them. So we must exhaust
          // the iterator before we start recursively rendering the children.
          // TODO: This is not great but I think it's inherent to the id
          // generation algorithm.
          var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

          if (!step.done) {
            var children = [];

            do {
              children.push(step.value);
              step = iterator.next();
            } while (!step.done);

            renderChildrenArray(request, task, children);
            return;
          }

          return;
        }
      }

      var childString = Object.prototype.toString.call(node);
      throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
    }

    if (typeof node === 'string') {
      var segment = task.blockedSegment;
      segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
      return;
    }

    if (typeof node === 'number') {
      var _segment = task.blockedSegment;
      _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
      return;
    }

    {
      if (typeof node === 'function') {
        error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
      }
    }
  }

  function renderChildrenArray(request, task, children) {
    var totalChildren = children.length;

    for (var i = 0; i < totalChildren; i++) {
      var prevTreeContext = task.treeContext;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

      try {
        // We need to use the non-destructive form so that we can safely pop back
        // up and render the sibling if something suspends.
        renderNode(request, task, children[i]);
      } finally {
        task.treeContext = prevTreeContext;
      }
    }
  }

  function spawnNewSuspendedTask(request, task, x) {
    // Something suspended, we'll need to create a new segment and resolve it later.
    var segment = task.blockedSegment;
    var insertionIndex = segment.chunks.length;
    var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
    segment.lastPushedText, // Assume we are text embedded at the trailing edge
    true);
    segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

    segment.lastPushedText = false;
    var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

    {
      if (task.componentStack !== null) {
        // We pop one task off the stack because the node that suspended will be tried again,
        // which will add it back onto the stack.
        newTask.componentStack = task.componentStack.parent;
      }
    }

    var ping = newTask.ping;
    x.then(ping, ping);
  } // This is a non-destructive form of rendering a node. If it suspends it spawns
  // a new task and restores the context of this task to what it was before.


  function renderNode(request, task, node) {
    // TODO: Store segment.children.length here and reset it in case something
    // suspended partially through writing something.
    // Snapshot the current context in case something throws to interrupt the
    // process.
    var previousFormatContext = task.blockedSegment.formatContext;
    var previousLegacyContext = task.legacyContext;
    var previousContext = task.context;
    var previousComponentStack = null;

    {
      previousComponentStack = task.componentStack;
    }

    try {
      return renderNodeDestructive(request, task, node);
    } catch (x) {
      resetHooksState();

      if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
        spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
        // functions in case nothing throws so we don't use "finally" here.

        task.blockedSegment.formatContext = previousFormatContext;
        task.legacyContext = previousLegacyContext;
        task.context = previousContext; // Restore all active ReactContexts to what they were before.

        switchContext(previousContext);

        {
          task.componentStack = previousComponentStack;
        }

        return;
      } else {
        // Restore the context. We assume that this will be restored by the inner
        // functions in case nothing throws so we don't use "finally" here.
        task.blockedSegment.formatContext = previousFormatContext;
        task.legacyContext = previousLegacyContext;
        task.context = previousContext; // Restore all active ReactContexts to what they were before.

        switchContext(previousContext);

        {
          task.componentStack = previousComponentStack;
        } // We assume that we don't need the correct context.
        // Let's terminate the rest of the tree and don't render any siblings.


        throw x;
      }
    }
  }

  function erroredTask(request, boundary, segment, error) {
    // Report the error to a global handler.
    var errorDigest = logRecoverableError(request, error);

    if (boundary === null) {
      fatalError(request, error);
    } else {
      boundary.pendingTasks--;

      if (!boundary.forceClientRender) {
        boundary.forceClientRender = true;
        boundary.errorDigest = errorDigest;

        {
          captureBoundaryErrorDetailsDev(boundary, error);
        } // Regardless of what happens next, this boundary won't be displayed,
        // so we can flush it, if the parent already flushed.


        if (boundary.parentFlushed) {
          // We don't have a preference where in the queue this goes since it's likely
          // to error on the client anyway. However, intentionally client-rendered
          // boundaries should be flushed earlier so that they can start on the client.
          // We reuse the same queue for errors.
          request.clientRenderedBoundaries.push(boundary);
        }
      }
    }

    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }

  function abortTaskSoft(task) {
    // This aborts task without aborting the parent boundary that it blocks.
    // It's used for when we didn't need this task to complete the tree.
    // If task was needed, then it should use abortTask instead.
    var request = this;
    var boundary = task.blockedBoundary;
    var segment = task.blockedSegment;
    segment.status = ABORTED;
    finishedTask(request, boundary, segment);
  }

  function abortTask(task, request, reason) {
    // This aborts the task and aborts the parent that it blocks, putting it into
    // client rendered mode.
    var boundary = task.blockedBoundary;
    var segment = task.blockedSegment;
    segment.status = ABORTED;

    if (boundary === null) {
      request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
      // the request;

      if (request.status !== CLOSED) {
        request.status = CLOSED;

        if (request.destination !== null) {
          close(request.destination);
        }
      }
    } else {
      boundary.pendingTasks--;

      if (!boundary.forceClientRender) {
        boundary.forceClientRender = true;

        var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

        boundary.errorDigest = request.onError(_error);

        {
          var errorPrefix = 'The server did not finish this Suspense boundary: ';

          if (_error && typeof _error.message === 'string') {
            _error = errorPrefix + _error.message;
          } else {
            // eslint-disable-next-line react-internal/safe-string-coercion
            _error = errorPrefix + String(_error);
          }

          var previousTaskInDev = currentTaskInDEV;
          currentTaskInDEV = task;

          try {
            captureBoundaryErrorDetailsDev(boundary, _error);
          } finally {
            currentTaskInDEV = previousTaskInDev;
          }
        }

        if (boundary.parentFlushed) {
          request.clientRenderedBoundaries.push(boundary);
        }
      } // If this boundary was still pending then we haven't already cancelled its fallbacks.
      // We'll need to abort the fallbacks, which will also error that parent boundary.


      boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
        return abortTask(fallbackTask, request, reason);
      });
      boundary.fallbackAbortableTasks.clear();
      request.allPendingTasks--;

      if (request.allPendingTasks === 0) {
        var onAllReady = request.onAllReady;
        onAllReady();
      }
    }
  }

  function queueCompletedSegment(boundary, segment) {
    if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
      // This is an empty segment. There's nothing to write, so we can instead transfer the ID
      // to the child. That way any existing references point to the child.
      var childSegment = segment.children[0];
      childSegment.id = segment.id;
      childSegment.parentFlushed = true;

      if (childSegment.status === COMPLETED) {
        queueCompletedSegment(boundary, childSegment);
      }
    } else {
      var completedSegments = boundary.completedSegments;
      completedSegments.push(segment);
    }
  }

  function finishedTask(request, boundary, segment) {
    if (boundary === null) {
      if (segment.parentFlushed) {
        if (request.completedRootSegment !== null) {
          throw new Error('There can only be one root segment. This is a bug in React.');
        }

        request.completedRootSegment = segment;
      }

      request.pendingRootTasks--;

      if (request.pendingRootTasks === 0) {
        // We have completed the shell so the shell can't error anymore.
        request.onShellError = noop$1;
        var onShellReady = request.onShellReady;
        onShellReady();
      }
    } else {
      boundary.pendingTasks--;

      if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
        // This must have been the last segment we were waiting on. This boundary is now complete.
        if (segment.parentFlushed) {
          // Our parent segment already flushed, so we need to schedule this segment to be emitted.
          // If it is a segment that was aborted, we'll write other content instead so we don't need
          // to emit it.
          if (segment.status === COMPLETED) {
            queueCompletedSegment(boundary, segment);
          }
        }

        if (boundary.parentFlushed) {
          // The segment might be part of a segment that didn't flush yet, but if the boundary's
          // parent flushed, we need to schedule the boundary to be emitted.
          request.completedBoundaries.push(boundary);
        } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
        // This needs to happen after we read the parentFlushed flags because aborting can finish
        // work which can trigger user code, which can start flushing, which can change those flags.


        boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
        boundary.fallbackAbortableTasks.clear();
      } else {
        if (segment.parentFlushed) {
          // Our parent already flushed, so we need to schedule this segment to be emitted.
          // If it is a segment that was aborted, we'll write other content instead so we don't need
          // to emit it.
          if (segment.status === COMPLETED) {
            queueCompletedSegment(boundary, segment);
            var completedSegments = boundary.completedSegments;

            if (completedSegments.length === 1) {
              // This is the first time since we last flushed that we completed anything.
              // We can schedule this boundary to emit its partially completed segments early
              // in case the parent has already been flushed.
              if (boundary.parentFlushed) {
                request.partialBoundaries.push(boundary);
              }
            }
          }
        }
      }
    }

    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      // This needs to be called at the very end so that we can synchronously write the result
      // in the callback if needed.
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }

  function retryTask(request, task) {
    var segment = task.blockedSegment;

    if (segment.status !== PENDING) {
      // We completed this by other means before we had a chance to retry it.
      return;
    } // We restore the context to what it was when we suspended.
    // We don't restore it after we leave because it's likely that we'll end up
    // needing a very similar context soon again.


    switchContext(task.context);
    var prevTaskInDEV = null;

    {
      prevTaskInDEV = currentTaskInDEV;
      currentTaskInDEV = task;
    }

    try {
      // We call the destructive form that mutates this task. That way if something
      // suspends again, we can reuse the same task instead of spawning a new one.
      renderNodeDestructive(request, task, task.node);
      pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
      task.abortSet.delete(task);
      segment.status = COMPLETED;
      finishedTask(request, task.blockedBoundary, segment);
    } catch (x) {
      resetHooksState();

      if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
        // Something suspended again, let's pick it back up later.
        var ping = task.ping;
        x.then(ping, ping);
      } else {
        task.abortSet.delete(task);
        segment.status = ERRORED;
        erroredTask(request, task.blockedBoundary, segment, x);
      }
    } finally {
      {
        currentTaskInDEV = prevTaskInDEV;
      }
    }
  }

  function performWork(request) {
    if (request.status === CLOSED) {
      return;
    }

    var prevContext = getActiveContext();
    var prevDispatcher = ReactCurrentDispatcher$1.current;
    ReactCurrentDispatcher$1.current = Dispatcher;
    var prevGetCurrentStackImpl;

    {
      prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
      ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
    }

    var prevResponseState = currentResponseState;
    setCurrentResponseState(request.responseState);

    try {
      var pingedTasks = request.pingedTasks;
      var i;

      for (i = 0; i < pingedTasks.length; i++) {
        var task = pingedTasks[i];
        retryTask(request, task);
      }

      pingedTasks.splice(0, i);

      if (request.destination !== null) {
        flushCompletedQueues(request, request.destination);
      }
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    } finally {
      setCurrentResponseState(prevResponseState);
      ReactCurrentDispatcher$1.current = prevDispatcher;

      {
        ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
      }

      if (prevDispatcher === Dispatcher) {
        // This means that we were in a reentrant work loop. This could happen
        // in a renderer that supports synchronous work like renderToString,
        // when it's called from within another renderer.
        // Normally we don't bother switching the contexts to their root/default
        // values when leaving because we'll likely need the same or similar
        // context again. However, when we're inside a synchronous loop like this
        // we'll to restore the context to what it was before returning.
        switchContext(prevContext);
      }
    }
  }

  function flushSubtree(request, destination, segment) {
    segment.parentFlushed = true;

    switch (segment.status) {
      case PENDING:
        {
          // We're emitting a placeholder for this segment to be filled in later.
          // Therefore we'll need to assign it an ID - to refer to it by.
          var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

          segment.lastPushedText = false;
          segment.textEmbedded = false;
          return writePlaceholder(destination, request.responseState, segmentID);
        }

      case COMPLETED:
        {
          segment.status = FLUSHED;
          var r = true;
          var chunks = segment.chunks;
          var chunkIdx = 0;
          var children = segment.children;

          for (var childIdx = 0; childIdx < children.length; childIdx++) {
            var nextChild = children[childIdx]; // Write all the chunks up until the next child.

            for (; chunkIdx < nextChild.index; chunkIdx++) {
              writeChunk(destination, chunks[chunkIdx]);
            }

            r = flushSegment(request, destination, nextChild);
          } // Finally just write all the remaining chunks


          for (; chunkIdx < chunks.length - 1; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          if (chunkIdx < chunks.length) {
            r = writeChunkAndReturn(destination, chunks[chunkIdx]);
          }

          return r;
        }

      default:
        {
          throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
        }
    }
  }

  function flushSegment(request, destination, segment) {
    var boundary = segment.boundary;

    if (boundary === null) {
      // Not a suspense boundary.
      return flushSubtree(request, destination, segment);
    }

    boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
    // emit the content or the fallback now.

    if (boundary.forceClientRender) {
      // Emit a client rendered suspense boundary wrapper.
      // We never queue the inner boundary so we'll never emit its content or partial segments.
      writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState);
    } else if (boundary.pendingTasks > 0) {
      // This boundary is still loading. Emit a pending suspense boundary wrapper.
      // Assign an ID to refer to the future content by.
      boundary.rootSegmentID = request.nextSegmentId++;

      if (boundary.completedSegments.length > 0) {
        // If this is at least partially complete, we can queue it to be partially emitted early.
        request.partialBoundaries.push(boundary);
      } /// This is the first time we should have referenced this ID.


      var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
      writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndPendingSuspenseBoundary(destination, request.responseState);
    } else if (boundary.byteSize > request.progressiveChunkSize) {
      // This boundary is large and will be emitted separately so that we can progressively show
      // other content. We add it to the queue during the flush because we have to ensure that
      // the parent flushes first so that there's something to inject it into.
      // We also have to make sure that it's emitted into the queue in a deterministic slot.
      // I.e. we can't insert it here when it completes.
      // Assign an ID to refer to the future content by.
      boundary.rootSegmentID = request.nextSegmentId++;
      request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

      writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndPendingSuspenseBoundary(destination, request.responseState);
    } else {
      // We can inline this boundary's content as a complete boundary.
      writeStartCompletedSuspenseBoundary$1(destination, request.responseState);
      var completedSegments = boundary.completedSegments;

      if (completedSegments.length !== 1) {
        throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
      }

      var contentSegment = completedSegments[0];
      flushSegment(request, destination, contentSegment);
      return writeEndCompletedSuspenseBoundary$1(destination, request.responseState);
    }
  }

  function flushClientRenderedBoundary(request, destination, boundary) {
    return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
  }

  function flushSegmentContainer(request, destination, segment) {
    writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
    flushSegment(request, destination, segment);
    return writeEndSegment(destination, segment.formatContext);
  }

  function flushCompletedBoundary(request, destination, boundary) {
    var completedSegments = boundary.completedSegments;
    var i = 0;

    for (; i < completedSegments.length; i++) {
      var segment = completedSegments[i];
      flushPartiallyCompletedSegment(request, destination, boundary, segment);
    }

    completedSegments.length = 0;
    return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
  }

  function flushPartialBoundary(request, destination, boundary) {
    var completedSegments = boundary.completedSegments;
    var i = 0;

    for (; i < completedSegments.length; i++) {
      var segment = completedSegments[i];

      if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
        i++;
        completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
        // might want to write later.

        return false;
      }
    }

    completedSegments.splice(0, i);
    return true;
  }

  function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
    if (segment.status === FLUSHED) {
      // We've already flushed this inline.
      return true;
    }

    var segmentID = segment.id;

    if (segmentID === -1) {
      // This segment wasn't previously referred to. This happens at the root of
      // a boundary. We make kind of a leap here and assume this is the root.
      var rootSegmentID = segment.id = boundary.rootSegmentID;

      if (rootSegmentID === -1) {
        throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
      }

      return flushSegmentContainer(request, destination, segment);
    } else {
      flushSegmentContainer(request, destination, segment);
      return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
    }
  }

  function flushCompletedQueues(request, destination) {

    try {
      // The structure of this is to go through each queue one by one and write
      // until the sink tells us to stop. When we should stop, we still finish writing
      // that item fully and then yield. At that point we remove the already completed
      // items up until the point we completed them.
      // TODO: Emit preloading.
      // TODO: It's kind of unfortunate to keep checking this array after we've already
      // emitted the root.
      var completedRootSegment = request.completedRootSegment;

      if (completedRootSegment !== null && request.pendingRootTasks === 0) {
        flushSegment(request, destination, completedRootSegment);
        request.completedRootSegment = null;
        writeCompletedRoot(destination, request.responseState);
      } // We emit client rendering instructions for already emitted boundaries first.
      // This is so that we can signal to the client to start client rendering them as
      // soon as possible.


      var clientRenderedBoundaries = request.clientRenderedBoundaries;
      var i;

      for (i = 0; i < clientRenderedBoundaries.length; i++) {
        var boundary = clientRenderedBoundaries[i];

        if (!flushClientRenderedBoundary(request, destination, boundary)) {
          request.destination = null;
          i++;
          clientRenderedBoundaries.splice(0, i);
          return;
        }
      }

      clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
      // that are completely done since we can actually show them, than it is to emit
      // any individual segments from a partially complete boundary.

      var completedBoundaries = request.completedBoundaries;

      for (i = 0; i < completedBoundaries.length; i++) {
        var _boundary = completedBoundaries[i];

        if (!flushCompletedBoundary(request, destination, _boundary)) {
          request.destination = null;
          i++;
          completedBoundaries.splice(0, i);
          return;
        }
      }

      completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
      // we continue with lower priorities.

      completeWriting(destination);
      beginWriting(destination); // TODO: Here we'll emit data used by hydration.
      // Next we emit any segments of any boundaries that are partially complete
      // but not deeply complete.

      var partialBoundaries = request.partialBoundaries;

      for (i = 0; i < partialBoundaries.length; i++) {
        var _boundary2 = partialBoundaries[i];

        if (!flushPartialBoundary(request, destination, _boundary2)) {
          request.destination = null;
          i++;
          partialBoundaries.splice(0, i);
          return;
        }
      }

      partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
      // boundaries added to it in case they were too larged to be inlined.
      // New ones might be added in this loop.

      var largeBoundaries = request.completedBoundaries;

      for (i = 0; i < largeBoundaries.length; i++) {
        var _boundary3 = largeBoundaries[i];

        if (!flushCompletedBoundary(request, destination, _boundary3)) {
          request.destination = null;
          i++;
          largeBoundaries.splice(0, i);
          return;
        }
      }

      largeBoundaries.splice(0, i);
    } finally {

      if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
      // either they have pending task or they're complete.
      ) {
          {
            if (request.abortableTasks.size !== 0) {
              error('There was still abortable task at the root when we closed. This is a bug in React.');
            }
          } // We're done.


          close(destination);
        }
    }
  }

  function startWork(request) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
  function startFlowing(request, destination) {
    if (request.status === CLOSING) {
      request.status = CLOSED;
      closeWithError(destination, request.fatalError);
      return;
    }

    if (request.status === CLOSED) {
      return;
    }

    if (request.destination !== null) {
      // We're already flowing.
      return;
    }

    request.destination = destination;

    try {
      flushCompletedQueues(request, destination);
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    }
  } // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

  function abort(request, reason) {
    try {
      var abortableTasks = request.abortableTasks;
      abortableTasks.forEach(function (task) {
        return abortTask(task, request, reason);
      });
      abortableTasks.clear();

      if (request.destination !== null) {
        flushCompletedQueues(request, request.destination);
      }
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    }
  }

  function onError() {// Non-fatal errors are ignored.
  }

  function renderToStringImpl(children, options, generateStaticMarkup, abortReason) {
    var didFatal = false;
    var fatalError = null;
    var result = '';
    var destination = {
      push: function (chunk) {
        if (chunk !== null) {
          result += chunk;
        }

        return true;
      },
      destroy: function (error) {
        didFatal = true;
        fatalError = error;
      }
    };
    var readyToStream = false;

    function onShellReady() {
      readyToStream = true;
    }

    var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined);
    startWork(request); // If anything suspended and is still pending, we'll abort it before writing.
    // That way we write only client-rendered boundaries from the start.

    abort(request, abortReason);
    startFlowing(request, destination);

    if (didFatal) {
      throw fatalError;
    }

    if (!readyToStream) {
      // Note: This error message is the one we use on the client. It doesn't
      // really make sense here. But this is the legacy server renderer, anyway.
      // We're going to delete it soon.
      throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.');
    }

    return result;
  }

  function renderToString(children, options) {
    return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
  }

  function renderToStaticMarkup(children, options) {
    return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
  }

  function renderToNodeStream() {
    throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.');
  }

  function renderToStaticNodeStream() {
    throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.');
  }

  exports.renderToNodeStream = renderToNodeStream;
  exports.renderToStaticMarkup = renderToStaticMarkup;
  exports.renderToStaticNodeStream = renderToStaticNodeStream;
  exports.renderToString = renderToString;
  exports.version = ReactVersion;

})));
/**
 * @license React
 * react-dom-server-legacy.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(w,F){"object"===typeof exports&&"undefined"!==typeof module?F(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],F):(w=w||self,F(w.ReactDOMServer={},w.React))})(this,function(w,F){function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
function ra(a){if(v.call(sa,a))return!0;if(v.call(ta,a))return!1;if(hb.test(a))return sa[a]=!0;ta[a]=!0;return!1}function q(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}function r(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=ib.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b=
"&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}function y(a,b){return{insertionMode:a,selectedValue:b}}function jb(a,b,c){switch(b){case "select":return y(1,null!=c.value?c.value:c.defaultValue);case "svg":return y(2,null);case "math":return y(3,null);case "foreignObject":return y(1,null);case "table":return y(4,null);case "thead":case "tbody":case "tfoot":return y(5,
null);case "colgroup":return y(7,null);case "tr":return y(6,null)}return 4<=a.insertionMode||0===a.insertionMode?y(1,null):a}function ua(a,b,c){if("object"!==typeof c)throw Error(l(62));b=!0;for(var d in c)if(v.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=r(d);f=r((""+f).trim())}else{e=d;var g=va.get(e);void 0!==g?e=g:(g=r(e.replace(kb,"-$1").toLowerCase().replace(lb,"-ms-")),va.set(e,g),e=g);f="number"===typeof f?0===f||v.call(L,d)?""+f:f+"px":r((""+
f).trim())}b?(b=!1,a.push(' style="',e,":",f)):a.push(";",e,":",f)}}b||a.push('"')}function x(a,b,c,d){switch(c){case "style":ua(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=p.hasOwnProperty(c)?p[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=b.attributeName;
switch(b.type){case 3:d&&a.push(" ",c,'=""');break;case 4:!0===d?a.push(" ",c,'=""'):!1!==d&&a.push(" ",c,'="',r(d),'"');break;case 5:isNaN(d)||a.push(" ",c,'="',r(d),'"');break;case 6:!isNaN(d)&&1<=d&&a.push(" ",c,'="',r(d),'"');break;default:b.sanitizeURL&&(d=""+d),a.push(" ",c,'="',r(d),'"')}}else if(ra(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(" ",c,'="',r(d),'"')}}function M(a,b,c){if(null!=
b){if(null!=c)throw Error(l(60));if("object"!==typeof b||!("__html"in b))throw Error(l(61));b=b.__html;null!==b&&void 0!==b&&a.push(""+b)}}function mb(a){var b="";F.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function aa(a,b,c,d){a.push(z(c));var f=c=null,e;for(e in b)if(v.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:x(a,d,e,g)}}a.push(">");M(a,f,c);return"string"===typeof c?(a.push(r(c)),null):c}function z(a){var b=
wa.get(a);if(void 0===b){if(!nb.test(a))throw Error(l(65,a));b="<"+a;wa.set(a,b)}return b}function ob(a,b,c,d,f){switch(b){case "select":a.push(z("select"));var e=null,g=null;for(t in c)if(v.call(c,t)){var h=c[t];if(null!=h)switch(t){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:x(a,d,t,h)}}a.push(">");M(a,g,e);return e;case "option":g=f.selectedValue;a.push(z("option"));var m=h=null,n=null;var t=null;for(e in c)if(v.call(c,e)){var k=
c[e];if(null!=k)switch(e){case "children":h=k;break;case "selected":n=k;break;case "dangerouslySetInnerHTML":t=k;break;case "value":m=k;default:x(a,d,e,k)}}if(null!=g)if(c=null!==m?""+m:mb(h),ba(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(' selected=""');break}}else""+g===c&&a.push(' selected=""');else n&&a.push(' selected=""');a.push(">");M(a,t,h);return h;case "textarea":a.push(z("textarea"));t=g=e=null;for(h in c)if(v.call(c,h)&&(m=c[h],null!=m))switch(h){case "children":t=m;break;case "value":e=
m;break;case "defaultValue":g=m;break;case "dangerouslySetInnerHTML":throw Error(l(91));default:x(a,d,h,m)}null===e&&null!==g&&(e=g);a.push(">");if(null!=t){if(null!=e)throw Error(l(92));if(ba(t)&&1<t.length)throw Error(l(93));e=""+t}"string"===typeof e&&"\n"===e[0]&&a.push("\n");null!==e&&a.push(r(""+e));return null;case "input":a.push(z("input"));m=t=h=e=null;for(g in c)if(v.call(c,g)&&(n=c[g],null!=n))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error(l(399,"input"));case "defaultChecked":m=
n;break;case "defaultValue":h=n;break;case "checked":t=n;break;case "value":e=n;break;default:x(a,d,g,n)}null!==t?x(a,d,"checked",t):null!==m&&x(a,d,"checked",m);null!==e?x(a,d,"value",e):null!==h&&x(a,d,"value",h);a.push("/>");return null;case "menuitem":a.push(z("menuitem"));for(var p in c)if(v.call(c,p)&&(e=c[p],null!=e))switch(p){case "children":case "dangerouslySetInnerHTML":throw Error(l(400));default:x(a,d,p,e)}a.push(">");return null;case "title":a.push(z("title"));e=null;for(k in c)if(v.call(c,
k)&&(g=c[k],null!=g))switch(k){case "children":e=g;break;case "dangerouslySetInnerHTML":throw Error(l(434));default:x(a,d,k,g)}a.push(">");return e;case "listing":case "pre":a.push(z(b));g=e=null;for(m in c)if(v.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:x(a,d,m,h)}a.push(">");if(null!=g){if(null!=e)throw Error(l(60));if("object"!==typeof g||!("__html"in g))throw Error(l(61));c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&
0<c.length&&"\n"===c[0]?a.push("\n",c):a.push(""+c))}"string"===typeof e&&"\n"===e[0]&&a.push("\n");return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(z(b));for(var q in c)if(v.call(c,q)&&(e=c[q],null!=e))switch(q){case "children":case "dangerouslySetInnerHTML":throw Error(l(399,b));default:x(a,d,q,e)}a.push("/>");return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return aa(a,
c,b,d);case "html":return 0===f.insertionMode&&a.push("<!DOCTYPE html>"),aa(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return aa(a,c,b,d);a.push(z(b));g=e=null;for(n in c)if(v.call(c,n)&&(h=c[n],null!=h))switch(n){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "style":ua(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ra(n)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(" ",n,'="',r(h),'"')}a.push(">");
M(a,g,e);return e}}function xa(a,b,c){a.push('\x3c!--$?--\x3e<template id="');if(null===c)throw Error(l(395));a.push(c);return a.push('"></template>')}function pb(a,b,c,d){switch(c.insertionMode){case 0:case 1:return a.push('<div hidden id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 2:return a.push('<svg aria-hidden="true" style="display:none" id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 3:return a.push('<math aria-hidden="true" style="display:none" id="'),
a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 4:return a.push('<table hidden id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 5:return a.push('<table hidden><tbody id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 6:return a.push('<table hidden><tr id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 7:return a.push('<table hidden><colgroup id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');
default:throw Error(l(397));}}function qb(a,b){switch(b.insertionMode){case 0:case 1:return a.push("</div>");case 2:return a.push("</svg>");case 3:return a.push("</math>");case 4:return a.push("</table>");case 5:return a.push("</tbody></table>");case 6:return a.push("</tr></table>");case 7:return a.push("</colgroup></table>");default:throw Error(l(397));}}function ca(a){return JSON.stringify(a).replace(rb,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";
default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}function sb(a,b){b=void 0===b?"":b;return{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:b+"P:",segmentPrefix:b+"S:",boundaryPrefix:b+"B:",idPrefix:b,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:a}}
function ya(a,b,c,d){if(c.generateStaticMarkup)return a.push(r(b)),!1;""===b?a=d:(d&&a.push("\x3c!-- --\x3e"),a.push(r(b)),a=!0);return a}function da(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case za:return"Fragment";case Aa:return"Portal";case Ba:return"Profiler";case Ca:return"StrictMode";case Da:return"Suspense";case Ea:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Fa:return(a.displayName||
"Context")+".Consumer";case Ga:return(a._context.displayName||"Context")+".Provider";case Ha:var b=a.render;a=a.displayName;a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ia:return b=a.displayName||null,null!==b?b:da(a.type)||"Memo";case ea:b=a._payload;a=a._init;try{return da(a(b))}catch(c){}}return null}function Ja(a,b){a=a.contextTypes;if(!a)return Ka;var c={},d;for(d in a)c[d]=b[d];return c}function N(a,b){if(a!==b){a.context._currentValue2=a.parentValue;
a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error(l(401));}else{if(null===c)throw Error(l(401));N(a,c)}b.context._currentValue2=b.value}}function La(a){a.context._currentValue2=a.parentValue;a=a.parent;null!==a&&La(a)}function Ma(a){var b=a.parent;null!==b&&Ma(b);a.context._currentValue2=a.value}function Na(a,b){a.context._currentValue2=a.parentValue;a=a.parent;if(null===a)throw Error(l(402));a.depth===b.depth?N(a,b):Na(a,b)}function Oa(a,b){var c=b.parent;if(null===c)throw Error(l(402));
a.depth===c.depth?N(a,c):Oa(a,c);b.context._currentValue2=b.value}function O(a){var b=D;b!==a&&(null===b?Ma(a):null===a?La(b):b.depth===a.depth?N(b,a):b.depth>a.depth?Na(b,a):Oa(b,a),D=a)}function Pa(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=Qa;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue2:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:G({},f,g),
a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&Qa.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===
b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=G({},e,h)):G(e,h))}a.state=e}else e.queue=null}function fa(a,b,c){var d=a.id;a=a.overflow;var f=32-P(d)-1;d&=~(1<<f);c+=1;var e=32-P(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-P(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}function tb(a){a>>>=0;return 0===a?32:31-(ub(a)/vb|0)|0}function wb(a,b){return a===
b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function E(){if(null===B)throw Error(l(321));return B}function Ra(){if(0<Q)throw Error(l(312));return{memoizedState:null,queue:null,next:null}}function ha(){null===k?null===R?(H=!1,R=k=Ra()):(H=!0,k=R):null===k.next?(H=!1,k=k.next=Ra()):(H=!0,k=k.next);return k}function ia(){ja=B=null;S=!1;R=null;Q=0;k=A=null}function Sa(a,b){return"function"===typeof b?b(a):b}function Ta(a,b,c){B=E();k=ha();if(H){var d=k.queue;b=d.dispatch;if(null!==A&&(c=A.get(d),void 0!==c)){A.delete(d);
d=k.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);k.memoizedState=d;return[d,b]}return[k.memoizedState,b]}a=a===Sa?"function"===typeof b?b():b:void 0!==c?c(b):b;k.memoizedState=a;a=k.queue={last:null,dispatch:null};a=a.dispatch=xb.bind(null,B,a);return[k.memoizedState,a]}function Ua(a,b){B=E();k=ha();b=void 0===b?null:b;if(null!==k){var c=k.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!yb(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=
a();k.memoizedState=[a,b];return a}function xb(a,b,c){if(25<=Q)throw Error(l(301));if(a===B)if(S=!0,a={action:c,next:null},null===A&&(A=new Map),c=A.get(b),void 0===c)A.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function zb(){throw Error(l(394));}function T(){}function Ab(a){console.error(a);return null}function I(){}function Bb(a,b,c,d,f,e,g,h,m){var n=[],l=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,
pendingRootTasks:0,completedRootSegment:null,abortableTasks:l,pingedTasks:n,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?Ab:f,onAllReady:void 0===e?I:e,onShellReady:void 0===g?I:g,onShellError:void 0===h?I:h,onFatalError:void 0===m?I:m};c=U(b,0,null,c,!1,!1);c.parentFlushed=!0;a=ka(b,a,null,c,l,Ka,null,Cb);n.push(a);return b}function ka(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var m={node:b,ping:function(){var b=
a.pingedTasks;b.push(m);1===b.length&&Va(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(m);return m}function U(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}function J(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+
typeof a+'" instead');return a}function V(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,a.destination.destroy(b)):(a.status=1,a.fatalError=b)}function Wa(a,b,c,d,f){B={};ja=b;K=0;for(a=c(d,f);S;)S=!1,K=0,Q+=1,k=null,a=c(d,f);ia();return a}function Xa(a,b,c,d,f){f=c.render();var e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error(l(108,
da(d)||"Unknown",h));d=G({},g,c)}b.legacyContext=d;u(a,b,f);b.legacyContext=g}else u(a,b,f)}function Ya(a,b){if(a&&a.defaultProps){b=G({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function la(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=Ja(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue2:f);Pa(e,c,d,f);Xa(a,b,e,c)}else{e=Ja(c,b.legacyContext);f=Wa(a,b,c,d,e);var g=0!==K;if("object"===
typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)Pa(f,c,d,e),Xa(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=fa(d,1,0);try{u(a,b,f)}finally{b.treeContext=d}}else u(a,b,f)}else if("string"===typeof c){f=b.blockedSegment;e=ob(f.chunks,c,d,a.responseState,f.formatContext);f.lastPushedText=!1;g=f.formatContext;f.formatContext=jb(g,c,d);ma(a,b,e);f.formatContext=g;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;
default:f.chunks.push("</",c,">")}f.lastPushedText=!1}else{switch(c){case Db:case Eb:case Ca:case Ba:case za:u(a,b,d.children);return;case Ea:u(a,b,d.children);return;case Fb:throw Error(l(343));case Da:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null},m=U(a,f.chunks.length,h,f.formatContext,!1,!1);f.children.push(m);
f.lastPushedText=!1;var n=U(a,0,null,f.formatContext,!1,!1);n.parentFlushed=!0;b.blockedBoundary=h;b.blockedSegment=n;try{if(ma(a,b,d),a.responseState.generateStaticMarkup||n.lastPushedText&&n.textEmbedded&&n.chunks.push("\x3c!-- --\x3e"),n.status=1,W(h,n),0===h.pendingTasks)break a}catch(t){n.status=4,h.forceClientRender=!0,h.errorDigest=J(a,t)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=ka(a,e,c,m,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&
null!==c)switch(c.$$typeof){case Ha:d=Wa(a,b,c.render,d,f);if(0!==K){c=b.treeContext;b.treeContext=fa(c,1,0);try{u(a,b,d)}finally{b.treeContext=c}}else u(a,b,d);return;case Ia:c=c.type;d=Ya(c,d);la(a,b,c,d,f);return;case Ga:f=d.children;c=c._context;d=d.value;e=c._currentValue2;c._currentValue2=d;g=D;D=d={parent:g,depth:null===g?0:g.depth+1,context:c,parentValue:e,value:d};b.context=d;u(a,b,f);a=D;if(null===a)throw Error(l(403));d=a.parentValue;a.context._currentValue2=d===Gb?a.context._defaultValue:
d;a=D=a.parent;b.context=a;return;case Fa:d=d.children;d=d(c._currentValue2);u(a,b,d);return;case ea:f=c._init;c=f(c._payload);d=Ya(c,d);la(a,b,c,d,void 0);return}throw Error(l(130,null==c?c:typeof c,""));}}function u(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Hb:la(a,b,c.type,c.props,c.ref);return;case Aa:throw Error(l(257));case ea:var d=c._init;c=d(c._payload);u(a,b,c);return}if(ba(c)){Za(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=$a&&c[$a]||c["@@iterator"],
d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=[];do f.push(c.value),c=d.next();while(!c.done);Za(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error(l(31,"[object Object]"===a?"object with keys {"+Object.keys(c).join(", ")+"}":a));}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=ya(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=ya(b.blockedSegment.chunks,""+c,a.responseState,
d.lastPushedText))}function Za(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=fa(e,d,f);try{ma(a,b,c[f])}finally{b.treeContext=e}}}function ma(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return u(a,b,c)}catch(m){if(ia(),"object"===typeof m&&null!==m&&"function"===typeof m.then){c=m;var g=b.blockedSegment,h=U(a,g.chunks.length,null,g.formatContext,g.lastPushedText,!0);g.children.push(h);g.lastPushedText=!1;a=ka(a,b.node,b.blockedBoundary,
h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;O(e)}else throw b.blockedSegment.formatContext=d,b.legacyContext=f,b.context=e,O(e),m;}}function Ib(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;ab(this,b,a)}function bb(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.push(null))):(d.pendingTasks--,d.forceClientRender||
(d.forceClientRender=!0,a=void 0===c?Error(l(432)):c,d.errorDigest=b.onError(a),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return bb(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,0===b.allPendingTasks&&(d=b.onAllReady,d()))}function W(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&W(a,c)}else a.completedSegments.push(b)}function ab(a,
b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error(l(389));a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=I,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&W(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(Ib,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&1===c.status&&(W(b,c),1===b.completedSegments.length&&b.parentFlushed&&
a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}function Va(a){if(2!==a.status){var b=D,c=na.current;na.current=cb;var d=X;X=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,m=g.blockedSegment;if(0===m.status){O(g.context);try{u(h,g,g.node),h.responseState.generateStaticMarkup||m.lastPushedText&&m.textEmbedded&&m.chunks.push("\x3c!-- --\x3e"),g.abortSet.delete(g),m.status=1,ab(h,g.blockedBoundary,m)}catch(C){if(ia(),
"object"===typeof C&&null!==C&&"function"===typeof C.then){var l=g.ping;C.then(l,l)}else{g.abortSet.delete(g);m.status=4;var k=g.blockedBoundary,p=C,q=J(h,p);null===k?V(h,p):(k.pendingTasks--,k.forceClientRender||(k.forceClientRender=!0,k.errorDigest=q,k.parentFlushed&&h.clientRenderedBoundaries.push(k)));h.allPendingTasks--;if(0===h.allPendingTasks){var r=h.onAllReady;r()}}}finally{}}}f.splice(0,e);null!==a.destination&&oa(a,a.destination)}catch(C){J(a,C),V(a,C)}finally{X=d,na.current=c,c===cb&&
O(b)}}}function Y(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;b.push('<template id="');b.push(a.placeholderPrefix);a=d.toString(16);b.push(a);return b.push('"></template>');case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)b.push(d[e]);f=Z(a,b,f)}for(;e<d.length-1;e++)b.push(d[e]);e<d.length&&(f=b.push(d[e]));return f;default:throw Error(l(390));
}}function Z(a,b,c){var d=c.boundary;if(null===d)return Y(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)return a.responseState.generateStaticMarkup||(d=d.errorDigest,b.push("\x3c!--$!--\x3e"),b.push("<template"),d&&(b.push(' data-dgst="'),d=r(d),b.push(d),b.push('"')),b.push("></template>")),Y(a,b,c),a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e"),a;if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;
var e=f.nextSuspenseID++;f=f.boundaryPrefix+e.toString(16);d=d.id=f;xa(b,a.responseState,d);Y(a,b,c);return b.push("\x3c!--/$--\x3e")}if(d.byteSize>a.progressiveChunkSize)return d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),xa(b,a.responseState,d.id),Y(a,b,c),b.push("\x3c!--/$--\x3e");a.responseState.generateStaticMarkup||b.push("\x3c!--$--\x3e");c=d.completedSegments;if(1!==c.length)throw Error(l(391));Z(a,b,c[0]);a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e");
return a}function db(a,b,c){pb(b,a.responseState,c.formatContext,c.id);Z(a,b,c);return qb(b,c.formatContext)}function eb(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)fb(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;b.push(a.startInlineScript);a.sentCompleteBoundaryFunction?b.push('$RC("'):(a.sentCompleteBoundaryFunction=!0,b.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'));
if(null===d)throw Error(l(395));c=c.toString(16);b.push(d);b.push('","');b.push(a.segmentPrefix);b.push(c);return b.push('")\x3c/script>')}function fb(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error(l(392));return db(a,b,d)}db(a,b,d);a=a.responseState;b.push(a.startInlineScript);a.sentCompleteSegmentFunction?b.push('$RS("'):(a.sentCompleteSegmentFunction=!0,b.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'));
b.push(a.segmentPrefix);f=f.toString(16);b.push(f);b.push('","');b.push(a.placeholderPrefix);b.push(f);return b.push('")\x3c/script>')}function oa(a,b){try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){Z(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)b.push(d[c]);c<d.length&&b.push(d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var h=a.responseState,m=g.id,k=g.errorDigest,p=g.errorMessage,q=g.errorComponentStack;
d.push(h.startInlineScript);h.sentClientRenderFunction?d.push('$RX("'):(h.sentClientRenderFunction=!0,d.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'));if(null===m)throw Error(l(395));d.push(m);d.push('"');if(k||p||q){d.push(",");var r=ca(k||"");d.push(r)}if(p||q){d.push(",");var v=ca(p||"");d.push(v)}if(q){d.push(",");var x=ca(q);d.push(x)}if(!d.push(")\x3c/script>")){a.destination=
null;e++;f.splice(0,e);return}}f.splice(0,e);var u=a.completedBoundaries;for(e=0;e<u.length;e++)if(!eb(a,b,u[e])){a.destination=null;e++;u.splice(0,e);return}u.splice(0,e);var w=a.partialBoundaries;for(e=0;e<w.length;e++){var z=w[e];a:{f=a;g=b;var y=z.completedSegments;for(h=0;h<y.length;h++)if(!fb(f,g,z,y[h])){h++;y.splice(0,h);var B=!1;break a}y.splice(0,h);B=!0}if(!B){a.destination=null;e++;w.splice(0,e);return}}w.splice(0,e);var A=a.completedBoundaries;for(e=0;e<A.length;e++)if(!eb(a,b,A[e])){a.destination=
null;e++;A.splice(0,e);return}A.splice(0,e)}finally{0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&b.push(null)}}function Jb(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return bb(c,a,b)});c.clear();null!==a.destination&&oa(a,a.destination)}catch(d){J(a,d),V(a,d)}}function Kb(){}function gb(a,b,c,d){var f=!1,e=null,g="",h={push:function(a){null!==a&&(g+=a);return!0},destroy:function(a){f=!0;e=a}},k=!1;a=Bb(a,sb(c,
b?b.identifierPrefix:void 0),{insertionMode:1,selectedValue:null},Infinity,Kb,void 0,function(){k=!0},void 0,void 0);Va(a);Jb(a,d);if(1===a.status)a.status=2,h.destroy(a.fatalError);else if(2!==a.status&&null===a.destination){a.destination=h;try{oa(a,h)}catch(n){J(a,n),V(a,n)}}if(f)throw e;if(!k)throw Error(l(426));return g}var v=Object.prototype.hasOwnProperty,hb=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,
ta={},sa={},p={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){p[a]=new q(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];p[b]=new q(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){p[a]=new q(a,2,!1,a.toLowerCase(),null,
!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){p[a]=new q(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){p[a]=new q(a,3,!1,a.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(a){p[a]=
new q(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){p[a]=new q(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){p[a]=new q(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){p[a]=new q(a,5,!1,a.toLowerCase(),null,!1,!1)});var pa=/[\-:]([a-z])/g,qa=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
a.replace(pa,qa);p[b]=new q(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(pa,qa);p[b]=new q(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(pa,qa);p[b]=new q(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){p[a]=new q(a,1,!1,a.toLowerCase(),null,!1,!1)});p.xlinkHref=new q("xlinkHref",
1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){p[a]=new q(a,1,!1,a.toLowerCase(),null,!0,!0)});var L={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,
gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Lb=["Webkit","ms","Moz","O"];Object.keys(L).forEach(function(a){Lb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);L[b]=L[a]})});var ib=/["'&<>]/,kb=/([A-Z])/g,lb=/^ms-/,ba=Array.isArray,
va=new Map,nb=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,wa=new Map,rb=/[<\u2028\u2029]/g,G=Object.assign,Hb=Symbol.for("react.element"),Aa=Symbol.for("react.portal"),za=Symbol.for("react.fragment"),Ca=Symbol.for("react.strict_mode"),Ba=Symbol.for("react.profiler"),Ga=Symbol.for("react.provider"),Fa=Symbol.for("react.context"),Ha=Symbol.for("react.forward_ref"),Da=Symbol.for("react.suspense"),Ea=Symbol.for("react.suspense_list"),Ia=Symbol.for("react.memo"),ea=Symbol.for("react.lazy"),Fb=Symbol.for("react.scope"),
Eb=Symbol.for("react.debug_trace_mode"),Db=Symbol.for("react.legacy_hidden"),Gb=Symbol.for("react.default_value"),$a=Symbol.iterator,Ka={},D=null,Qa={isMounted:function(a){return!1},enqueueSetState:function(a,b,c){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b,c){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(a,b){}},Cb={id:1,overflow:""},P=Math.clz32?Math.clz32:tb,ub=Math.log,vb=Math.LN2,yb="function"===typeof Object.is?Object.is:
wb,B=null,ja=null,R=null,k=null,H=!1,S=!1,K=0,A=null,Q=0,cb={readContext:function(a){return a._currentValue2},useContext:function(a){E();return a._currentValue2},useMemo:Ua,useReducer:Ta,useRef:function(a){B=E();k=ha();var b=k.memoizedState;return null===b?(a={current:a},k.memoizedState=a):b},useState:function(a){return Ta(Sa,a)},useInsertionEffect:T,useLayoutEffect:function(a,b){},useCallback:function(a,b){return Ua(function(){return a},b)},useImperativeHandle:T,useEffect:T,useDebugValue:T,useDeferredValue:function(a){E();
return a},useTransition:function(){E();return[!1,zb]},useId:function(){var a=ja.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-P(a)-1)).toString(32)+b;var c=X;if(null===c)throw Error(l(404));b=K++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b,c){E();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error(l(407));return c()}},X=null,na=F.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;w.renderToNodeStream=
function(){throw Error(l(207));};w.renderToStaticMarkup=function(a,b){return gb(a,b,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')};w.renderToStaticNodeStream=function(){throw Error(l(208));};w.renderToString=function(a,b){return gb(a,b,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')};
w.version="18.3.1"});
})();
/**
 * @license React
 * react-dom-server.browser.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
  (global = global || self, factory(global.ReactDOMServer = {}, global.React));
}(this, (function (exports, React) { 'use strict';

  var ReactVersion = '18.3.1';

  var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

  // by calls to these methods by a Babel plugin.
  //
  // In PROD (or in packages without access to React internals),
  // they are left as they are instead.

  function warn(format) {
    {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }
  }
  function error(format) {
    {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }
  }

  function printWarning(level, format, args) {
    // When changing this logic, you might want to also
    // update consoleWithStackDev.www.js as well.
    {
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var stack = ReactDebugCurrentFrame.getStackAddendum();

      if (stack !== '') {
        format += '%s';
        args = args.concat([stack]);
      } // eslint-disable-next-line react-internal/safe-string-coercion


      var argsWithFormat = args.map(function (item) {
        return String(item);
      }); // Careful: RN currently depends on this prefix

      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
      // breaks IE9: https://github.com/facebook/react/issues/13610
      // eslint-disable-next-line react-internal/no-production-logging

      Function.prototype.apply.call(console[level], console, argsWithFormat);
    }
  }

  function scheduleWork(callback) {
    callback();
  }
  var VIEW_SIZE = 512;
  var currentView = null;
  var writtenBytes = 0;
  function beginWriting(destination) {
    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = 0;
  }
  function writeChunk(destination, chunk) {
    if (chunk.length === 0) {
      return;
    }

    if (chunk.length > VIEW_SIZE) {
      // this chunk may overflow a single view which implies it was not
      // one that is cached by the streaming renderer. We will enqueu
      // it directly and expect it is not re-used
      if (writtenBytes > 0) {
        destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
        currentView = new Uint8Array(VIEW_SIZE);
        writtenBytes = 0;
      }

      destination.enqueue(chunk);
      return;
    }

    var bytesToWrite = chunk;
    var allowableBytes = currentView.length - writtenBytes;

    if (allowableBytes < bytesToWrite.length) {
      // this chunk would overflow the current view. We enqueue a full view
      // and start a new view with the remaining chunk
      if (allowableBytes === 0) {
        // the current view is already full, send it
        destination.enqueue(currentView);
      } else {
        // fill up the current view and apply the remaining chunk bytes
        // to a new view.
        currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view

        destination.enqueue(currentView);
        bytesToWrite = bytesToWrite.subarray(allowableBytes);
      }

      currentView = new Uint8Array(VIEW_SIZE);
      writtenBytes = 0;
    }

    currentView.set(bytesToWrite, writtenBytes);
    writtenBytes += bytesToWrite.length;
  }
  function writeChunkAndReturn(destination, chunk) {
    writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more

    return true;
  }
  function completeWriting(destination) {
    if (currentView && writtenBytes > 0) {
      destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
      currentView = null;
      writtenBytes = 0;
    }
  }
  function close(destination) {
    destination.close();
  }
  var textEncoder = new TextEncoder();
  function stringToChunk(content) {
    return textEncoder.encode(content);
  }
  function stringToPrecomputedChunk(content) {
    return textEncoder.encode(content);
  }
  function closeWithError(destination, error) {
    if (typeof destination.error === 'function') {
      // $FlowFixMe: This is an Error object or the destination accepts other types.
      destination.error(error);
    } else {
      // Earlier implementations doesn't support this method. In that environment you're
      // supposed to throw from a promise returned but we don't return a promise in our
      // approach. We could fork this implementation but this is environment is an edge
      // case to begin with. It's even less common to run this in an older environment.
      // Even then, this is not where errors are supposed to happen and they get reported
      // to a global callback in addition to this anyway. So it's fine just to close this.
      destination.close();
    }
  }

  /*
   * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
   * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
   *
   * The functions in this module will throw an easier-to-understand,
   * easier-to-debug exception with a clear errors message message explaining the
   * problem. (Instead of a confusing exception thrown inside the implementation
   * of the `value` object).
   */
  // $FlowFixMe only called in DEV, so void return is not possible.
  function typeName(value) {
    {
      // toStringTag is needed for namespaced types like Temporal.Instant
      var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
      var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
      return type;
    }
  } // $FlowFixMe only called in DEV, so void return is not possible.


  function willCoercionThrow(value) {
    {
      try {
        testStringCoercion(value);
        return false;
      } catch (e) {
        return true;
      }
    }
  }

  function testStringCoercion(value) {
    // If you ended up here by following an exception call stack, here's what's
    // happened: you supplied an object or symbol value to React (as a prop, key,
    // DOM attribute, CSS property, string ref, etc.) and when React tried to
    // coerce it to a string using `'' + value`, an exception was thrown.
    //
    // The most common types that will cause this exception are `Symbol` instances
    // and Temporal objects like `Temporal.Instant`. But any object that has a
    // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
    // exception. (Library authors do this to prevent users from using built-in
    // numeric operators like `+` or comparison operators like `>=` because custom
    // methods are needed to perform accurate arithmetic or comparison.)
    //
    // To fix the problem, coerce this object or symbol value to a string before
    // passing it to React. The most reliable way is usually `String(value)`.
    //
    // To find which value is throwing, check the browser or debugger console.
    // Before this exception was thrown, there should be `console.error` output
    // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
    // problem and how that type was used: key, atrribute, input value prop, etc.
    // In most cases, this console output also shows the component and its
    // ancestor components where the exception happened.
    //
    // eslint-disable-next-line react-internal/safe-string-coercion
    return '' + value;
  }

  function checkAttributeStringCoercion(value, attributeName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkCSSPropertyStringCoercion(value, propName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkHtmlStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }

  var hasOwnProperty = Object.prototype.hasOwnProperty;

  // A reserved attribute.
  // It is handled by React separately and shouldn't be written to the DOM.
  var RESERVED = 0; // A simple string attribute.
  // Attributes that aren't in the filter are presumed to have this type.

  var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
  // "enumerated" attributes with "true" and "false" as possible values.
  // When true, it should be set to a "true" string.
  // When false, it should be set to a "false" string.

  var BOOLEANISH_STRING = 2; // A real boolean attribute.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.

  var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.
  // For any other value, should be present with that value.

  var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
  // When falsy, it should be removed.

  var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
  // When falsy, it should be removed.

  var POSITIVE_NUMERIC = 6;

  /* eslint-disable max-len */
  var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  /* eslint-enable max-len */

  var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
  var illegalAttributeNameCache = {};
  var validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
      return true;
    }

    if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
      return false;
    }

    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
      validatedAttributeNameCache[attributeName] = true;
      return true;
    }

    illegalAttributeNameCache[attributeName] = true;

    {
      error('Invalid attribute name: `%s`', attributeName);
    }

    return false;
  }
  function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
    if (propertyInfo !== null && propertyInfo.type === RESERVED) {
      return false;
    }

    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return true;

      case 'boolean':
        {
          if (isCustomComponentTag) {
            return false;
          }

          if (propertyInfo !== null) {
            return !propertyInfo.acceptsBooleans;
          } else {
            var prefix = name.toLowerCase().slice(0, 5);
            return prefix !== 'data-' && prefix !== 'aria-';
          }
        }

      default:
        return false;
    }
  }
  function getPropertyInfo(name) {
    return properties.hasOwnProperty(name) ? properties[name] : null;
  }

  function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
    this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
    this.attributeName = attributeName;
    this.attributeNamespace = attributeNamespace;
    this.mustUseProperty = mustUseProperty;
    this.propertyName = name;
    this.type = type;
    this.sanitizeURL = sanitizeURL;
    this.removeEmptyString = removeEmptyString;
  } // When adding attributes to this list, be sure to also add them to
  // the `possibleStandardNames` module to ensure casing and incorrect
  // name warnings.


  var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

  var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
  // elements (not just inputs). Now that ReactDOMInput assigns to the
  // defaultValue property -- do we need this?
  'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

  reservedProps.forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // A few React string attributes have a different name.
  // This is a mapping from React prop names to the attribute names.

  [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
    var name = _ref[0],
        attributeName = _ref[1];
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" HTML attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).

  ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" SVG attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).
  // Since these are SVG attributes, their attribute names are case-sensitive.

  ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML boolean attributes.

  ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
  // on the client side because the browsers are inconsistent. Instead we call focus().
  'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
  'itemScope'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are the few React props that we set as DOM properties
  // rather than attributes. These are all booleans.

  ['checked', // Note: `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`. We have special logic for handling this.
  'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that are "overloaded booleans": they behave like
  // booleans, but can also accept a string value.

  ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be positive numbers.

  ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be numbers.

  ['rowSpan', 'start'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  });
  var CAMELIZE = /[\-\:]([a-z])/g;

  var capitalize = function (token) {
    return token[1].toUpperCase();
  }; // This is a list of all SVG attributes that need special casing, namespacing,
  // or boolean value assignment. Regular attributes that just accept strings
  // and have the same names are omitted, just like in the HTML attribute filter.
  // Some of these attributes can be hard to find. This list was created by
  // scraping the MDN documentation.


  ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // String SVG attributes with the xlink namespace.

  ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
    false);
  }); // String SVG attributes with the xml namespace.

  ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
    false);
  }); // These attribute exists both in HTML and SVG.
  // The attribute name is case-sensitive in SVG so we can't just use
  // the React name like we do for attributes that exist only in HTML.

  ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These attributes accept URLs. These must not allow javascript: URLS.
  // These will also need to accept Trusted Types object in the future.

  var xlinkHref = 'xlinkHref';
  properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
  'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
  false);
  ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    true, // sanitizeURL
    true);
  });

  /**
   * CSS properties which accept numbers but are not in units of "px".
   */
  var isUnitlessNumber = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    // SVG-related properties
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  };
  /**
   * @param {string} prefix vendor-specific prefix, eg: Webkit
   * @param {string} key style name, eg: transitionDuration
   * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
   * WebkitTransitionDuration
   */

  function prefixKey(prefix, key) {
    return prefix + key.charAt(0).toUpperCase() + key.substring(1);
  }
  /**
   * Support style names that may come passed in prefixed by adding permutations
   * of vendor prefixes.
   */


  var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
  // infinite loop, because it iterates over the newly added props too.

  Object.keys(isUnitlessNumber).forEach(function (prop) {
    prefixes.forEach(function (prefix) {
      isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
    });
  });

  var hasReadOnlyValue = {
    button: true,
    checkbox: true,
    image: true,
    hidden: true,
    radio: true,
    reset: true,
    submit: true
  };
  function checkControlledValueProps(tagName, props) {
    {
      if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
        error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }

      if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
        error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }
    }
  }

  function isCustomComponent(tagName, props) {
    if (tagName.indexOf('-') === -1) {
      return typeof props.is === 'string';
    }

    switch (tagName) {
      // These are reserved SVG and MathML elements.
      // We don't mind this list too much because we expect it to never grow.
      // The alternative is to track the namespace in a few places which is convoluted.
      // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
      case 'annotation-xml':
      case 'color-profile':
      case 'font-face':
      case 'font-face-src':
      case 'font-face-uri':
      case 'font-face-format':
      case 'font-face-name':
      case 'missing-glyph':
        return false;

      default:
        return true;
    }
  }

  var ariaProperties = {
    'aria-current': 0,
    // state
    'aria-description': 0,
    'aria-details': 0,
    'aria-disabled': 0,
    // state
    'aria-hidden': 0,
    // state
    'aria-invalid': 0,
    // state
    'aria-keyshortcuts': 0,
    'aria-label': 0,
    'aria-roledescription': 0,
    // Widget Attributes
    'aria-autocomplete': 0,
    'aria-checked': 0,
    'aria-expanded': 0,
    'aria-haspopup': 0,
    'aria-level': 0,
    'aria-modal': 0,
    'aria-multiline': 0,
    'aria-multiselectable': 0,
    'aria-orientation': 0,
    'aria-placeholder': 0,
    'aria-pressed': 0,
    'aria-readonly': 0,
    'aria-required': 0,
    'aria-selected': 0,
    'aria-sort': 0,
    'aria-valuemax': 0,
    'aria-valuemin': 0,
    'aria-valuenow': 0,
    'aria-valuetext': 0,
    // Live Region Attributes
    'aria-atomic': 0,
    'aria-busy': 0,
    'aria-live': 0,
    'aria-relevant': 0,
    // Drag-and-Drop Attributes
    'aria-dropeffect': 0,
    'aria-grabbed': 0,
    // Relationship Attributes
    'aria-activedescendant': 0,
    'aria-colcount': 0,
    'aria-colindex': 0,
    'aria-colspan': 0,
    'aria-controls': 0,
    'aria-describedby': 0,
    'aria-errormessage': 0,
    'aria-flowto': 0,
    'aria-labelledby': 0,
    'aria-owns': 0,
    'aria-posinset': 0,
    'aria-rowcount': 0,
    'aria-rowindex': 0,
    'aria-rowspan': 0,
    'aria-setsize': 0
  };

  var warnedProperties = {};
  var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  function validateProperty(tagName, name) {
    {
      if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
        return true;
      }

      if (rARIACamel.test(name)) {
        var ariaName = 'aria-' + name.slice(4).toLowerCase();
        var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (correctName == null) {
          error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

          warnedProperties[name] = true;
          return true;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== correctName) {
          error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

          warnedProperties[name] = true;
          return true;
        }
      }

      if (rARIA.test(name)) {
        var lowerCasedName = name.toLowerCase();
        var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (standardName == null) {
          warnedProperties[name] = true;
          return false;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== standardName) {
          error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties[name] = true;
          return true;
        }
      }
    }

    return true;
  }

  function warnInvalidARIAProps(type, props) {
    {
      var invalidProps = [];

      for (var key in props) {
        var isValid = validateProperty(type, key);

        if (!isValid) {
          invalidProps.push(key);
        }
      }

      var unknownPropString = invalidProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (invalidProps.length === 1) {
        error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      } else if (invalidProps.length > 1) {
        error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      }
    }
  }

  function validateProperties(type, props) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnInvalidARIAProps(type, props);
  }

  var didWarnValueNull = false;
  function validateProperties$1(type, props) {
    {
      if (type !== 'input' && type !== 'textarea' && type !== 'select') {
        return;
      }

      if (props != null && props.value === null && !didWarnValueNull) {
        didWarnValueNull = true;

        if (type === 'select' && props.multiple) {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
        } else {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
        }
      }
    }
  }

  // When adding attributes to the HTML or SVG allowed attribute list, be sure to
  // also add them to this module to ensure casing and incorrect name
  // warnings.
  var possibleStandardNames = {
    // HTML
    accept: 'accept',
    acceptcharset: 'acceptCharset',
    'accept-charset': 'acceptCharset',
    accesskey: 'accessKey',
    action: 'action',
    allowfullscreen: 'allowFullScreen',
    alt: 'alt',
    as: 'as',
    async: 'async',
    autocapitalize: 'autoCapitalize',
    autocomplete: 'autoComplete',
    autocorrect: 'autoCorrect',
    autofocus: 'autoFocus',
    autoplay: 'autoPlay',
    autosave: 'autoSave',
    capture: 'capture',
    cellpadding: 'cellPadding',
    cellspacing: 'cellSpacing',
    challenge: 'challenge',
    charset: 'charSet',
    checked: 'checked',
    children: 'children',
    cite: 'cite',
    class: 'className',
    classid: 'classID',
    classname: 'className',
    cols: 'cols',
    colspan: 'colSpan',
    content: 'content',
    contenteditable: 'contentEditable',
    contextmenu: 'contextMenu',
    controls: 'controls',
    controlslist: 'controlsList',
    coords: 'coords',
    crossorigin: 'crossOrigin',
    dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
    data: 'data',
    datetime: 'dateTime',
    default: 'default',
    defaultchecked: 'defaultChecked',
    defaultvalue: 'defaultValue',
    defer: 'defer',
    dir: 'dir',
    disabled: 'disabled',
    disablepictureinpicture: 'disablePictureInPicture',
    disableremoteplayback: 'disableRemotePlayback',
    download: 'download',
    draggable: 'draggable',
    enctype: 'encType',
    enterkeyhint: 'enterKeyHint',
    for: 'htmlFor',
    form: 'form',
    formmethod: 'formMethod',
    formaction: 'formAction',
    formenctype: 'formEncType',
    formnovalidate: 'formNoValidate',
    formtarget: 'formTarget',
    frameborder: 'frameBorder',
    headers: 'headers',
    height: 'height',
    hidden: 'hidden',
    high: 'high',
    href: 'href',
    hreflang: 'hrefLang',
    htmlfor: 'htmlFor',
    httpequiv: 'httpEquiv',
    'http-equiv': 'httpEquiv',
    icon: 'icon',
    id: 'id',
    imagesizes: 'imageSizes',
    imagesrcset: 'imageSrcSet',
    innerhtml: 'innerHTML',
    inputmode: 'inputMode',
    integrity: 'integrity',
    is: 'is',
    itemid: 'itemID',
    itemprop: 'itemProp',
    itemref: 'itemRef',
    itemscope: 'itemScope',
    itemtype: 'itemType',
    keyparams: 'keyParams',
    keytype: 'keyType',
    kind: 'kind',
    label: 'label',
    lang: 'lang',
    list: 'list',
    loop: 'loop',
    low: 'low',
    manifest: 'manifest',
    marginwidth: 'marginWidth',
    marginheight: 'marginHeight',
    max: 'max',
    maxlength: 'maxLength',
    media: 'media',
    mediagroup: 'mediaGroup',
    method: 'method',
    min: 'min',
    minlength: 'minLength',
    multiple: 'multiple',
    muted: 'muted',
    name: 'name',
    nomodule: 'noModule',
    nonce: 'nonce',
    novalidate: 'noValidate',
    open: 'open',
    optimum: 'optimum',
    pattern: 'pattern',
    placeholder: 'placeholder',
    playsinline: 'playsInline',
    poster: 'poster',
    preload: 'preload',
    profile: 'profile',
    radiogroup: 'radioGroup',
    readonly: 'readOnly',
    referrerpolicy: 'referrerPolicy',
    rel: 'rel',
    required: 'required',
    reversed: 'reversed',
    role: 'role',
    rows: 'rows',
    rowspan: 'rowSpan',
    sandbox: 'sandbox',
    scope: 'scope',
    scoped: 'scoped',
    scrolling: 'scrolling',
    seamless: 'seamless',
    selected: 'selected',
    shape: 'shape',
    size: 'size',
    sizes: 'sizes',
    span: 'span',
    spellcheck: 'spellCheck',
    src: 'src',
    srcdoc: 'srcDoc',
    srclang: 'srcLang',
    srcset: 'srcSet',
    start: 'start',
    step: 'step',
    style: 'style',
    summary: 'summary',
    tabindex: 'tabIndex',
    target: 'target',
    title: 'title',
    type: 'type',
    usemap: 'useMap',
    value: 'value',
    width: 'width',
    wmode: 'wmode',
    wrap: 'wrap',
    // SVG
    about: 'about',
    accentheight: 'accentHeight',
    'accent-height': 'accentHeight',
    accumulate: 'accumulate',
    additive: 'additive',
    alignmentbaseline: 'alignmentBaseline',
    'alignment-baseline': 'alignmentBaseline',
    allowreorder: 'allowReorder',
    alphabetic: 'alphabetic',
    amplitude: 'amplitude',
    arabicform: 'arabicForm',
    'arabic-form': 'arabicForm',
    ascent: 'ascent',
    attributename: 'attributeName',
    attributetype: 'attributeType',
    autoreverse: 'autoReverse',
    azimuth: 'azimuth',
    basefrequency: 'baseFrequency',
    baselineshift: 'baselineShift',
    'baseline-shift': 'baselineShift',
    baseprofile: 'baseProfile',
    bbox: 'bbox',
    begin: 'begin',
    bias: 'bias',
    by: 'by',
    calcmode: 'calcMode',
    capheight: 'capHeight',
    'cap-height': 'capHeight',
    clip: 'clip',
    clippath: 'clipPath',
    'clip-path': 'clipPath',
    clippathunits: 'clipPathUnits',
    cliprule: 'clipRule',
    'clip-rule': 'clipRule',
    color: 'color',
    colorinterpolation: 'colorInterpolation',
    'color-interpolation': 'colorInterpolation',
    colorinterpolationfilters: 'colorInterpolationFilters',
    'color-interpolation-filters': 'colorInterpolationFilters',
    colorprofile: 'colorProfile',
    'color-profile': 'colorProfile',
    colorrendering: 'colorRendering',
    'color-rendering': 'colorRendering',
    contentscripttype: 'contentScriptType',
    contentstyletype: 'contentStyleType',
    cursor: 'cursor',
    cx: 'cx',
    cy: 'cy',
    d: 'd',
    datatype: 'datatype',
    decelerate: 'decelerate',
    descent: 'descent',
    diffuseconstant: 'diffuseConstant',
    direction: 'direction',
    display: 'display',
    divisor: 'divisor',
    dominantbaseline: 'dominantBaseline',
    'dominant-baseline': 'dominantBaseline',
    dur: 'dur',
    dx: 'dx',
    dy: 'dy',
    edgemode: 'edgeMode',
    elevation: 'elevation',
    enablebackground: 'enableBackground',
    'enable-background': 'enableBackground',
    end: 'end',
    exponent: 'exponent',
    externalresourcesrequired: 'externalResourcesRequired',
    fill: 'fill',
    fillopacity: 'fillOpacity',
    'fill-opacity': 'fillOpacity',
    fillrule: 'fillRule',
    'fill-rule': 'fillRule',
    filter: 'filter',
    filterres: 'filterRes',
    filterunits: 'filterUnits',
    floodopacity: 'floodOpacity',
    'flood-opacity': 'floodOpacity',
    floodcolor: 'floodColor',
    'flood-color': 'floodColor',
    focusable: 'focusable',
    fontfamily: 'fontFamily',
    'font-family': 'fontFamily',
    fontsize: 'fontSize',
    'font-size': 'fontSize',
    fontsizeadjust: 'fontSizeAdjust',
    'font-size-adjust': 'fontSizeAdjust',
    fontstretch: 'fontStretch',
    'font-stretch': 'fontStretch',
    fontstyle: 'fontStyle',
    'font-style': 'fontStyle',
    fontvariant: 'fontVariant',
    'font-variant': 'fontVariant',
    fontweight: 'fontWeight',
    'font-weight': 'fontWeight',
    format: 'format',
    from: 'from',
    fx: 'fx',
    fy: 'fy',
    g1: 'g1',
    g2: 'g2',
    glyphname: 'glyphName',
    'glyph-name': 'glyphName',
    glyphorientationhorizontal: 'glyphOrientationHorizontal',
    'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
    glyphorientationvertical: 'glyphOrientationVertical',
    'glyph-orientation-vertical': 'glyphOrientationVertical',
    glyphref: 'glyphRef',
    gradienttransform: 'gradientTransform',
    gradientunits: 'gradientUnits',
    hanging: 'hanging',
    horizadvx: 'horizAdvX',
    'horiz-adv-x': 'horizAdvX',
    horizoriginx: 'horizOriginX',
    'horiz-origin-x': 'horizOriginX',
    ideographic: 'ideographic',
    imagerendering: 'imageRendering',
    'image-rendering': 'imageRendering',
    in2: 'in2',
    in: 'in',
    inlist: 'inlist',
    intercept: 'intercept',
    k1: 'k1',
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
    k: 'k',
    kernelmatrix: 'kernelMatrix',
    kernelunitlength: 'kernelUnitLength',
    kerning: 'kerning',
    keypoints: 'keyPoints',
    keysplines: 'keySplines',
    keytimes: 'keyTimes',
    lengthadjust: 'lengthAdjust',
    letterspacing: 'letterSpacing',
    'letter-spacing': 'letterSpacing',
    lightingcolor: 'lightingColor',
    'lighting-color': 'lightingColor',
    limitingconeangle: 'limitingConeAngle',
    local: 'local',
    markerend: 'markerEnd',
    'marker-end': 'markerEnd',
    markerheight: 'markerHeight',
    markermid: 'markerMid',
    'marker-mid': 'markerMid',
    markerstart: 'markerStart',
    'marker-start': 'markerStart',
    markerunits: 'markerUnits',
    markerwidth: 'markerWidth',
    mask: 'mask',
    maskcontentunits: 'maskContentUnits',
    maskunits: 'maskUnits',
    mathematical: 'mathematical',
    mode: 'mode',
    numoctaves: 'numOctaves',
    offset: 'offset',
    opacity: 'opacity',
    operator: 'operator',
    order: 'order',
    orient: 'orient',
    orientation: 'orientation',
    origin: 'origin',
    overflow: 'overflow',
    overlineposition: 'overlinePosition',
    'overline-position': 'overlinePosition',
    overlinethickness: 'overlineThickness',
    'overline-thickness': 'overlineThickness',
    paintorder: 'paintOrder',
    'paint-order': 'paintOrder',
    panose1: 'panose1',
    'panose-1': 'panose1',
    pathlength: 'pathLength',
    patterncontentunits: 'patternContentUnits',
    patterntransform: 'patternTransform',
    patternunits: 'patternUnits',
    pointerevents: 'pointerEvents',
    'pointer-events': 'pointerEvents',
    points: 'points',
    pointsatx: 'pointsAtX',
    pointsaty: 'pointsAtY',
    pointsatz: 'pointsAtZ',
    prefix: 'prefix',
    preservealpha: 'preserveAlpha',
    preserveaspectratio: 'preserveAspectRatio',
    primitiveunits: 'primitiveUnits',
    property: 'property',
    r: 'r',
    radius: 'radius',
    refx: 'refX',
    refy: 'refY',
    renderingintent: 'renderingIntent',
    'rendering-intent': 'renderingIntent',
    repeatcount: 'repeatCount',
    repeatdur: 'repeatDur',
    requiredextensions: 'requiredExtensions',
    requiredfeatures: 'requiredFeatures',
    resource: 'resource',
    restart: 'restart',
    result: 'result',
    results: 'results',
    rotate: 'rotate',
    rx: 'rx',
    ry: 'ry',
    scale: 'scale',
    security: 'security',
    seed: 'seed',
    shaperendering: 'shapeRendering',
    'shape-rendering': 'shapeRendering',
    slope: 'slope',
    spacing: 'spacing',
    specularconstant: 'specularConstant',
    specularexponent: 'specularExponent',
    speed: 'speed',
    spreadmethod: 'spreadMethod',
    startoffset: 'startOffset',
    stddeviation: 'stdDeviation',
    stemh: 'stemh',
    stemv: 'stemv',
    stitchtiles: 'stitchTiles',
    stopcolor: 'stopColor',
    'stop-color': 'stopColor',
    stopopacity: 'stopOpacity',
    'stop-opacity': 'stopOpacity',
    strikethroughposition: 'strikethroughPosition',
    'strikethrough-position': 'strikethroughPosition',
    strikethroughthickness: 'strikethroughThickness',
    'strikethrough-thickness': 'strikethroughThickness',
    string: 'string',
    stroke: 'stroke',
    strokedasharray: 'strokeDasharray',
    'stroke-dasharray': 'strokeDasharray',
    strokedashoffset: 'strokeDashoffset',
    'stroke-dashoffset': 'strokeDashoffset',
    strokelinecap: 'strokeLinecap',
    'stroke-linecap': 'strokeLinecap',
    strokelinejoin: 'strokeLinejoin',
    'stroke-linejoin': 'strokeLinejoin',
    strokemiterlimit: 'strokeMiterlimit',
    'stroke-miterlimit': 'strokeMiterlimit',
    strokewidth: 'strokeWidth',
    'stroke-width': 'strokeWidth',
    strokeopacity: 'strokeOpacity',
    'stroke-opacity': 'strokeOpacity',
    suppresscontenteditablewarning: 'suppressContentEditableWarning',
    suppresshydrationwarning: 'suppressHydrationWarning',
    surfacescale: 'surfaceScale',
    systemlanguage: 'systemLanguage',
    tablevalues: 'tableValues',
    targetx: 'targetX',
    targety: 'targetY',
    textanchor: 'textAnchor',
    'text-anchor': 'textAnchor',
    textdecoration: 'textDecoration',
    'text-decoration': 'textDecoration',
    textlength: 'textLength',
    textrendering: 'textRendering',
    'text-rendering': 'textRendering',
    to: 'to',
    transform: 'transform',
    typeof: 'typeof',
    u1: 'u1',
    u2: 'u2',
    underlineposition: 'underlinePosition',
    'underline-position': 'underlinePosition',
    underlinethickness: 'underlineThickness',
    'underline-thickness': 'underlineThickness',
    unicode: 'unicode',
    unicodebidi: 'unicodeBidi',
    'unicode-bidi': 'unicodeBidi',
    unicoderange: 'unicodeRange',
    'unicode-range': 'unicodeRange',
    unitsperem: 'unitsPerEm',
    'units-per-em': 'unitsPerEm',
    unselectable: 'unselectable',
    valphabetic: 'vAlphabetic',
    'v-alphabetic': 'vAlphabetic',
    values: 'values',
    vectoreffect: 'vectorEffect',
    'vector-effect': 'vectorEffect',
    version: 'version',
    vertadvy: 'vertAdvY',
    'vert-adv-y': 'vertAdvY',
    vertoriginx: 'vertOriginX',
    'vert-origin-x': 'vertOriginX',
    vertoriginy: 'vertOriginY',
    'vert-origin-y': 'vertOriginY',
    vhanging: 'vHanging',
    'v-hanging': 'vHanging',
    videographic: 'vIdeographic',
    'v-ideographic': 'vIdeographic',
    viewbox: 'viewBox',
    viewtarget: 'viewTarget',
    visibility: 'visibility',
    vmathematical: 'vMathematical',
    'v-mathematical': 'vMathematical',
    vocab: 'vocab',
    widths: 'widths',
    wordspacing: 'wordSpacing',
    'word-spacing': 'wordSpacing',
    writingmode: 'writingMode',
    'writing-mode': 'writingMode',
    x1: 'x1',
    x2: 'x2',
    x: 'x',
    xchannelselector: 'xChannelSelector',
    xheight: 'xHeight',
    'x-height': 'xHeight',
    xlinkactuate: 'xlinkActuate',
    'xlink:actuate': 'xlinkActuate',
    xlinkarcrole: 'xlinkArcrole',
    'xlink:arcrole': 'xlinkArcrole',
    xlinkhref: 'xlinkHref',
    'xlink:href': 'xlinkHref',
    xlinkrole: 'xlinkRole',
    'xlink:role': 'xlinkRole',
    xlinkshow: 'xlinkShow',
    'xlink:show': 'xlinkShow',
    xlinktitle: 'xlinkTitle',
    'xlink:title': 'xlinkTitle',
    xlinktype: 'xlinkType',
    'xlink:type': 'xlinkType',
    xmlbase: 'xmlBase',
    'xml:base': 'xmlBase',
    xmllang: 'xmlLang',
    'xml:lang': 'xmlLang',
    xmlns: 'xmlns',
    'xml:space': 'xmlSpace',
    xmlnsxlink: 'xmlnsXlink',
    'xmlns:xlink': 'xmlnsXlink',
    xmlspace: 'xmlSpace',
    y1: 'y1',
    y2: 'y2',
    y: 'y',
    ychannelselector: 'yChannelSelector',
    z: 'z',
    zoomandpan: 'zoomAndPan'
  };

  var validateProperty$1 = function () {};

  {
    var warnedProperties$1 = {};
    var EVENT_NAME_REGEX = /^on./;
    var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
    var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
    var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

    validateProperty$1 = function (tagName, name, value, eventRegistry) {
      if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
        return true;
      }

      var lowerCasedName = name.toLowerCase();

      if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
        error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

        warnedProperties$1[name] = true;
        return true;
      } // We can't rely on the event system being injected on the server.


      if (eventRegistry != null) {
        var registrationNameDependencies = eventRegistry.registrationNameDependencies,
            possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

        if (registrationNameDependencies.hasOwnProperty(name)) {
          return true;
        }

        var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

        if (registrationName != null) {
          error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

          warnedProperties$1[name] = true;
          return true;
        }

        if (EVENT_NAME_REGEX.test(name)) {
          error('Unknown event handler property `%s`. It will be ignored.', name);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (EVENT_NAME_REGEX.test(name)) {
        // If no event plugins have been injected, we are in a server environment.
        // So we can't tell if the event name is correct for sure, but we can filter
        // out known bad ones like `onclick`. We can't suggest a specific replacement though.
        if (INVALID_EVENT_NAME_REGEX.test(name)) {
          error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Let the ARIA attribute hook validate ARIA attributes


      if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
        return true;
      }

      if (lowerCasedName === 'innerhtml') {
        error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'aria') {
        error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
        error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'number' && isNaN(value)) {
        error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

        warnedProperties$1[name] = true;
        return true;
      }

      var propertyInfo = getPropertyInfo(name);
      var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        var standardName = possibleStandardNames[lowerCasedName];

        if (standardName !== name) {
          error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (!isReserved && name !== lowerCasedName) {
        // Unknown attributes should have lowercase casing since that's how they
        // will be cased anyway with server rendering.
        error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        if (value) {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
        } else {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Now that we've validated casing, do not validate
      // data types for reserved props


      if (isReserved) {
        return true;
      } // Warn when a known attribute is a bad type


      if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        warnedProperties$1[name] = true;
        return false;
      } // Warn when passing the strings 'false' or 'true' into a boolean prop


      if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
        error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

        warnedProperties$1[name] = true;
        return true;
      }

      return true;
    };
  }

  var warnUnknownProperties = function (type, props, eventRegistry) {
    {
      var unknownProps = [];

      for (var key in props) {
        var isValid = validateProperty$1(type, key, props[key], eventRegistry);

        if (!isValid) {
          unknownProps.push(key);
        }
      }

      var unknownPropString = unknownProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (unknownProps.length === 1) {
        error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      } else if (unknownProps.length > 1) {
        error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      }
    }
  };

  function validateProperties$2(type, props, eventRegistry) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnUnknownProperties(type, props, eventRegistry);
  }

  var warnValidStyle = function () {};

  {
    // 'msTransform' is correct, but the other prefixes should be capitalized
    var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
    var msPattern = /^-ms-/;
    var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

    var badStyleValueWithSemicolonPattern = /;\s*$/;
    var warnedStyleNames = {};
    var warnedStyleValues = {};
    var warnedForNaNValue = false;
    var warnedForInfinityValue = false;

    var camelize = function (string) {
      return string.replace(hyphenPattern, function (_, character) {
        return character.toUpperCase();
      });
    };

    var warnHyphenatedStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
      // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
      // is converted to lowercase `ms`.
      camelize(name.replace(msPattern, 'ms-')));
    };

    var warnBadVendoredStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
    };

    var warnStyleValueWithSemicolon = function (name, value) {
      if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
        return;
      }

      warnedStyleValues[value] = true;

      error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
    };

    var warnStyleValueIsNaN = function (name, value) {
      if (warnedForNaNValue) {
        return;
      }

      warnedForNaNValue = true;

      error('`NaN` is an invalid value for the `%s` css style property.', name);
    };

    var warnStyleValueIsInfinity = function (name, value) {
      if (warnedForInfinityValue) {
        return;
      }

      warnedForInfinityValue = true;

      error('`Infinity` is an invalid value for the `%s` css style property.', name);
    };

    warnValidStyle = function (name, value) {
      if (name.indexOf('-') > -1) {
        warnHyphenatedStyleName(name);
      } else if (badVendoredStyleNamePattern.test(name)) {
        warnBadVendoredStyleName(name);
      } else if (badStyleValueWithSemicolonPattern.test(value)) {
        warnStyleValueWithSemicolon(name, value);
      }

      if (typeof value === 'number') {
        if (isNaN(value)) {
          warnStyleValueIsNaN(name, value);
        } else if (!isFinite(value)) {
          warnStyleValueIsInfinity(name, value);
        }
      }
    };
  }

  var warnValidStyle$1 = warnValidStyle;

  // code copied and modified from escape-html
  var matchHtmlRegExp = /["'&<>]/;
  /**
   * Escapes special characters and HTML entities in a given html string.
   *
   * @param  {string} string HTML string to escape for later insertion
   * @return {string}
   * @public
   */

  function escapeHtml(string) {
    {
      checkHtmlStringCoercion(string);
    }

    var str = '' + string;
    var match = matchHtmlRegExp.exec(str);

    if (!match) {
      return str;
    }

    var escape;
    var html = '';
    var index;
    var lastIndex = 0;

    for (index = match.index; index < str.length; index++) {
      switch (str.charCodeAt(index)) {
        case 34:
          // "
          escape = '&quot;';
          break;

        case 38:
          // &
          escape = '&amp;';
          break;

        case 39:
          // '
          escape = '&#x27;'; // modified from escape-html; used to be '&#39'

          break;

        case 60:
          // <
          escape = '&lt;';
          break;

        case 62:
          // >
          escape = '&gt;';
          break;

        default:
          continue;
      }

      if (lastIndex !== index) {
        html += str.substring(lastIndex, index);
      }

      lastIndex = index + 1;
      html += escape;
    }

    return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  } // end code copied and modified from escape-html

  /**
   * Escapes text to prevent scripting attacks.
   *
   * @param {*} text Text value to escape.
   * @return {string} An escaped string.
   */


  function escapeTextForBrowser(text) {
    if (typeof text === 'boolean' || typeof text === 'number') {
      // this shortcircuit helps perf for types that we know will never have
      // special characters, especially given that this function is used often
      // for numeric dom ids.
      return '' + text;
    }

    return escapeHtml(text);
  }

  var uppercasePattern = /([A-Z])/g;
  var msPattern$1 = /^ms-/;
  /**
   * Hyphenates a camelcased CSS property name, for example:
   *
   *   > hyphenateStyleName('backgroundColor')
   *   < "background-color"
   *   > hyphenateStyleName('MozTransition')
   *   < "-moz-transition"
   *   > hyphenateStyleName('msTransition')
   *   < "-ms-transition"
   *
   * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
   * is converted to `-ms-`.
   */

  function hyphenateStyleName(name) {
    return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
  }

  // and any newline or tab are filtered out as if they're not part of the URL.
  // https://url.spec.whatwg.org/#url-parsing
  // Tab or newline are defined as \r\n\t:
  // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  // A C0 control is a code point in the range \u0000 NULL to \u001F
  // INFORMATION SEPARATOR ONE, inclusive:
  // https://infra.spec.whatwg.org/#c0-control-or-space

  /* eslint-disable max-len */

  var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
  var didWarn = false;

  function sanitizeURL(url) {
    {
      if (!didWarn && isJavaScriptProtocol.test(url)) {
        didWarn = true;

        error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
      }
    }
  }

  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

  function isArray(a) {
    return isArrayImpl(a);
  }

  var startInlineScript = stringToPrecomputedChunk('<script>');
  var endInlineScript = stringToPrecomputedChunk('</script>');
  var startScriptSrc = stringToPrecomputedChunk('<script src="');
  var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
  var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
  /**
   * This escaping function is designed to work with bootstrapScriptContent only.
   * because we know we are escaping the entire script. We can avoid for instance
   * escaping html comment string sequences that are valid javascript as well because
   * if there are no sebsequent <script sequences the html parser will never enter
   * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
   *
   * While untrusted script content should be made safe before using this api it will
   * ensure that the script cannot be early terminated or never terminated state
   */

  function escapeBootstrapScriptContent(scriptText) {
    {
      checkHtmlStringCoercion(scriptText);
    }

    return ('' + scriptText).replace(scriptRegex, scriptReplacer);
  }

  var scriptRegex = /(<\/|<)(s)(cript)/gi;

  var scriptReplacer = function (match, prefix, s, suffix) {
    return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
  }; // Allows us to keep track of what we've already written so we can refer back to it.


  function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
    var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
    var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
    var bootstrapChunks = [];

    if (bootstrapScriptContent !== undefined) {
      bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
    }

    if (bootstrapScripts !== undefined) {
      for (var i = 0; i < bootstrapScripts.length; i++) {
        bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
      }
    }

    if (bootstrapModules !== undefined) {
      for (var _i = 0; _i < bootstrapModules.length; _i++) {
        bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
      }
    }

    return {
      bootstrapChunks: bootstrapChunks,
      startInlineScript: inlineScriptWithNonce,
      placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
      segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
      boundaryPrefix: idPrefix + 'B:',
      idPrefix: idPrefix,
      nextSuspenseID: 0,
      sentCompleteSegmentFunction: false,
      sentCompleteBoundaryFunction: false,
      sentClientRenderFunction: false
    };
  } // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
  // modes. We only include the variants as they matter for the sake of our purposes.
  // We don't actually provide the namespace therefore we use constants instead of the string.

  var ROOT_HTML_MODE = 0; // Used for the root most element tag.

  var HTML_MODE = 1;
  var SVG_MODE = 2;
  var MATHML_MODE = 3;
  var HTML_TABLE_MODE = 4;
  var HTML_TABLE_BODY_MODE = 5;
  var HTML_TABLE_ROW_MODE = 6;
  var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
  // still makes sense

  function createFormatContext(insertionMode, selectedValue) {
    return {
      insertionMode: insertionMode,
      selectedValue: selectedValue
    };
  }

  function createRootFormatContext(namespaceURI) {
    var insertionMode = namespaceURI === 'http://www.w3.org/2000/svg' ? SVG_MODE : namespaceURI === 'http://www.w3.org/1998/Math/MathML' ? MATHML_MODE : ROOT_HTML_MODE;
    return createFormatContext(insertionMode, null);
  }
  function getChildFormatContext(parentContext, type, props) {
    switch (type) {
      case 'select':
        return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

      case 'svg':
        return createFormatContext(SVG_MODE, null);

      case 'math':
        return createFormatContext(MATHML_MODE, null);

      case 'foreignObject':
        return createFormatContext(HTML_MODE, null);
      // Table parents are special in that their children can only be created at all if they're
      // wrapped in a table parent. So we need to encode that we're entering this mode.

      case 'table':
        return createFormatContext(HTML_TABLE_MODE, null);

      case 'thead':
      case 'tbody':
      case 'tfoot':
        return createFormatContext(HTML_TABLE_BODY_MODE, null);

      case 'colgroup':
        return createFormatContext(HTML_COLGROUP_MODE, null);

      case 'tr':
        return createFormatContext(HTML_TABLE_ROW_MODE, null);
    }

    if (parentContext.insertionMode >= HTML_TABLE_MODE) {
      // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
      // entered plain HTML again.
      return createFormatContext(HTML_MODE, null);
    }

    if (parentContext.insertionMode === ROOT_HTML_MODE) {
      // We've emitted the root and is now in plain HTML mode.
      return createFormatContext(HTML_MODE, null);
    }

    return parentContext;
  }
  var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
  function assignSuspenseBoundaryID(responseState) {
    var generatedID = responseState.nextSuspenseID++;
    return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
  }
  function makeId(responseState, treeId, localId) {
    var idPrefix = responseState.idPrefix;
    var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
    // that represents the position of this useId hook among all the useId
    // hooks for this fiber.

    if (localId > 0) {
      id += 'H' + localId.toString(32);
    }

    return id + ':';
  }

  function encodeHTMLTextNode(text) {
    return escapeTextForBrowser(text);
  }

  var textSeparator = stringToPrecomputedChunk('<!-- -->');
  function pushTextInstance(target, text, responseState, textEmbedded) {
    if (text === '') {
      // Empty text doesn't have a DOM node representation and the hydration is aware of this.
      return textEmbedded;
    }

    if (textEmbedded) {
      target.push(textSeparator);
    }

    target.push(stringToChunk(encodeHTMLTextNode(text)));
    return true;
  } // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
  // emit a text separator when we don't know for sure it is safe to omit

  function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
    if (lastPushedText && textEmbedded) {
      target.push(textSeparator);
    }
  }
  var styleNameCache = new Map();

  function processStyleName(styleName) {
    var chunk = styleNameCache.get(styleName);

    if (chunk !== undefined) {
      return chunk;
    }

    var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
    styleNameCache.set(styleName, result);
    return result;
  }

  var styleAttributeStart = stringToPrecomputedChunk(' style="');
  var styleAssign = stringToPrecomputedChunk(':');
  var styleSeparator = stringToPrecomputedChunk(';');

  function pushStyle(target, responseState, style) {
    if (typeof style !== 'object') {
      throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
    }

    var isFirst = true;

    for (var styleName in style) {
      if (!hasOwnProperty.call(style, styleName)) {
        continue;
      } // If you provide unsafe user data here they can inject arbitrary CSS
      // which may be problematic (I couldn't repro this):
      // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
      // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
      // This is not an XSS hole but instead a potential CSS injection issue
      // which has lead to a greater discussion about how we're going to
      // trust URLs moving forward. See #2115901


      var styleValue = style[styleName];

      if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
        // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
        continue;
      }

      var nameChunk = void 0;
      var valueChunk = void 0;
      var isCustomProperty = styleName.indexOf('--') === 0;

      if (isCustomProperty) {
        nameChunk = stringToChunk(escapeTextForBrowser(styleName));

        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      } else {
        {
          warnValidStyle$1(styleName, styleValue);
        }

        nameChunk = processStyleName(styleName);

        if (typeof styleValue === 'number') {
          if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
            valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
          } else {
            valueChunk = stringToChunk('' + styleValue);
          }
        } else {
          {
            checkCSSPropertyStringCoercion(styleValue, styleName);
          }

          valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
        }
      }

      if (isFirst) {
        isFirst = false; // If it's first, we don't need any separators prefixed.

        target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
      } else {
        target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
      }
    }

    if (!isFirst) {
      target.push(attributeEnd);
    }
  }

  var attributeSeparator = stringToPrecomputedChunk(' ');
  var attributeAssign = stringToPrecomputedChunk('="');
  var attributeEnd = stringToPrecomputedChunk('"');
  var attributeEmptyString = stringToPrecomputedChunk('=""');

  function pushAttribute(target, responseState, name, value) {
    switch (name) {
      case 'style':
        {
          pushStyle(target, responseState, value);
          return;
        }

      case 'defaultValue':
      case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

      case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

      case 'suppressContentEditableWarning':
      case 'suppressHydrationWarning':
        // Ignored. These are built-in to React on the client.
        return;
    }

    if ( // shouldIgnoreAttribute
    // We have already filtered out null/undefined and reserved words.
    name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
      return;
    }

    var propertyInfo = getPropertyInfo(name);

    if (propertyInfo !== null) {
      // shouldRemoveAttribute
      switch (typeof value) {
        case 'function': // $FlowIssue symbol is perfectly valid here

        case 'symbol':
          // eslint-disable-line
          return;

        case 'boolean':
          {
            if (!propertyInfo.acceptsBooleans) {
              return;
            }
          }
      }

      var attributeName = propertyInfo.attributeName;
      var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

      switch (propertyInfo.type) {
        case BOOLEAN:
          if (value) {
            target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
          }

          return;

        case OVERLOADED_BOOLEAN:
          if (value === true) {
            target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
          } else if (value === false) ; else {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          return;

        case NUMERIC:
          if (!isNaN(value)) {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          break;

        case POSITIVE_NUMERIC:
          if (!isNaN(value) && value >= 1) {
            target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
          }

          break;

        default:
          if (propertyInfo.sanitizeURL) {
            {
              checkAttributeStringCoercion(value, attributeName);
            }

            value = '' + value;
            sanitizeURL(value);
          }

          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
      }
    } else if (isAttributeNameSafe(name)) {
      // shouldRemoveAttribute
      switch (typeof value) {
        case 'function': // $FlowIssue symbol is perfectly valid here

        case 'symbol':
          // eslint-disable-line
          return;

        case 'boolean':
          {
            var prefix = name.toLowerCase().slice(0, 5);

            if (prefix !== 'data-' && prefix !== 'aria-') {
              return;
            }
          }
      }

      target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  }

  var endOfStartTag = stringToPrecomputedChunk('>');
  var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

  function pushInnerHTML(target, innerHTML, children) {
    if (innerHTML != null) {
      if (children != null) {
        throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      }

      if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
        throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
      }

      var html = innerHTML.__html;

      if (html !== null && html !== undefined) {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  } // TODO: Move these to ResponseState so that we warn for every request.
  // It would help debugging in stateful servers (e.g. service worker).


  var didWarnDefaultInputValue = false;
  var didWarnDefaultChecked = false;
  var didWarnDefaultSelectValue = false;
  var didWarnDefaultTextareaValue = false;
  var didWarnInvalidOptionChildren = false;
  var didWarnInvalidOptionInnerHTML = false;
  var didWarnSelectedSetOnOption = false;

  function checkSelectProp(props, propName) {
    {
      var value = props[propName];

      if (value != null) {
        var array = isArray(value);

        if (props.multiple && !array) {
          error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
        } else if (!props.multiple && array) {
          error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
        }
      }
    }
  }

  function pushStartSelect(target, props, responseState) {
    {
      checkControlledValueProps('select', props);
      checkSelectProp(props, 'value');
      checkSelectProp(props, 'defaultValue');

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
        error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

        didWarnDefaultSelectValue = true;
      }
    }

    target.push(startChunkForTag('select'));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            // TODO: This doesn't really make sense for select since it can't use the controlled
            // value in the innerHTML.
            innerHTML = propValue;
            break;

          case 'defaultValue':
          case 'value':
            // These are set on the Context instead and applied to the nested options.
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  function flattenOptionChildren(children) {
    var content = ''; // Flatten children and warn if they aren't strings or numbers;
    // invalid types are ignored.

    React.Children.forEach(children, function (child) {
      if (child == null) {
        return;
      }

      content += child;

      {
        if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
          didWarnInvalidOptionChildren = true;

          error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
        }
      }
    });
    return content;
  }

  var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

  function pushStartOption(target, props, responseState, formatContext) {
    var selectedValue = formatContext.selectedValue;
    target.push(startChunkForTag('option'));
    var children = null;
    var value = null;
    var selected = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'selected':
            // ignore
            selected = propValue;

            {
              // TODO: Remove support for `selected` in <option>.
              if (!didWarnSelectedSetOnOption) {
                error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

                didWarnSelectedSetOnOption = true;
              }
            }

            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;
          // eslint-disable-next-line-no-fallthrough

          case 'value':
            value = propValue;
          // We intentionally fallthrough to also set the attribute on the node.
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (selectedValue != null) {
      var stringValue;

      if (value !== null) {
        {
          checkAttributeStringCoercion(value, 'value');
        }

        stringValue = '' + value;
      } else {
        {
          if (innerHTML !== null) {
            if (!didWarnInvalidOptionInnerHTML) {
              didWarnInvalidOptionInnerHTML = true;

              error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
            }
          }
        }

        stringValue = flattenOptionChildren(children);
      }

      if (isArray(selectedValue)) {
        // multiple
        for (var i = 0; i < selectedValue.length; i++) {
          {
            checkAttributeStringCoercion(selectedValue[i], 'value');
          }

          var v = '' + selectedValue[i];

          if (v === stringValue) {
            target.push(selectedMarkerAttribute);
            break;
          }
        }
      } else {
        {
          checkAttributeStringCoercion(selectedValue, 'select.value');
        }

        if ('' + selectedValue === stringValue) {
          target.push(selectedMarkerAttribute);
        }
      }
    } else if (selected) {
      target.push(selectedMarkerAttribute);
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  function pushInput(target, props, responseState) {
    {
      checkControlledValueProps('input', props);

      if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
        error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

        didWarnDefaultChecked = true;
      }

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
        error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

        didWarnDefaultInputValue = true;
      }
    }

    target.push(startChunkForTag('input'));
    var value = null;
    var defaultValue = null;
    var checked = null;
    var defaultChecked = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          case 'defaultChecked':
            defaultChecked = propValue;
            break;

          case 'defaultValue':
            defaultValue = propValue;
            break;

          case 'checked':
            checked = propValue;
            break;

          case 'value':
            value = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (checked !== null) {
      pushAttribute(target, responseState, 'checked', checked);
    } else if (defaultChecked !== null) {
      pushAttribute(target, responseState, 'checked', defaultChecked);
    }

    if (value !== null) {
      pushAttribute(target, responseState, 'value', value);
    } else if (defaultValue !== null) {
      pushAttribute(target, responseState, 'value', defaultValue);
    }

    target.push(endOfStartTagSelfClosing);
    return null;
  }

  function pushStartTextArea(target, props, responseState) {
    {
      checkControlledValueProps('textarea', props);

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
        error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

        didWarnDefaultTextareaValue = true;
      }
    }

    target.push(startChunkForTag('textarea'));
    var value = null;
    var defaultValue = null;
    var children = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'value':
            value = propValue;
            break;

          case 'defaultValue':
            defaultValue = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    if (value === null && defaultValue !== null) {
      value = defaultValue;
    }

    target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

    if (children != null) {
      {
        error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
      }

      if (value != null) {
        throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
      }

      if (isArray(children)) {
        if (children.length > 1) {
          throw new Error('<textarea> can only have at most one child.');
        } // TODO: remove the coercion and the DEV check below because it will
        // always be overwritten by the coercion several lines below it. #22309


        {
          checkHtmlStringCoercion(children[0]);
        }

        value = '' + children[0];
      }

      {
        checkHtmlStringCoercion(children);
      }

      value = '' + children;
    }

    if (typeof value === 'string' && value[0] === '\n') {
      // text/html ignores the first character in these tags if it's a newline
      // Prefer to break application/xml over text/html (for now) by adding
      // a newline specifically to get eaten by the parser. (Alternately for
      // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
      // \r is normalized out by HTMLTextAreaElement#value.)
      // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
      // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
      // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
      // See: Parsing of "textarea" "listing" and "pre" elements
      //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
      target.push(leadingNewline);
    } // ToString and push directly instead of recurse over children.
    // We don't really support complex children in the value anyway.
    // This also currently avoids a trailing comment node which breaks textarea.


    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      target.push(stringToChunk(encodeHTMLTextNode('' + value)));
    }

    return null;
  }

  function pushSelfClosing(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTagSelfClosing);
    return null;
  }

  function pushStartMenuItem(target, props, responseState) {
    target.push(startChunkForTag('menuitem'));

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
          case 'dangerouslySetInnerHTML':
            throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    return null;
  }

  function pushStartTitle(target, props, responseState) {
    target.push(startChunkForTag('title'));
    var children = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
          // eslint-disable-next-line-no-fallthrough

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);

    {
      var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

      if (Array.isArray(children) && children.length > 1) {
        error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      } else if (child != null && child.$$typeof != null) {
        error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
        error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
      }
    }

    return children;
  }

  function pushStartGenericElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);

    if (typeof children === 'string') {
      // Special case children as a string to avoid the unnecessary comment.
      // TODO: Remove this special case after the general optimization is in place.
      target.push(stringToChunk(encodeHTMLTextNode(children)));
      return null;
    }

    return children;
  }

  function pushStartCustomElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          case 'style':
            pushStyle(target, responseState, propValue);
            break;

          case 'suppressContentEditableWarning':
          case 'suppressHydrationWarning':
            // Ignored. These are built-in to React on the client.
            break;

          default:
            if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
              target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
            }

            break;
        }
      }
    }

    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    return children;
  }

  var leadingNewline = stringToPrecomputedChunk('\n');

  function pushStartPreformattedElement(target, props, tag, responseState) {
    target.push(startChunkForTag(tag));
    var children = null;
    var innerHTML = null;

    for (var propKey in props) {
      if (hasOwnProperty.call(props, propKey)) {
        var propValue = props[propKey];

        if (propValue == null) {
          continue;
        }

        switch (propKey) {
          case 'children':
            children = propValue;
            break;

          case 'dangerouslySetInnerHTML':
            innerHTML = propValue;
            break;

          default:
            pushAttribute(target, responseState, propKey, propValue);
            break;
        }
      }
    }

    target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    // TODO: This doesn't deal with the case where the child is an array
    // or component that returns a string.

    if (innerHTML != null) {
      if (children != null) {
        throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      }

      if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
        throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
      }

      var html = innerHTML.__html;

      if (html !== null && html !== undefined) {
        if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
          target.push(leadingNewline, stringToChunk(html));
        } else {
          {
            checkHtmlStringCoercion(html);
          }

          target.push(stringToChunk('' + html));
        }
      }
    }

    if (typeof children === 'string' && children[0] === '\n') {
      target.push(leadingNewline);
    }

    return children;
  } // We accept any tag to be rendered but since this gets injected into arbitrary
  // HTML, we want to make sure that it's a safe tag.
  // http://www.w3.org/TR/REC-xml/#NT-Name


  var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

  var validatedTagCache = new Map();

  function startChunkForTag(tag) {
    var tagStartChunk = validatedTagCache.get(tag);

    if (tagStartChunk === undefined) {
      if (!VALID_TAG_REGEX.test(tag)) {
        throw new Error("Invalid tag: " + tag);
      }

      tagStartChunk = stringToPrecomputedChunk('<' + tag);
      validatedTagCache.set(tag, tagStartChunk);
    }

    return tagStartChunk;
  }

  var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
  function pushStartInstance(target, type, props, responseState, formatContext) {
    {
      validateProperties(type, props);
      validateProperties$1(type, props);
      validateProperties$2(type, props, null);

      if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
        error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
      }

      if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
          error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
        }
      }
    }

    switch (type) {
      // Special tags
      case 'select':
        return pushStartSelect(target, props, responseState);

      case 'option':
        return pushStartOption(target, props, responseState, formatContext);

      case 'textarea':
        return pushStartTextArea(target, props, responseState);

      case 'input':
        return pushInput(target, props, responseState);

      case 'menuitem':
        return pushStartMenuItem(target, props, responseState);

      case 'title':
        return pushStartTitle(target, props, responseState);
      // Newline eating tags

      case 'listing':
      case 'pre':
        {
          return pushStartPreformattedElement(target, props, type, responseState);
        }
      // Omitted close tags

      case 'area':
      case 'base':
      case 'br':
      case 'col':
      case 'embed':
      case 'hr':
      case 'img':
      case 'keygen':
      case 'link':
      case 'meta':
      case 'param':
      case 'source':
      case 'track':
      case 'wbr':
        {
          return pushSelfClosing(target, props, type, responseState);
        }
      // These are reserved SVG and MathML elements, that are never custom elements.
      // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

      case 'annotation-xml':
      case 'color-profile':
      case 'font-face':
      case 'font-face-src':
      case 'font-face-uri':
      case 'font-face-format':
      case 'font-face-name':
      case 'missing-glyph':
        {
          return pushStartGenericElement(target, props, type, responseState);
        }

      case 'html':
        {
          if (formatContext.insertionMode === ROOT_HTML_MODE) {
            // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
            // then we also emit the DOCTYPE as part of the root content as a convenience for
            // rendering the whole document.
            target.push(DOCTYPE);
          }

          return pushStartGenericElement(target, props, type, responseState);
        }

      default:
        {
          if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
            // Generic element
            return pushStartGenericElement(target, props, type, responseState);
          } else {
            // Custom element
            return pushStartCustomElement(target, props, type, responseState);
          }
        }
    }
  }
  var endTag1 = stringToPrecomputedChunk('</');
  var endTag2 = stringToPrecomputedChunk('>');
  function pushEndInstance(target, type, props) {
    switch (type) {
      // Omitted close tags
      // TODO: Instead of repeating this switch we could try to pass a flag from above.
      // That would require returning a tuple. Which might be ok if it gets inlined.
      case 'area':
      case 'base':
      case 'br':
      case 'col':
      case 'embed':
      case 'hr':
      case 'img':
      case 'input':
      case 'keygen':
      case 'link':
      case 'meta':
      case 'param':
      case 'source':
      case 'track':
      case 'wbr':
        {
          // No close tag needed.
          break;
        }

      default:
        {
          target.push(endTag1, stringToChunk(type), endTag2);
        }
    }
  }
  function writeCompletedRoot(destination, responseState) {
    var bootstrapChunks = responseState.bootstrapChunks;
    var i = 0;

    for (; i < bootstrapChunks.length - 1; i++) {
      writeChunk(destination, bootstrapChunks[i]);
    }

    if (i < bootstrapChunks.length) {
      return writeChunkAndReturn(destination, bootstrapChunks[i]);
    }

    return true;
  } // Structural Nodes
  // A placeholder is a node inside a hidden partial tree that can be filled in later, but before
  // display. It's never visible to users. We use the template tag because it can be used in every
  // type of parent. <script> tags also work in every other tag except <colgroup>.

  var placeholder1 = stringToPrecomputedChunk('<template id="');
  var placeholder2 = stringToPrecomputedChunk('"></template>');
  function writePlaceholder(destination, responseState, id) {
    writeChunk(destination, placeholder1);
    writeChunk(destination, responseState.placeholderPrefix);
    var formattedID = stringToChunk(id.toString(16));
    writeChunk(destination, formattedID);
    return writeChunkAndReturn(destination, placeholder2);
  } // Suspense boundaries are encoded as comments.

  var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
  var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
  var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
  var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
  var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
  var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
  var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
  var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
  var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
  var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
  var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
  function writeStartCompletedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
  }
  function writeStartPendingSuspenseBoundary(destination, responseState, id) {
    writeChunk(destination, startPendingSuspenseBoundary1);

    if (id === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    writeChunk(destination, id);
    return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
  }
  function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
    var result;
    result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
    writeChunk(destination, clientRenderedSuspenseBoundaryError1);

    if (errorDigest) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    {
      if (errorMesssage) {
        writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
        writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
        writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
      }

      if (errorComponentStack) {
        writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
        writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
        writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
      }
    }

    result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
    return result;
  }
  function writeEndCompletedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  function writeEndPendingSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
  var startSegmentHTML2 = stringToPrecomputedChunk('">');
  var endSegmentHTML = stringToPrecomputedChunk('</div>');
  var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
  var startSegmentSVG2 = stringToPrecomputedChunk('">');
  var endSegmentSVG = stringToPrecomputedChunk('</svg>');
  var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
  var startSegmentMathML2 = stringToPrecomputedChunk('">');
  var endSegmentMathML = stringToPrecomputedChunk('</math>');
  var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
  var startSegmentTable2 = stringToPrecomputedChunk('">');
  var endSegmentTable = stringToPrecomputedChunk('</table>');
  var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
  var startSegmentTableBody2 = stringToPrecomputedChunk('">');
  var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
  var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
  var startSegmentTableRow2 = stringToPrecomputedChunk('">');
  var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
  var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
  var startSegmentColGroup2 = stringToPrecomputedChunk('">');
  var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
  function writeStartSegment(destination, responseState, formatContext, id) {
    switch (formatContext.insertionMode) {
      case ROOT_HTML_MODE:
      case HTML_MODE:
        {
          writeChunk(destination, startSegmentHTML);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentHTML2);
        }

      case SVG_MODE:
        {
          writeChunk(destination, startSegmentSVG);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentSVG2);
        }

      case MATHML_MODE:
        {
          writeChunk(destination, startSegmentMathML);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentMathML2);
        }

      case HTML_TABLE_MODE:
        {
          writeChunk(destination, startSegmentTable);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTable2);
        }
      // TODO: For the rest of these, there will be extra wrapper nodes that never
      // get deleted from the document. We need to delete the table too as part
      // of the injected scripts. They are invisible though so it's not too terrible
      // and it's kind of an edge case to suspend in a table. Totally supported though.

      case HTML_TABLE_BODY_MODE:
        {
          writeChunk(destination, startSegmentTableBody);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTableBody2);
        }

      case HTML_TABLE_ROW_MODE:
        {
          writeChunk(destination, startSegmentTableRow);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentTableRow2);
        }

      case HTML_COLGROUP_MODE:
        {
          writeChunk(destination, startSegmentColGroup);
          writeChunk(destination, responseState.segmentPrefix);
          writeChunk(destination, stringToChunk(id.toString(16)));
          return writeChunkAndReturn(destination, startSegmentColGroup2);
        }

      default:
        {
          throw new Error('Unknown insertion mode. This is a bug in React.');
        }
    }
  }
  function writeEndSegment(destination, formatContext) {
    switch (formatContext.insertionMode) {
      case ROOT_HTML_MODE:
      case HTML_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentHTML);
        }

      case SVG_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentSVG);
        }

      case MATHML_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentMathML);
        }

      case HTML_TABLE_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTable);
        }

      case HTML_TABLE_BODY_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTableBody);
        }

      case HTML_TABLE_ROW_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentTableRow);
        }

      case HTML_COLGROUP_MODE:
        {
          return writeChunkAndReturn(destination, endSegmentColGroup);
        }

      default:
        {
          throw new Error('Unknown insertion mode. This is a bug in React.');
        }
    }
  } // Instruction Set
  // The following code is the source scripts that we then minify and inline below,
  // with renamed function names that we hope don't collide:
  // const COMMENT_NODE = 8;
  // const SUSPENSE_START_DATA = '$';
  // const SUSPENSE_END_DATA = '/$';
  // const SUSPENSE_PENDING_START_DATA = '$?';
  // const SUSPENSE_FALLBACK_START_DATA = '$!';
  //
  // function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
  //   // Find the fallback's first element.
  //   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  //   if (!suspenseIdNode) {
  //     // The user must have already navigated away from this tree.
  //     // E.g. because the parent was hydrated.
  //     return;
  //   }
  //   // Find the boundary around the fallback. This is always the previous node.
  //   const suspenseNode = suspenseIdNode.previousSibling;
  //   // Tag it to be client rendered.
  //   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
  //   // assign error metadata to first sibling
  //   let dataset = suspenseIdNode.dataset;
  //   if (errorDigest) dataset.dgst = errorDigest;
  //   if (errorMsg) dataset.msg = errorMsg;
  //   if (errorComponentStack) dataset.stck = errorComponentStack;
  //   // Tell React to retry it if the parent already hydrated.
  //   if (suspenseNode._reactRetry) {
  //     suspenseNode._reactRetry();
  //   }
  // }
  //
  // function completeBoundary(suspenseBoundaryID, contentID) {
  //   // Find the fallback's first element.
  //   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  //   const contentNode = document.getElementById(contentID);
  //   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
  //   // This might also help by not causing recalcing each time we move a child from here to the target.
  //   contentNode.parentNode.removeChild(contentNode);
  //   if (!suspenseIdNode) {
  //     // The user must have already navigated away from this tree.
  //     // E.g. because the parent was hydrated. That's fine there's nothing to do
  //     // but we have to make sure that we already deleted the container node.
  //     return;
  //   }
  //   // Find the boundary around the fallback. This is always the previous node.
  //   const suspenseNode = suspenseIdNode.previousSibling;
  //
  //   // Clear all the existing children. This is complicated because
  //   // there can be embedded Suspense boundaries in the fallback.
  //   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
  //   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
  //   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
  //   const parentInstance = suspenseNode.parentNode;
  //   let node = suspenseNode.nextSibling;
  //   let depth = 0;
  //   do {
  //     if (node && node.nodeType === COMMENT_NODE) {
  //       const data = node.data;
  //       if (data === SUSPENSE_END_DATA) {
  //         if (depth === 0) {
  //           break;
  //         } else {
  //           depth--;
  //         }
  //       } else if (
  //         data === SUSPENSE_START_DATA ||
  //         data === SUSPENSE_PENDING_START_DATA ||
  //         data === SUSPENSE_FALLBACK_START_DATA
  //       ) {
  //         depth++;
  //       }
  //     }
  //
  //     const nextNode = node.nextSibling;
  //     parentInstance.removeChild(node);
  //     node = nextNode;
  //   } while (node);
  //
  //   const endOfBoundary = node;
  //
  //   // Insert all the children from the contentNode between the start and end of suspense boundary.
  //   while (contentNode.firstChild) {
  //     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
  //   }
  //   suspenseNode.data = SUSPENSE_START_DATA;
  //   if (suspenseNode._reactRetry) {
  //     suspenseNode._reactRetry();
  //   }
  // }
  //
  // function completeSegment(containerID, placeholderID) {
  //   const segmentContainer = document.getElementById(containerID);
  //   const placeholderNode = document.getElementById(placeholderID);
  //   // We always expect both nodes to exist here because, while we might
  //   // have navigated away from the main tree, we still expect the detached
  //   // tree to exist.
  //   segmentContainer.parentNode.removeChild(segmentContainer);
  //   while (segmentContainer.firstChild) {
  //     placeholderNode.parentNode.insertBefore(
  //       segmentContainer.firstChild,
  //       placeholderNode,
  //     );
  //   }
  //   placeholderNode.parentNode.removeChild(placeholderNode);
  // }

  var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
  var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
  var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
  var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
  var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
  var completeSegmentScript2 = stringToPrecomputedChunk('","');
  var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
  function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentCompleteSegmentFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentCompleteSegmentFunction = true;
      writeChunk(destination, completeSegmentScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, completeSegmentScript1Partial);
    }

    writeChunk(destination, responseState.segmentPrefix);
    var formattedID = stringToChunk(contentSegmentID.toString(16));
    writeChunk(destination, formattedID);
    writeChunk(destination, completeSegmentScript2);
    writeChunk(destination, responseState.placeholderPrefix);
    writeChunk(destination, formattedID);
    return writeChunkAndReturn(destination, completeSegmentScript3);
  }
  var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
  var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
  var completeBoundaryScript2 = stringToPrecomputedChunk('","');
  var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
  function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentCompleteBoundaryFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentCompleteBoundaryFunction = true;
      writeChunk(destination, completeBoundaryScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, completeBoundaryScript1Partial);
    }

    if (boundaryID === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    var formattedContentID = stringToChunk(contentSegmentID.toString(16));
    writeChunk(destination, boundaryID);
    writeChunk(destination, completeBoundaryScript2);
    writeChunk(destination, responseState.segmentPrefix);
    writeChunk(destination, formattedContentID);
    return writeChunkAndReturn(destination, completeBoundaryScript3);
  }
  var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
  var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
  var clientRenderScript1A = stringToPrecomputedChunk('"');
  var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
  var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
  function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
    writeChunk(destination, responseState.startInlineScript);

    if (!responseState.sentClientRenderFunction) {
      // The first time we write this, we'll need to include the full implementation.
      responseState.sentClientRenderFunction = true;
      writeChunk(destination, clientRenderScript1Full);
    } else {
      // Future calls can just reuse the same function.
      writeChunk(destination, clientRenderScript1Partial);
    }

    if (boundaryID === null) {
      throw new Error('An ID must have been assigned before we can complete the boundary.');
    }

    writeChunk(destination, boundaryID);
    writeChunk(destination, clientRenderScript1A);

    if (errorDigest || errorMessage || errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
    }

    if (errorMessage || errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderErrorScriptArgInterstitial);
      writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
    }

    return writeChunkAndReturn(destination, clientRenderScript2);
  }
  var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

  function escapeJSStringsForInstructionScripts(input) {
    var escaped = JSON.stringify(input);
    return escaped.replace(regexForJSStringsInScripts, function (match) {
      switch (match) {
        // santizing breaking out of strings and script tags
        case '<':
          return "\\u003c";

        case "\u2028":
          return "\\u2028";

        case "\u2029":
          return "\\u2029";

        default:
          {
            // eslint-disable-next-line react-internal/prod-error-codes
            throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
          }
      }
    });
  }

  var assign = Object.assign;

  // ATTENTION
  // When adding new symbols to this file,
  // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  // The Symbol used to tag the ReactElement-like types.
  var REACT_ELEMENT_TYPE = Symbol.for('react.element');
  var REACT_PORTAL_TYPE = Symbol.for('react.portal');
  var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
  var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
  var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
  var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
  var REACT_CONTEXT_TYPE = Symbol.for('react.context');
  var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
  var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
  var REACT_MEMO_TYPE = Symbol.for('react.memo');
  var REACT_LAZY_TYPE = Symbol.for('react.lazy');
  var REACT_SCOPE_TYPE = Symbol.for('react.scope');
  var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
  var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
  var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
  var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';
  function getIteratorFn(maybeIterable) {
    if (maybeIterable === null || typeof maybeIterable !== 'object') {
      return null;
    }

    var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

    if (typeof maybeIterator === 'function') {
      return maybeIterator;
    }

    return null;
  }

  function getWrappedName(outerType, innerType, wrapperName) {
    var displayName = outerType.displayName;

    if (displayName) {
      return displayName;
    }

    var functionName = innerType.displayName || innerType.name || '';
    return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
  } // Keep in sync with react-reconciler/getComponentNameFromFiber


  function getContextName(type) {
    return type.displayName || 'Context';
  } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


  function getComponentNameFromType(type) {
    if (type == null) {
      // Host root, text node or just invalid type.
      return null;
    }

    {
      if (typeof type.tag === 'number') {
        error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
      }
    }

    if (typeof type === 'function') {
      return type.displayName || type.name || null;
    }

    if (typeof type === 'string') {
      return type;
    }

    switch (type) {
      case REACT_FRAGMENT_TYPE:
        return 'Fragment';

      case REACT_PORTAL_TYPE:
        return 'Portal';

      case REACT_PROFILER_TYPE:
        return 'Profiler';

      case REACT_STRICT_MODE_TYPE:
        return 'StrictMode';

      case REACT_SUSPENSE_TYPE:
        return 'Suspense';

      case REACT_SUSPENSE_LIST_TYPE:
        return 'SuspenseList';

    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_CONTEXT_TYPE:
          var context = type;
          return getContextName(context) + '.Consumer';

        case REACT_PROVIDER_TYPE:
          var provider = type;
          return getContextName(provider._context) + '.Provider';

        case REACT_FORWARD_REF_TYPE:
          return getWrappedName(type, type.render, 'ForwardRef');

        case REACT_MEMO_TYPE:
          var outerName = type.displayName || null;

          if (outerName !== null) {
            return outerName;
          }

          return getComponentNameFromType(type.type) || 'Memo';

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              return getComponentNameFromType(init(payload));
            } catch (x) {
              return null;
            }
          }

        // eslint-disable-next-line no-fallthrough
      }
    }

    return null;
  }

  // Helpers to patch console.logs to avoid logging during side-effect free
  // replaying on render function. This currently only patches the object
  // lazily which won't cover if the log function was extracted eagerly.
  // We could also eagerly patch the method.
  var disabledDepth = 0;
  var prevLog;
  var prevInfo;
  var prevWarn;
  var prevError;
  var prevGroup;
  var prevGroupCollapsed;
  var prevGroupEnd;

  function disabledLog() {}

  disabledLog.__reactDisabledLog = true;
  function disableLogs() {
    {
      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      disabledDepth++;
    }
  }
  function reenableLogs() {
    {
      disabledDepth--;

      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        var props = {
          configurable: true,
          enumerable: true,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          log: assign({}, props, {
            value: prevLog
          }),
          info: assign({}, props, {
            value: prevInfo
          }),
          warn: assign({}, props, {
            value: prevWarn
          }),
          error: assign({}, props, {
            value: prevError
          }),
          group: assign({}, props, {
            value: prevGroup
          }),
          groupCollapsed: assign({}, props, {
            value: prevGroupCollapsed
          }),
          groupEnd: assign({}, props, {
            value: prevGroupEnd
          })
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      if (disabledDepth < 0) {
        error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
      }
    }
  }

  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  var prefix;
  function describeBuiltInComponentFrame(name, source, ownerFn) {
    {
      if (prefix === undefined) {
        // Extract the VM specific prefix used by each line.
        try {
          throw Error();
        } catch (x) {
          var match = x.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || '';
        }
      } // We use the prefix to ensure our stacks line up with native stack frames.


      return '\n' + prefix + name;
    }
  }
  var reentry = false;
  var componentFrameCache;

  {
    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
    componentFrameCache = new PossiblyWeakMap();
  }

  function describeNativeComponentFrame(fn, construct) {
    // If something asked for a stack inside a fake render, it should get ignored.
    if ( !fn || reentry) {
      return '';
    }

    {
      var frame = componentFrameCache.get(fn);

      if (frame !== undefined) {
        return frame;
      }
    }

    var control;
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

    Error.prepareStackTrace = undefined;
    var previousDispatcher;

    {
      previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
      // for warnings.

      ReactCurrentDispatcher.current = null;
      disableLogs();
    }

    try {
      // This should throw.
      if (construct) {
        // Something should be setting the props in the constructor.
        var Fake = function () {
          throw Error();
        }; // $FlowFixMe


        Object.defineProperty(Fake.prototype, 'props', {
          set: function () {
            // We use a throwing setter instead of frozen or non-writable props
            // because that won't throw in a non-strict mode function.
            throw Error();
          }
        });

        if (typeof Reflect === 'object' && Reflect.construct) {
          // We construct a different control for this case to include any extra
          // frames added by the construct call.
          try {
            Reflect.construct(Fake, []);
          } catch (x) {
            control = x;
          }

          Reflect.construct(fn, [], Fake);
        } else {
          try {
            Fake.call();
          } catch (x) {
            control = x;
          }

          fn.call(Fake.prototype);
        }
      } else {
        try {
          throw Error();
        } catch (x) {
          control = x;
        }

        fn();
      }
    } catch (sample) {
      // This is inlined manually because closure doesn't do it for us.
      if (sample && control && typeof sample.stack === 'string') {
        // This extracts the first frame from the sample that isn't also in the control.
        // Skipping one frame that we assume is the frame that calls the two.
        var sampleLines = sample.stack.split('\n');
        var controlLines = control.stack.split('\n');
        var s = sampleLines.length - 1;
        var c = controlLines.length - 1;

        while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
          // We expect at least one stack frame to be shared.
          // Typically this will be the root most one. However, stack frames may be
          // cut off due to maximum stack limits. In this case, one maybe cut off
          // earlier than the other. We assume that the sample is longer or the same
          // and there for cut off earlier. So we should find the root most frame in
          // the sample somewhere in the control.
          c--;
        }

        for (; s >= 1 && c >= 0; s--, c--) {
          // Next we find the first one that isn't the same which should be the
          // frame that called our sample function and the control.
          if (sampleLines[s] !== controlLines[c]) {
            // In V8, the first line is describing the message but other VMs don't.
            // If we're about to return the first line, and the control is also on the same
            // line, that's a pretty good indicator that our sample threw at same line as
            // the control. I.e. before we entered the sample frame. So we ignore this result.
            // This can happen if you passed a class to function component, or non-function.
            if (s !== 1 || c !== 1) {
              do {
                s--;
                c--; // We may still have similar intermediate frames from the construct call.
                // The next one that isn't the same should be our match though.

                if (c < 0 || sampleLines[s] !== controlLines[c]) {
                  // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                  var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                  // but we have a user-provided "displayName"
                  // splice it in to make the stack more readable.


                  if (fn.displayName && _frame.includes('<anonymous>')) {
                    _frame = _frame.replace('<anonymous>', fn.displayName);
                  }

                  {
                    if (typeof fn === 'function') {
                      componentFrameCache.set(fn, _frame);
                    }
                  } // Return the line we found.


                  return _frame;
                }
              } while (s >= 1 && c >= 0);
            }

            break;
          }
        }
      }
    } finally {
      reentry = false;

      {
        ReactCurrentDispatcher.current = previousDispatcher;
        reenableLogs();
      }

      Error.prepareStackTrace = previousPrepareStackTrace;
    } // Fallback to just using the name if we couldn't make it throw.


    var name = fn ? fn.displayName || fn.name : '';
    var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

    {
      if (typeof fn === 'function') {
        componentFrameCache.set(fn, syntheticFrame);
      }
    }

    return syntheticFrame;
  }

  function describeClassComponentFrame(ctor, source, ownerFn) {
    {
      return describeNativeComponentFrame(ctor, true);
    }
  }
  function describeFunctionComponentFrame(fn, source, ownerFn) {
    {
      return describeNativeComponentFrame(fn, false);
    }
  }

  function shouldConstruct(Component) {
    var prototype = Component.prototype;
    return !!(prototype && prototype.isReactComponent);
  }

  function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

    if (type == null) {
      return '';
    }

    if (typeof type === 'function') {
      {
        return describeNativeComponentFrame(type, shouldConstruct(type));
      }
    }

    if (typeof type === 'string') {
      return describeBuiltInComponentFrame(type);
    }

    switch (type) {
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame('Suspense');

      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame('SuspenseList');
    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeFunctionComponentFrame(type.render);

        case REACT_MEMO_TYPE:
          // Memo may contain any component type so we recursively resolve it.
          return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              // Lazy may contain any component type so we recursively resolve it.
              return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
            } catch (x) {}
          }
      }
    }

    return '';
  }

  var loggedTypeFailures = {};
  var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

  function setCurrentlyValidatingElement(element) {
    {
      if (element) {
        var owner = element._owner;
        var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
        ReactDebugCurrentFrame.setExtraStackFrame(stack);
      } else {
        ReactDebugCurrentFrame.setExtraStackFrame(null);
      }
    }
  }

  function checkPropTypes(typeSpecs, values, location, componentName, element) {
    {
      // $FlowFixMe This is okay but Flow doesn't know it.
      var has = Function.call.bind(hasOwnProperty);

      for (var typeSpecName in typeSpecs) {
        if (has(typeSpecs, typeSpecName)) {
          var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
          // fail the render phase where it didn't fail before. So we log it.
          // After these have been cleaned up, we'll let them throw.

          try {
            // This is intentionally an invariant that gets caught. It's the same
            // behavior as without this statement except with a better message.
            if (typeof typeSpecs[typeSpecName] !== 'function') {
              // eslint-disable-next-line react-internal/prod-error-codes
              var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
              err.name = 'Invariant Violation';
              throw err;
            }

            error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
          } catch (ex) {
            error$1 = ex;
          }

          if (error$1 && !(error$1 instanceof Error)) {
            setCurrentlyValidatingElement(element);

            error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

            setCurrentlyValidatingElement(null);
          }

          if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
            // Only monitor this failure once because there tends to be a lot of the
            // same error.
            loggedTypeFailures[error$1.message] = true;
            setCurrentlyValidatingElement(element);

            error('Failed %s type: %s', location, error$1.message);

            setCurrentlyValidatingElement(null);
          }
        }
      }
    }
  }

  var warnedAboutMissingGetChildContext;

  {
    warnedAboutMissingGetChildContext = {};
  }

  var emptyContextObject = {};

  {
    Object.freeze(emptyContextObject);
  }

  function getMaskedContext(type, unmaskedContext) {
    {
      var contextTypes = type.contextTypes;

      if (!contextTypes) {
        return emptyContextObject;
      }

      var context = {};

      for (var key in contextTypes) {
        context[key] = unmaskedContext[key];
      }

      {
        var name = getComponentNameFromType(type) || 'Unknown';
        checkPropTypes(contextTypes, context, 'context', name);
      }

      return context;
    }
  }
  function processChildContext(instance, type, parentContext, childContextTypes) {
    {
      // TODO (bvaughn) Replace this behavior with an invariant() in the future.
      // It has only been added in Fiber to match the (unintentional) behavior in Stack.
      if (typeof instance.getChildContext !== 'function') {
        {
          var componentName = getComponentNameFromType(type) || 'Unknown';

          if (!warnedAboutMissingGetChildContext[componentName]) {
            warnedAboutMissingGetChildContext[componentName] = true;

            error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
          }
        }

        return parentContext;
      }

      var childContext = instance.getChildContext();

      for (var contextKey in childContext) {
        if (!(contextKey in childContextTypes)) {
          throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
        }
      }

      {
        var name = getComponentNameFromType(type) || 'Unknown';
        checkPropTypes(childContextTypes, childContext, 'child context', name);
      }

      return assign({}, parentContext, childContext);
    }
  }

  var rendererSigil;

  {
    // Use this to detect multiple renderers using the same context
    rendererSigil = {};
  } // Used to store the parent path of all context overrides in a shared linked list.
  // Forming a reverse tree.


  var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
  // This global (actually thread local) state represents what state all those "current",
  // fields are currently in.

  var currentActiveSnapshot = null;

  function popNode(prev) {
    {
      prev.context._currentValue = prev.parentValue;
    }
  }

  function pushNode(next) {
    {
      next.context._currentValue = next.value;
    }
  }

  function popToNearestCommonAncestor(prev, next) {
    if (prev === next) ; else {
      popNode(prev);
      var parentPrev = prev.parent;
      var parentNext = next.parent;

      if (parentPrev === null) {
        if (parentNext !== null) {
          throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
        }
      } else {
        if (parentNext === null) {
          throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
        }

        popToNearestCommonAncestor(parentPrev, parentNext);
      } // On the way back, we push the new ones that weren't common.


      pushNode(next);
    }
  }

  function popAllPrevious(prev) {
    popNode(prev);
    var parentPrev = prev.parent;

    if (parentPrev !== null) {
      popAllPrevious(parentPrev);
    }
  }

  function pushAllNext(next) {
    var parentNext = next.parent;

    if (parentNext !== null) {
      pushAllNext(parentNext);
    }

    pushNode(next);
  }

  function popPreviousToCommonLevel(prev, next) {
    popNode(prev);
    var parentPrev = prev.parent;

    if (parentPrev === null) {
      throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
    }

    if (parentPrev.depth === next.depth) {
      // We found the same level. Now we just need to find a shared ancestor.
      popToNearestCommonAncestor(parentPrev, next);
    } else {
      // We must still be deeper.
      popPreviousToCommonLevel(parentPrev, next);
    }
  }

  function popNextToCommonLevel(prev, next) {
    var parentNext = next.parent;

    if (parentNext === null) {
      throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
    }

    if (prev.depth === parentNext.depth) {
      // We found the same level. Now we just need to find a shared ancestor.
      popToNearestCommonAncestor(prev, parentNext);
    } else {
      // We must still be deeper.
      popNextToCommonLevel(prev, parentNext);
    }

    pushNode(next);
  } // Perform context switching to the new snapshot.
  // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
  // updating all the context's current values. That way reads, always just read the current value.
  // At the cost of updating contexts even if they're never read by this subtree.


  function switchContext(newSnapshot) {
    // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
    // We also need to update any new contexts that are now on the stack with the deepest value.
    // The easiest way to update new contexts is to just reapply them in reverse order from the
    // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
    // for that. Therefore this algorithm is recursive.
    // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
    // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
    // 3) Then we reapply new contexts on the way back up the stack.
    var prev = currentActiveSnapshot;
    var next = newSnapshot;

    if (prev !== next) {
      if (prev === null) {
        // $FlowFixMe: This has to be non-null since it's not equal to prev.
        pushAllNext(next);
      } else if (next === null) {
        popAllPrevious(prev);
      } else if (prev.depth === next.depth) {
        popToNearestCommonAncestor(prev, next);
      } else if (prev.depth > next.depth) {
        popPreviousToCommonLevel(prev, next);
      } else {
        popNextToCommonLevel(prev, next);
      }

      currentActiveSnapshot = next;
    }
  }
  function pushProvider(context, nextValue) {
    var prevValue;

    {
      prevValue = context._currentValue;
      context._currentValue = nextValue;

      {
        if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
          error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
        }

        context._currentRenderer = rendererSigil;
      }
    }

    var prevNode = currentActiveSnapshot;
    var newNode = {
      parent: prevNode,
      depth: prevNode === null ? 0 : prevNode.depth + 1,
      context: context,
      parentValue: prevValue,
      value: nextValue
    };
    currentActiveSnapshot = newNode;
    return newNode;
  }
  function popProvider(context) {
    var prevSnapshot = currentActiveSnapshot;

    if (prevSnapshot === null) {
      throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
    }

    {
      if (prevSnapshot.context !== context) {
        error('The parent context is not the expected context. This is probably a bug in React.');
      }
    }

    {
      var value = prevSnapshot.parentValue;

      if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
        prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
      } else {
        prevSnapshot.context._currentValue = value;
      }

      {
        if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
          error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
        }

        context._currentRenderer = rendererSigil;
      }
    }

    return currentActiveSnapshot = prevSnapshot.parent;
  }
  function getActiveContext() {
    return currentActiveSnapshot;
  }
  function readContext(context) {
    var value =  context._currentValue ;
    return value;
  }

  /**
   * `ReactInstanceMap` maintains a mapping from a public facing stateful
   * instance (key) and the internal representation (value). This allows public
   * methods to accept the user facing instance as an argument and map them back
   * to internal methods.
   *
   * Note that this module is currently shared and assumed to be stateless.
   * If this becomes an actual Map, that will break.
   */
  function get(key) {
    return key._reactInternals;
  }
  function set(key, value) {
    key._reactInternals = value;
  }

  var didWarnAboutNoopUpdateForComponent = {};
  var didWarnAboutDeprecatedWillMount = {};
  var didWarnAboutUninitializedState;
  var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
  var didWarnAboutLegacyLifecyclesAndDerivedState;
  var didWarnAboutUndefinedDerivedState;
  var warnOnUndefinedDerivedState;
  var warnOnInvalidCallback;
  var didWarnAboutDirectlyAssigningPropsToState;
  var didWarnAboutContextTypeAndContextTypes;
  var didWarnAboutInvalidateContextType;

  {
    didWarnAboutUninitializedState = new Set();
    didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
    didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
    didWarnAboutDirectlyAssigningPropsToState = new Set();
    didWarnAboutUndefinedDerivedState = new Set();
    didWarnAboutContextTypeAndContextTypes = new Set();
    didWarnAboutInvalidateContextType = new Set();
    var didWarnOnInvalidCallback = new Set();

    warnOnInvalidCallback = function (callback, callerName) {
      if (callback === null || typeof callback === 'function') {
        return;
      }

      var key = callerName + '_' + callback;

      if (!didWarnOnInvalidCallback.has(key)) {
        didWarnOnInvalidCallback.add(key);

        error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
      }
    };

    warnOnUndefinedDerivedState = function (type, partialState) {
      if (partialState === undefined) {
        var componentName = getComponentNameFromType(type) || 'Component';

        if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
          didWarnAboutUndefinedDerivedState.add(componentName);

          error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
        }
      }
    };
  }

  function warnNoop(publicInstance, callerName) {
    {
      var _constructor = publicInstance.constructor;
      var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
      var warningKey = componentName + '.' + callerName;

      if (didWarnAboutNoopUpdateForComponent[warningKey]) {
        return;
      }

      error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

      didWarnAboutNoopUpdateForComponent[warningKey] = true;
    }
  }

  var classComponentUpdater = {
    isMounted: function (inst) {
      return false;
    },
    enqueueSetState: function (inst, payload, callback) {
      var internals = get(inst);

      if (internals.queue === null) {
        warnNoop(inst, 'setState');
      } else {
        internals.queue.push(payload);

        {
          if (callback !== undefined && callback !== null) {
            warnOnInvalidCallback(callback, 'setState');
          }
        }
      }
    },
    enqueueReplaceState: function (inst, payload, callback) {
      var internals = get(inst);
      internals.replace = true;
      internals.queue = [payload];

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    },
    enqueueForceUpdate: function (inst, callback) {
      var internals = get(inst);

      if (internals.queue === null) {
        warnNoop(inst, 'forceUpdate');
      } else {
        {
          if (callback !== undefined && callback !== null) {
            warnOnInvalidCallback(callback, 'setState');
          }
        }
      }
    }
  };

  function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
    var partialState = getDerivedStateFromProps(nextProps, prevState);

    {
      warnOnUndefinedDerivedState(ctor, partialState);
    } // Merge the partial state and the previous state.


    var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
    return newState;
  }

  function constructClassInstance(ctor, props, maskedLegacyContext) {
    var context = emptyContextObject;
    var contextType = ctor.contextType;

    {
      if ('contextType' in ctor) {
        var isValid = // Allow null for conditional declaration
        contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

        if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
          didWarnAboutInvalidateContextType.add(ctor);
          var addendum = '';

          if (contextType === undefined) {
            addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
          } else if (typeof contextType !== 'object') {
            addendum = ' However, it is set to a ' + typeof contextType + '.';
          } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
            addendum = ' Did you accidentally pass the Context.Provider instead?';
          } else if (contextType._context !== undefined) {
            // <Context.Consumer>
            addendum = ' Did you accidentally pass the Context.Consumer instead?';
          } else {
            addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
          }

          error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
        }
      }
    }

    if (typeof contextType === 'object' && contextType !== null) {
      context = readContext(contextType);
    } else {
      context = maskedLegacyContext;
    }

    var instance = new ctor(props, context);

    {
      if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutUninitializedState.has(componentName)) {
          didWarnAboutUninitializedState.add(componentName);

          error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
        }
      } // If new component APIs are defined, "unsafe" lifecycles won't be called.
      // Warn about these lifecycles if they are present.
      // Don't warn about react-lifecycles-compat polyfilled methods though.


      if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
        var foundWillMountName = null;
        var foundWillReceivePropsName = null;
        var foundWillUpdateName = null;

        if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
          foundWillMountName = 'componentWillMount';
        } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
          foundWillMountName = 'UNSAFE_componentWillMount';
        }

        if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
          foundWillReceivePropsName = 'componentWillReceiveProps';
        } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
          foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
        }

        if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
          foundWillUpdateName = 'componentWillUpdate';
        } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
          foundWillUpdateName = 'UNSAFE_componentWillUpdate';
        }

        if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
          var _componentName = getComponentNameFromType(ctor) || 'Component';

          var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

          if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
            didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

            error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
          }
        }
      }
    }

    return instance;
  }

  function checkClassInstance(instance, ctor, newProps) {
    {
      var name = getComponentNameFromType(ctor) || 'Component';
      var renderPresent = instance.render;

      if (!renderPresent) {
        if (ctor.prototype && typeof ctor.prototype.render === 'function') {
          error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
        } else {
          error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
        }
      }

      if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
        error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
      }

      if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
        error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
      }

      if (instance.propTypes) {
        error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
      }

      if (instance.contextType) {
        error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
      }

      {
        if (instance.contextTypes) {
          error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
        }

        if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
          didWarnAboutContextTypeAndContextTypes.add(ctor);

          error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
        }
      }

      if (typeof instance.componentShouldUpdate === 'function') {
        error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
      }

      if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
        error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
      }

      if (typeof instance.componentDidUnmount === 'function') {
        error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
      }

      if (typeof instance.componentDidReceiveProps === 'function') {
        error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
      }

      if (typeof instance.componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
      }

      if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
      }

      var hasMutatedProps = instance.props !== newProps;

      if (instance.props !== undefined && hasMutatedProps) {
        error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
      }

      if (instance.defaultProps) {
        error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
        didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

        error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
      }

      if (typeof instance.getDerivedStateFromProps === 'function') {
        error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof instance.getDerivedStateFromError === 'function') {
        error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
        error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
      }

      var _state = instance.state;

      if (_state && (typeof _state !== 'object' || isArray(_state))) {
        error('%s.state: must be set to an object or null', name);
      }

      if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
        error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
      }
    }
  }

  function callComponentWillMount(type, instance) {
    var oldState = instance.state;

    if (typeof instance.componentWillMount === 'function') {
      {
        if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
          var componentName = getComponentNameFromType(type) || 'Unknown';

          if (!didWarnAboutDeprecatedWillMount[componentName]) {
            warn( // keep this warning in sync with ReactStrictModeWarning.js
            'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

            didWarnAboutDeprecatedWillMount[componentName] = true;
          }
        }
      }

      instance.componentWillMount();
    }

    if (typeof instance.UNSAFE_componentWillMount === 'function') {
      instance.UNSAFE_componentWillMount();
    }

    if (oldState !== instance.state) {
      {
        error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
      }

      classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
    }
  }

  function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
    if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
      var oldQueue = internalInstance.queue;
      var oldReplace = internalInstance.replace;
      internalInstance.queue = null;
      internalInstance.replace = false;

      if (oldReplace && oldQueue.length === 1) {
        inst.state = oldQueue[0];
      } else {
        var nextState = oldReplace ? oldQueue[0] : inst.state;
        var dontMutate = true;

        for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
          var partial = oldQueue[i];
          var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

          if (partialState != null) {
            if (dontMutate) {
              dontMutate = false;
              nextState = assign({}, nextState, partialState);
            } else {
              assign(nextState, partialState);
            }
          }
        }

        inst.state = nextState;
      }
    } else {
      internalInstance.queue = null;
    }
  } // Invokes the mount life-cycles on a previously never rendered instance.


  function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
    {
      checkClassInstance(instance, ctor, newProps);
    }

    var initialState = instance.state !== undefined ? instance.state : null;
    instance.updater = classComponentUpdater;
    instance.props = newProps;
    instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
    // The internal instance will be used to manage updates that happen during this mount.

    var internalInstance = {
      queue: [],
      replace: false
    };
    set(instance, internalInstance);
    var contextType = ctor.contextType;

    if (typeof contextType === 'object' && contextType !== null) {
      instance.context = readContext(contextType);
    } else {
      instance.context = maskedLegacyContext;
    }

    {
      if (instance.state === newProps) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
          didWarnAboutDirectlyAssigningPropsToState.add(componentName);

          error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
        }
      }
    }

    var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

    if (typeof getDerivedStateFromProps === 'function') {
      instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
    } // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.


    if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
      callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
      // process them now.

      processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
    }
  }

  // Ids are base 32 strings whose binary representation corresponds to the
  // position of a node in a tree.
  // Every time the tree forks into multiple children, we add additional bits to
  // the left of the sequence that represent the position of the child within the
  // current level of children.
  //
  //      00101       00010001011010101
  //      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
  //   Fork 5 of 20       Parent id
  //
  // The leading 0s are important. In the above example, you only need 3 bits to
  // represent slot 5. However, you need 5 bits to represent all the forks at
  // the current level, so we must account for the empty bits at the end.
  //
  // For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
  // the zeroth id at a level would be indistinguishable from its parent.
  //
  // If a node has only one child, and does not materialize an id (i.e. does not
  // contain a useId hook), then we don't need to allocate any space in the
  // sequence. It's treated as a transparent indirection. For example, these two
  // trees produce the same ids:
  //
  // <>                          <>
  //   <Indirection>               <A />
  //     <A />                     <B />
  //   </Indirection>            </>
  //   <B />
  // </>
  //
  // However, we cannot skip any node that materializes an id. Otherwise, a parent
  // id that does not fork would be indistinguishable from its child id. For
  // example, this tree does not fork, but the parent and child must have
  // different ids.
  //
  // <Parent>
  //   <Child />
  // </Parent>
  //
  // To handle this scenario, every time we materialize an id, we allocate a
  // new level with a single slot. You can think of this as a fork with only one
  // prong, or an array of children with length 1.
  //
  // It's possible for the size of the sequence to exceed 32 bits, the max
  // size for bitwise operations. When this happens, we make more room by
  // converting the right part of the id to a string and storing it in an overflow
  // variable. We use a base 32 string representation, because 32 is the largest
  // power of 2 that is supported by toString(). We want the base to be large so
  // that the resulting ids are compact, and we want the base to be a power of 2
  // because every log2(base) bits corresponds to a single character, i.e. every
  // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
  // affecting the final result.
  var emptyTreeContext = {
    id: 1,
    overflow: ''
  };
  function getTreeId(context) {
    var overflow = context.overflow;
    var idWithLeadingBit = context.id;
    var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
    return id.toString(32) + overflow;
  }
  function pushTreeContext(baseContext, totalChildren, index) {
    var baseIdWithLeadingBit = baseContext.id;
    var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
    // of the id; we use it to account for leading 0s.

    var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
    var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
    var slot = index + 1;
    var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
    // consideration the leading 1 we use to mark the end of the sequence.

    if (length > 30) {
      // We overflowed the bitwise-safe range. Fall back to slower algorithm.
      // This branch assumes the length of the base id is greater than 5; it won't
      // work for smaller ids, because you need 5 bits per character.
      //
      // We encode the id in multiple steps: first the base id, then the
      // remaining digits.
      //
      // Each 5 bit sequence corresponds to a single base 32 character. So for
      // example, if the current id is 23 bits long, we can convert 20 of those
      // bits into a string of 4 characters, with 3 bits left over.
      //
      // First calculate how many bits in the base id represent a complete
      // sequence of characters.
      var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

      var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

      var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

      var restOfBaseId = baseId >> numberOfOverflowBits;
      var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
      // we made more room, this time it won't overflow.

      var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
      var restOfNewBits = slot << restOfBaseLength;
      var id = restOfNewBits | restOfBaseId;
      var overflow = newOverflow + baseOverflow;
      return {
        id: 1 << restOfLength | id,
        overflow: overflow
      };
    } else {
      // Normal path
      var newBits = slot << baseLength;

      var _id = newBits | baseId;

      var _overflow = baseOverflow;
      return {
        id: 1 << length | _id,
        overflow: _overflow
      };
    }
  }

  function getBitLength(number) {
    return 32 - clz32(number);
  }

  function getLeadingBit(id) {
    return 1 << getBitLength(id) - 1;
  } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
  // Based on:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

  var log = Math.log;
  var LN2 = Math.LN2;

  function clz32Fallback(x) {
    var asUint = x >>> 0;

    if (asUint === 0) {
      return 32;
    }

    return 31 - (log(asUint) / LN2 | 0) | 0;
  }

  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */
  function is(x, y) {
    return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
    ;
  }

  var objectIs = typeof Object.is === 'function' ? Object.is : is;

  var currentlyRenderingComponent = null;
  var currentlyRenderingTask = null;
  var firstWorkInProgressHook = null;
  var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

  var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

  var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

  var localIdCounter = 0; // Lazily created map of render-phase updates

  var renderPhaseUpdates = null; // Counter to prevent infinite loops.

  var numberOfReRenders = 0;
  var RE_RENDER_LIMIT = 25;
  var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

  var currentHookNameInDev;

  function resolveCurrentlyRenderingComponent() {
    if (currentlyRenderingComponent === null) {
      throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
    }

    {
      if (isInHookUserCodeInDev) {
        error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
      }
    }

    return currentlyRenderingComponent;
  }

  function areHookInputsEqual(nextDeps, prevDeps) {
    if (prevDeps === null) {
      {
        error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
      }

      return false;
    }

    {
      // Don't bother comparing lengths in prod because these arrays should be
      // passed inline.
      if (nextDeps.length !== prevDeps.length) {
        error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
      }
    }

    for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
      if (objectIs(nextDeps[i], prevDeps[i])) {
        continue;
      }

      return false;
    }

    return true;
  }

  function createHook() {
    if (numberOfReRenders > 0) {
      throw new Error('Rendered more hooks than during the previous render');
    }

    return {
      memoizedState: null,
      queue: null,
      next: null
    };
  }

  function createWorkInProgressHook() {
    if (workInProgressHook === null) {
      // This is the first hook in the list
      if (firstWorkInProgressHook === null) {
        isReRender = false;
        firstWorkInProgressHook = workInProgressHook = createHook();
      } else {
        // There's already a work-in-progress. Reuse it.
        isReRender = true;
        workInProgressHook = firstWorkInProgressHook;
      }
    } else {
      if (workInProgressHook.next === null) {
        isReRender = false; // Append to the end of the list

        workInProgressHook = workInProgressHook.next = createHook();
      } else {
        // There's already a work-in-progress. Reuse it.
        isReRender = true;
        workInProgressHook = workInProgressHook.next;
      }
    }

    return workInProgressHook;
  }

  function prepareToUseHooks(task, componentIdentity) {
    currentlyRenderingComponent = componentIdentity;
    currentlyRenderingTask = task;

    {
      isInHookUserCodeInDev = false;
    } // The following should have already been reset
    // didScheduleRenderPhaseUpdate = false;
    // localIdCounter = 0;
    // firstWorkInProgressHook = null;
    // numberOfReRenders = 0;
    // renderPhaseUpdates = null;
    // workInProgressHook = null;


    localIdCounter = 0;
  }
  function finishHooks(Component, props, children, refOrContext) {
    // This must be called after every function component to prevent hooks from
    // being used in classes.
    while (didScheduleRenderPhaseUpdate) {
      // Updates were scheduled during the render phase. They are stored in
      // the `renderPhaseUpdates` map. Call the component again, reusing the
      // work-in-progress hooks and applying the additional updates on top. Keep
      // restarting until no more updates are scheduled.
      didScheduleRenderPhaseUpdate = false;
      localIdCounter = 0;
      numberOfReRenders += 1; // Start over from the beginning of the list

      workInProgressHook = null;
      children = Component(props, refOrContext);
    }

    resetHooksState();
    return children;
  }
  function checkDidRenderIdHook() {
    // This should be called immediately after every finishHooks call.
    // Conceptually, it's part of the return value of finishHooks; it's only a
    // separate function to avoid using an array tuple.
    var didRenderIdHook = localIdCounter !== 0;
    return didRenderIdHook;
  } // Reset the internal hooks state if an error occurs while rendering a component

  function resetHooksState() {
    {
      isInHookUserCodeInDev = false;
    }

    currentlyRenderingComponent = null;
    currentlyRenderingTask = null;
    didScheduleRenderPhaseUpdate = false;
    firstWorkInProgressHook = null;
    numberOfReRenders = 0;
    renderPhaseUpdates = null;
    workInProgressHook = null;
  }

  function readContext$1(context) {
    {
      if (isInHookUserCodeInDev) {
        error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
      }
    }

    return readContext(context);
  }

  function useContext(context) {
    {
      currentHookNameInDev = 'useContext';
    }

    resolveCurrentlyRenderingComponent();
    return readContext(context);
  }

  function basicStateReducer(state, action) {
    // $FlowFixMe: Flow doesn't like mixed types
    return typeof action === 'function' ? action(state) : action;
  }

  function useState(initialState) {
    {
      currentHookNameInDev = 'useState';
    }

    return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
    initialState);
  }
  function useReducer(reducer, initialArg, init) {
    {
      if (reducer !== basicStateReducer) {
        currentHookNameInDev = 'useReducer';
      }
    }

    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();

    if (isReRender) {
      // This is a re-render. Apply the new render phase updates to the previous
      // current hook.
      var queue = workInProgressHook.queue;
      var dispatch = queue.dispatch;

      if (renderPhaseUpdates !== null) {
        // Render phase updates are stored in a map of queue -> linked list
        var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

        if (firstRenderPhaseUpdate !== undefined) {
          renderPhaseUpdates.delete(queue);
          var newState = workInProgressHook.memoizedState;
          var update = firstRenderPhaseUpdate;

          do {
            // Process this render phase update. We don't have to check the
            // priority because it will always be the same as the current
            // render's.
            var action = update.action;

            {
              isInHookUserCodeInDev = true;
            }

            newState = reducer(newState, action);

            {
              isInHookUserCodeInDev = false;
            }

            update = update.next;
          } while (update !== null);

          workInProgressHook.memoizedState = newState;
          return [newState, dispatch];
        }
      }

      return [workInProgressHook.memoizedState, dispatch];
    } else {
      {
        isInHookUserCodeInDev = true;
      }

      var initialState;

      if (reducer === basicStateReducer) {
        // Special case for `useState`.
        initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
      } else {
        initialState = init !== undefined ? init(initialArg) : initialArg;
      }

      {
        isInHookUserCodeInDev = false;
      }

      workInProgressHook.memoizedState = initialState;

      var _queue = workInProgressHook.queue = {
        last: null,
        dispatch: null
      };

      var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

      return [workInProgressHook.memoizedState, _dispatch];
    }
  }

  function useMemo(nextCreate, deps) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;

    if (workInProgressHook !== null) {
      var prevState = workInProgressHook.memoizedState;

      if (prevState !== null) {
        if (nextDeps !== null) {
          var prevDeps = prevState[1];

          if (areHookInputsEqual(nextDeps, prevDeps)) {
            return prevState[0];
          }
        }
      }
    }

    {
      isInHookUserCodeInDev = true;
    }

    var nextValue = nextCreate();

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = [nextValue, nextDeps];
    return nextValue;
  }

  function useRef(initialValue) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    var previousRef = workInProgressHook.memoizedState;

    if (previousRef === null) {
      var ref = {
        current: initialValue
      };

      {
        Object.seal(ref);
      }

      workInProgressHook.memoizedState = ref;
      return ref;
    } else {
      return previousRef;
    }
  }

  function useLayoutEffect(create, inputs) {
    {
      currentHookNameInDev = 'useLayoutEffect';

      error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
    }
  }

  function dispatchAction(componentIdentity, queue, action) {
    if (numberOfReRenders >= RE_RENDER_LIMIT) {
      throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
    }

    if (componentIdentity === currentlyRenderingComponent) {
      // This is a render phase update. Stash it in a lazily-created map of
      // queue -> linked list of updates. After this render pass, we'll restart
      // and apply the stashed updates on top of the work-in-progress hook.
      didScheduleRenderPhaseUpdate = true;
      var update = {
        action: action,
        next: null
      };

      if (renderPhaseUpdates === null) {
        renderPhaseUpdates = new Map();
      }

      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate === undefined) {
        renderPhaseUpdates.set(queue, update);
      } else {
        // Append the update to the end of the list.
        var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

        while (lastRenderPhaseUpdate.next !== null) {
          lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        }

        lastRenderPhaseUpdate.next = update;
      }
    }
  }

  function useCallback(callback, deps) {
    return useMemo(function () {
      return callback;
    }, deps);
  } // TODO Decide on how to implement this hook for server rendering.
  // If a mutation occurs during render, consider triggering a Suspense boundary
  // and falling back to client rendering.

  function useMutableSource(source, getSnapshot, subscribe) {
    resolveCurrentlyRenderingComponent();
    return getSnapshot(source._source);
  }

  function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    if (getServerSnapshot === undefined) {
      throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
    }

    return getServerSnapshot();
  }

  function useDeferredValue(value) {
    resolveCurrentlyRenderingComponent();
    return value;
  }

  function unsupportedStartTransition() {
    throw new Error('startTransition cannot be called during server rendering.');
  }

  function useTransition() {
    resolveCurrentlyRenderingComponent();
    return [false, unsupportedStartTransition];
  }

  function useId() {
    var task = currentlyRenderingTask;
    var treeId = getTreeId(task.treeContext);
    var responseState = currentResponseState;

    if (responseState === null) {
      throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
    }

    var localId = localIdCounter++;
    return makeId(responseState, treeId, localId);
  }

  function noop() {}

  var Dispatcher = {
    readContext: readContext$1,
    useContext: useContext,
    useMemo: useMemo,
    useReducer: useReducer,
    useRef: useRef,
    useState: useState,
    useInsertionEffect: noop,
    useLayoutEffect: useLayoutEffect,
    useCallback: useCallback,
    // useImperativeHandle is not run in the server environment
    useImperativeHandle: noop,
    // Effects are not run in the server environment.
    useEffect: noop,
    // Debugging effect
    useDebugValue: noop,
    useDeferredValue: useDeferredValue,
    useTransition: useTransition,
    useId: useId,
    // Subscriptions are not setup in a server environment.
    useMutableSource: useMutableSource,
    useSyncExternalStore: useSyncExternalStore
  };

  var currentResponseState = null;
  function setCurrentResponseState(responseState) {
    currentResponseState = responseState;
  }

  function getStackByComponentStackNode(componentStack) {
    try {
      var info = '';
      var node = componentStack;

      do {
        switch (node.tag) {
          case 0:
            info += describeBuiltInComponentFrame(node.type, null, null);
            break;

          case 1:
            info += describeFunctionComponentFrame(node.type, null, null);
            break;

          case 2:
            info += describeClassComponentFrame(node.type, null, null);
            break;
        }

        node = node.parent;
      } while (node);

      return info;
    } catch (x) {
      return '\nError generating stack: ' + x.message + '\n' + x.stack;
    }
  }

  var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
  var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
  var PENDING = 0;
  var COMPLETED = 1;
  var FLUSHED = 2;
  var ABORTED = 3;
  var ERRORED = 4;
  var OPEN = 0;
  var CLOSING = 1;
  var CLOSED = 2;
  // This is a default heuristic for how to split up the HTML content into progressive
  // loading. Our goal is to be able to display additional new content about every 500ms.
  // Faster than that is unnecessary and should be throttled on the client. It also
  // adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
  // end device but higher end suffer less from the overhead than lower end does from
  // not getting small enough pieces. We error on the side of low end.
  // We base this on low end 3G speeds which is about 500kbits per second. We assume
  // that there can be a reasonable drop off from max bandwidth which leaves you with
  // as little as 80%. We can receive half of that each 500ms - at best. In practice,
  // a little bandwidth is lost to processing and contention - e.g. CSS and images that
  // are downloaded along with the main content. So we estimate about half of that to be
  // the lower end throughput. In other words, we expect that you can at least show
  // about 12.5kb of content per 500ms. Not counting starting latency for the first
  // paint.
  // 500 * 1024 / 8 * .8 * 0.5 / 2
  var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

  function defaultErrorHandler(error) {
    console['error'](error); // Don't transform to our wrapper

    return null;
  }

  function noop$1() {}

  function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
    var pingedTasks = [];
    var abortSet = new Set();
    var request = {
      destination: null,
      responseState: responseState,
      progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
      status: OPEN,
      fatalError: null,
      nextSegmentId: 0,
      allPendingTasks: 0,
      pendingRootTasks: 0,
      completedRootSegment: null,
      abortableTasks: abortSet,
      pingedTasks: pingedTasks,
      clientRenderedBoundaries: [],
      completedBoundaries: [],
      partialBoundaries: [],
      onError: onError === undefined ? defaultErrorHandler : onError,
      onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
      onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
      onShellError: onShellError === undefined ? noop$1 : onShellError,
      onFatalError: onFatalError === undefined ? noop$1 : onFatalError
    }; // This segment represents the root fallback.

    var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
    false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

    rootSegment.parentFlushed = true;
    var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
    pingedTasks.push(rootTask);
    return request;
  }

  function pingTask(request, task) {
    var pingedTasks = request.pingedTasks;
    pingedTasks.push(task);

    if (pingedTasks.length === 1) {
      scheduleWork(function () {
        return performWork(request);
      });
    }
  }

  function createSuspenseBoundary(request, fallbackAbortableTasks) {
    return {
      id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
      rootSegmentID: -1,
      parentFlushed: false,
      pendingTasks: 0,
      forceClientRender: false,
      completedSegments: [],
      byteSize: 0,
      fallbackAbortableTasks: fallbackAbortableTasks,
      errorDigest: null
    };
  }

  function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
    request.allPendingTasks++;

    if (blockedBoundary === null) {
      request.pendingRootTasks++;
    } else {
      blockedBoundary.pendingTasks++;
    }

    var task = {
      node: node,
      ping: function () {
        return pingTask(request, task);
      },
      blockedBoundary: blockedBoundary,
      blockedSegment: blockedSegment,
      abortSet: abortSet,
      legacyContext: legacyContext,
      context: context,
      treeContext: treeContext
    };

    {
      task.componentStack = null;
    }

    abortSet.add(task);
    return task;
  }

  function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
    return {
      status: PENDING,
      id: -1,
      // lazily assigned later
      index: index,
      parentFlushed: false,
      chunks: [],
      children: [],
      formatContext: formatContext,
      boundary: boundary,
      lastPushedText: lastPushedText,
      textEmbedded: textEmbedded
    };
  } // DEV-only global reference to the currently executing task


  var currentTaskInDEV = null;

  function getCurrentStackInDEV() {
    {
      if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
        return '';
      }

      return getStackByComponentStackNode(currentTaskInDEV.componentStack);
    }
  }

  function pushBuiltInComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 0,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function pushFunctionComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 1,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function pushClassComponentStackInDEV(task, type) {
    {
      task.componentStack = {
        tag: 2,
        parent: task.componentStack,
        type: type
      };
    }
  }

  function popComponentStackInDEV(task) {
    {
      if (task.componentStack === null) {
        error('Unexpectedly popped too many stack frames. This is a bug in React.');
      } else {
        task.componentStack = task.componentStack.parent;
      }
    }
  } // stash the component stack of an unwinding error until it is processed


  var lastBoundaryErrorComponentStackDev = null;

  function captureBoundaryErrorDetailsDev(boundary, error) {
    {
      var errorMessage;

      if (typeof error === 'string') {
        errorMessage = error;
      } else if (error && typeof error.message === 'string') {
        errorMessage = error.message;
      } else {
        // eslint-disable-next-line react-internal/safe-string-coercion
        errorMessage = String(error);
      }

      var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
      lastBoundaryErrorComponentStackDev = null;
      boundary.errorMessage = errorMessage;
      boundary.errorComponentStack = errorComponentStack;
    }
  }

  function logRecoverableError(request, error) {
    // If this callback errors, we intentionally let that error bubble up to become a fatal error
    // so that someone fixes the error reporting instead of hiding it.
    var errorDigest = request.onError(error);

    if (errorDigest != null && typeof errorDigest !== 'string') {
      // eslint-disable-next-line react-internal/prod-error-codes
      throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
    }

    return errorDigest;
  }

  function fatalError(request, error) {
    // This is called outside error handling code such as if the root errors outside
    // a suspense boundary or if the root suspense boundary's fallback errors.
    // It's also called if React itself or its host configs errors.
    var onShellError = request.onShellError;
    onShellError(error);
    var onFatalError = request.onFatalError;
    onFatalError(error);

    if (request.destination !== null) {
      request.status = CLOSED;
      closeWithError(request.destination, error);
    } else {
      request.status = CLOSING;
      request.fatalError = error;
    }
  }

  function renderSuspenseBoundary(request, task, props) {
    pushBuiltInComponentStackInDEV(task, 'Suspense');
    var parentBoundary = task.blockedBoundary;
    var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
    // the fallback so that we can later replace that segment with the content.
    // This also lets us split out the main content even if it doesn't suspend,
    // in case it ends up generating a large subtree of content.

    var fallback = props.fallback;
    var content = props.children;
    var fallbackAbortSet = new Set();
    var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
    var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

    var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
    false, false);
    parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

    parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

    var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
    false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
    // no parent segment so there's nothing to wait on.

    contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
    // I suspect that there might be some efficiency benefits from not creating the suspended task
    // and instead just using the stack if possible.
    // TODO: Call this directly instead of messing with saving and restoring contexts.
    // We can reuse the current context and task to render the content immediately without
    // context switching. We just need to temporarily switch which boundary and which segment
    // we're writing to. If something suspends, it'll spawn new suspended task with that context.

    task.blockedBoundary = newBoundary;
    task.blockedSegment = contentRootSegment;

    try {
      // We use the safe form because we don't handle suspending here. Only error handling.
      renderNode(request, task, content);
      pushSegmentFinale(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
      contentRootSegment.status = COMPLETED;
      queueCompletedSegment(newBoundary, contentRootSegment);

      if (newBoundary.pendingTasks === 0) {
        // This must have been the last segment we were waiting on. This boundary is now complete.
        // Therefore we won't need the fallback. We early return so that we don't have to create
        // the fallback.
        popComponentStackInDEV(task);
        return;
      }
    } catch (error) {
      contentRootSegment.status = ERRORED;
      newBoundary.forceClientRender = true;
      newBoundary.errorDigest = logRecoverableError(request, error);

      {
        captureBoundaryErrorDetailsDev(newBoundary, error);
      } // We don't need to decrement any task numbers because we didn't spawn any new task.
      // We don't need to schedule any task because we know the parent has written yet.
      // We do need to fallthrough to create the fallback though.

    } finally {
      task.blockedBoundary = parentBoundary;
      task.blockedSegment = parentSegment;
    } // We create suspended task for the fallback because we don't want to actually work
    // on it yet in case we finish the main content, so we queue for later.


    var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

    {
      suspendedFallbackTask.componentStack = task.componentStack;
    } // TODO: This should be queued at a separate lower priority queue so that we only work
    // on preparing fallbacks if we don't have any more main content to task on.


    request.pingedTasks.push(suspendedFallbackTask);
    popComponentStackInDEV(task);
  }

  function renderHostElement(request, task, type, props) {
    pushBuiltInComponentStackInDEV(task, type);
    var segment = task.blockedSegment;
    var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
    segment.lastPushedText = false;
    var prevContext = segment.formatContext;
    segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
    // need to pop back up and finish this subtree of HTML.

    renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
    // the correct context. Therefore this is not in a finally.

    segment.formatContext = prevContext;
    pushEndInstance(segment.chunks, type);
    segment.lastPushedText = false;
    popComponentStackInDEV(task);
  }

  function shouldConstruct$1(Component) {
    return Component.prototype && Component.prototype.isReactComponent;
  }

  function renderWithHooks(request, task, Component, props, secondArg) {
    var componentIdentity = {};
    prepareToUseHooks(task, componentIdentity);
    var result = Component(props, secondArg);
    return finishHooks(Component, props, result, secondArg);
  }

  function finishClassComponent(request, task, instance, Component, props) {
    var nextChildren = instance.render();

    {
      if (instance.props !== props) {
        if (!didWarnAboutReassigningProps) {
          error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
        }

        didWarnAboutReassigningProps = true;
      }
    }

    {
      var childContextTypes = Component.childContextTypes;

      if (childContextTypes !== null && childContextTypes !== undefined) {
        var previousContext = task.legacyContext;
        var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
        task.legacyContext = mergedContext;
        renderNodeDestructive(request, task, nextChildren);
        task.legacyContext = previousContext;
        return;
      }
    }

    renderNodeDestructive(request, task, nextChildren);
  }

  function renderClassComponent(request, task, Component, props) {
    pushClassComponentStackInDEV(task, Component);
    var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
    var instance = constructClassInstance(Component, props, maskedContext);
    mountClassInstance(instance, Component, props, maskedContext);
    finishClassComponent(request, task, instance, Component, props);
    popComponentStackInDEV(task);
  }

  var didWarnAboutBadClass = {};
  var didWarnAboutModulePatternComponent = {};
  var didWarnAboutContextTypeOnFunctionComponent = {};
  var didWarnAboutGetDerivedStateOnFunctionComponent = {};
  var didWarnAboutReassigningProps = false;
  var didWarnAboutDefaultPropsOnFunctionComponent = {};
  var didWarnAboutGenerators = false;
  var didWarnAboutMaps = false;
  var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
  // components for some reason.

  function renderIndeterminateComponent(request, task, Component, props) {
    var legacyContext;

    {
      legacyContext = getMaskedContext(Component, task.legacyContext);
    }

    pushFunctionComponentStackInDEV(task, Component);

    {
      if (Component.prototype && typeof Component.prototype.render === 'function') {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutBadClass[componentName]) {
          error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

          didWarnAboutBadClass[componentName] = true;
        }
      }
    }

    var value = renderWithHooks(request, task, Component, props, legacyContext);
    var hasId = checkDidRenderIdHook();

    {
      // Support for module components is deprecated and is removed behind a flag.
      // Whether or not it would crash later, we want to show a good message in DEV first.
      if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
        var _componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

          didWarnAboutModulePatternComponent[_componentName] = true;
        }
      }
    }

    if ( // Run these checks in production only if the flag is off.
    // Eventually we'll delete this branch altogether.
     typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      {
        var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName2]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

          didWarnAboutModulePatternComponent[_componentName2] = true;
        }
      }

      mountClassInstance(value, Component, props, legacyContext);
      finishClassComponent(request, task, value, Component, props);
    } else {

      {
        validateFunctionComponentInDev(Component);
      } // We're now successfully past this task, and we don't have to pop back to
      // the previous task every again, so we can use the destructive recursive form.


      if (hasId) {
        // This component materialized an id. We treat this as its own level, with
        // a single "child" slot.
        var prevTreeContext = task.treeContext;
        var totalChildren = 1;
        var index = 0;
        task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

        try {
          renderNodeDestructive(request, task, value);
        } finally {
          task.treeContext = prevTreeContext;
        }
      } else {
        renderNodeDestructive(request, task, value);
      }
    }

    popComponentStackInDEV(task);
  }

  function validateFunctionComponentInDev(Component) {
    {
      if (Component) {
        if (Component.childContextTypes) {
          error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
        }
      }

      if ( Component.defaultProps !== undefined) {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
          error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

          didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
        }
      }

      if (typeof Component.getDerivedStateFromProps === 'function') {
        var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
          error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

          didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
        }
      }

      if (typeof Component.contextType === 'object' && Component.contextType !== null) {
        var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
          error('%s: Function components do not support contextType.', _componentName4);

          didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
        }
      }
    }
  }

  function resolveDefaultProps(Component, baseProps) {
    if (Component && Component.defaultProps) {
      // Resolve default props. Taken from ReactElement
      var props = assign({}, baseProps);
      var defaultProps = Component.defaultProps;

      for (var propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }

      return props;
    }

    return baseProps;
  }

  function renderForwardRef(request, task, type, props, ref) {
    pushFunctionComponentStackInDEV(task, type.render);
    var children = renderWithHooks(request, task, type.render, props, ref);
    var hasId = checkDidRenderIdHook();

    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, children);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, children);
    }

    popComponentStackInDEV(task);
  }

  function renderMemo(request, task, type, props, ref) {
    var innerType = type.type;
    var resolvedProps = resolveDefaultProps(innerType, props);
    renderElement(request, task, innerType, resolvedProps, ref);
  }

  function renderContextConsumer(request, task, context, props) {
    // The logic below for Context differs depending on PROD or DEV mode. In
    // DEV mode, we create a separate object for Context.Consumer that acts
    // like a proxy to Context. This proxy object adds unnecessary code in PROD
    // so we use the old behaviour (Context.Consumer references Context) to
    // reduce size and overhead. The separate object references context via
    // a property called "_context", which also gives us the ability to check
    // in DEV mode if this property exists or not and warn if it does not.
    {
      if (context._context === undefined) {
        // This may be because it's a Context (rather than a Consumer).
        // Or it may be because it's older React where they're the same thing.
        // We only want to warn if we're sure it's a new React.
        if (context !== context.Consumer) {
          if (!hasWarnedAboutUsingContextAsConsumer) {
            hasWarnedAboutUsingContextAsConsumer = true;

            error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
          }
        }
      } else {
        context = context._context;
      }
    }

    var render = props.children;

    {
      if (typeof render !== 'function') {
        error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
      }
    }

    var newValue = readContext(context);
    var newChildren = render(newValue);
    renderNodeDestructive(request, task, newChildren);
  }

  function renderContextProvider(request, task, type, props) {
    var context = type._context;
    var value = props.value;
    var children = props.children;
    var prevSnapshot;

    {
      prevSnapshot = task.context;
    }

    task.context = pushProvider(context, value);
    renderNodeDestructive(request, task, children);
    task.context = popProvider(context);

    {
      if (prevSnapshot !== task.context) {
        error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
      }
    }
  }

  function renderLazyComponent(request, task, lazyComponent, props, ref) {
    pushBuiltInComponentStackInDEV(task, 'Lazy');
    var payload = lazyComponent._payload;
    var init = lazyComponent._init;
    var Component = init(payload);
    var resolvedProps = resolveDefaultProps(Component, props);
    renderElement(request, task, Component, resolvedProps, ref);
    popComponentStackInDEV(task);
  }

  function renderElement(request, task, type, props, ref) {
    if (typeof type === 'function') {
      if (shouldConstruct$1(type)) {
        renderClassComponent(request, task, type, props);
        return;
      } else {
        renderIndeterminateComponent(request, task, type, props);
        return;
      }
    }

    if (typeof type === 'string') {
      renderHostElement(request, task, type, props);
      return;
    }

    switch (type) {
      // TODO: LegacyHidden acts the same as a fragment. This only works
      // because we currently assume that every instance of LegacyHidden is
      // accompanied by a host component wrapper. In the hidden mode, the host
      // component is given a `hidden` attribute, which ensures that the
      // initial HTML is not visible. To support the use of LegacyHidden as a
      // true fragment, without an extra DOM node, we would have to hide the
      // initial HTML in some other way.
      // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
      case REACT_LEGACY_HIDDEN_TYPE:
      case REACT_DEBUG_TRACING_MODE_TYPE:
      case REACT_STRICT_MODE_TYPE:
      case REACT_PROFILER_TYPE:
      case REACT_FRAGMENT_TYPE:
        {
          renderNodeDestructive(request, task, props.children);
          return;
        }

      case REACT_SUSPENSE_LIST_TYPE:
        {
          pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

          renderNodeDestructive(request, task, props.children);
          popComponentStackInDEV(task);
          return;
        }

      case REACT_SCOPE_TYPE:
        {

          throw new Error('ReactDOMServer does not yet support scope components.');
        }
      // eslint-disable-next-line-no-fallthrough

      case REACT_SUSPENSE_TYPE:
        {
          {
            renderSuspenseBoundary(request, task, props);
          }

          return;
        }
    }

    if (typeof type === 'object' && type !== null) {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          {
            renderForwardRef(request, task, type, props, ref);
            return;
          }

        case REACT_MEMO_TYPE:
          {
            renderMemo(request, task, type, props, ref);
            return;
          }

        case REACT_PROVIDER_TYPE:
          {
            renderContextProvider(request, task, type, props);
            return;
          }

        case REACT_CONTEXT_TYPE:
          {
            renderContextConsumer(request, task, type, props);
            return;
          }

        case REACT_LAZY_TYPE:
          {
            renderLazyComponent(request, task, type, props);
            return;
          }
      }
    }

    var info = '';

    {
      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
        info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
      }
    }

    throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
  }

  function validateIterable(iterable, iteratorFn) {
    {
      // We don't support rendering Generators because it's a mutation.
      // See https://github.com/facebook/react/issues/12995
      if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
      iterable[Symbol.toStringTag] === 'Generator') {
        if (!didWarnAboutGenerators) {
          error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
        }

        didWarnAboutGenerators = true;
      } // Warn about using Maps as children


      if (iterable.entries === iteratorFn) {
        if (!didWarnAboutMaps) {
          error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
        }

        didWarnAboutMaps = true;
      }
    }
  }

  function renderNodeDestructive(request, task, node) {
    {
      // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
      // a component stack at the right place in the tree. We don't do this in renderNode
      // becuase it is not called at every layer of the tree and we may lose frames
      try {
        return renderNodeDestructiveImpl(request, task, node);
      } catch (x) {
        if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
          // This is an error, stash the component stack if it is null.
          lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
        } // rethrow so normal suspense logic can handle thrown value accordingly


        throw x;
      }
    }
  } // This function by it self renders a node and consumes the task by mutating it
  // to update the current execution state.


  function renderNodeDestructiveImpl(request, task, node) {
    // Stash the node we're working on. We'll pick up from this task in case
    // something suspends.
    task.node = node; // Handle object types

    if (typeof node === 'object' && node !== null) {
      switch (node.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var element = node;
            var type = element.type;
            var props = element.props;
            var ref = element.ref;
            renderElement(request, task, type, props, ref);
            return;
          }

        case REACT_PORTAL_TYPE:
          throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
        // eslint-disable-next-line-no-fallthrough

        case REACT_LAZY_TYPE:
          {
            var lazyNode = node;
            var payload = lazyNode._payload;
            var init = lazyNode._init;
            var resolvedNode;

            {
              try {
                resolvedNode = init(payload);
              } catch (x) {
                if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                  // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                  // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                  // vs Component position. We do not want the frame for Errors so we exclusively do this in
                  // the wakeable branch
                  pushBuiltInComponentStackInDEV(task, 'Lazy');
                }

                throw x;
              }
            }

            renderNodeDestructive(request, task, resolvedNode);
            return;
          }
      }

      if (isArray(node)) {
        renderChildrenArray(request, task, node);
        return;
      }

      var iteratorFn = getIteratorFn(node);

      if (iteratorFn) {
        {
          validateIterable(node, iteratorFn);
        }

        var iterator = iteratorFn.call(node);

        if (iterator) {
          // We need to know how many total children are in this set, so that we
          // can allocate enough id slots to acommodate them. So we must exhaust
          // the iterator before we start recursively rendering the children.
          // TODO: This is not great but I think it's inherent to the id
          // generation algorithm.
          var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

          if (!step.done) {
            var children = [];

            do {
              children.push(step.value);
              step = iterator.next();
            } while (!step.done);

            renderChildrenArray(request, task, children);
            return;
          }

          return;
        }
      }

      var childString = Object.prototype.toString.call(node);
      throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
    }

    if (typeof node === 'string') {
      var segment = task.blockedSegment;
      segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
      return;
    }

    if (typeof node === 'number') {
      var _segment = task.blockedSegment;
      _segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
      return;
    }

    {
      if (typeof node === 'function') {
        error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
      }
    }
  }

  function renderChildrenArray(request, task, children) {
    var totalChildren = children.length;

    for (var i = 0; i < totalChildren; i++) {
      var prevTreeContext = task.treeContext;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

      try {
        // We need to use the non-destructive form so that we can safely pop back
        // up and render the sibling if something suspends.
        renderNode(request, task, children[i]);
      } finally {
        task.treeContext = prevTreeContext;
      }
    }
  }

  function spawnNewSuspendedTask(request, task, x) {
    // Something suspended, we'll need to create a new segment and resolve it later.
    var segment = task.blockedSegment;
    var insertionIndex = segment.chunks.length;
    var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
    segment.lastPushedText, // Assume we are text embedded at the trailing edge
    true);
    segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

    segment.lastPushedText = false;
    var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

    {
      if (task.componentStack !== null) {
        // We pop one task off the stack because the node that suspended will be tried again,
        // which will add it back onto the stack.
        newTask.componentStack = task.componentStack.parent;
      }
    }

    var ping = newTask.ping;
    x.then(ping, ping);
  } // This is a non-destructive form of rendering a node. If it suspends it spawns
  // a new task and restores the context of this task to what it was before.


  function renderNode(request, task, node) {
    // TODO: Store segment.children.length here and reset it in case something
    // suspended partially through writing something.
    // Snapshot the current context in case something throws to interrupt the
    // process.
    var previousFormatContext = task.blockedSegment.formatContext;
    var previousLegacyContext = task.legacyContext;
    var previousContext = task.context;
    var previousComponentStack = null;

    {
      previousComponentStack = task.componentStack;
    }

    try {
      return renderNodeDestructive(request, task, node);
    } catch (x) {
      resetHooksState();

      if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
        spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
        // functions in case nothing throws so we don't use "finally" here.

        task.blockedSegment.formatContext = previousFormatContext;
        task.legacyContext = previousLegacyContext;
        task.context = previousContext; // Restore all active ReactContexts to what they were before.

        switchContext(previousContext);

        {
          task.componentStack = previousComponentStack;
        }

        return;
      } else {
        // Restore the context. We assume that this will be restored by the inner
        // functions in case nothing throws so we don't use "finally" here.
        task.blockedSegment.formatContext = previousFormatContext;
        task.legacyContext = previousLegacyContext;
        task.context = previousContext; // Restore all active ReactContexts to what they were before.

        switchContext(previousContext);

        {
          task.componentStack = previousComponentStack;
        } // We assume that we don't need the correct context.
        // Let's terminate the rest of the tree and don't render any siblings.


        throw x;
      }
    }
  }

  function erroredTask(request, boundary, segment, error) {
    // Report the error to a global handler.
    var errorDigest = logRecoverableError(request, error);

    if (boundary === null) {
      fatalError(request, error);
    } else {
      boundary.pendingTasks--;

      if (!boundary.forceClientRender) {
        boundary.forceClientRender = true;
        boundary.errorDigest = errorDigest;

        {
          captureBoundaryErrorDetailsDev(boundary, error);
        } // Regardless of what happens next, this boundary won't be displayed,
        // so we can flush it, if the parent already flushed.


        if (boundary.parentFlushed) {
          // We don't have a preference where in the queue this goes since it's likely
          // to error on the client anyway. However, intentionally client-rendered
          // boundaries should be flushed earlier so that they can start on the client.
          // We reuse the same queue for errors.
          request.clientRenderedBoundaries.push(boundary);
        }
      }
    }

    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }

  function abortTaskSoft(task) {
    // This aborts task without aborting the parent boundary that it blocks.
    // It's used for when we didn't need this task to complete the tree.
    // If task was needed, then it should use abortTask instead.
    var request = this;
    var boundary = task.blockedBoundary;
    var segment = task.blockedSegment;
    segment.status = ABORTED;
    finishedTask(request, boundary, segment);
  }

  function abortTask(task, request, reason) {
    // This aborts the task and aborts the parent that it blocks, putting it into
    // client rendered mode.
    var boundary = task.blockedBoundary;
    var segment = task.blockedSegment;
    segment.status = ABORTED;

    if (boundary === null) {
      request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
      // the request;

      if (request.status !== CLOSED) {
        request.status = CLOSED;

        if (request.destination !== null) {
          close(request.destination);
        }
      }
    } else {
      boundary.pendingTasks--;

      if (!boundary.forceClientRender) {
        boundary.forceClientRender = true;

        var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

        boundary.errorDigest = request.onError(_error);

        {
          var errorPrefix = 'The server did not finish this Suspense boundary: ';

          if (_error && typeof _error.message === 'string') {
            _error = errorPrefix + _error.message;
          } else {
            // eslint-disable-next-line react-internal/safe-string-coercion
            _error = errorPrefix + String(_error);
          }

          var previousTaskInDev = currentTaskInDEV;
          currentTaskInDEV = task;

          try {
            captureBoundaryErrorDetailsDev(boundary, _error);
          } finally {
            currentTaskInDEV = previousTaskInDev;
          }
        }

        if (boundary.parentFlushed) {
          request.clientRenderedBoundaries.push(boundary);
        }
      } // If this boundary was still pending then we haven't already cancelled its fallbacks.
      // We'll need to abort the fallbacks, which will also error that parent boundary.


      boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
        return abortTask(fallbackTask, request, reason);
      });
      boundary.fallbackAbortableTasks.clear();
      request.allPendingTasks--;

      if (request.allPendingTasks === 0) {
        var onAllReady = request.onAllReady;
        onAllReady();
      }
    }
  }

  function queueCompletedSegment(boundary, segment) {
    if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
      // This is an empty segment. There's nothing to write, so we can instead transfer the ID
      // to the child. That way any existing references point to the child.
      var childSegment = segment.children[0];
      childSegment.id = segment.id;
      childSegment.parentFlushed = true;

      if (childSegment.status === COMPLETED) {
        queueCompletedSegment(boundary, childSegment);
      }
    } else {
      var completedSegments = boundary.completedSegments;
      completedSegments.push(segment);
    }
  }

  function finishedTask(request, boundary, segment) {
    if (boundary === null) {
      if (segment.parentFlushed) {
        if (request.completedRootSegment !== null) {
          throw new Error('There can only be one root segment. This is a bug in React.');
        }

        request.completedRootSegment = segment;
      }

      request.pendingRootTasks--;

      if (request.pendingRootTasks === 0) {
        // We have completed the shell so the shell can't error anymore.
        request.onShellError = noop$1;
        var onShellReady = request.onShellReady;
        onShellReady();
      }
    } else {
      boundary.pendingTasks--;

      if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
        // This must have been the last segment we were waiting on. This boundary is now complete.
        if (segment.parentFlushed) {
          // Our parent segment already flushed, so we need to schedule this segment to be emitted.
          // If it is a segment that was aborted, we'll write other content instead so we don't need
          // to emit it.
          if (segment.status === COMPLETED) {
            queueCompletedSegment(boundary, segment);
          }
        }

        if (boundary.parentFlushed) {
          // The segment might be part of a segment that didn't flush yet, but if the boundary's
          // parent flushed, we need to schedule the boundary to be emitted.
          request.completedBoundaries.push(boundary);
        } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
        // This needs to happen after we read the parentFlushed flags because aborting can finish
        // work which can trigger user code, which can start flushing, which can change those flags.


        boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
        boundary.fallbackAbortableTasks.clear();
      } else {
        if (segment.parentFlushed) {
          // Our parent already flushed, so we need to schedule this segment to be emitted.
          // If it is a segment that was aborted, we'll write other content instead so we don't need
          // to emit it.
          if (segment.status === COMPLETED) {
            queueCompletedSegment(boundary, segment);
            var completedSegments = boundary.completedSegments;

            if (completedSegments.length === 1) {
              // This is the first time since we last flushed that we completed anything.
              // We can schedule this boundary to emit its partially completed segments early
              // in case the parent has already been flushed.
              if (boundary.parentFlushed) {
                request.partialBoundaries.push(boundary);
              }
            }
          }
        }
      }
    }

    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      // This needs to be called at the very end so that we can synchronously write the result
      // in the callback if needed.
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }

  function retryTask(request, task) {
    var segment = task.blockedSegment;

    if (segment.status !== PENDING) {
      // We completed this by other means before we had a chance to retry it.
      return;
    } // We restore the context to what it was when we suspended.
    // We don't restore it after we leave because it's likely that we'll end up
    // needing a very similar context soon again.


    switchContext(task.context);
    var prevTaskInDEV = null;

    {
      prevTaskInDEV = currentTaskInDEV;
      currentTaskInDEV = task;
    }

    try {
      // We call the destructive form that mutates this task. That way if something
      // suspends again, we can reuse the same task instead of spawning a new one.
      renderNodeDestructive(request, task, task.node);
      pushSegmentFinale(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
      task.abortSet.delete(task);
      segment.status = COMPLETED;
      finishedTask(request, task.blockedBoundary, segment);
    } catch (x) {
      resetHooksState();

      if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
        // Something suspended again, let's pick it back up later.
        var ping = task.ping;
        x.then(ping, ping);
      } else {
        task.abortSet.delete(task);
        segment.status = ERRORED;
        erroredTask(request, task.blockedBoundary, segment, x);
      }
    } finally {
      {
        currentTaskInDEV = prevTaskInDEV;
      }
    }
  }

  function performWork(request) {
    if (request.status === CLOSED) {
      return;
    }

    var prevContext = getActiveContext();
    var prevDispatcher = ReactCurrentDispatcher$1.current;
    ReactCurrentDispatcher$1.current = Dispatcher;
    var prevGetCurrentStackImpl;

    {
      prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
      ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
    }

    var prevResponseState = currentResponseState;
    setCurrentResponseState(request.responseState);

    try {
      var pingedTasks = request.pingedTasks;
      var i;

      for (i = 0; i < pingedTasks.length; i++) {
        var task = pingedTasks[i];
        retryTask(request, task);
      }

      pingedTasks.splice(0, i);

      if (request.destination !== null) {
        flushCompletedQueues(request, request.destination);
      }
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    } finally {
      setCurrentResponseState(prevResponseState);
      ReactCurrentDispatcher$1.current = prevDispatcher;

      {
        ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
      }

      if (prevDispatcher === Dispatcher) {
        // This means that we were in a reentrant work loop. This could happen
        // in a renderer that supports synchronous work like renderToString,
        // when it's called from within another renderer.
        // Normally we don't bother switching the contexts to their root/default
        // values when leaving because we'll likely need the same or similar
        // context again. However, when we're inside a synchronous loop like this
        // we'll to restore the context to what it was before returning.
        switchContext(prevContext);
      }
    }
  }

  function flushSubtree(request, destination, segment) {
    segment.parentFlushed = true;

    switch (segment.status) {
      case PENDING:
        {
          // We're emitting a placeholder for this segment to be filled in later.
          // Therefore we'll need to assign it an ID - to refer to it by.
          var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

          segment.lastPushedText = false;
          segment.textEmbedded = false;
          return writePlaceholder(destination, request.responseState, segmentID);
        }

      case COMPLETED:
        {
          segment.status = FLUSHED;
          var r = true;
          var chunks = segment.chunks;
          var chunkIdx = 0;
          var children = segment.children;

          for (var childIdx = 0; childIdx < children.length; childIdx++) {
            var nextChild = children[childIdx]; // Write all the chunks up until the next child.

            for (; chunkIdx < nextChild.index; chunkIdx++) {
              writeChunk(destination, chunks[chunkIdx]);
            }

            r = flushSegment(request, destination, nextChild);
          } // Finally just write all the remaining chunks


          for (; chunkIdx < chunks.length - 1; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          if (chunkIdx < chunks.length) {
            r = writeChunkAndReturn(destination, chunks[chunkIdx]);
          }

          return r;
        }

      default:
        {
          throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
        }
    }
  }

  function flushSegment(request, destination, segment) {
    var boundary = segment.boundary;

    if (boundary === null) {
      // Not a suspense boundary.
      return flushSubtree(request, destination, segment);
    }

    boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
    // emit the content or the fallback now.

    if (boundary.forceClientRender) {
      // Emit a client rendered suspense boundary wrapper.
      // We never queue the inner boundary so we'll never emit its content or partial segments.
      writeStartClientRenderedSuspenseBoundary(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndClientRenderedSuspenseBoundary(destination, request.responseState);
    } else if (boundary.pendingTasks > 0) {
      // This boundary is still loading. Emit a pending suspense boundary wrapper.
      // Assign an ID to refer to the future content by.
      boundary.rootSegmentID = request.nextSegmentId++;

      if (boundary.completedSegments.length > 0) {
        // If this is at least partially complete, we can queue it to be partially emitted early.
        request.partialBoundaries.push(boundary);
      } /// This is the first time we should have referenced this ID.


      var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
      writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndPendingSuspenseBoundary(destination, request.responseState);
    } else if (boundary.byteSize > request.progressiveChunkSize) {
      // This boundary is large and will be emitted separately so that we can progressively show
      // other content. We add it to the queue during the flush because we have to ensure that
      // the parent flushes first so that there's something to inject it into.
      // We also have to make sure that it's emitted into the queue in a deterministic slot.
      // I.e. we can't insert it here when it completes.
      // Assign an ID to refer to the future content by.
      boundary.rootSegmentID = request.nextSegmentId++;
      request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

      writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

      flushSubtree(request, destination, segment);
      return writeEndPendingSuspenseBoundary(destination, request.responseState);
    } else {
      // We can inline this boundary's content as a complete boundary.
      writeStartCompletedSuspenseBoundary(destination, request.responseState);
      var completedSegments = boundary.completedSegments;

      if (completedSegments.length !== 1) {
        throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
      }

      var contentSegment = completedSegments[0];
      flushSegment(request, destination, contentSegment);
      return writeEndCompletedSuspenseBoundary(destination, request.responseState);
    }
  }

  function flushClientRenderedBoundary(request, destination, boundary) {
    return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
  }

  function flushSegmentContainer(request, destination, segment) {
    writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
    flushSegment(request, destination, segment);
    return writeEndSegment(destination, segment.formatContext);
  }

  function flushCompletedBoundary(request, destination, boundary) {
    var completedSegments = boundary.completedSegments;
    var i = 0;

    for (; i < completedSegments.length; i++) {
      var segment = completedSegments[i];
      flushPartiallyCompletedSegment(request, destination, boundary, segment);
    }

    completedSegments.length = 0;
    return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
  }

  function flushPartialBoundary(request, destination, boundary) {
    var completedSegments = boundary.completedSegments;
    var i = 0;

    for (; i < completedSegments.length; i++) {
      var segment = completedSegments[i];

      if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
        i++;
        completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
        // might want to write later.

        return false;
      }
    }

    completedSegments.splice(0, i);
    return true;
  }

  function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
    if (segment.status === FLUSHED) {
      // We've already flushed this inline.
      return true;
    }

    var segmentID = segment.id;

    if (segmentID === -1) {
      // This segment wasn't previously referred to. This happens at the root of
      // a boundary. We make kind of a leap here and assume this is the root.
      var rootSegmentID = segment.id = boundary.rootSegmentID;

      if (rootSegmentID === -1) {
        throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
      }

      return flushSegmentContainer(request, destination, segment);
    } else {
      flushSegmentContainer(request, destination, segment);
      return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
    }
  }

  function flushCompletedQueues(request, destination) {
    beginWriting();

    try {
      // The structure of this is to go through each queue one by one and write
      // until the sink tells us to stop. When we should stop, we still finish writing
      // that item fully and then yield. At that point we remove the already completed
      // items up until the point we completed them.
      // TODO: Emit preloading.
      // TODO: It's kind of unfortunate to keep checking this array after we've already
      // emitted the root.
      var completedRootSegment = request.completedRootSegment;

      if (completedRootSegment !== null && request.pendingRootTasks === 0) {
        flushSegment(request, destination, completedRootSegment);
        request.completedRootSegment = null;
        writeCompletedRoot(destination, request.responseState);
      } // We emit client rendering instructions for already emitted boundaries first.
      // This is so that we can signal to the client to start client rendering them as
      // soon as possible.


      var clientRenderedBoundaries = request.clientRenderedBoundaries;
      var i;

      for (i = 0; i < clientRenderedBoundaries.length; i++) {
        var boundary = clientRenderedBoundaries[i];

        if (!flushClientRenderedBoundary(request, destination, boundary)) {
          request.destination = null;
          i++;
          clientRenderedBoundaries.splice(0, i);
          return;
        }
      }

      clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
      // that are completely done since we can actually show them, than it is to emit
      // any individual segments from a partially complete boundary.

      var completedBoundaries = request.completedBoundaries;

      for (i = 0; i < completedBoundaries.length; i++) {
        var _boundary = completedBoundaries[i];

        if (!flushCompletedBoundary(request, destination, _boundary)) {
          request.destination = null;
          i++;
          completedBoundaries.splice(0, i);
          return;
        }
      }

      completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
      // we continue with lower priorities.

      completeWriting(destination);
      beginWriting(destination); // TODO: Here we'll emit data used by hydration.
      // Next we emit any segments of any boundaries that are partially complete
      // but not deeply complete.

      var partialBoundaries = request.partialBoundaries;

      for (i = 0; i < partialBoundaries.length; i++) {
        var _boundary2 = partialBoundaries[i];

        if (!flushPartialBoundary(request, destination, _boundary2)) {
          request.destination = null;
          i++;
          partialBoundaries.splice(0, i);
          return;
        }
      }

      partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
      // boundaries added to it in case they were too larged to be inlined.
      // New ones might be added in this loop.

      var largeBoundaries = request.completedBoundaries;

      for (i = 0; i < largeBoundaries.length; i++) {
        var _boundary3 = largeBoundaries[i];

        if (!flushCompletedBoundary(request, destination, _boundary3)) {
          request.destination = null;
          i++;
          largeBoundaries.splice(0, i);
          return;
        }
      }

      largeBoundaries.splice(0, i);
    } finally {
      completeWriting(destination);

      if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
      // either they have pending task or they're complete.
      ) {
          {
            if (request.abortableTasks.size !== 0) {
              error('There was still abortable task at the root when we closed. This is a bug in React.');
            }
          } // We're done.


          close(destination);
        }
    }
  }

  function startWork(request) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
  function startFlowing(request, destination) {
    if (request.status === CLOSING) {
      request.status = CLOSED;
      closeWithError(destination, request.fatalError);
      return;
    }

    if (request.status === CLOSED) {
      return;
    }

    if (request.destination !== null) {
      // We're already flowing.
      return;
    }

    request.destination = destination;

    try {
      flushCompletedQueues(request, destination);
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    }
  } // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

  function abort(request, reason) {
    try {
      var abortableTasks = request.abortableTasks;
      abortableTasks.forEach(function (task) {
        return abortTask(task, request, reason);
      });
      abortableTasks.clear();

      if (request.destination !== null) {
        flushCompletedQueues(request, request.destination);
      }
    } catch (error) {
      logRecoverableError(request, error);
      fatalError(request, error);
    }
  }

  function renderToReadableStream(children, options) {
    return new Promise(function (resolve, reject) {
      var onFatalError;
      var onAllReady;
      var allReady = new Promise(function (res, rej) {
        onAllReady = res;
        onFatalError = rej;
      });

      function onShellReady() {
        var stream = new ReadableStream({
          type: 'bytes',
          pull: function (controller) {
            startFlowing(request, controller);
          },
          cancel: function (reason) {
            abort(request);
          }
        }, // $FlowFixMe size() methods are not allowed on byte streams.
        {
          highWaterMark: 0
        }); // TODO: Move to sub-classing ReadableStream.

        stream.allReady = allReady;
        resolve(stream);
      }

      function onShellError(error) {
        // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`.
        // However, `allReady` will be rejected by `onFatalError` as well.
        // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`.
        allReady.catch(function () {});
        reject(error);
      }

      var request = createRequest(children, createResponseState(options ? options.identifierPrefix : undefined, options ? options.nonce : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError);

      if (options && options.signal) {
        var signal = options.signal;

        var listener = function () {
          abort(request, signal.reason);
          signal.removeEventListener('abort', listener);
        };

        signal.addEventListener('abort', listener);
      }

      startWork(request);
    });
  }

  exports.renderToReadableStream = renderToReadableStream;
  exports.version = ReactVersion;

})));
/**
 * @license React
 * react-dom-server.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(I,M){"object"===typeof exports&&"undefined"!==typeof module?M(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],M):(I=I||self,M(I.ReactDOMServer={},I.React))})(this,function(I,M){function n(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
function k(a,b){if(0!==b.length)if(512<b.length)0<A&&(a.enqueue(new Uint8Array(B.buffer,0,A)),B=new Uint8Array(512),A=0),a.enqueue(b);else{var c=B.length-A;c<b.length&&(0===c?a.enqueue(B):(B.set(b.subarray(0,c),A),a.enqueue(B),b=b.subarray(c)),B=new Uint8Array(512),A=0);B.set(b,A);A+=b.length}}function r(a,b){k(a,b);return!0}function Ea(a){B&&0<A&&(a.enqueue(new Uint8Array(B.buffer,0,A)),B=null,A=0)}function p(a){return Fa.encode(a)}function g(a){return Fa.encode(a)}function Ga(a,b){"function"===
typeof a.error?a.error(b):a.close()}function Ha(a){if(w.call(Ia,a))return!0;if(w.call(Ja,a))return!1;if(Cb.test(a))return Ia[a]=!0;Ja[a]=!0;return!1}function v(a,b,c,d,f,e,h){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=h}function u(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=Db.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b=
"&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}function Eb(a,b,c,d,f){a=void 0===a?"":a;b=void 0===b?Fb:g('<script nonce="'+u(b)+'">');var e=[];void 0!==c&&e.push(b,p((""+c).replace(Gb,Hb)),Ib);if(void 0!==d)for(c=0;c<d.length;c++)e.push(Jb,p(u(d[c])),Ka);if(void 0!==f)for(d=0;d<f.length;d++)e.push(Kb,p(u(f[d])),Ka);return{bootstrapChunks:e,
startInlineScript:b,placeholderPrefix:g(a+"P:"),segmentPrefix:g(a+"S:"),boundaryPrefix:a+"B:",idPrefix:a,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}function C(a,b){return{insertionMode:a,selectedValue:b}}function Lb(a){return C("http://www.w3.org/2000/svg"===a?2:"http://www.w3.org/1998/Math/MathML"===a?3:0,null)}function Mb(a,b,c){switch(b){case "select":return C(1,null!=c.value?c.value:c.defaultValue);case "svg":return C(2,null);case "math":return C(3,
null);case "foreignObject":return C(1,null);case "table":return C(4,null);case "thead":case "tbody":case "tfoot":return C(5,null);case "colgroup":return C(7,null);case "tr":return C(6,null)}return 4<=a.insertionMode||0===a.insertionMode?C(1,null):a}function La(a,b,c,d){if(""===b)return d;d&&a.push(ka);a.push(p(u(b)));return!0}function Ma(a,b,c){if("object"!==typeof c)throw Error(n(62));b=!0;for(var d in c)if(w.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=
p(u(d));f=p(u((""+f).trim()))}else{e=d;var h=Na.get(e);void 0!==h?e=h:(h=g(u(e.replace(Nb,"-$1").toLowerCase().replace(Ob,"-ms-"))),Na.set(e,h),e=h);f="number"===typeof f?0===f||w.call(U,d)?p(""+f):p(f+"px"):p(u((""+f).trim()))}b?(b=!1,a.push(Pb,e,Oa,f)):a.push(Qb,e,Oa,f)}}b||a.push(J)}function y(a,b,c,d){switch(c){case "style":Ma(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||
"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=t.hasOwnProperty(c)?t[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=p(b.attributeName);switch(b.type){case 3:d&&a.push(E,c,Pa);break;case 4:!0===d?a.push(E,c,Pa):!1!==d&&a.push(E,c,N,p(u(d)),J);break;case 5:isNaN(d)||a.push(E,c,N,p(u(d)),J);break;case 6:!isNaN(d)&&1<=d&&a.push(E,c,N,p(u(d)),J);break;default:b.sanitizeURL&&(d=""+d),a.push(E,c,N,p(u(d)),J)}}else if(Ha(c)){switch(typeof d){case "function":case "symbol":return;
case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(E,p(c),N,p(u(d)),J)}}function V(a,b,c){if(null!=b){if(null!=c)throw Error(n(60));if("object"!==typeof b||!("__html"in b))throw Error(n(61));b=b.__html;null!==b&&void 0!==b&&a.push(p(""+b))}}function Rb(a){var b="";M.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function la(a,b,c,d){a.push(z(c));var f=c=null,e;for(e in b)if(w.call(b,e)){var h=b[e];if(null!=h)switch(e){case "children":c=h;break;case "dangerouslySetInnerHTML":f=
h;break;default:y(a,d,e,h)}}a.push(F);V(a,f,c);return"string"===typeof c?(a.push(p(u(c))),null):c}function z(a){var b=Qa.get(a);if(void 0===b){if(!Sb.test(a))throw Error(n(65,a));b=g("<"+a);Qa.set(a,b)}return b}function Tb(a,b,c,d,f){switch(b){case "select":a.push(z("select"));var e=null,h=null;for(q in c)if(w.call(c,q)){var m=c[q];if(null!=m)switch(q){case "children":e=m;break;case "dangerouslySetInnerHTML":h=m;break;case "defaultValue":case "value":break;default:y(a,d,q,m)}}a.push(F);V(a,h,e);return e;
case "option":h=f.selectedValue;a.push(z("option"));var g=m=null,k=null;var q=null;for(e in c)if(w.call(c,e)){var l=c[e];if(null!=l)switch(e){case "children":m=l;break;case "selected":k=l;break;case "dangerouslySetInnerHTML":q=l;break;case "value":g=l;default:y(a,d,e,l)}}if(null!=h)if(c=null!==g?""+g:Rb(m),ma(h))for(d=0;d<h.length;d++){if(""+h[d]===c){a.push(na);break}}else""+h===c&&a.push(na);else k&&a.push(na);a.push(F);V(a,q,m);return m;case "textarea":a.push(z("textarea"));q=h=e=null;for(m in c)if(w.call(c,
m)&&(g=c[m],null!=g))switch(m){case "children":q=g;break;case "value":e=g;break;case "defaultValue":h=g;break;case "dangerouslySetInnerHTML":throw Error(n(91));default:y(a,d,m,g)}null===e&&null!==h&&(e=h);a.push(F);if(null!=q){if(null!=e)throw Error(n(92));if(ma(q)&&1<q.length)throw Error(n(93));e=""+q}"string"===typeof e&&"\n"===e[0]&&a.push(oa);null!==e&&a.push(p(u(""+e)));return null;case "input":a.push(z("input"));g=q=m=e=null;for(h in c)if(w.call(c,h)&&(k=c[h],null!=k))switch(h){case "children":case "dangerouslySetInnerHTML":throw Error(n(399,
"input"));case "defaultChecked":g=k;break;case "defaultValue":m=k;break;case "checked":q=k;break;case "value":e=k;break;default:y(a,d,h,k)}null!==q?y(a,d,"checked",q):null!==g&&y(a,d,"checked",g);null!==e?y(a,d,"value",e):null!==m&&y(a,d,"value",m);a.push(Ra);return null;case "menuitem":a.push(z("menuitem"));for(var r in c)if(w.call(c,r)&&(e=c[r],null!=e))switch(r){case "children":case "dangerouslySetInnerHTML":throw Error(n(400));default:y(a,d,r,e)}a.push(F);return null;case "title":a.push(z("title"));
e=null;for(l in c)if(w.call(c,l)&&(h=c[l],null!=h))switch(l){case "children":e=h;break;case "dangerouslySetInnerHTML":throw Error(n(434));default:y(a,d,l,h)}a.push(F);return e;case "listing":case "pre":a.push(z(b));h=e=null;for(g in c)if(w.call(c,g)&&(m=c[g],null!=m))switch(g){case "children":e=m;break;case "dangerouslySetInnerHTML":h=m;break;default:y(a,d,g,m)}a.push(F);if(null!=h){if(null!=e)throw Error(n(60));if("object"!==typeof h||!("__html"in h))throw Error(n(61));c=h.__html;null!==c&&void 0!==
c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push(oa,p(c)):a.push(p(""+c)))}"string"===typeof e&&"\n"===e[0]&&a.push(oa);return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(z(b));for(var t in c)if(w.call(c,t)&&(e=c[t],null!=e))switch(t){case "children":case "dangerouslySetInnerHTML":throw Error(n(399,b));default:y(a,d,t,e)}a.push(Ra);return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return la(a,
c,b,d);case "html":return 0===f.insertionMode&&a.push(Ub),la(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return la(a,c,b,d);a.push(z(b));h=e=null;for(k in c)if(w.call(c,k)&&(m=c[k],null!=m))switch(k){case "children":e=m;break;case "dangerouslySetInnerHTML":h=m;break;case "style":Ma(a,d,m);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:Ha(k)&&"function"!==typeof m&&"symbol"!==typeof m&&a.push(E,p(k),N,p(u(m)),J)}a.push(F);V(a,h,e);return e}}
function Ta(a,b,c){k(a,Vb);if(null===c)throw Error(n(395));k(a,c);return r(a,Wb)}function Xb(a,b,c,d){switch(c.insertionMode){case 0:case 1:return k(a,Yb),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,Zb);case 2:return k(a,$b),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,ac);case 3:return k(a,bc),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,cc);case 4:return k(a,dc),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,ec);case 5:return k(a,fc),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,gc);
case 6:return k(a,hc),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,ic);case 7:return k(a,jc),k(a,b.segmentPrefix),k(a,p(d.toString(16))),r(a,kc);default:throw Error(n(397));}}function lc(a,b){switch(b.insertionMode){case 0:case 1:return r(a,mc);case 2:return r(a,nc);case 3:return r(a,oc);case 4:return r(a,pc);case 5:return r(a,qc);case 6:return r(a,rc);case 7:return r(a,sc);default:throw Error(n(397));}}function pa(a){return JSON.stringify(a).replace(tc,function(a){switch(a){case "<":return"\\u003c";
case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}function qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Ua:return"Fragment";case Va:return"Portal";case Wa:return"Profiler";case Xa:return"StrictMode";
case Ya:return"Suspense";case Za:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case $a:return(a.displayName||"Context")+".Consumer";case ab:return(a._context.displayName||"Context")+".Provider";case bb:var b=a.render;a=a.displayName;a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case cb:return b=a.displayName||null,null!==b?b:qa(a.type)||"Memo";case ra:b=a._payload;a=a._init;try{return qa(a(b))}catch(c){}}return null}function db(a,b){a=a.contextTypes;
if(!a)return eb;var c={},d;for(d in a)c[d]=b[d];return c}function W(a,b){if(a!==b){a.context._currentValue=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error(n(401));}else{if(null===c)throw Error(n(401));W(a,c)}b.context._currentValue=b.value}}function fb(a){a.context._currentValue=a.parentValue;a=a.parent;null!==a&&fb(a)}function gb(a){var b=a.parent;null!==b&&gb(b);a.context._currentValue=a.value}function hb(a,b){a.context._currentValue=a.parentValue;a=a.parent;if(null===
a)throw Error(n(402));a.depth===b.depth?W(a,b):hb(a,b)}function ib(a,b){var c=b.parent;if(null===c)throw Error(n(402));a.depth===c.depth?W(a,c):ib(a,c);b.context._currentValue=b.value}function X(a){var b=K;b!==a&&(null===b?gb(a):null===a?fb(b):b.depth===a.depth?W(b,a):b.depth>a.depth?hb(b,a):ib(b,a),K=a)}function jb(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=kb;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var h=b.contextType;a.context="object"===typeof h&&null!==
h?h._currentValue:d;h=b.getDerivedStateFromProps;"function"===typeof h&&(h=h(c,f),f=null===h||void 0===h?f:P({},f,h),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&kb.enqueueReplaceState(a,
a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,h=e.replace,e.queue=null,e.replace=!1,h&&1===b.length)a.state=b[0];else{e=h?b[0]:a.state;f=!0;for(h=h?1:0;h<b.length;h++){var g=b[h];g="function"===typeof g?g.call(a,e,c,d):g;null!=g&&(f?(f=!1,e=P({},e,g)):P(e,g))}a.state=e}else e.queue=null}function sa(a,b,c){var d=a.id;a=a.overflow;var f=32-Y(d)-1;d&=~(1<<f);c+=1;var e=32-Y(b)+f;if(30<e){var h=f-f%5;e=(d&(1<<h)-1).toString(32);d>>=h;f-=h;return{id:1<<32-Y(b)+f|c<<f|d,overflow:e+a}}return{id:1<<
e|c<<f|d,overflow:a}}function uc(a){a>>>=0;return 0===a?32:31-(vc(a)/wc|0)|0}function xc(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function L(){if(null===D)throw Error(n(321));return D}function lb(){if(0<Z)throw Error(n(312));return{memoizedState:null,queue:null,next:null}}function ta(){null===l?null===aa?(Q=!1,aa=l=lb()):(Q=!0,l=aa):null===l.next?(Q=!1,l=l.next=lb()):(Q=!0,l=l.next);return l}function ua(){va=D=null;ba=!1;aa=null;Z=0;l=G=null}function mb(a,b){return"function"===typeof b?
b(a):b}function nb(a,b,c){D=L();l=ta();if(Q){var d=l.queue;b=d.dispatch;if(null!==G&&(c=G.get(d),void 0!==c)){G.delete(d);d=l.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);l.memoizedState=d;return[d,b]}return[l.memoizedState,b]}a=a===mb?"function"===typeof b?b():b:void 0!==c?c(b):b;l.memoizedState=a;a=l.queue={last:null,dispatch:null};a=a.dispatch=yc.bind(null,D,a);return[l.memoizedState,a]}function ob(a,b){D=L();l=ta();b=void 0===b?null:b;if(null!==l){var c=l.memoizedState;if(null!==
c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!zc(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();l.memoizedState=[a,b];return a}function yc(a,b,c){if(25<=Z)throw Error(n(301));if(a===D)if(ba=!0,a={action:c,next:null},null===G&&(G=new Map),c=G.get(b),void 0===c)G.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function Ac(){throw Error(n(394));}function ca(){}function Bc(a){console.error(a);return null}function R(){}function Cc(a,b,c,d,f,e,
h,g,k){var m=[],q=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:q,pingedTasks:m,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?Bc:f,onAllReady:void 0===e?R:e,onShellReady:void 0===h?R:h,onShellError:void 0===g?R:g,onFatalError:void 0===k?R:k};c=da(b,0,null,c,!1,!1);c.parentFlushed=!0;a=wa(b,a,null,c,
q,eb,null,Dc);m.push(a);return b}function wa(a,b,c,d,f,e,h,g){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var m={node:b,ping:function(){var b=a.pingedTasks;b.push(m);1===b.length&&pb(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:h,treeContext:g};f.add(m);return m}function da(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}function S(a,b){a=a.onError(b);if(null!=
a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function ea(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,Ga(a.destination,b)):(a.status=1,a.fatalError=b)}function qb(a,b,c,d,f){D={};va=b;T=0;for(a=c(d,f);ba;)ba=!1,T=0,Z+=1,l=null,a=c(d,f);ua();return a}
function rb(a,b,c,d,f){f=c.render();var e=d.childContextTypes;if(null!==e&&void 0!==e){var h=b.legacyContext;if("function"!==typeof c.getChildContext)d=h;else{c=c.getChildContext();for(var g in c)if(!(g in e))throw Error(n(108,qa(d)||"Unknown",g));d=P({},h,c)}b.legacyContext=d;x(a,b,f);b.legacyContext=h}else x(a,b,f)}function sb(a,b){if(a&&a.defaultProps){b=P({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function xa(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&
c.prototype.isReactComponent){f=db(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue:f);jb(e,c,d,f);rb(a,b,e,c)}else{e=db(c,b.legacyContext);f=qb(a,b,c,d,e);var h=0!==T;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)jb(f,c,d,e),rb(a,b,f,c);else if(h){d=b.treeContext;b.treeContext=sa(d,1,0);try{x(a,b,f)}finally{b.treeContext=d}}else x(a,b,f)}else if("string"===typeof c){f=b.blockedSegment;e=Tb(f.chunks,c,d,a.responseState,
f.formatContext);f.lastPushedText=!1;h=f.formatContext;f.formatContext=Mb(h,c,d);ya(a,b,e);f.formatContext=h;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push(Ec,p(c),Fc)}f.lastPushedText=!1}else{switch(c){case Gc:case Hc:case Xa:case Wa:case Ua:x(a,b,d.children);return;case Za:x(a,b,d.children);return;case Ic:throw Error(n(343));
case Ya:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;h=new Set;var g={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:h,errorDigest:null},k=da(a,f.chunks.length,g,f.formatContext,!1,!1);f.children.push(k);f.lastPushedText=!1;var l=da(a,0,null,f.formatContext,!1,!1);l.parentFlushed=!0;b.blockedBoundary=g;b.blockedSegment=l;try{if(ya(a,b,d),l.lastPushedText&&l.textEmbedded&&l.chunks.push(ka),
l.status=1,fa(g,l),0===g.pendingTasks)break a}catch(q){l.status=4,g.forceClientRender=!0,g.errorDigest=S(a,q)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=wa(a,e,c,k,h,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case bb:d=qb(a,b,c.render,d,f);if(0!==T){c=b.treeContext;b.treeContext=sa(c,1,0);try{x(a,b,d)}finally{b.treeContext=c}}else x(a,b,d);return;case cb:c=c.type;d=sb(c,d);xa(a,b,c,d,f);return;case ab:f=d.children;
c=c._context;d=d.value;e=c._currentValue;c._currentValue=d;h=K;K=d={parent:h,depth:null===h?0:h.depth+1,context:c,parentValue:e,value:d};b.context=d;x(a,b,f);a=K;if(null===a)throw Error(n(403));d=a.parentValue;a.context._currentValue=d===Jc?a.context._defaultValue:d;a=K=a.parent;b.context=a;return;case $a:d=d.children;d=d(c._currentValue);x(a,b,d);return;case ra:f=c._init;c=f(c._payload);d=sb(c,d);xa(a,b,c,d,void 0);return}throw Error(n(130,null==c?c:typeof c,""));}}function x(a,b,c){b.node=c;if("object"===
typeof c&&null!==c){switch(c.$$typeof){case Kc:xa(a,b,c.type,c.props,c.ref);return;case Va:throw Error(n(257));case ra:var d=c._init;c=d(c._payload);x(a,b,c);return}if(ma(c)){tb(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=ub&&c[ub]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=[];do f.push(c.value),c=d.next();while(!c.done);tb(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error(n(31,"[object Object]"===a?"object with keys {"+
Object.keys(c).join(", ")+"}":a));}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=La(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=La(b.blockedSegment.chunks,""+c,a.responseState,d.lastPushedText))}function tb(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=sa(e,d,f);try{ya(a,b,c[f])}finally{b.treeContext=e}}}function ya(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;
try{return x(a,b,c)}catch(O){if(ua(),"object"===typeof O&&null!==O&&"function"===typeof O.then){c=O;var h=b.blockedSegment,g=da(a,h.chunks.length,null,h.formatContext,h.lastPushedText,!0);h.children.push(g);h.lastPushedText=!1;a=wa(a,b.node,b.blockedBoundary,g,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;X(e)}else throw b.blockedSegment.formatContext=d,b.legacyContext=f,b.context=e,X(e),O;}}function Lc(a){var b=
a.blockedBoundary;a=a.blockedSegment;a.status=3;vb(this,b,a)}function wb(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.close())):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,a=void 0===c?Error(n(432)):c,d.errorDigest=b.onError(a),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return wb(a,b,c)}),d.fallbackAbortableTasks.clear(),
b.allPendingTasks--,0===b.allPendingTasks&&(d=b.onAllReady,d()))}function fa(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&fa(a,c)}else a.completedSegments.push(b)}function vb(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error(n(389));a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=R,b=a.onShellReady,b())}else b.pendingTasks--,
b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&fa(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(Lc,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&1===c.status&&(fa(b,c),1===b.completedSegments.length&&b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}function pb(a){if(2!==a.status){var b=K,c=za.current;za.current=xb;var d=ha;ha=a.responseState;try{var f=a.pingedTasks,
e;for(e=0;e<f.length;e++){var h=f[e];var g=a,k=h.blockedSegment;if(0===k.status){X(h.context);try{x(g,h,h.node),k.lastPushedText&&k.textEmbedded&&k.chunks.push(ka),h.abortSet.delete(h),k.status=1,vb(g,h.blockedBoundary,k)}catch(H){if(ua(),"object"===typeof H&&null!==H&&"function"===typeof H.then){var l=h.ping;H.then(l,l)}else{h.abortSet.delete(h);k.status=4;var q=h.blockedBoundary,n=H,p=S(g,n);null===q?ea(g,n):(q.pendingTasks--,q.forceClientRender||(q.forceClientRender=!0,q.errorDigest=p,q.parentFlushed&&
g.clientRenderedBoundaries.push(q)));g.allPendingTasks--;if(0===g.allPendingTasks){var r=g.onAllReady;r()}}}finally{}}}f.splice(0,e);null!==a.destination&&Aa(a,a.destination)}catch(H){S(a,H),ea(a,H)}finally{ha=d,za.current=c,c===xb&&X(b)}}}function ia(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;k(b,Mc);k(b,a.placeholderPrefix);a=p(d.toString(16));k(b,a);return r(b,Nc);case 1:c.status=2;var f=!0;d=c.chunks;var e=
0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)k(b,d[e]);f=ja(a,b,f)}for(;e<d.length-1;e++)k(b,d[e]);e<d.length&&(f=r(b,d[e]));return f;default:throw Error(n(390));}}function ja(a,b,c){var d=c.boundary;if(null===d)return ia(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)d=d.errorDigest,r(b,Oc),k(b,Pc),d&&(k(b,Qc),k(b,p(u(d))),k(b,Rc)),r(b,Sc),ia(a,b,c);else if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=
a.responseState;var e=f.nextSuspenseID++;f=g(f.boundaryPrefix+e.toString(16));d=d.id=f;Ta(b,a.responseState,d);ia(a,b,c)}else if(d.byteSize>a.progressiveChunkSize)d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),Ta(b,a.responseState,d.id),ia(a,b,c);else{r(b,Tc);c=d.completedSegments;if(1!==c.length)throw Error(n(391));ja(a,b,c[0])}return r(b,Uc)}function yb(a,b,c){Xb(b,a.responseState,c.formatContext,c.id);ja(a,b,c);return lc(b,c.formatContext)}function zb(a,b,c){for(var d=c.completedSegments,
f=0;f<d.length;f++)Ab(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;k(b,a.startInlineScript);a.sentCompleteBoundaryFunction?k(b,Vc):(a.sentCompleteBoundaryFunction=!0,k(b,Wc));if(null===d)throw Error(n(395));c=p(c.toString(16));k(b,d);k(b,Xc);k(b,a.segmentPrefix);k(b,c);return r(b,Yc)}function Ab(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error(n(392));return yb(a,b,d)}yb(a,b,d);a=a.responseState;k(b,a.startInlineScript);a.sentCompleteSegmentFunction?
k(b,Zc):(a.sentCompleteSegmentFunction=!0,k(b,$c));k(b,a.segmentPrefix);f=p(f.toString(16));k(b,f);k(b,ad);k(b,a.placeholderPrefix);k(b,f);return r(b,bd)}function Aa(a,b){B=new Uint8Array(512);A=0;try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){ja(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)k(b,d[c]);c<d.length&&r(b,d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var m=a.responseState,l=g.id,
t=g.errorDigest,q=g.errorMessage,u=g.errorComponentStack;k(d,m.startInlineScript);m.sentClientRenderFunction?k(d,cd):(m.sentClientRenderFunction=!0,k(d,dd));if(null===l)throw Error(n(395));k(d,l);k(d,ed);if(t||q||u)k(d,Ba),k(d,p(pa(t||"")));if(q||u)k(d,Ba),k(d,p(pa(q||"")));u&&(k(d,Ba),k(d,p(pa(u))));if(!r(d,fd)){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e);var v=a.completedBoundaries;for(e=0;e<v.length;e++)if(!zb(a,b,v[e])){a.destination=null;e++;v.splice(0,e);return}v.splice(0,e);
Ea(b);B=new Uint8Array(512);A=0;var w=a.partialBoundaries;for(e=0;e<w.length;e++){var y=w[e];a:{f=a;g=b;var x=y.completedSegments;for(m=0;m<x.length;m++)if(!Ab(f,g,y,x[m])){m++;x.splice(0,m);var C=!1;break a}x.splice(0,m);C=!0}if(!C){a.destination=null;e++;w.splice(0,e);return}}w.splice(0,e);var z=a.completedBoundaries;for(e=0;e<z.length;e++)if(!zb(a,b,z[e])){a.destination=null;e++;z.splice(0,e);return}z.splice(0,e)}finally{Ea(b),0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&
0===a.completedBoundaries.length&&b.close()}}function Bb(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return wb(c,a,b)});c.clear();null!==a.destination&&Aa(a,a.destination)}catch(d){S(a,d),ea(a,d)}}var B=null,A=0,Fa=new TextEncoder,w=Object.prototype.hasOwnProperty,Cb=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,
Ja={},Ia={},t={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){t[a]=new v(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];t[b]=new v(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){t[a]=new v(a,2,!1,a.toLowerCase(),null,
!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){t[a]=new v(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){t[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(a){t[a]=
new v(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){t[a]=new v(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){t[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){t[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var Ca=/[\-:]([a-z])/g,Da=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
a.replace(Ca,Da);t[b]=new v(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Ca,Da);t[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Ca,Da);t[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){t[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});t.xlinkHref=new v("xlinkHref",
1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){t[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});var U={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,
gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},gd=["Webkit","ms","Moz","O"];Object.keys(U).forEach(function(a){gd.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);U[b]=U[a]})});var Db=/["'&<>]/,Nb=/([A-Z])/g,Ob=/^ms-/,ma=Array.isArray,
Fb=g("<script>"),Ib=g("\x3c/script>"),Jb=g('<script src="'),Kb=g('<script type="module" src="'),Ka=g('" async="">\x3c/script>'),Gb=/(<\/|<)(s)(cript)/gi,Hb=function(a,b,c,d){return""+b+("s"===c?"\\u0073":"\\u0053")+d},ka=g("\x3c!-- --\x3e"),Na=new Map,Pb=g(' style="'),Oa=g(":"),Qb=g(";"),E=g(" "),N=g('="'),J=g('"'),Pa=g('=""'),F=g(">"),Ra=g("/>"),na=g(' selected=""'),oa=g("\n"),Sb=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Qa=new Map,Ub=g("<!DOCTYPE html>"),Ec=g("</"),Fc=g(">"),Mc=g('<template id="'),Nc=g('"></template>'),
Tc=g("\x3c!--$--\x3e"),Vb=g('\x3c!--$?--\x3e<template id="'),Wb=g('"></template>'),Oc=g("\x3c!--$!--\x3e"),Uc=g("\x3c!--/$--\x3e"),Pc=g("<template"),Rc=g('"'),Qc=g(' data-dgst="');g(' data-msg="');g(' data-stck="');var Sc=g("></template>"),Yb=g('<div hidden id="'),Zb=g('">'),mc=g("</div>"),$b=g('<svg aria-hidden="true" style="display:none" id="'),ac=g('">'),nc=g("</svg>"),bc=g('<math aria-hidden="true" style="display:none" id="'),cc=g('">'),oc=g("</math>"),dc=g('<table hidden id="'),ec=g('">'),pc=
g("</table>"),fc=g('<table hidden><tbody id="'),gc=g('">'),qc=g("</tbody></table>"),hc=g('<table hidden><tr id="'),ic=g('">'),rc=g("</tr></table>"),jc=g('<table hidden><colgroup id="'),kc=g('">'),sc=g("</colgroup></table>"),$c=g('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),Zc=g('$RS("'),ad=g('","'),bd=g('")\x3c/script>'),Wc=g('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),
Vc=g('$RC("'),Xc=g('","'),Yc=g('")\x3c/script>'),dd=g('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),cd=g('$RX("'),ed=g('"'),fd=g(")\x3c/script>"),Ba=g(","),tc=/[<\u2028\u2029]/g,P=Object.assign,Kc=Symbol.for("react.element"),Va=Symbol.for("react.portal"),Ua=Symbol.for("react.fragment"),Xa=Symbol.for("react.strict_mode"),Wa=Symbol.for("react.profiler"),ab=Symbol.for("react.provider"),
$a=Symbol.for("react.context"),bb=Symbol.for("react.forward_ref"),Ya=Symbol.for("react.suspense"),Za=Symbol.for("react.suspense_list"),cb=Symbol.for("react.memo"),ra=Symbol.for("react.lazy"),Ic=Symbol.for("react.scope"),Hc=Symbol.for("react.debug_trace_mode"),Gc=Symbol.for("react.legacy_hidden"),Jc=Symbol.for("react.default_value"),ub=Symbol.iterator,eb={},K=null,kb={isMounted:function(a){return!1},enqueueSetState:function(a,b,c){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,
b,c){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(a,b){}},Dc={id:1,overflow:""},Y=Math.clz32?Math.clz32:uc,vc=Math.log,wc=Math.LN2,zc="function"===typeof Object.is?Object.is:xc,D=null,va=null,aa=null,l=null,Q=!1,ba=!1,T=0,G=null,Z=0,xb={readContext:function(a){return a._currentValue},useContext:function(a){L();return a._currentValue},useMemo:ob,useReducer:nb,useRef:function(a){D=L();l=ta();var b=l.memoizedState;return null===b?(a={current:a},l.memoizedState=a):b},useState:function(a){return nb(mb,
a)},useInsertionEffect:ca,useLayoutEffect:function(a,b){},useCallback:function(a,b){return ob(function(){return a},b)},useImperativeHandle:ca,useEffect:ca,useDebugValue:ca,useDeferredValue:function(a){L();return a},useTransition:function(){L();return[!1,Ac]},useId:function(){var a=va.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-Y(a)-1)).toString(32)+b;var c=ha;if(null===c)throw Error(n(404));b=T++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b,
c){L();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error(n(407));return c()}},ha=null,za=M.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;I.renderToReadableStream=function(a,b){return new Promise(function(c,d){var f,e,g=new Promise(function(a,b){e=a;f=b}),k=Cc(a,Eb(b?b.identifierPrefix:void 0,b?b.nonce:void 0,b?b.bootstrapScriptContent:void 0,b?b.bootstrapScripts:void 0,b?b.bootstrapModules:void 0),Lb(b?b.namespaceURI:void 0),b?b.progressiveChunkSize:
void 0,b?b.onError:void 0,e,function(){var a=new ReadableStream({type:"bytes",pull:function(a){if(1===k.status)k.status=2,Ga(a,k.fatalError);else if(2!==k.status&&null===k.destination){k.destination=a;try{Aa(k,a)}catch(Sa){S(k,Sa),ea(k,Sa)}}},cancel:function(a){Bb(k)}},{highWaterMark:0});a.allReady=g;c(a)},function(a){g.catch(function(){});d(a)},f);if(b&&b.signal){var l=b.signal,n=function(){Bb(k,l.reason);l.removeEventListener("abort",n)};l.addEventListener("abort",n)}pb(k)})};I.version="18.3.1"});
})();
/**
 * @license React
 * react-dom-test-utils.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
  (global = global || self, factory(global.ReactTestUtils = {}, global.React, global.ReactDOM));
}(this, (function (exports, React, ReactDOM) { 'use strict';

  var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

  // by calls to these methods by a Babel plugin.
  //
  // In PROD (or in packages without access to React internals),
  // they are left as they are instead.

  function warn(format) {
    {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }
  }
  function error(format) {
    {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }
  }

  function printWarning(level, format, args) {
    // When changing this logic, you might want to also
    // update consoleWithStackDev.www.js as well.
    {
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var stack = ReactDebugCurrentFrame.getStackAddendum();

      if (stack !== '') {
        format += '%s';
        args = args.concat([stack]);
      } // eslint-disable-next-line react-internal/safe-string-coercion


      var argsWithFormat = args.map(function (item) {
        return String(item);
      }); // Careful: RN currently depends on this prefix

      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
      // breaks IE9: https://github.com/facebook/react/issues/13610
      // eslint-disable-next-line react-internal/no-production-logging

      Function.prototype.apply.call(console[level], console, argsWithFormat);
    }
  }

  /**
   * `ReactInstanceMap` maintains a mapping from a public facing stateful
   * instance (key) and the internal representation (value). This allows public
   * methods to accept the user facing instance as an argument and map them back
   * to internal methods.
   *
   * Note that this module is currently shared and assumed to be stateless.
   * If this becomes an actual Map, that will break.
   */
  function get(key) {
    return key._reactInternals;
  }

  var FunctionComponent = 0;
  var ClassComponent = 1;

  var HostRoot = 3; // Root of a host tree. Could be nested inside another node.

  var HostComponent = 5;
  var HostText = 6;

  // Don't change these two values. They're used by React Dev Tools.
  var NoFlags =
  /*                      */
  0;

  var Placement =
  /*                    */
  2;
  var Hydrating =
  /*                    */
  4096;

  var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  function getNearestMountedFiber(fiber) {
    var node = fiber;
    var nearestMounted = fiber;

    if (!fiber.alternate) {
      // If there is no alternate, this might be a new tree that isn't inserted
      // yet. If it is, then it will have a pending insertion effect on it.
      var nextNode = node;

      do {
        node = nextNode;

        if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
          // This is an insertion or in-progress hydration. The nearest possible
          // mounted fiber is the parent but we need to continue to figure out
          // if that one is still mounted.
          nearestMounted = node.return;
        }

        nextNode = node.return;
      } while (nextNode);
    } else {
      while (node.return) {
        node = node.return;
      }
    }

    if (node.tag === HostRoot) {
      // TODO: Check if this was a nested HostRoot when used with
      // renderContainerIntoSubtree.
      return nearestMounted;
    } // If we didn't hit the root, that means that we're in an disconnected tree
    // that has been unmounted.


    return null;
  }

  function assertIsMounted(fiber) {
    if (getNearestMountedFiber(fiber) !== fiber) {
      throw new Error('Unable to find node on an unmounted component.');
    }
  }

  function findCurrentFiberUsingSlowPath(fiber) {
    var alternate = fiber.alternate;

    if (!alternate) {
      // If there is no alternate, then we only need to check if it is mounted.
      var nearestMounted = getNearestMountedFiber(fiber);

      if (nearestMounted === null) {
        throw new Error('Unable to find node on an unmounted component.');
      }

      if (nearestMounted !== fiber) {
        return null;
      }

      return fiber;
    } // If we have two possible branches, we'll walk backwards up to the root
    // to see what path the root points to. On the way we may hit one of the
    // special cases and we'll deal with them.


    var a = fiber;
    var b = alternate;

    while (true) {
      var parentA = a.return;

      if (parentA === null) {
        // We're at the root.
        break;
      }

      var parentB = parentA.alternate;

      if (parentB === null) {
        // There is no alternate. This is an unusual case. Currently, it only
        // happens when a Suspense component is hidden. An extra fragment fiber
        // is inserted in between the Suspense fiber and its children. Skip
        // over this extra fragment fiber and proceed to the next parent.
        var nextParent = parentA.return;

        if (nextParent !== null) {
          a = b = nextParent;
          continue;
        } // If there's no parent, we're at the root.


        break;
      } // If both copies of the parent fiber point to the same child, we can
      // assume that the child is current. This happens when we bailout on low
      // priority: the bailed out fiber's child reuses the current child.


      if (parentA.child === parentB.child) {
        var child = parentA.child;

        while (child) {
          if (child === a) {
            // We've determined that A is the current branch.
            assertIsMounted(parentA);
            return fiber;
          }

          if (child === b) {
            // We've determined that B is the current branch.
            assertIsMounted(parentA);
            return alternate;
          }

          child = child.sibling;
        } // We should never have an alternate for any mounting node. So the only
        // way this could possibly happen is if this was unmounted, if at all.


        throw new Error('Unable to find node on an unmounted component.');
      }

      if (a.return !== b.return) {
        // The return pointer of A and the return pointer of B point to different
        // fibers. We assume that return pointers never criss-cross, so A must
        // belong to the child set of A.return, and B must belong to the child
        // set of B.return.
        a = parentA;
        b = parentB;
      } else {
        // The return pointers point to the same fiber. We'll have to use the
        // default, slow path: scan the child sets of each parent alternate to see
        // which child belongs to which set.
        //
        // Search parent A's child set
        var didFindChild = false;
        var _child = parentA.child;

        while (_child) {
          if (_child === a) {
            didFindChild = true;
            a = parentA;
            b = parentB;
            break;
          }

          if (_child === b) {
            didFindChild = true;
            b = parentA;
            a = parentB;
            break;
          }

          _child = _child.sibling;
        }

        if (!didFindChild) {
          // Search parent B's child set
          _child = parentB.child;

          while (_child) {
            if (_child === a) {
              didFindChild = true;
              a = parentB;
              b = parentA;
              break;
            }

            if (_child === b) {
              didFindChild = true;
              b = parentB;
              a = parentA;
              break;
            }

            _child = _child.sibling;
          }

          if (!didFindChild) {
            throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
          }
        }
      }

      if (a.alternate !== b) {
        throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
      }
    } // If the root is not a host container, we're in a disconnected tree. I.e.
    // unmounted.


    if (a.tag !== HostRoot) {
      throw new Error('Unable to find node on an unmounted component.');
    }

    if (a.stateNode.current === a) {
      // We've determined that A is the current branch.
      return fiber;
    } // Otherwise B has to be current branch.


    return alternate;
  }

  var assign = Object.assign;

  /**
   * `charCode` represents the actual "character code" and is safe to use with
   * `String.fromCharCode`. As such, only keys that correspond to printable
   * characters produce a valid `charCode`, the only exception to this is Enter.
   * The Tab-key is considered non-printable and does not have a `charCode`,
   * presumably because it does not produce a tab-character in browsers.
   *
   * @param {object} nativeEvent Native browser event.
   * @return {number} Normalized `charCode` property.
   */
  function getEventCharCode(nativeEvent) {
    var charCode;
    var keyCode = nativeEvent.keyCode;

    if ('charCode' in nativeEvent) {
      charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.

      if (charCode === 0 && keyCode === 13) {
        charCode = 13;
      }
    } else {
      // IE8 does not implement `charCode`, but `keyCode` has the correct value.
      charCode = keyCode;
    } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
    // report Enter as charCode 10 when ctrl is pressed.


    if (charCode === 10) {
      charCode = 13;
    } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
    // Must not discard the (non-)printable Enter-key.


    if (charCode >= 32 || charCode === 13) {
      return charCode;
    }

    return 0;
  }

  function functionThatReturnsTrue() {
    return true;
  }

  function functionThatReturnsFalse() {
    return false;
  } // This is intentionally a factory so that we have different returned constructors.
  // If we had a single constructor, it would be megamorphic and engines would deopt.


  function createSyntheticEvent(Interface) {
    /**
     * Synthetic events are dispatched by event plugins, typically in response to a
     * top-level event delegation handler.
     *
     * These systems should generally use pooling to reduce the frequency of garbage
     * collection. The system should check `isPersistent` to determine whether the
     * event should be released into the pool after being dispatched. Users that
     * need a persisted event should invoke `persist`.
     *
     * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
     * normalizing browser quirks. Subclasses do not necessarily have to implement a
     * DOM interface; custom application-specific events can also subclass this.
     */
    function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
      this._reactName = reactName;
      this._targetInst = targetInst;
      this.type = reactEventType;
      this.nativeEvent = nativeEvent;
      this.target = nativeEventTarget;
      this.currentTarget = null;

      for (var _propName in Interface) {
        if (!Interface.hasOwnProperty(_propName)) {
          continue;
        }

        var normalize = Interface[_propName];

        if (normalize) {
          this[_propName] = normalize(nativeEvent);
        } else {
          this[_propName] = nativeEvent[_propName];
        }
      }

      var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;

      if (defaultPrevented) {
        this.isDefaultPrevented = functionThatReturnsTrue;
      } else {
        this.isDefaultPrevented = functionThatReturnsFalse;
      }

      this.isPropagationStopped = functionThatReturnsFalse;
      return this;
    }

    assign(SyntheticBaseEvent.prototype, {
      preventDefault: function () {
        this.defaultPrevented = true;
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.preventDefault) {
          event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
        } else if (typeof event.returnValue !== 'unknown') {
          event.returnValue = false;
        }

        this.isDefaultPrevented = functionThatReturnsTrue;
      },
      stopPropagation: function () {
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.stopPropagation) {
          event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
        } else if (typeof event.cancelBubble !== 'unknown') {
          // The ChangeEventPlugin registers a "propertychange" event for
          // IE. This event does not support bubbling or cancelling, and
          // any references to cancelBubble throw "Member not found".  A
          // typeof check of "unknown" circumvents this issue (and is also
          // IE specific).
          event.cancelBubble = true;
        }

        this.isPropagationStopped = functionThatReturnsTrue;
      },

      /**
       * We release all dispatched `SyntheticEvent`s after each event loop, adding
       * them back into the pool. This allows a way to hold onto a reference that
       * won't be added back into the pool.
       */
      persist: function () {// Modern event system doesn't use pooling.
      },

      /**
       * Checks if this event should be released back into the pool.
       *
       * @return {boolean} True if this should not be released, false otherwise.
       */
      isPersistent: functionThatReturnsTrue
    });
    return SyntheticBaseEvent;
  }
  /**
   * @interface Event
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var EventInterface = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function (event) {
      return event.timeStamp || Date.now();
    },
    defaultPrevented: 0,
    isTrusted: 0
  };
  var SyntheticEvent = createSyntheticEvent(EventInterface);

  var UIEventInterface = assign({}, EventInterface, {
    view: 0,
    detail: 0
  });

  var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
  var lastMovementX;
  var lastMovementY;
  var lastMouseEvent;

  function updateMouseMovementPolyfillState(event) {
    if (event !== lastMouseEvent) {
      if (lastMouseEvent && event.type === 'mousemove') {
        lastMovementX = event.screenX - lastMouseEvent.screenX;
        lastMovementY = event.screenY - lastMouseEvent.screenY;
      } else {
        lastMovementX = 0;
        lastMovementY = 0;
      }

      lastMouseEvent = event;
    }
  }
  /**
   * @interface MouseEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var MouseEventInterface = assign({}, UIEventInterface, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: getEventModifierState,
    button: 0,
    buttons: 0,
    relatedTarget: function (event) {
      if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
      return event.relatedTarget;
    },
    movementX: function (event) {
      if ('movementX' in event) {
        return event.movementX;
      }

      updateMouseMovementPolyfillState(event);
      return lastMovementX;
    },
    movementY: function (event) {
      if ('movementY' in event) {
        return event.movementY;
      } // Don't need to call updateMouseMovementPolyfillState() here
      // because it's guaranteed to have already run when movementX
      // was copied.


      return lastMovementY;
    }
  });

  var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
  /**
   * @interface DragEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var DragEventInterface = assign({}, MouseEventInterface, {
    dataTransfer: 0
  });

  var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
  /**
   * @interface FocusEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var FocusEventInterface = assign({}, UIEventInterface, {
    relatedTarget: 0
  });

  var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
   * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
   */

  var AnimationEventInterface = assign({}, EventInterface, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  });

  var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/clipboard-apis/
   */

  var ClipboardEventInterface = assign({}, EventInterface, {
    clipboardData: function (event) {
      return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
    }
  });

  var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
   */

  var CompositionEventInterface = assign({}, EventInterface, {
    data: 0
  });

  var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
  /**
   * Normalization of deprecated HTML5 `key` values
   * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
   */

  var normalizeKey = {
    Esc: 'Escape',
    Spacebar: ' ',
    Left: 'ArrowLeft',
    Up: 'ArrowUp',
    Right: 'ArrowRight',
    Down: 'ArrowDown',
    Del: 'Delete',
    Win: 'OS',
    Menu: 'ContextMenu',
    Apps: 'ContextMenu',
    Scroll: 'ScrollLock',
    MozPrintableKey: 'Unidentified'
  };
  /**
   * Translation from legacy `keyCode` to HTML5 `key`
   * Only special keys supported, all others depend on keyboard layout or browser
   * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
   */

  var translateToKey = {
    '8': 'Backspace',
    '9': 'Tab',
    '12': 'Clear',
    '13': 'Enter',
    '16': 'Shift',
    '17': 'Control',
    '18': 'Alt',
    '19': 'Pause',
    '20': 'CapsLock',
    '27': 'Escape',
    '32': ' ',
    '33': 'PageUp',
    '34': 'PageDown',
    '35': 'End',
    '36': 'Home',
    '37': 'ArrowLeft',
    '38': 'ArrowUp',
    '39': 'ArrowRight',
    '40': 'ArrowDown',
    '45': 'Insert',
    '46': 'Delete',
    '112': 'F1',
    '113': 'F2',
    '114': 'F3',
    '115': 'F4',
    '116': 'F5',
    '117': 'F6',
    '118': 'F7',
    '119': 'F8',
    '120': 'F9',
    '121': 'F10',
    '122': 'F11',
    '123': 'F12',
    '144': 'NumLock',
    '145': 'ScrollLock',
    '224': 'Meta'
  };
  /**
   * @param {object} nativeEvent Native browser event.
   * @return {string} Normalized `key` property.
   */

  function getEventKey(nativeEvent) {
    if (nativeEvent.key) {
      // Normalize inconsistent values reported by browsers due to
      // implementations of a working draft specification.
      // FireFox implements `key` but returns `MozPrintableKey` for all
      // printable characters (normalized to `Unidentified`), ignore it.
      var key = normalizeKey[nativeEvent.key] || nativeEvent.key;

      if (key !== 'Unidentified') {
        return key;
      }
    } // Browser does not implement `key`, polyfill as much of it as we can.


    if (nativeEvent.type === 'keypress') {
      var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
      // thus be captured by `keypress`, no other non-printable key should.

      return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
    }

    if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
      // While user keyboard layout determines the actual meaning of each
      // `keyCode` value, almost all function keys have a universal value.
      return translateToKey[nativeEvent.keyCode] || 'Unidentified';
    }

    return '';
  }
  /**
   * Translation from modifier key to the associated property in the event.
   * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
   */


  var modifierKeyToProp = {
    Alt: 'altKey',
    Control: 'ctrlKey',
    Meta: 'metaKey',
    Shift: 'shiftKey'
  }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
  // getModifierState. If getModifierState is not supported, we map it to a set of
  // modifier keys exposed by the event. In this case, Lock-keys are not supported.

  function modifierStateGetter(keyArg) {
    var syntheticEvent = this;
    var nativeEvent = syntheticEvent.nativeEvent;

    if (nativeEvent.getModifierState) {
      return nativeEvent.getModifierState(keyArg);
    }

    var keyProp = modifierKeyToProp[keyArg];
    return keyProp ? !!nativeEvent[keyProp] : false;
  }

  function getEventModifierState(nativeEvent) {
    return modifierStateGetter;
  }
  /**
   * @interface KeyboardEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var KeyboardEventInterface = assign({}, UIEventInterface, {
    key: getEventKey,
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: getEventModifierState,
    // Legacy Interface
    charCode: function (event) {
      // `charCode` is the result of a KeyPress event and represents the value of
      // the actual printable character.
      // KeyPress is deprecated, but its replacement is not yet final and not
      // implemented in any major browser. Only KeyPress has charCode.
      if (event.type === 'keypress') {
        return getEventCharCode(event);
      }

      return 0;
    },
    keyCode: function (event) {
      // `keyCode` is the result of a KeyDown/Up event and represents the value of
      // physical keyboard key.
      // The actual meaning of the value depends on the users' keyboard layout
      // which cannot be detected. Assuming that it is a US keyboard layout
      // provides a surprisingly accurate mapping for US and European users.
      // Due to this, it is left to the user to implement at this time.
      if (event.type === 'keydown' || event.type === 'keyup') {
        return event.keyCode;
      }

      return 0;
    },
    which: function (event) {
      // `which` is an alias for either `keyCode` or `charCode` depending on the
      // type of the event.
      if (event.type === 'keypress') {
        return getEventCharCode(event);
      }

      if (event.type === 'keydown' || event.type === 'keyup') {
        return event.keyCode;
      }

      return 0;
    }
  });

  var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
  /**
   * @interface PointerEvent
   * @see http://www.w3.org/TR/pointerevents/
   */

  var PointerEventInterface = assign({}, MouseEventInterface, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
  });

  var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
  /**
   * @interface TouchEvent
   * @see http://www.w3.org/TR/touch-events/
   */

  var TouchEventInterface = assign({}, UIEventInterface, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: getEventModifierState
  });

  var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
   * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
   */

  var TransitionEventInterface = assign({}, EventInterface, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  });

  var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
  /**
   * @interface WheelEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var WheelEventInterface = assign({}, MouseEventInterface, {
    deltaX: function (event) {
      return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
      'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
    },
    deltaY: function (event) {
      return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
      'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
      'wheelDelta' in event ? -event.wheelDelta : 0;
    },
    deltaZ: 0,
    // Browsers without "deltaMode" is reporting in raw wheel delta where one
    // notch on the scroll is always +/- 120, roughly equivalent to pixels.
    // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
    // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
    deltaMode: 0
  });

  var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);

  /**
   * HTML nodeType values that represent the type of the node
   */
  var ELEMENT_NODE = 1;

  function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
    var funcArgs = Array.prototype.slice.call(arguments, 3);

    try {
      func.apply(context, funcArgs);
    } catch (error) {
      this.onError(error);
    }
  }

  var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;

  {
    // In DEV mode, we swap out invokeGuardedCallback for a special version
    // that plays more nicely with the browser's DevTools. The idea is to preserve
    // "Pause on exceptions" behavior. Because React wraps all user-provided
    // functions in invokeGuardedCallback, and the production version of
    // invokeGuardedCallback uses a try-catch, all user exceptions are treated
    // like caught exceptions, and the DevTools won't pause unless the developer
    // takes the extra step of enabling pause on caught exceptions. This is
    // unintuitive, though, because even though React has caught the error, from
    // the developer's perspective, the error is uncaught.
    //
    // To preserve the expected "Pause on exceptions" behavior, we don't use a
    // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
    // DOM node, and call the user-provided callback from inside an event handler
    // for that fake event. If the callback throws, the error is "captured" using
    // a global event handler. But because the error happens in a different
    // event loop context, it does not interrupt the normal program flow.
    // Effectively, this gives us try-catch behavior without actually using
    // try-catch. Neat!
    // Check that the browser supports the APIs we need to implement our special
    // DEV version of invokeGuardedCallback
    if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
      var fakeNode = document.createElement('react');

      invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
        // If document doesn't exist we know for sure we will crash in this method
        // when we call document.createEvent(). However this can cause confusing
        // errors: https://github.com/facebook/create-react-app/issues/3482
        // So we preemptively throw with a better message instead.
        if (typeof document === 'undefined' || document === null) {
          throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
        }

        var evt = document.createEvent('Event');
        var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
        // set this to true at the beginning, then set it to false right after
        // calling the function. If the function errors, `didError` will never be
        // set to false. This strategy works even if the browser is flaky and
        // fails to call our global error handler, because it doesn't rely on
        // the error event at all.

        var didError = true; // Keeps track of the value of window.event so that we can reset it
        // during the callback to let user code access window.event in the
        // browsers that support it.

        var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
        // dispatching: https://github.com/facebook/react/issues/13688

        var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');

        function restoreAfterDispatch() {
          // We immediately remove the callback from event listeners so that
          // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
          // nested call would trigger the fake event handlers of any call higher
          // in the stack.
          fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
          // window.event assignment in both IE <= 10 as they throw an error
          // "Member not found" in strict mode, and in Firefox which does not
          // support window.event.

          if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
            window.event = windowEvent;
          }
        } // Create an event handler for our fake event. We will synchronously
        // dispatch our fake event using `dispatchEvent`. Inside the handler, we
        // call the user-provided callback.


        var funcArgs = Array.prototype.slice.call(arguments, 3);

        function callCallback() {
          didCall = true;
          restoreAfterDispatch();
          func.apply(context, funcArgs);
          didError = false;
        } // Create a global error event handler. We use this to capture the value
        // that was thrown. It's possible that this error handler will fire more
        // than once; for example, if non-React code also calls `dispatchEvent`
        // and a handler for that event throws. We should be resilient to most of
        // those cases. Even if our error event handler fires more than once, the
        // last error event is always used. If the callback actually does error,
        // we know that the last error event is the correct one, because it's not
        // possible for anything else to have happened in between our callback
        // erroring and the code that follows the `dispatchEvent` call below. If
        // the callback doesn't error, but the error event was fired, we know to
        // ignore it because `didError` will be false, as described above.


        var error; // Use this to track whether the error event is ever called.

        var didSetError = false;
        var isCrossOriginError = false;

        function handleWindowError(event) {
          error = event.error;
          didSetError = true;

          if (error === null && event.colno === 0 && event.lineno === 0) {
            isCrossOriginError = true;
          }

          if (event.defaultPrevented) {
            // Some other error handler has prevented default.
            // Browsers silence the error report if this happens.
            // We'll remember this to later decide whether to log it or not.
            if (error != null && typeof error === 'object') {
              try {
                error._suppressLogging = true;
              } catch (inner) {// Ignore.
              }
            }
          }
        } // Create a fake event type.


        var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers

        window.addEventListener('error', handleWindowError);
        fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
        // errors, it will trigger our global error handler.

        evt.initEvent(evtType, false, false);
        fakeNode.dispatchEvent(evt);

        if (windowEventDescriptor) {
          Object.defineProperty(window, 'event', windowEventDescriptor);
        }

        if (didCall && didError) {
          if (!didSetError) {
            // The callback errored, but the error event never fired.
            // eslint-disable-next-line react-internal/prod-error-codes
            error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
          } else if (isCrossOriginError) {
            // eslint-disable-next-line react-internal/prod-error-codes
            error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
          }

          this.onError(error);
        } // Remove our event listeners


        window.removeEventListener('error', handleWindowError);

        if (!didCall) {
          // Something went really wrong, and our event was not dispatched.
          // https://github.com/facebook/react/issues/16734
          // https://github.com/facebook/react/issues/16585
          // Fall back to the production implementation.
          restoreAfterDispatch();
          return invokeGuardedCallbackProd.apply(this, arguments);
        }
      };
    }
  }

  var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;

  var hasError = false;
  var caughtError = null; // Used by event system to capture/rethrow the first error.

  var hasRethrowError = false;
  var rethrowError = null;
  var reporter = {
    onError: function (error) {
      hasError = true;
      caughtError = error;
    }
  };
  /**
   * Call a function while guarding against errors that happens within it.
   * Returns an error if it throws, otherwise null.
   *
   * In production, this is implemented using a try-catch. The reason we don't
   * use a try-catch directly is so that we can swap out a different
   * implementation in DEV mode.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */

  function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
    hasError = false;
    caughtError = null;
    invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  }
  /**
   * Same as invokeGuardedCallback, but instead of returning an error, it stores
   * it in a global so it can be rethrown by `rethrowCaughtError` later.
   * TODO: See if caughtError and rethrowError can be unified.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */

  function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
    invokeGuardedCallback.apply(this, arguments);

    if (hasError) {
      var error = clearCaughtError();

      if (!hasRethrowError) {
        hasRethrowError = true;
        rethrowError = error;
      }
    }
  }
  /**
   * During execution of guarded functions we will capture the first error which
   * we will rethrow to be handled by the top level error handler.
   */

  function rethrowCaughtError() {
    if (hasRethrowError) {
      var error = rethrowError;
      hasRethrowError = false;
      rethrowError = null;
      throw error;
    }
  }
  function clearCaughtError() {
    if (hasError) {
      var error = caughtError;
      hasError = false;
      caughtError = null;
      return error;
    } else {
      throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
    }
  }

  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

  function isArray(a) {
    return isArrayImpl(a);
  }

  var SecretInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  var EventInternals = SecretInternals.Events;
  var getInstanceFromNode = EventInternals[0];
  var getNodeFromInstance = EventInternals[1];
  var getFiberCurrentPropsFromNode = EventInternals[2];
  var enqueueStateRestore = EventInternals[3];
  var restoreStateIfNeeded = EventInternals[4];
  var reactAct = React.unstable_act;

  function Event(suffix) {}

  var hasWarnedAboutDeprecatedMockComponent = false;
  /**
   * @class ReactTestUtils
   */

  function findAllInRenderedFiberTreeInternal(fiber, test) {
    if (!fiber) {
      return [];
    }

    var currentParent = findCurrentFiberUsingSlowPath(fiber);

    if (!currentParent) {
      return [];
    }

    var node = currentParent;
    var ret = [];

    while (true) {
      if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
        var publicInst = node.stateNode;

        if (test(publicInst)) {
          ret.push(publicInst);
        }
      }

      if (node.child) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === currentParent) {
        return ret;
      }

      while (!node.sibling) {
        if (!node.return || node.return === currentParent) {
          return ret;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }
  }

  function validateClassInstance(inst, methodName) {
    if (!inst) {
      // This is probably too relaxed but it's existing behavior.
      return;
    }

    if (get(inst)) {
      // This is a public instance indeed.
      return;
    }

    var received;
    var stringified = String(inst);

    if (isArray(inst)) {
      received = 'an array';
    } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
      received = 'a DOM node';
    } else if (stringified === '[object Object]') {
      received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
    } else {
      received = stringified;
    }

    throw new Error(methodName + "(...): the first argument must be a React class instance. " + ("Instead received: " + received + "."));
  }
  /**
   * Utilities for making it easy to test React components.
   *
   * See https://reactjs.org/docs/test-utils.html
   *
   * Todo: Support the entire DOM.scry query syntax. For now, these simple
   * utilities will suffice for testing purposes.
   * @lends ReactTestUtils
   */


  var didWarnAboutReactTestUtilsDeprecation = false;

  function renderIntoDocument(element) {
    {
      if (!didWarnAboutReactTestUtilsDeprecation) {
        didWarnAboutReactTestUtilsDeprecation = true;

        error('ReactDOMTestUtils is deprecated and will be removed in a future ' + 'major release, because it exposes internal implementation details ' + 'that are highly likely to change between releases. Upgrade to a ' + 'modern testing library, such as @testing-library/react. See ' + 'https://react.dev/warnings/react-dom-test-utils for more info.');
      }
    }

    var div = document.createElement('div'); // None of our tests actually require attaching the container to the
    // DOM, and doing so creates a mess that we rely on test isolation to
    // clean up, so we're going to stop honoring the name of this method
    // (and probably rename it eventually) if no problems arise.
    // document.documentElement.appendChild(div);

    return ReactDOM.render(element, div);
  }

  function isElement(element) {
    return React.isValidElement(element);
  }

  function isElementOfType(inst, convenienceConstructor) {
    return React.isValidElement(inst) && inst.type === convenienceConstructor;
  }

  function isDOMComponent(inst) {
    return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  }

  function isDOMComponentElement(inst) {
    return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  }

  function isCompositeComponent(inst) {
    if (isDOMComponent(inst)) {
      // Accessing inst.setState warns; just return false as that'll be what
      // this returns when we have DOM nodes as refs directly
      return false;
    }

    return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  }

  function isCompositeComponentWithType(inst, type) {
    if (!isCompositeComponent(inst)) {
      return false;
    }

    var internalInstance = get(inst);
    var constructor = internalInstance.type;
    return constructor === type;
  }

  function findAllInRenderedTree(inst, test) {
    validateClassInstance(inst, 'findAllInRenderedTree');

    if (!inst) {
      return [];
    }

    var internalInstance = get(inst);
    return findAllInRenderedFiberTreeInternal(internalInstance, test);
  }
  /**
   * Finds all instances of components in the rendered tree that are DOM
   * components with the class name matching `className`.
   * @return {array} an array of all the matches.
   */


  function scryRenderedDOMComponentsWithClass(root, classNames) {
    validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
    return findAllInRenderedTree(root, function (inst) {
      if (isDOMComponent(inst)) {
        var className = inst.className;

        if (typeof className !== 'string') {
          // SVG, probably.
          className = inst.getAttribute('class') || '';
        }

        var classList = className.split(/\s+/);

        if (!isArray(classNames)) {
          if (classNames === undefined) {
            throw new Error('TestUtils.scryRenderedDOMComponentsWithClass expects a ' + 'className as a second argument.');
          }

          classNames = classNames.split(/\s+/);
        }

        return classNames.every(function (name) {
          return classList.indexOf(name) !== -1;
        });
      }

      return false;
    });
  }
  /**
   * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
   * and returns that one result, or throws exception if there is any other
   * number of matches besides one.
   * @return {!ReactDOMComponent} The one match.
   */


  function findRenderedDOMComponentWithClass(root, className) {
    validateClassInstance(root, 'findRenderedDOMComponentWithClass');
    var all = scryRenderedDOMComponentsWithClass(root, className);

    if (all.length !== 1) {
      throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
    }

    return all[0];
  }
  /**
   * Finds all instances of components in the rendered tree that are DOM
   * components with the tag name matching `tagName`.
   * @return {array} an array of all the matches.
   */


  function scryRenderedDOMComponentsWithTag(root, tagName) {
    validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
    return findAllInRenderedTree(root, function (inst) {
      return isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
    });
  }
  /**
   * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
   * and returns that one result, or throws exception if there is any other
   * number of matches besides one.
   * @return {!ReactDOMComponent} The one match.
   */


  function findRenderedDOMComponentWithTag(root, tagName) {
    validateClassInstance(root, 'findRenderedDOMComponentWithTag');
    var all = scryRenderedDOMComponentsWithTag(root, tagName);

    if (all.length !== 1) {
      throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
    }

    return all[0];
  }
  /**
   * Finds all instances of components with type equal to `componentType`.
   * @return {array} an array of all the matches.
   */


  function scryRenderedComponentsWithType(root, componentType) {
    validateClassInstance(root, 'scryRenderedComponentsWithType');
    return findAllInRenderedTree(root, function (inst) {
      return isCompositeComponentWithType(inst, componentType);
    });
  }
  /**
   * Same as `scryRenderedComponentsWithType` but expects there to be one result
   * and returns that one result, or throws exception if there is any other
   * number of matches besides one.
   * @return {!ReactComponent} The one match.
   */


  function findRenderedComponentWithType(root, componentType) {
    validateClassInstance(root, 'findRenderedComponentWithType');
    var all = scryRenderedComponentsWithType(root, componentType);

    if (all.length !== 1) {
      throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
    }

    return all[0];
  }
  /**
   * Pass a mocked component module to this method to augment it with
   * useful methods that allow it to be used as a dummy React component.
   * Instead of rendering as usual, the component will become a simple
   * <div> containing any provided children.
   *
   * @param {object} module the mock function object exported from a
   *                        module that defines the component to be mocked
   * @param {?string} mockTagName optional dummy root tag name to return
   *                              from render method (overrides
   *                              module.mockTagName if provided)
   * @return {object} the ReactTestUtils object (for chaining)
   */


  function mockComponent(module, mockTagName) {
    {
      if (!hasWarnedAboutDeprecatedMockComponent) {
        hasWarnedAboutDeprecatedMockComponent = true;

        warn('ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.');
      }
    }

    mockTagName = mockTagName || module.mockTagName || 'div';
    module.prototype.render.mockImplementation(function () {
      return React.createElement(mockTagName, null, this.props.children);
    });
    return this;
  }

  function nativeTouchData(x, y) {
    return {
      touches: [{
        pageX: x,
        pageY: y
      }]
    };
  } // Start of inline: the below functions were inlined from
  // EventPropagator.js, as they deviated from ReactDOM's newer
  // implementations.

  /**
   * Dispatch the event to the listener.
   * @param {SyntheticEvent} event SyntheticEvent to handle
   * @param {function} listener Application-level callback
   * @param {*} inst Internal component instance
   */


  function executeDispatch(event, listener, inst) {
    var type = event.type || 'unknown-event';
    event.currentTarget = getNodeFromInstance(inst);
    invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
    event.currentTarget = null;
  }
  /**
   * Standard/simple iteration through an event's collected dispatches.
   */


  function executeDispatchesInOrder(event) {
    var dispatchListeners = event._dispatchListeners;
    var dispatchInstances = event._dispatchInstances;

    if (isArray(dispatchListeners)) {
      for (var i = 0; i < dispatchListeners.length; i++) {
        if (event.isPropagationStopped()) {
          break;
        } // Listeners and Instances are two parallel arrays that are always in sync.


        executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
      }
    } else if (dispatchListeners) {
      executeDispatch(event, dispatchListeners, dispatchInstances);
    }

    event._dispatchListeners = null;
    event._dispatchInstances = null;
  }
  /**
   * Dispatches an event and releases it back into the pool, unless persistent.
   *
   * @param {?object} event Synthetic event to be dispatched.
   * @private
   */


  var executeDispatchesAndRelease = function (event) {
    if (event) {
      executeDispatchesInOrder(event);

      if (!event.isPersistent()) {
        event.constructor.release(event);
      }
    }
  };

  function isInteractive(tag) {
    return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
  }

  function getParent(inst) {
    do {
      inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
      // That is depending on if we want nested subtrees (layers) to bubble
      // events to their parent. We could also go through parentNode on the
      // host node but that wouldn't work for React Native and doesn't let us
      // do the portal feature.
    } while (inst && inst.tag !== HostComponent);

    if (inst) {
      return inst;
    }

    return null;
  }
  /**
   * Simulates the traversal of a two-phase, capture/bubble event dispatch.
   */


  function traverseTwoPhase(inst, fn, arg) {
    var path = [];

    while (inst) {
      path.push(inst);
      inst = getParent(inst);
    }

    var i;

    for (i = path.length; i-- > 0;) {
      fn(path[i], 'captured', arg);
    }

    for (i = 0; i < path.length; i++) {
      fn(path[i], 'bubbled', arg);
    }
  }

  function shouldPreventMouseEvent(name, type, props) {
    switch (name) {
      case 'onClick':
      case 'onClickCapture':
      case 'onDoubleClick':
      case 'onDoubleClickCapture':
      case 'onMouseDown':
      case 'onMouseDownCapture':
      case 'onMouseMove':
      case 'onMouseMoveCapture':
      case 'onMouseUp':
      case 'onMouseUpCapture':
      case 'onMouseEnter':
        return !!(props.disabled && isInteractive(type));

      default:
        return false;
    }
  }
  /**
   * @param {object} inst The instance, which is the source of events.
   * @param {string} registrationName Name of listener (e.g. `onClick`).
   * @return {?function} The stored callback.
   */


  function getListener(inst, registrationName) {
    // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
    // live here; needs to be moved to a better place soon
    var stateNode = inst.stateNode;

    if (!stateNode) {
      // Work in progress (ex: onload events in incremental mode).
      return null;
    }

    var props = getFiberCurrentPropsFromNode(stateNode);

    if (!props) {
      // Work in progress.
      return null;
    }

    var listener = props[registrationName];

    if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
      return null;
    }

    if (listener && typeof listener !== 'function') {
      throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
    }

    return listener;
  }

  function listenerAtPhase(inst, event, propagationPhase) {
    var registrationName = event._reactName;

    if (propagationPhase === 'captured') {
      registrationName += 'Capture';
    }

    return getListener(inst, registrationName);
  }

  function accumulateDispatches(inst, ignoredDirection, event) {
    if (inst && event && event._reactName) {
      var registrationName = event._reactName;
      var listener = getListener(inst, registrationName);

      if (listener) {
        if (event._dispatchListeners == null) {
          event._dispatchListeners = [];
        }

        if (event._dispatchInstances == null) {
          event._dispatchInstances = [];
        }

        event._dispatchListeners.push(listener);

        event._dispatchInstances.push(inst);
      }
    }
  }

  function accumulateDirectionalDispatches(inst, phase, event) {
    {
      if (!inst) {
        error('Dispatching inst must not be null');
      }
    }

    var listener = listenerAtPhase(inst, event, phase);

    if (listener) {
      if (event._dispatchListeners == null) {
        event._dispatchListeners = [];
      }

      if (event._dispatchInstances == null) {
        event._dispatchInstances = [];
      }

      event._dispatchListeners.push(listener);

      event._dispatchInstances.push(inst);
    }
  }

  function accumulateDirectDispatchesSingle(event) {
    if (event && event._reactName) {
      accumulateDispatches(event._targetInst, null, event);
    }
  }

  function accumulateTwoPhaseDispatchesSingle(event) {
    if (event && event._reactName) {
      traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
    }
  } // End of inline


  var Simulate = {};
  var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
  /**
   * Exports:
   *
   * - `Simulate.click(Element)`
   * - `Simulate.mouseMove(Element)`
   * - `Simulate.change(Element)`
   * - ... (All keys from event plugin `eventTypes` objects)
   */

  function makeSimulator(eventType) {
    return function (domNode, eventData) {
      if (React.isValidElement(domNode)) {
        throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a React element. Pass the DOM node you wish to simulate the event on instead. ' + 'Note that TestUtils.Simulate will not work if you are using shallow rendering.');
      }

      if (isCompositeComponent(domNode)) {
        throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a component instance. Pass the DOM node you wish to simulate the event on instead.');
      }

      var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
      var fakeNativeEvent = new Event();
      fakeNativeEvent.target = domNode;
      fakeNativeEvent.type = eventType.toLowerCase();
      var targetInst = getInstanceFromNode(domNode);
      var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
      // sure it's marked and won't warn when setting additional properties.

      event.persist();
      assign(event, eventData);

      if (directDispatchEventTypes.has(eventType)) {
        accumulateDirectDispatchesSingle(event);
      } else {
        accumulateTwoPhaseDispatchesSingle(event);
      }

      ReactDOM.unstable_batchedUpdates(function () {
        // Normally extractEvent enqueues a state restore, but we'll just always
        // do that since we're by-passing it here.
        enqueueStateRestore(domNode);
        executeDispatchesAndRelease(event);
        rethrowCaughtError();
      });
      restoreStateIfNeeded();
    };
  } // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.


  var simulatedEventTypes = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'auxClick', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'pointerCancel', 'pointerDown', 'pointerUp', 'rateChange', 'reset', 'resize', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'mouseMove', 'mouseOut', 'mouseOver', 'pointerMove', 'pointerOut', 'pointerOver', 'scroll', 'toggle', 'touchMove', 'wheel', 'abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'playing', 'progress', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'transitionEnd', 'waiting', 'mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave', 'change', 'select', 'beforeInput', 'compositionEnd', 'compositionStart', 'compositionUpdate'];

  function buildSimulators() {
    simulatedEventTypes.forEach(function (eventType) {
      Simulate[eventType] = makeSimulator(eventType);
    });
  }

  buildSimulators();
  var didWarnAboutUsingAct = false;
  var act =  function actWithWarning(callback) {
    {
      if (!didWarnAboutUsingAct) {
        didWarnAboutUsingAct = true;

        error('`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. ' + 'Import `act` from `react` instead of `react-dom/test-utils`. ' + 'See https://react.dev/warnings/react-dom-test-utils for more info.');
      }
    }

    return reactAct(callback);
  } ;

  exports.Simulate = Simulate;
  exports.act = act;
  exports.findAllInRenderedTree = findAllInRenderedTree;
  exports.findRenderedComponentWithType = findRenderedComponentWithType;
  exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
  exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
  exports.isCompositeComponent = isCompositeComponent;
  exports.isCompositeComponentWithType = isCompositeComponentWithType;
  exports.isDOMComponent = isDOMComponent;
  exports.isDOMComponentElement = isDOMComponentElement;
  exports.isElement = isElement;
  exports.isElementOfType = isElementOfType;
  exports.mockComponent = mockComponent;
  exports.nativeTouchData = nativeTouchData;
  exports.renderIntoDocument = renderIntoDocument;
  exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
  exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
  exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
  exports.traverseTwoPhase = traverseTwoPhase;

})));
/**
 * @license React
 * react-dom-test-utils.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(f,q){"object"===typeof exports&&"undefined"!==typeof module?q(exports,require("react-dom")):"function"===typeof define&&define.amd?define(["exports","react","react-dom"],q):(f=f||self,q(f.ReactTestUtils={},f.React,f.ReactDOM))})(this,function(f,q,C){function K(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function L(a){if(K(a)!==a)throw Error("Unable to find node on an unmounted component.");
}function V(a){var b=a.alternate;if(!b){b=K(a);if(null===b)throw Error("Unable to find node on an unmounted component.");return b!==a?null:a}for(var c=a,d=b;;){var g=c.return;if(null===g)break;var h=g.alternate;if(null===h){d=g.return;if(null!==d){c=d;continue}break}if(g.child===h.child){for(h=g.child;h;){if(h===c)return L(g),a;if(h===d)return L(g),b;h=h.sibling}throw Error("Unable to find node on an unmounted component.");}if(c.return!==d.return)c=g,d=h;else{for(var e=!1,m=g.child;m;){if(m===c){e=
!0;c=g;d=h;break}if(m===d){e=!0;d=g;c=h;break}m=m.sibling}if(!e){for(m=h.child;m;){if(m===c){e=!0;c=h;d=g;break}if(m===d){e=!0;d=h;c=g;break}m=m.sibling}if(!e)throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");}}if(c.alternate!==d)throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");}if(3!==c.tag)throw Error("Unable to find node on an unmounted component.");
return c.stateNode.current===c?a:b}function D(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function x(){return!0}function M(){return!1}function n(a){function b(c,b,g,h,e){this._reactName=c;this._targetInst=g;this.type=b;this.nativeEvent=h;this.target=e;this.currentTarget=null;for(var d in a)a.hasOwnProperty(d)&&(c=a[d],this[d]=c?c(h):h[d]);this.isDefaultPrevented=(null!=h.defaultPrevented?h.defaultPrevented:!1===h.returnValue)?
x:M;this.isPropagationStopped=M;return this}k(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=x)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=x)},persist:function(){},isPersistent:x});return b}function W(a){var b=this.nativeEvent;
return b.getModifierState?b.getModifierState(a):(a=X[a])?!!b[a]:!1}function E(a){return W}function Y(a,b,c,d,g,h,e,f,k){v=!1;y=null;Z.apply(aa,arguments)}function ba(a,b,c,d,g,h,e,f,k){Y.apply(this,arguments);if(v){if(v){var m=y;v=!1;y=null}else throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");z||(z=!0,F=m)}}function ca(a){}function da(a,b){if(!a)return[];a=V(a);if(!a)return[];for(var c=a,d=[];;){if(5===c.tag||
6===c.tag||1===c.tag||0===c.tag){var g=c.stateNode;b(g)&&d.push(g)}if(c.child)c.child.return=c,c=c.child;else{if(c===a)return d;for(;!c.sibling;){if(!c.return||c.return===a)return d;c=c.return}c.sibling.return=c.return;c=c.sibling}}}function t(a,b){if(a&&!a._reactInternals){var c=String(a);a=G(a)?"an array":a&&1===a.nodeType&&a.tagName?"a DOM node":"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c;throw Error(b+"(...): the first argument must be a React class instance. Instead received: "+
(a+"."));}}function A(a){return!(!a||1!==a.nodeType||!a.tagName)}function H(a){return A(a)?!1:null!=a&&"function"===typeof a.render&&"function"===typeof a.setState}function N(a,b){return H(a)?a._reactInternals.type===b:!1}function B(a,b){t(a,"findAllInRenderedTree");return a?da(a._reactInternals,b):[]}function O(a,b){t(a,"scryRenderedDOMComponentsWithClass");return B(a,function(a){if(A(a)){var c=a.className;"string"!==typeof c&&(c=a.getAttribute("class")||"");var g=c.split(/\s+/);if(!G(b)){if(void 0===
b)throw Error("TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.");b=b.split(/\s+/)}return b.every(function(a){return-1!==g.indexOf(a)})}return!1})}function P(a,b){t(a,"scryRenderedDOMComponentsWithTag");return B(a,function(a){return A(a)&&a.tagName.toUpperCase()===b.toUpperCase()})}function Q(a,b){t(a,"scryRenderedComponentsWithType");return B(a,function(a){return N(a,b)})}function R(a,b,c){var d=a.type||"unknown-event";a.currentTarget=ea(c);ba(d,b,void 0,a);
a.currentTarget=null}function S(a,b,c){for(var d=[];a;){d.push(a);do a=a.return;while(a&&5!==a.tag);a=a?a:null}for(a=d.length;0<a--;)b(d[a],"captured",c);for(a=0;a<d.length;a++)b(d[a],"bubbled",c)}function T(a,b){var c=a.stateNode;if(!c)return null;var d=fa(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=
!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error("Expected `"+b+"` listener to be a function, instead got a value of `"+typeof c+"` type.");return c}function ha(a,b,c){a&&c&&c._reactName&&(b=T(a,c._reactName))&&(null==c._dispatchListeners&&(c._dispatchListeners=[]),null==c._dispatchInstances&&(c._dispatchInstances=[]),c._dispatchListeners.push(b),c._dispatchInstances.push(a))}function ia(a,
b,c){var d=c._reactName;"captured"===b&&(d+="Capture");if(b=T(a,d))null==c._dispatchListeners&&(c._dispatchListeners=[]),null==c._dispatchInstances&&(c._dispatchInstances=[]),c._dispatchListeners.push(b),c._dispatchInstances.push(a)}function ja(a){return function(b,c){if(q.isValidElement(b))throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering.");
if(H(b))throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead.");var d="on"+a[0].toUpperCase()+a.slice(1),g=new ca;g.target=b;g.type=a.toLowerCase();var f=ka(b),e=new la(d,g.type,f,g,b);e.persist();k(e,c);ma.has(a)?e&&e._reactName&&ha(e._targetInst,null,e):e&&e._reactName&&S(e._targetInst,ia,e);C.unstable_batchedUpdates(function(){na(b);if(e){var a=e._dispatchListeners,c=e._dispatchInstances;
if(G(a))for(var d=0;d<a.length&&!e.isPropagationStopped();d++)R(e,a[d],c[d]);else a&&R(e,a,c);e._dispatchListeners=null;e._dispatchInstances=null;e.isPersistent()||e.constructor.release(e)}if(z)throw a=F,z=!1,F=null,a;});oa()}}var k=Object.assign,r={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},la=n(r),u=k({},r,{view:0,detail:0});n(u);var I,J,w,l=k({},u,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,
altKey:0,metaKey:0,getModifierState:E,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in a)return a.movementX;a!==w&&(w&&"mousemove"===a.type?(I=a.screenX-w.screenX,J=a.screenY-w.screenY):J=I=0,w=a);return I},movementY:function(a){return"movementY"in a?a.movementY:J}});n(l);var p=k({},l,{dataTransfer:0});n(p);p=k({},u,{relatedTarget:0});n(p);p=k({},r,{animationName:0,
elapsedTime:0,pseudoElement:0});n(p);p=k({},r,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}});n(p);p=k({},r,{data:0});n(p);var pa={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},qa={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",
33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},X={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};p=k({},u,{key:function(a){if(a.key){var b=pa[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=D(a),13===a?"Enter":String.fromCharCode(a)):
"keydown"===a.type||"keyup"===a.type?qa[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:E,charCode:function(a){return"keypress"===a.type?D(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?D(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}});n(p);p=k({},l,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,
isPrimary:0});n(p);u=k({},u,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:E});n(u);r=k({},r,{propertyName:0,elapsedTime:0,pseudoElement:0});n(r);l=k({},l,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0});n(l);var Z=function(a,b,c,d,f,h,e,k,l){var g=Array.prototype.slice.call(arguments,
3);try{b.apply(c,g)}catch(ra){this.onError(ra)}},v=!1,y=null,z=!1,F=null,aa={onError:function(a){v=!0;y=a}},G=Array.isArray;l=C.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;var ka=l[0],ea=l[1],fa=l[2],na=l[3],oa=l[4];l=q.unstable_act;var U={},ma=new Set(["mouseEnter","mouseLeave","pointerEnter","pointerLeave"]),sa="blur cancel click close contextMenu copy cut auxClick doubleClick dragEnd dragStart drop focus input invalid keyDown keyPress keyUp mouseDown mouseUp paste pause play pointerCancel pointerDown pointerUp rateChange reset resize seeked submit touchCancel touchEnd touchStart volumeChange drag dragEnter dragExit dragLeave dragOver mouseMove mouseOut mouseOver pointerMove pointerOut pointerOver scroll toggle touchMove wheel abort animationEnd animationIteration animationStart canPlay canPlayThrough durationChange emptied encrypted ended error gotPointerCapture load loadedData loadedMetadata loadStart lostPointerCapture playing progress seeking stalled suspend timeUpdate transitionEnd waiting mouseEnter mouseLeave pointerEnter pointerLeave change select beforeInput compositionEnd compositionStart compositionUpdate".split(" ");
(function(){sa.forEach(function(a){U[a]=ja(a)})})();f.Simulate=U;f.act=l;f.findAllInRenderedTree=B;f.findRenderedComponentWithType=function(a,b){t(a,"findRenderedComponentWithType");a=Q(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for componentType:"+b);return a[0]};f.findRenderedDOMComponentWithClass=function(a,b){t(a,"findRenderedDOMComponentWithClass");a=O(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for class:"+
b);return a[0]};f.findRenderedDOMComponentWithTag=function(a,b){t(a,"findRenderedDOMComponentWithTag");a=P(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for tag:"+b);return a[0]};f.isCompositeComponent=H;f.isCompositeComponentWithType=N;f.isDOMComponent=A;f.isDOMComponentElement=function(a){return!!(a&&q.isValidElement(a)&&a.tagName)};f.isElement=function(a){return q.isValidElement(a)};f.isElementOfType=function(a,b){return q.isValidElement(a)&&a.type===b};
f.mockComponent=function(a,b){b=b||a.mockTagName||"div";a.prototype.render.mockImplementation(function(){return q.createElement(b,null,this.props.children)});return this};f.nativeTouchData=function(a,b){return{touches:[{pageX:a,pageY:b}]}};f.renderIntoDocument=function(a){var b=document.createElement("div");return C.render(a,b)};f.scryRenderedComponentsWithType=Q;f.scryRenderedDOMComponentsWithClass=O;f.scryRenderedDOMComponentsWithTag=P;f.traverseTwoPhase=S});
})();
/**
 * @license React
 * react-dom.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
  (global = global || self, factory(global.ReactDOM = {}, global.React));
}(this, (function (exports, React) { 'use strict';

  var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

  var suppressWarning = false;
  function setSuppressWarning(newSuppressWarning) {
    {
      suppressWarning = newSuppressWarning;
    }
  } // In DEV, calls to console.warn and console.error get replaced
  // by calls to these methods by a Babel plugin.
  //
  // In PROD (or in packages without access to React internals),
  // they are left as they are instead.

  function warn(format) {
    {
      if (!suppressWarning) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }
  }
  function error(format) {
    {
      if (!suppressWarning) {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }
  }

  function printWarning(level, format, args) {
    // When changing this logic, you might want to also
    // update consoleWithStackDev.www.js as well.
    {
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var stack = ReactDebugCurrentFrame.getStackAddendum();

      if (stack !== '') {
        format += '%s';
        args = args.concat([stack]);
      } // eslint-disable-next-line react-internal/safe-string-coercion


      var argsWithFormat = args.map(function (item) {
        return String(item);
      }); // Careful: RN currently depends on this prefix

      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
      // breaks IE9: https://github.com/facebook/react/issues/13610
      // eslint-disable-next-line react-internal/no-production-logging

      Function.prototype.apply.call(console[level], console, argsWithFormat);
    }
  }

  var FunctionComponent = 0;
  var ClassComponent = 1;
  var IndeterminateComponent = 2; // Before we know whether it is function or class

  var HostRoot = 3; // Root of a host tree. Could be nested inside another node.

  var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.

  var HostComponent = 5;
  var HostText = 6;
  var Fragment = 7;
  var Mode = 8;
  var ContextConsumer = 9;
  var ContextProvider = 10;
  var ForwardRef = 11;
  var Profiler = 12;
  var SuspenseComponent = 13;
  var MemoComponent = 14;
  var SimpleMemoComponent = 15;
  var LazyComponent = 16;
  var IncompleteClassComponent = 17;
  var DehydratedFragment = 18;
  var SuspenseListComponent = 19;
  var ScopeComponent = 21;
  var OffscreenComponent = 22;
  var LegacyHiddenComponent = 23;
  var CacheComponent = 24;
  var TracingMarkerComponent = 25;

  // -----------------------------------------------------------------------------

  var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing
  // the react-reconciler package.

  var enableNewReconciler = false; // Support legacy Primer support on internal FB www

  var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics.

  var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber

  var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz
  // React DOM Chopping Block
  //
  // Similar to main Chopping Block but only flags related to React DOM. These are
  // grouped because we will likely batch all of them into a single major release.
  // -----------------------------------------------------------------------------
  // Disable support for comment nodes as React DOM containers. Already disabled
  // in open source, but www codebase still relies on it. Need to remove.

  var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection.
  // and client rendering, mostly to allow JSX attributes to apply to the custom
  // element's object properties instead of only HTML attributes.
  // https://github.com/facebook/react/issues/11347

  var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements
  var warnAboutStringRefs = true; // -----------------------------------------------------------------------------
  // Debugging and DevTools
  // -----------------------------------------------------------------------------
  // Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
  // for an experimental timeline tool.

  var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState

  var enableProfilerTimer = true; // Record durations for commit and passive effects phases.

  var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update".

  var allNativeEvents = new Set();
  /**
   * Mapping from registration name to event name
   */


  var registrationNameDependencies = {};
  /**
   * Mapping from lowercase registration names to the properly cased version,
   * used to warn in the case of missing event handlers. Available
   * only in true.
   * @type {Object}
   */

  var possibleRegistrationNames =  {} ; // Trust the developer to only use possibleRegistrationNames in true

  function registerTwoPhaseEvent(registrationName, dependencies) {
    registerDirectEvent(registrationName, dependencies);
    registerDirectEvent(registrationName + 'Capture', dependencies);
  }
  function registerDirectEvent(registrationName, dependencies) {
    {
      if (registrationNameDependencies[registrationName]) {
        error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);
      }
    }

    registrationNameDependencies[registrationName] = dependencies;

    {
      var lowerCasedName = registrationName.toLowerCase();
      possibleRegistrationNames[lowerCasedName] = registrationName;

      if (registrationName === 'onDoubleClick') {
        possibleRegistrationNames.ondblclick = registrationName;
      }
    }

    for (var i = 0; i < dependencies.length; i++) {
      allNativeEvents.add(dependencies[i]);
    }
  }

  var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');

  var hasOwnProperty = Object.prototype.hasOwnProperty;

  /*
   * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
   * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
   *
   * The functions in this module will throw an easier-to-understand,
   * easier-to-debug exception with a clear errors message message explaining the
   * problem. (Instead of a confusing exception thrown inside the implementation
   * of the `value` object).
   */
  // $FlowFixMe only called in DEV, so void return is not possible.
  function typeName(value) {
    {
      // toStringTag is needed for namespaced types like Temporal.Instant
      var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
      var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
      return type;
    }
  } // $FlowFixMe only called in DEV, so void return is not possible.


  function willCoercionThrow(value) {
    {
      try {
        testStringCoercion(value);
        return false;
      } catch (e) {
        return true;
      }
    }
  }

  function testStringCoercion(value) {
    // If you ended up here by following an exception call stack, here's what's
    // happened: you supplied an object or symbol value to React (as a prop, key,
    // DOM attribute, CSS property, string ref, etc.) and when React tried to
    // coerce it to a string using `'' + value`, an exception was thrown.
    //
    // The most common types that will cause this exception are `Symbol` instances
    // and Temporal objects like `Temporal.Instant`. But any object that has a
    // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
    // exception. (Library authors do this to prevent users from using built-in
    // numeric operators like `+` or comparison operators like `>=` because custom
    // methods are needed to perform accurate arithmetic or comparison.)
    //
    // To fix the problem, coerce this object or symbol value to a string before
    // passing it to React. The most reliable way is usually `String(value)`.
    //
    // To find which value is throwing, check the browser or debugger console.
    // Before this exception was thrown, there should be `console.error` output
    // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
    // problem and how that type was used: key, atrribute, input value prop, etc.
    // In most cases, this console output also shows the component and its
    // ancestor components where the exception happened.
    //
    // eslint-disable-next-line react-internal/safe-string-coercion
    return '' + value;
  }

  function checkAttributeStringCoercion(value, attributeName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkKeyStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkPropStringCoercion(value, propName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkCSSPropertyStringCoercion(value, propName) {
    {
      if (willCoercionThrow(value)) {
        error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkHtmlStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }
  function checkFormFieldValueStringCoercion(value) {
    {
      if (willCoercionThrow(value)) {
        error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

        return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
      }
    }
  }

  // A reserved attribute.
  // It is handled by React separately and shouldn't be written to the DOM.
  var RESERVED = 0; // A simple string attribute.
  // Attributes that aren't in the filter are presumed to have this type.

  var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
  // "enumerated" attributes with "true" and "false" as possible values.
  // When true, it should be set to a "true" string.
  // When false, it should be set to a "false" string.

  var BOOLEANISH_STRING = 2; // A real boolean attribute.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.

  var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
  // When true, it should be present (set either to an empty string or its name).
  // When false, it should be omitted.
  // For any other value, should be present with that value.

  var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
  // When falsy, it should be removed.

  var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
  // When falsy, it should be removed.

  var POSITIVE_NUMERIC = 6;

  /* eslint-disable max-len */
  var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  /* eslint-enable max-len */

  var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
  var illegalAttributeNameCache = {};
  var validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
      return true;
    }

    if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
      return false;
    }

    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
      validatedAttributeNameCache[attributeName] = true;
      return true;
    }

    illegalAttributeNameCache[attributeName] = true;

    {
      error('Invalid attribute name: `%s`', attributeName);
    }

    return false;
  }
  function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
    if (propertyInfo !== null) {
      return propertyInfo.type === RESERVED;
    }

    if (isCustomComponentTag) {
      return false;
    }

    if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
      return true;
    }

    return false;
  }
  function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
    if (propertyInfo !== null && propertyInfo.type === RESERVED) {
      return false;
    }

    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return true;

      case 'boolean':
        {
          if (isCustomComponentTag) {
            return false;
          }

          if (propertyInfo !== null) {
            return !propertyInfo.acceptsBooleans;
          } else {
            var prefix = name.toLowerCase().slice(0, 5);
            return prefix !== 'data-' && prefix !== 'aria-';
          }
        }

      default:
        return false;
    }
  }
  function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
    if (value === null || typeof value === 'undefined') {
      return true;
    }

    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
      return true;
    }

    if (isCustomComponentTag) {

      return false;
    }

    if (propertyInfo !== null) {

      switch (propertyInfo.type) {
        case BOOLEAN:
          return !value;

        case OVERLOADED_BOOLEAN:
          return value === false;

        case NUMERIC:
          return isNaN(value);

        case POSITIVE_NUMERIC:
          return isNaN(value) || value < 1;
      }
    }

    return false;
  }
  function getPropertyInfo(name) {
    return properties.hasOwnProperty(name) ? properties[name] : null;
  }

  function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
    this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
    this.attributeName = attributeName;
    this.attributeNamespace = attributeNamespace;
    this.mustUseProperty = mustUseProperty;
    this.propertyName = name;
    this.type = type;
    this.sanitizeURL = sanitizeURL;
    this.removeEmptyString = removeEmptyString;
  } // When adding attributes to this list, be sure to also add them to
  // the `possibleStandardNames` module to ensure casing and incorrect
  // name warnings.


  var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

  var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
  // elements (not just inputs). Now that ReactDOMInput assigns to the
  // defaultValue property -- do we need this?
  'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

  reservedProps.forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // A few React string attributes have a different name.
  // This is a mapping from React prop names to the attribute names.

  [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
    var name = _ref[0],
        attributeName = _ref[1];
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" HTML attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).

  ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are "enumerated" SVG attributes that accept "true" and "false".
  // In React, we let users pass `true` and `false` even though technically
  // these aren't boolean attributes (they are coerced to strings).
  // Since these are SVG attributes, their attribute names are case-sensitive.

  ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML boolean attributes.

  ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
  // on the client side because the browsers are inconsistent. Instead we call focus().
  'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
  'itemScope'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are the few React props that we set as DOM properties
  // rather than attributes. These are all booleans.

  ['checked', // Note: `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`. We have special logic for handling this.
  'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that are "overloaded booleans": they behave like
  // booleans, but can also accept a string value.

  ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be positive numbers.

  ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
    name, // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These are HTML attributes that must be numbers.

  ['rowSpan', 'start'].forEach(function (name) {
    properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
    name.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  });
  var CAMELIZE = /[\-\:]([a-z])/g;

  var capitalize = function (token) {
    return token[1].toUpperCase();
  }; // This is a list of all SVG attributes that need special casing, namespacing,
  // or boolean value assignment. Regular attributes that just accept strings
  // and have the same names are omitted, just like in the HTML attribute filter.
  // Some of these attributes can be hard to find. This list was created by
  // scraping the MDN documentation.


  ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // String SVG attributes with the xlink namespace.

  ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
    false);
  }); // String SVG attributes with the xml namespace.

  ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
  // you'll need to set attributeName to name.toLowerCase()
  // instead in the assignment below.
  ].forEach(function (attributeName) {
    var name = attributeName.replace(CAMELIZE, capitalize);
    properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
    attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
    false);
  }); // These attribute exists both in HTML and SVG.
  // The attribute name is case-sensitive in SVG so we can't just use
  // the React name like we do for attributes that exist only in HTML.

  ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    false, // sanitizeURL
    false);
  }); // These attributes accept URLs. These must not allow javascript: URLS.
  // These will also need to accept Trusted Types object in the future.

  var xlinkHref = 'xlinkHref';
  properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
  'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
  false);
  ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
    properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
    attributeName.toLowerCase(), // attributeName
    null, // attributeNamespace
    true, // sanitizeURL
    true);
  });

  // and any newline or tab are filtered out as if they're not part of the URL.
  // https://url.spec.whatwg.org/#url-parsing
  // Tab or newline are defined as \r\n\t:
  // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  // A C0 control is a code point in the range \u0000 NULL to \u001F
  // INFORMATION SEPARATOR ONE, inclusive:
  // https://infra.spec.whatwg.org/#c0-control-or-space

  /* eslint-disable max-len */

  var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
  var didWarn = false;

  function sanitizeURL(url) {
    {
      if (!didWarn && isJavaScriptProtocol.test(url)) {
        didWarn = true;

        error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
      }
    }
  }

  /**
   * Get the value for a property on a node. Only used in DEV for SSR validation.
   * The "expected" argument is used as a hint of what the expected value is.
   * Some properties have multiple equivalent values.
   */
  function getValueForProperty(node, name, expected, propertyInfo) {
    {
      if (propertyInfo.mustUseProperty) {
        var propertyName = propertyInfo.propertyName;
        return node[propertyName];
      } else {
        // This check protects multiple uses of `expected`, which is why the
        // react-internal/safe-string-coercion rule is disabled in several spots
        // below.
        {
          checkAttributeStringCoercion(expected, name);
        }

        if ( propertyInfo.sanitizeURL) {
          // If we haven't fully disabled javascript: URLs, and if
          // the hydration is successful of a javascript: URL, we
          // still want to warn on the client.
          // eslint-disable-next-line react-internal/safe-string-coercion
          sanitizeURL('' + expected);
        }

        var attributeName = propertyInfo.attributeName;
        var stringValue = null;

        if (propertyInfo.type === OVERLOADED_BOOLEAN) {
          if (node.hasAttribute(attributeName)) {
            var value = node.getAttribute(attributeName);

            if (value === '') {
              return true;
            }

            if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
              return value;
            } // eslint-disable-next-line react-internal/safe-string-coercion


            if (value === '' + expected) {
              return expected;
            }

            return value;
          }
        } else if (node.hasAttribute(attributeName)) {
          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
            // We had an attribute but shouldn't have had one, so read it
            // for the error message.
            return node.getAttribute(attributeName);
          }

          if (propertyInfo.type === BOOLEAN) {
            // If this was a boolean, it doesn't matter what the value is
            // the fact that we have it is the same as the expected.
            return expected;
          } // Even if this property uses a namespace we use getAttribute
          // because we assume its namespaced name is the same as our config.
          // To use getAttributeNS we need the local name which we don't have
          // in our config atm.


          stringValue = node.getAttribute(attributeName);
        }

        if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
          return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion
        } else if (stringValue === '' + expected) {
          return expected;
        } else {
          return stringValue;
        }
      }
    }
  }
  /**
   * Get the value for a attribute on a node. Only used in DEV for SSR validation.
   * The third argument is used as a hint of what the expected value is. Some
   * attributes have multiple equivalent values.
   */

  function getValueForAttribute(node, name, expected, isCustomComponentTag) {
    {
      if (!isAttributeNameSafe(name)) {
        return;
      }

      if (!node.hasAttribute(name)) {
        return expected === undefined ? undefined : null;
      }

      var value = node.getAttribute(name);

      {
        checkAttributeStringCoercion(expected, name);
      }

      if (value === '' + expected) {
        return expected;
      }

      return value;
    }
  }
  /**
   * Sets the value for a property on a node.
   *
   * @param {DOMElement} node
   * @param {string} name
   * @param {*} value
   */

  function setValueForProperty(node, name, value, isCustomComponentTag) {
    var propertyInfo = getPropertyInfo(name);

    if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
      return;
    }

    if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
      value = null;
    }


    if (isCustomComponentTag || propertyInfo === null) {
      if (isAttributeNameSafe(name)) {
        var _attributeName = name;

        if (value === null) {
          node.removeAttribute(_attributeName);
        } else {
          {
            checkAttributeStringCoercion(value, name);
          }

          node.setAttribute(_attributeName,  '' + value);
        }
      }

      return;
    }

    var mustUseProperty = propertyInfo.mustUseProperty;

    if (mustUseProperty) {
      var propertyName = propertyInfo.propertyName;

      if (value === null) {
        var type = propertyInfo.type;
        node[propertyName] = type === BOOLEAN ? false : '';
      } else {
        // Contrary to `setAttribute`, object properties are properly
        // `toString`ed by IE8/9.
        node[propertyName] = value;
      }

      return;
    } // The rest are treated as attributes with special cases.


    var attributeName = propertyInfo.attributeName,
        attributeNamespace = propertyInfo.attributeNamespace;

    if (value === null) {
      node.removeAttribute(attributeName);
    } else {
      var _type = propertyInfo.type;
      var attributeValue;

      if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
        // If attribute type is boolean, we know for sure it won't be an execution sink
        // and we won't require Trusted Type here.
        attributeValue = '';
      } else {
        // `setAttribute` with objects becomes only `[object]` in IE8/9,
        // ('' + value) makes it output the correct toString()-value.
        {
          {
            checkAttributeStringCoercion(value, attributeName);
          }

          attributeValue = '' + value;
        }

        if (propertyInfo.sanitizeURL) {
          sanitizeURL(attributeValue.toString());
        }
      }

      if (attributeNamespace) {
        node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
      } else {
        node.setAttribute(attributeName, attributeValue);
      }
    }
  }

  // ATTENTION
  // When adding new symbols to this file,
  // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  // The Symbol used to tag the ReactElement-like types.
  var REACT_ELEMENT_TYPE = Symbol.for('react.element');
  var REACT_PORTAL_TYPE = Symbol.for('react.portal');
  var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
  var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
  var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
  var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
  var REACT_CONTEXT_TYPE = Symbol.for('react.context');
  var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
  var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
  var REACT_MEMO_TYPE = Symbol.for('react.memo');
  var REACT_LAZY_TYPE = Symbol.for('react.lazy');
  var REACT_SCOPE_TYPE = Symbol.for('react.scope');
  var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
  var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
  var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
  var REACT_CACHE_TYPE = Symbol.for('react.cache');
  var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker');
  var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';
  function getIteratorFn(maybeIterable) {
    if (maybeIterable === null || typeof maybeIterable !== 'object') {
      return null;
    }

    var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

    if (typeof maybeIterator === 'function') {
      return maybeIterator;
    }

    return null;
  }

  var assign = Object.assign;

  // Helpers to patch console.logs to avoid logging during side-effect free
  // replaying on render function. This currently only patches the object
  // lazily which won't cover if the log function was extracted eagerly.
  // We could also eagerly patch the method.
  var disabledDepth = 0;
  var prevLog;
  var prevInfo;
  var prevWarn;
  var prevError;
  var prevGroup;
  var prevGroupCollapsed;
  var prevGroupEnd;

  function disabledLog() {}

  disabledLog.__reactDisabledLog = true;
  function disableLogs() {
    {
      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      disabledDepth++;
    }
  }
  function reenableLogs() {
    {
      disabledDepth--;

      if (disabledDepth === 0) {
        /* eslint-disable react-internal/no-production-logging */
        var props = {
          configurable: true,
          enumerable: true,
          writable: true
        }; // $FlowFixMe Flow thinks console is immutable.

        Object.defineProperties(console, {
          log: assign({}, props, {
            value: prevLog
          }),
          info: assign({}, props, {
            value: prevInfo
          }),
          warn: assign({}, props, {
            value: prevWarn
          }),
          error: assign({}, props, {
            value: prevError
          }),
          group: assign({}, props, {
            value: prevGroup
          }),
          groupCollapsed: assign({}, props, {
            value: prevGroupCollapsed
          }),
          groupEnd: assign({}, props, {
            value: prevGroupEnd
          })
        });
        /* eslint-enable react-internal/no-production-logging */
      }

      if (disabledDepth < 0) {
        error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
      }
    }
  }

  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  var prefix;
  function describeBuiltInComponentFrame(name, source, ownerFn) {
    {
      if (prefix === undefined) {
        // Extract the VM specific prefix used by each line.
        try {
          throw Error();
        } catch (x) {
          var match = x.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || '';
        }
      } // We use the prefix to ensure our stacks line up with native stack frames.


      return '\n' + prefix + name;
    }
  }
  var reentry = false;
  var componentFrameCache;

  {
    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
    componentFrameCache = new PossiblyWeakMap();
  }

  function describeNativeComponentFrame(fn, construct) {
    // If something asked for a stack inside a fake render, it should get ignored.
    if ( !fn || reentry) {
      return '';
    }

    {
      var frame = componentFrameCache.get(fn);

      if (frame !== undefined) {
        return frame;
      }
    }

    var control;
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

    Error.prepareStackTrace = undefined;
    var previousDispatcher;

    {
      previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
      // for warnings.

      ReactCurrentDispatcher.current = null;
      disableLogs();
    }

    try {
      // This should throw.
      if (construct) {
        // Something should be setting the props in the constructor.
        var Fake = function () {
          throw Error();
        }; // $FlowFixMe


        Object.defineProperty(Fake.prototype, 'props', {
          set: function () {
            // We use a throwing setter instead of frozen or non-writable props
            // because that won't throw in a non-strict mode function.
            throw Error();
          }
        });

        if (typeof Reflect === 'object' && Reflect.construct) {
          // We construct a different control for this case to include any extra
          // frames added by the construct call.
          try {
            Reflect.construct(Fake, []);
          } catch (x) {
            control = x;
          }

          Reflect.construct(fn, [], Fake);
        } else {
          try {
            Fake.call();
          } catch (x) {
            control = x;
          }

          fn.call(Fake.prototype);
        }
      } else {
        try {
          throw Error();
        } catch (x) {
          control = x;
        }

        fn();
      }
    } catch (sample) {
      // This is inlined manually because closure doesn't do it for us.
      if (sample && control && typeof sample.stack === 'string') {
        // This extracts the first frame from the sample that isn't also in the control.
        // Skipping one frame that we assume is the frame that calls the two.
        var sampleLines = sample.stack.split('\n');
        var controlLines = control.stack.split('\n');
        var s = sampleLines.length - 1;
        var c = controlLines.length - 1;

        while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
          // We expect at least one stack frame to be shared.
          // Typically this will be the root most one. However, stack frames may be
          // cut off due to maximum stack limits. In this case, one maybe cut off
          // earlier than the other. We assume that the sample is longer or the same
          // and there for cut off earlier. So we should find the root most frame in
          // the sample somewhere in the control.
          c--;
        }

        for (; s >= 1 && c >= 0; s--, c--) {
          // Next we find the first one that isn't the same which should be the
          // frame that called our sample function and the control.
          if (sampleLines[s] !== controlLines[c]) {
            // In V8, the first line is describing the message but other VMs don't.
            // If we're about to return the first line, and the control is also on the same
            // line, that's a pretty good indicator that our sample threw at same line as
            // the control. I.e. before we entered the sample frame. So we ignore this result.
            // This can happen if you passed a class to function component, or non-function.
            if (s !== 1 || c !== 1) {
              do {
                s--;
                c--; // We may still have similar intermediate frames from the construct call.
                // The next one that isn't the same should be our match though.

                if (c < 0 || sampleLines[s] !== controlLines[c]) {
                  // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                  var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                  // but we have a user-provided "displayName"
                  // splice it in to make the stack more readable.


                  if (fn.displayName && _frame.includes('<anonymous>')) {
                    _frame = _frame.replace('<anonymous>', fn.displayName);
                  }

                  {
                    if (typeof fn === 'function') {
                      componentFrameCache.set(fn, _frame);
                    }
                  } // Return the line we found.


                  return _frame;
                }
              } while (s >= 1 && c >= 0);
            }

            break;
          }
        }
      }
    } finally {
      reentry = false;

      {
        ReactCurrentDispatcher.current = previousDispatcher;
        reenableLogs();
      }

      Error.prepareStackTrace = previousPrepareStackTrace;
    } // Fallback to just using the name if we couldn't make it throw.


    var name = fn ? fn.displayName || fn.name : '';
    var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

    {
      if (typeof fn === 'function') {
        componentFrameCache.set(fn, syntheticFrame);
      }
    }

    return syntheticFrame;
  }

  function describeClassComponentFrame(ctor, source, ownerFn) {
    {
      return describeNativeComponentFrame(ctor, true);
    }
  }
  function describeFunctionComponentFrame(fn, source, ownerFn) {
    {
      return describeNativeComponentFrame(fn, false);
    }
  }

  function shouldConstruct(Component) {
    var prototype = Component.prototype;
    return !!(prototype && prototype.isReactComponent);
  }

  function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

    if (type == null) {
      return '';
    }

    if (typeof type === 'function') {
      {
        return describeNativeComponentFrame(type, shouldConstruct(type));
      }
    }

    if (typeof type === 'string') {
      return describeBuiltInComponentFrame(type);
    }

    switch (type) {
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame('Suspense');

      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame('SuspenseList');
    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeFunctionComponentFrame(type.render);

        case REACT_MEMO_TYPE:
          // Memo may contain any component type so we recursively resolve it.
          return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              // Lazy may contain any component type so we recursively resolve it.
              return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
            } catch (x) {}
          }
      }
    }

    return '';
  }

  function describeFiber(fiber) {
    var owner =  fiber._debugOwner ? fiber._debugOwner.type : null ;
    var source =  fiber._debugSource ;

    switch (fiber.tag) {
      case HostComponent:
        return describeBuiltInComponentFrame(fiber.type);

      case LazyComponent:
        return describeBuiltInComponentFrame('Lazy');

      case SuspenseComponent:
        return describeBuiltInComponentFrame('Suspense');

      case SuspenseListComponent:
        return describeBuiltInComponentFrame('SuspenseList');

      case FunctionComponent:
      case IndeterminateComponent:
      case SimpleMemoComponent:
        return describeFunctionComponentFrame(fiber.type);

      case ForwardRef:
        return describeFunctionComponentFrame(fiber.type.render);

      case ClassComponent:
        return describeClassComponentFrame(fiber.type);

      default:
        return '';
    }
  }

  function getStackByFiberInDevAndProd(workInProgress) {
    try {
      var info = '';
      var node = workInProgress;

      do {
        info += describeFiber(node);
        node = node.return;
      } while (node);

      return info;
    } catch (x) {
      return '\nError generating stack: ' + x.message + '\n' + x.stack;
    }
  }

  function getWrappedName(outerType, innerType, wrapperName) {
    var displayName = outerType.displayName;

    if (displayName) {
      return displayName;
    }

    var functionName = innerType.displayName || innerType.name || '';
    return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
  } // Keep in sync with react-reconciler/getComponentNameFromFiber


  function getContextName(type) {
    return type.displayName || 'Context';
  } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


  function getComponentNameFromType(type) {
    if (type == null) {
      // Host root, text node or just invalid type.
      return null;
    }

    {
      if (typeof type.tag === 'number') {
        error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
      }
    }

    if (typeof type === 'function') {
      return type.displayName || type.name || null;
    }

    if (typeof type === 'string') {
      return type;
    }

    switch (type) {
      case REACT_FRAGMENT_TYPE:
        return 'Fragment';

      case REACT_PORTAL_TYPE:
        return 'Portal';

      case REACT_PROFILER_TYPE:
        return 'Profiler';

      case REACT_STRICT_MODE_TYPE:
        return 'StrictMode';

      case REACT_SUSPENSE_TYPE:
        return 'Suspense';

      case REACT_SUSPENSE_LIST_TYPE:
        return 'SuspenseList';

    }

    if (typeof type === 'object') {
      switch (type.$$typeof) {
        case REACT_CONTEXT_TYPE:
          var context = type;
          return getContextName(context) + '.Consumer';

        case REACT_PROVIDER_TYPE:
          var provider = type;
          return getContextName(provider._context) + '.Provider';

        case REACT_FORWARD_REF_TYPE:
          return getWrappedName(type, type.render, 'ForwardRef');

        case REACT_MEMO_TYPE:
          var outerName = type.displayName || null;

          if (outerName !== null) {
            return outerName;
          }

          return getComponentNameFromType(type.type) || 'Memo';

        case REACT_LAZY_TYPE:
          {
            var lazyComponent = type;
            var payload = lazyComponent._payload;
            var init = lazyComponent._init;

            try {
              return getComponentNameFromType(init(payload));
            } catch (x) {
              return null;
            }
          }

        // eslint-disable-next-line no-fallthrough
      }
    }

    return null;
  }

  function getWrappedName$1(outerType, innerType, wrapperName) {
    var functionName = innerType.displayName || innerType.name || '';
    return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
  } // Keep in sync with shared/getComponentNameFromType


  function getContextName$1(type) {
    return type.displayName || 'Context';
  }

  function getComponentNameFromFiber(fiber) {
    var tag = fiber.tag,
        type = fiber.type;

    switch (tag) {
      case CacheComponent:
        return 'Cache';

      case ContextConsumer:
        var context = type;
        return getContextName$1(context) + '.Consumer';

      case ContextProvider:
        var provider = type;
        return getContextName$1(provider._context) + '.Provider';

      case DehydratedFragment:
        return 'DehydratedFragment';

      case ForwardRef:
        return getWrappedName$1(type, type.render, 'ForwardRef');

      case Fragment:
        return 'Fragment';

      case HostComponent:
        // Host component type is the display name (e.g. "div", "View")
        return type;

      case HostPortal:
        return 'Portal';

      case HostRoot:
        return 'Root';

      case HostText:
        return 'Text';

      case LazyComponent:
        // Name comes from the type in this case; we don't have a tag.
        return getComponentNameFromType(type);

      case Mode:
        if (type === REACT_STRICT_MODE_TYPE) {
          // Don't be less specific than shared/getComponentNameFromType
          return 'StrictMode';
        }

        return 'Mode';

      case OffscreenComponent:
        return 'Offscreen';

      case Profiler:
        return 'Profiler';

      case ScopeComponent:
        return 'Scope';

      case SuspenseComponent:
        return 'Suspense';

      case SuspenseListComponent:
        return 'SuspenseList';

      case TracingMarkerComponent:
        return 'TracingMarker';
      // The display name for this tags come from the user-provided type:

      case ClassComponent:
      case FunctionComponent:
      case IncompleteClassComponent:
      case IndeterminateComponent:
      case MemoComponent:
      case SimpleMemoComponent:
        if (typeof type === 'function') {
          return type.displayName || type.name || null;
        }

        if (typeof type === 'string') {
          return type;
        }

        break;

    }

    return null;
  }

  var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  var current = null;
  var isRendering = false;
  function getCurrentFiberOwnerNameInDevOrNull() {
    {
      if (current === null) {
        return null;
      }

      var owner = current._debugOwner;

      if (owner !== null && typeof owner !== 'undefined') {
        return getComponentNameFromFiber(owner);
      }
    }

    return null;
  }

  function getCurrentFiberStackInDev() {
    {
      if (current === null) {
        return '';
      } // Safe because if current fiber exists, we are reconciling,
      // and it is guaranteed to be the work-in-progress version.


      return getStackByFiberInDevAndProd(current);
    }
  }

  function resetCurrentFiber() {
    {
      ReactDebugCurrentFrame.getCurrentStack = null;
      current = null;
      isRendering = false;
    }
  }
  function setCurrentFiber(fiber) {
    {
      ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
      current = fiber;
      isRendering = false;
    }
  }
  function getCurrentFiber() {
    {
      return current;
    }
  }
  function setIsRendering(rendering) {
    {
      isRendering = rendering;
    }
  }

  // Flow does not allow string concatenation of most non-string types. To work
  // around this limitation, we use an opaque type that can only be obtained by
  // passing the value through getToStringValue first.
  function toString(value) {
    // The coercion safety check is performed in getToStringValue().
    // eslint-disable-next-line react-internal/safe-string-coercion
    return '' + value;
  }
  function getToStringValue(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
      case 'string':
      case 'undefined':
        return value;

      case 'object':
        {
          checkFormFieldValueStringCoercion(value);
        }

        return value;

      default:
        // function, symbol are assigned as empty strings
        return '';
    }
  }

  var hasReadOnlyValue = {
    button: true,
    checkbox: true,
    image: true,
    hidden: true,
    radio: true,
    reset: true,
    submit: true
  };
  function checkControlledValueProps(tagName, props) {
    {
      if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
        error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }

      if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
        error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
      }
    }
  }

  function isCheckable(elem) {
    var type = elem.type;
    var nodeName = elem.nodeName;
    return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
  }

  function getTracker(node) {
    return node._valueTracker;
  }

  function detachTracker(node) {
    node._valueTracker = null;
  }

  function getValueFromNode(node) {
    var value = '';

    if (!node) {
      return value;
    }

    if (isCheckable(node)) {
      value = node.checked ? 'true' : 'false';
    } else {
      value = node.value;
    }

    return value;
  }

  function trackValueOnNode(node) {
    var valueField = isCheckable(node) ? 'checked' : 'value';
    var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);

    {
      checkFormFieldValueStringCoercion(node[valueField]);
    }

    var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
    // and don't track value will cause over reporting of changes,
    // but it's better then a hard failure
    // (needed for certain tests that spyOn input values and Safari)

    if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
      return;
    }

    var get = descriptor.get,
        set = descriptor.set;
    Object.defineProperty(node, valueField, {
      configurable: true,
      get: function () {
        return get.call(this);
      },
      set: function (value) {
        {
          checkFormFieldValueStringCoercion(value);
        }

        currentValue = '' + value;
        set.call(this, value);
      }
    }); // We could've passed this the first time
    // but it triggers a bug in IE11 and Edge 14/15.
    // Calling defineProperty() again should be equivalent.
    // https://github.com/facebook/react/issues/11768

    Object.defineProperty(node, valueField, {
      enumerable: descriptor.enumerable
    });
    var tracker = {
      getValue: function () {
        return currentValue;
      },
      setValue: function (value) {
        {
          checkFormFieldValueStringCoercion(value);
        }

        currentValue = '' + value;
      },
      stopTracking: function () {
        detachTracker(node);
        delete node[valueField];
      }
    };
    return tracker;
  }

  function track(node) {
    if (getTracker(node)) {
      return;
    } // TODO: Once it's just Fiber we can move this to node._wrapperState


    node._valueTracker = trackValueOnNode(node);
  }
  function updateValueIfChanged(node) {
    if (!node) {
      return false;
    }

    var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
    // that trying again will succeed

    if (!tracker) {
      return true;
    }

    var lastValue = tracker.getValue();
    var nextValue = getValueFromNode(node);

    if (nextValue !== lastValue) {
      tracker.setValue(nextValue);
      return true;
    }

    return false;
  }

  function getActiveElement(doc) {
    doc = doc || (typeof document !== 'undefined' ? document : undefined);

    if (typeof doc === 'undefined') {
      return null;
    }

    try {
      return doc.activeElement || doc.body;
    } catch (e) {
      return doc.body;
    }
  }

  var didWarnValueDefaultValue = false;
  var didWarnCheckedDefaultChecked = false;
  var didWarnControlledToUncontrolled = false;
  var didWarnUncontrolledToControlled = false;

  function isControlled(props) {
    var usesChecked = props.type === 'checkbox' || props.type === 'radio';
    return usesChecked ? props.checked != null : props.value != null;
  }
  /**
   * Implements an <input> host component that allows setting these optional
   * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
   *
   * If `checked` or `value` are not supplied (or null/undefined), user actions
   * that affect the checked state or value will trigger updates to the element.
   *
   * If they are supplied (and not null/undefined), the rendered element will not
   * trigger updates to the element. Instead, the props must change in order for
   * the rendered element to be updated.
   *
   * The rendered element will be initialized as unchecked (or `defaultChecked`)
   * with an empty value (or `defaultValue`).
   *
   * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
   */


  function getHostProps(element, props) {
    var node = element;
    var checked = props.checked;
    var hostProps = assign({}, props, {
      defaultChecked: undefined,
      defaultValue: undefined,
      value: undefined,
      checked: checked != null ? checked : node._wrapperState.initialChecked
    });
    return hostProps;
  }
  function initWrapperState(element, props) {
    {
      checkControlledValueProps('input', props);

      if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
        error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);

        didWarnCheckedDefaultChecked = true;
      }

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
        error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);

        didWarnValueDefaultValue = true;
      }
    }

    var node = element;
    var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
    node._wrapperState = {
      initialChecked: props.checked != null ? props.checked : props.defaultChecked,
      initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
      controlled: isControlled(props)
    };
  }
  function updateChecked(element, props) {
    var node = element;
    var checked = props.checked;

    if (checked != null) {
      setValueForProperty(node, 'checked', checked, false);
    }
  }
  function updateWrapper(element, props) {
    var node = element;

    {
      var controlled = isControlled(props);

      if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
        error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');

        didWarnUncontrolledToControlled = true;
      }

      if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
        error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');

        didWarnControlledToUncontrolled = true;
      }
    }

    updateChecked(element, props);
    var value = getToStringValue(props.value);
    var type = props.type;

    if (value != null) {
      if (type === 'number') {
        if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
        // eslint-disable-next-line
        node.value != value) {
          node.value = toString(value);
        }
      } else if (node.value !== toString(value)) {
        node.value = toString(value);
      }
    } else if (type === 'submit' || type === 'reset') {
      // Submit/reset inputs need the attribute removed completely to avoid
      // blank-text buttons.
      node.removeAttribute('value');
      return;
    }

    {
      // When syncing the value attribute, the value comes from a cascade of
      // properties:
      //  1. The value React property
      //  2. The defaultValue React property
      //  3. Otherwise there should be no change
      if (props.hasOwnProperty('value')) {
        setDefaultValue(node, props.type, value);
      } else if (props.hasOwnProperty('defaultValue')) {
        setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
      }
    }

    {
      // When syncing the checked attribute, it only changes when it needs
      // to be removed, such as transitioning from a checkbox into a text input
      if (props.checked == null && props.defaultChecked != null) {
        node.defaultChecked = !!props.defaultChecked;
      }
    }
  }
  function postMountWrapper(element, props, isHydrating) {
    var node = element; // Do not assign value if it is already set. This prevents user text input
    // from being lost during SSR hydration.

    if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
      var type = props.type;
      var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
      // default value provided by the browser. See: #12872

      if (isButton && (props.value === undefined || props.value === null)) {
        return;
      }

      var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
      // from being lost during SSR hydration.

      if (!isHydrating) {
        {
          // When syncing the value attribute, the value property should use
          // the wrapperState._initialValue property. This uses:
          //
          //   1. The value React property when present
          //   2. The defaultValue React property when present
          //   3. An empty string
          if (initialValue !== node.value) {
            node.value = initialValue;
          }
        }
      }

      {
        // Otherwise, the value attribute is synchronized to the property,
        // so we assign defaultValue to the same thing as the value property
        // assignment step above.
        node.defaultValue = initialValue;
      }
    } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
    // this is needed to work around a chrome bug where setting defaultChecked
    // will sometimes influence the value of checked (even after detachment).
    // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
    // We need to temporarily unset name to avoid disrupting radio button groups.


    var name = node.name;

    if (name !== '') {
      node.name = '';
    }

    {
      // When syncing the checked attribute, both the checked property and
      // attribute are assigned at the same time using defaultChecked. This uses:
      //
      //   1. The checked React property when present
      //   2. The defaultChecked React property when present
      //   3. Otherwise, false
      node.defaultChecked = !node.defaultChecked;
      node.defaultChecked = !!node._wrapperState.initialChecked;
    }

    if (name !== '') {
      node.name = name;
    }
  }
  function restoreControlledState(element, props) {
    var node = element;
    updateWrapper(node, props);
    updateNamedCousins(node, props);
  }

  function updateNamedCousins(rootNode, props) {
    var name = props.name;

    if (props.type === 'radio' && name != null) {
      var queryRoot = rootNode;

      while (queryRoot.parentNode) {
        queryRoot = queryRoot.parentNode;
      } // If `rootNode.form` was non-null, then we could try `form.elements`,
      // but that sometimes behaves strangely in IE8. We could also try using
      // `form.getElementsByName`, but that will only return direct children
      // and won't include inputs that use the HTML5 `form=` attribute. Since
      // the input might not even be in a form. It might not even be in the
      // document. Let's just use the local `querySelectorAll` to ensure we don't
      // miss anything.


      {
        checkAttributeStringCoercion(name, 'name');
      }

      var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');

      for (var i = 0; i < group.length; i++) {
        var otherNode = group[i];

        if (otherNode === rootNode || otherNode.form !== rootNode.form) {
          continue;
        } // This will throw if radio buttons rendered by different copies of React
        // and the same name are rendered into the same form (same as #1939).
        // That's probably okay; we don't support it just as we don't support
        // mixing React radio buttons with non-React ones.


        var otherProps = getFiberCurrentPropsFromNode(otherNode);

        if (!otherProps) {
          throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.');
        } // We need update the tracked value on the named cousin since the value
        // was changed but the input saw no event or value set


        updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
        // was previously checked to update will cause it to be come re-checked
        // as appropriate.

        updateWrapper(otherNode, otherProps);
      }
    }
  } // In Chrome, assigning defaultValue to certain input types triggers input validation.
  // For number inputs, the display value loses trailing decimal points. For email inputs,
  // Chrome raises "The specified value <x> is not a valid email address".
  //
  // Here we check to see if the defaultValue has actually changed, avoiding these problems
  // when the user is inputting text
  //
  // https://github.com/facebook/react/issues/7253


  function setDefaultValue(node, type, value) {
    if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
    type !== 'number' || getActiveElement(node.ownerDocument) !== node) {
      if (value == null) {
        node.defaultValue = toString(node._wrapperState.initialValue);
      } else if (node.defaultValue !== toString(value)) {
        node.defaultValue = toString(value);
      }
    }
  }

  var didWarnSelectedSetOnOption = false;
  var didWarnInvalidChild = false;
  var didWarnInvalidInnerHTML = false;
  /**
   * Implements an <option> host component that warns when `selected` is set.
   */

  function validateProps(element, props) {
    {
      // If a value is not provided, then the children must be simple.
      if (props.value == null) {
        if (typeof props.children === 'object' && props.children !== null) {
          React.Children.forEach(props.children, function (child) {
            if (child == null) {
              return;
            }

            if (typeof child === 'string' || typeof child === 'number') {
              return;
            }

            if (!didWarnInvalidChild) {
              didWarnInvalidChild = true;

              error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
            }
          });
        } else if (props.dangerouslySetInnerHTML != null) {
          if (!didWarnInvalidInnerHTML) {
            didWarnInvalidInnerHTML = true;

            error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
          }
        }
      } // TODO: Remove support for `selected` in <option>.


      if (props.selected != null && !didWarnSelectedSetOnOption) {
        error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

        didWarnSelectedSetOnOption = true;
      }
    }
  }
  function postMountWrapper$1(element, props) {
    // value="" should make a value attribute (#6219)
    if (props.value != null) {
      element.setAttribute('value', toString(getToStringValue(props.value)));
    }
  }

  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

  function isArray(a) {
    return isArrayImpl(a);
  }

  var didWarnValueDefaultValue$1;

  {
    didWarnValueDefaultValue$1 = false;
  }

  function getDeclarationErrorAddendum() {
    var ownerName = getCurrentFiberOwnerNameInDevOrNull();

    if (ownerName) {
      return '\n\nCheck the render method of `' + ownerName + '`.';
    }

    return '';
  }

  var valuePropNames = ['value', 'defaultValue'];
  /**
   * Validation function for `value` and `defaultValue`.
   */

  function checkSelectPropTypes(props) {
    {
      checkControlledValueProps('select', props);

      for (var i = 0; i < valuePropNames.length; i++) {
        var propName = valuePropNames[i];

        if (props[propName] == null) {
          continue;
        }

        var propNameIsArray = isArray(props[propName]);

        if (props.multiple && !propNameIsArray) {
          error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
        } else if (!props.multiple && propNameIsArray) {
          error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
        }
      }
    }
  }

  function updateOptions(node, multiple, propValue, setDefaultSelected) {
    var options = node.options;

    if (multiple) {
      var selectedValues = propValue;
      var selectedValue = {};

      for (var i = 0; i < selectedValues.length; i++) {
        // Prefix to avoid chaos with special keys.
        selectedValue['$' + selectedValues[i]] = true;
      }

      for (var _i = 0; _i < options.length; _i++) {
        var selected = selectedValue.hasOwnProperty('$' + options[_i].value);

        if (options[_i].selected !== selected) {
          options[_i].selected = selected;
        }

        if (selected && setDefaultSelected) {
          options[_i].defaultSelected = true;
        }
      }
    } else {
      // Do not set `select.value` as exact behavior isn't consistent across all
      // browsers for all cases.
      var _selectedValue = toString(getToStringValue(propValue));

      var defaultSelected = null;

      for (var _i2 = 0; _i2 < options.length; _i2++) {
        if (options[_i2].value === _selectedValue) {
          options[_i2].selected = true;

          if (setDefaultSelected) {
            options[_i2].defaultSelected = true;
          }

          return;
        }

        if (defaultSelected === null && !options[_i2].disabled) {
          defaultSelected = options[_i2];
        }
      }

      if (defaultSelected !== null) {
        defaultSelected.selected = true;
      }
    }
  }
  /**
   * Implements a <select> host component that allows optionally setting the
   * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
   * stringable. If `multiple` is true, the prop must be an array of stringables.
   *
   * If `value` is not supplied (or null/undefined), user actions that change the
   * selected option will trigger updates to the rendered options.
   *
   * If it is supplied (and not null/undefined), the rendered options will not
   * update in response to user actions. Instead, the `value` prop must change in
   * order for the rendered options to update.
   *
   * If `defaultValue` is provided, any options with the supplied values will be
   * selected.
   */


  function getHostProps$1(element, props) {
    return assign({}, props, {
      value: undefined
    });
  }
  function initWrapperState$1(element, props) {
    var node = element;

    {
      checkSelectPropTypes(props);
    }

    node._wrapperState = {
      wasMultiple: !!props.multiple
    };

    {
      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
        error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

        didWarnValueDefaultValue$1 = true;
      }
    }
  }
  function postMountWrapper$2(element, props) {
    var node = element;
    node.multiple = !!props.multiple;
    var value = props.value;

    if (value != null) {
      updateOptions(node, !!props.multiple, value, false);
    } else if (props.defaultValue != null) {
      updateOptions(node, !!props.multiple, props.defaultValue, true);
    }
  }
  function postUpdateWrapper(element, props) {
    var node = element;
    var wasMultiple = node._wrapperState.wasMultiple;
    node._wrapperState.wasMultiple = !!props.multiple;
    var value = props.value;

    if (value != null) {
      updateOptions(node, !!props.multiple, value, false);
    } else if (wasMultiple !== !!props.multiple) {
      // For simplicity, reapply `defaultValue` if `multiple` is toggled.
      if (props.defaultValue != null) {
        updateOptions(node, !!props.multiple, props.defaultValue, true);
      } else {
        // Revert the select back to its default unselected state.
        updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
      }
    }
  }
  function restoreControlledState$1(element, props) {
    var node = element;
    var value = props.value;

    if (value != null) {
      updateOptions(node, !!props.multiple, value, false);
    }
  }

  var didWarnValDefaultVal = false;

  /**
   * Implements a <textarea> host component that allows setting `value`, and
   * `defaultValue`. This differs from the traditional DOM API because value is
   * usually set as PCDATA children.
   *
   * If `value` is not supplied (or null/undefined), user actions that affect the
   * value will trigger updates to the element.
   *
   * If `value` is supplied (and not null/undefined), the rendered element will
   * not trigger updates to the element. Instead, the `value` prop must change in
   * order for the rendered element to be updated.
   *
   * The rendered element will be initialized with an empty value, the prop
   * `defaultValue` if specified, or the children content (deprecated).
   */
  function getHostProps$2(element, props) {
    var node = element;

    if (props.dangerouslySetInnerHTML != null) {
      throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
    } // Always set children to the same thing. In IE9, the selection range will
    // get reset if `textContent` is mutated.  We could add a check in setTextContent
    // to only set the value if/when the value differs from the node value (which would
    // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
    // solution. The value can be a boolean or object so that's why it's forced
    // to be a string.


    var hostProps = assign({}, props, {
      value: undefined,
      defaultValue: undefined,
      children: toString(node._wrapperState.initialValue)
    });

    return hostProps;
  }
  function initWrapperState$2(element, props) {
    var node = element;

    {
      checkControlledValueProps('textarea', props);

      if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
        error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');

        didWarnValDefaultVal = true;
      }
    }

    var initialValue = props.value; // Only bother fetching default value if we're going to use it

    if (initialValue == null) {
      var children = props.children,
          defaultValue = props.defaultValue;

      if (children != null) {
        {
          error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
        }

        {
          if (defaultValue != null) {
            throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
          }

          if (isArray(children)) {
            if (children.length > 1) {
              throw new Error('<textarea> can only have at most one child.');
            }

            children = children[0];
          }

          defaultValue = children;
        }
      }

      if (defaultValue == null) {
        defaultValue = '';
      }

      initialValue = defaultValue;
    }

    node._wrapperState = {
      initialValue: getToStringValue(initialValue)
    };
  }
  function updateWrapper$1(element, props) {
    var node = element;
    var value = getToStringValue(props.value);
    var defaultValue = getToStringValue(props.defaultValue);

    if (value != null) {
      // Cast `value` to a string to ensure the value is set correctly. While
      // browsers typically do this as necessary, jsdom doesn't.
      var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed

      if (newValue !== node.value) {
        node.value = newValue;
      }

      if (props.defaultValue == null && node.defaultValue !== newValue) {
        node.defaultValue = newValue;
      }
    }

    if (defaultValue != null) {
      node.defaultValue = toString(defaultValue);
    }
  }
  function postMountWrapper$3(element, props) {
    var node = element; // This is in postMount because we need access to the DOM node, which is not
    // available until after the component has mounted.

    var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
    // initial value. In IE10/IE11 there is a bug where the placeholder attribute
    // will populate textContent as well.
    // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/

    if (textContent === node._wrapperState.initialValue) {
      if (textContent !== '' && textContent !== null) {
        node.value = textContent;
      }
    }
  }
  function restoreControlledState$2(element, props) {
    // DOM component is still mounted; update
    updateWrapper$1(element, props);
  }

  var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace.

  function getIntrinsicNamespace(type) {
    switch (type) {
      case 'svg':
        return SVG_NAMESPACE;

      case 'math':
        return MATH_NAMESPACE;

      default:
        return HTML_NAMESPACE;
    }
  }
  function getChildNamespace(parentNamespace, type) {
    if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
      // No (or default) parent namespace: potential entry point.
      return getIntrinsicNamespace(type);
    }

    if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
      // We're leaving SVG.
      return HTML_NAMESPACE;
    } // By default, pass namespace below.


    return parentNamespace;
  }

  /* globals MSApp */

  /**
   * Create a function which has 'unsafe' privileges (required by windows8 apps)
   */
  var createMicrosoftUnsafeLocalFunction = function (func) {
    if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
      return function (arg0, arg1, arg2, arg3) {
        MSApp.execUnsafeLocalFunction(function () {
          return func(arg0, arg1, arg2, arg3);
        });
      };
    } else {
      return func;
    }
  };

  var reusableSVGContainer;
  /**
   * Set the innerHTML property of a node
   *
   * @param {DOMElement} node
   * @param {string} html
   * @internal
   */

  var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
    if (node.namespaceURI === SVG_NAMESPACE) {

      if (!('innerHTML' in node)) {
        // IE does not have innerHTML for SVG nodes, so instead we inject the
        // new markup in a temp node and then move the child nodes across into
        // the target node
        reusableSVGContainer = reusableSVGContainer || document.createElement('div');
        reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
        var svgNode = reusableSVGContainer.firstChild;

        while (node.firstChild) {
          node.removeChild(node.firstChild);
        }

        while (svgNode.firstChild) {
          node.appendChild(svgNode.firstChild);
        }

        return;
      }
    }

    node.innerHTML = html;
  });

  /**
   * HTML nodeType values that represent the type of the node
   */
  var ELEMENT_NODE = 1;
  var TEXT_NODE = 3;
  var COMMENT_NODE = 8;
  var DOCUMENT_NODE = 9;
  var DOCUMENT_FRAGMENT_NODE = 11;

  /**
   * Set the textContent property of a node. For text updates, it's faster
   * to set the `nodeValue` of the Text node directly instead of using
   * `.textContent` which will remove the existing node and create a new one.
   *
   * @param {DOMElement} node
   * @param {string} text
   * @internal
   */

  var setTextContent = function (node, text) {
    if (text) {
      var firstChild = node.firstChild;

      if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
        firstChild.nodeValue = text;
        return;
      }
    }

    node.textContent = text;
  };

  // List derived from Gecko source code:
  // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
  var shorthandToLonghand = {
    animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
    background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
    backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
    border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
    borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
    borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
    borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
    borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
    borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
    borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
    borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
    borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
    borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
    borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
    borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
    borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
    borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
    columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
    columns: ['columnCount', 'columnWidth'],
    flex: ['flexBasis', 'flexGrow', 'flexShrink'],
    flexFlow: ['flexDirection', 'flexWrap'],
    font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
    fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
    gap: ['columnGap', 'rowGap'],
    grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
    gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
    gridColumn: ['gridColumnEnd', 'gridColumnStart'],
    gridColumnGap: ['columnGap'],
    gridGap: ['columnGap', 'rowGap'],
    gridRow: ['gridRowEnd', 'gridRowStart'],
    gridRowGap: ['rowGap'],
    gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
    listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
    margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
    marker: ['markerEnd', 'markerMid', 'markerStart'],
    mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
    maskPosition: ['maskPositionX', 'maskPositionY'],
    outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
    overflow: ['overflowX', 'overflowY'],
    padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
    placeContent: ['alignContent', 'justifyContent'],
    placeItems: ['alignItems', 'justifyItems'],
    placeSelf: ['alignSelf', 'justifySelf'],
    textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
    textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
    transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
    wordWrap: ['overflowWrap']
  };

  /**
   * CSS properties which accept numbers but are not in units of "px".
   */
  var isUnitlessNumber = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    // SVG-related properties
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  };
  /**
   * @param {string} prefix vendor-specific prefix, eg: Webkit
   * @param {string} key style name, eg: transitionDuration
   * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
   * WebkitTransitionDuration
   */

  function prefixKey(prefix, key) {
    return prefix + key.charAt(0).toUpperCase() + key.substring(1);
  }
  /**
   * Support style names that may come passed in prefixed by adding permutations
   * of vendor prefixes.
   */


  var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
  // infinite loop, because it iterates over the newly added props too.

  Object.keys(isUnitlessNumber).forEach(function (prop) {
    prefixes.forEach(function (prefix) {
      isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
    });
  });

  /**
   * Convert a value into the proper css writable value. The style name `name`
   * should be logical (no hyphens), as specified
   * in `CSSProperty.isUnitlessNumber`.
   *
   * @param {string} name CSS property name such as `topMargin`.
   * @param {*} value CSS property value such as `10px`.
   * @return {string} Normalized style value with dimensions applied.
   */

  function dangerousStyleValue(name, value, isCustomProperty) {
    // Note that we've removed escapeTextForBrowser() calls here since the
    // whole string will be escaped when the attribute is injected into
    // the markup. If you provide unsafe user data here they can inject
    // arbitrary CSS which may be problematic (I couldn't repro this):
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
    // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
    // This is not an XSS hole but instead a potential CSS injection issue
    // which has lead to a greater discussion about how we're going to
    // trust URLs moving forward. See #2115901
    var isEmpty = value == null || typeof value === 'boolean' || value === '';

    if (isEmpty) {
      return '';
    }

    if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
      return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
    }

    {
      checkCSSPropertyStringCoercion(value, name);
    }

    return ('' + value).trim();
  }

  var uppercasePattern = /([A-Z])/g;
  var msPattern = /^ms-/;
  /**
   * Hyphenates a camelcased CSS property name, for example:
   *
   *   > hyphenateStyleName('backgroundColor')
   *   < "background-color"
   *   > hyphenateStyleName('MozTransition')
   *   < "-moz-transition"
   *   > hyphenateStyleName('msTransition')
   *   < "-ms-transition"
   *
   * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
   * is converted to `-ms-`.
   */

  function hyphenateStyleName(name) {
    return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
  }

  var warnValidStyle = function () {};

  {
    // 'msTransform' is correct, but the other prefixes should be capitalized
    var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
    var msPattern$1 = /^-ms-/;
    var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

    var badStyleValueWithSemicolonPattern = /;\s*$/;
    var warnedStyleNames = {};
    var warnedStyleValues = {};
    var warnedForNaNValue = false;
    var warnedForInfinityValue = false;

    var camelize = function (string) {
      return string.replace(hyphenPattern, function (_, character) {
        return character.toUpperCase();
      });
    };

    var warnHyphenatedStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
      // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
      // is converted to lowercase `ms`.
      camelize(name.replace(msPattern$1, 'ms-')));
    };

    var warnBadVendoredStyleName = function (name) {
      if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
        return;
      }

      warnedStyleNames[name] = true;

      error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
    };

    var warnStyleValueWithSemicolon = function (name, value) {
      if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
        return;
      }

      warnedStyleValues[value] = true;

      error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
    };

    var warnStyleValueIsNaN = function (name, value) {
      if (warnedForNaNValue) {
        return;
      }

      warnedForNaNValue = true;

      error('`NaN` is an invalid value for the `%s` css style property.', name);
    };

    var warnStyleValueIsInfinity = function (name, value) {
      if (warnedForInfinityValue) {
        return;
      }

      warnedForInfinityValue = true;

      error('`Infinity` is an invalid value for the `%s` css style property.', name);
    };

    warnValidStyle = function (name, value) {
      if (name.indexOf('-') > -1) {
        warnHyphenatedStyleName(name);
      } else if (badVendoredStyleNamePattern.test(name)) {
        warnBadVendoredStyleName(name);
      } else if (badStyleValueWithSemicolonPattern.test(value)) {
        warnStyleValueWithSemicolon(name, value);
      }

      if (typeof value === 'number') {
        if (isNaN(value)) {
          warnStyleValueIsNaN(name, value);
        } else if (!isFinite(value)) {
          warnStyleValueIsInfinity(name, value);
        }
      }
    };
  }

  var warnValidStyle$1 = warnValidStyle;

  /**
   * Operations for dealing with CSS properties.
   */

  /**
   * This creates a string that is expected to be equivalent to the style
   * attribute generated by server-side rendering. It by-passes warnings and
   * security checks so it's not safe to use this value for anything other than
   * comparison. It is only used in DEV for SSR validation.
   */

  function createDangerousStringForStyles(styles) {
    {
      var serialized = '';
      var delimiter = '';

      for (var styleName in styles) {
        if (!styles.hasOwnProperty(styleName)) {
          continue;
        }

        var styleValue = styles[styleName];

        if (styleValue != null) {
          var isCustomProperty = styleName.indexOf('--') === 0;
          serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
          serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
          delimiter = ';';
        }
      }

      return serialized || null;
    }
  }
  /**
   * Sets the value for multiple styles on a node.  If a value is specified as
   * '' (empty string), the corresponding style property will be unset.
   *
   * @param {DOMElement} node
   * @param {object} styles
   */

  function setValueForStyles(node, styles) {
    var style = node.style;

    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }

      var isCustomProperty = styleName.indexOf('--') === 0;

      {
        if (!isCustomProperty) {
          warnValidStyle$1(styleName, styles[styleName]);
        }
      }

      var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);

      if (styleName === 'float') {
        styleName = 'cssFloat';
      }

      if (isCustomProperty) {
        style.setProperty(styleName, styleValue);
      } else {
        style[styleName] = styleValue;
      }
    }
  }

  function isValueEmpty(value) {
    return value == null || typeof value === 'boolean' || value === '';
  }
  /**
   * Given {color: 'red', overflow: 'hidden'} returns {
   *   color: 'color',
   *   overflowX: 'overflow',
   *   overflowY: 'overflow',
   * }. This can be read as "the overflowY property was set by the overflow
   * shorthand". That is, the values are the property that each was derived from.
   */


  function expandShorthandMap(styles) {
    var expanded = {};

    for (var key in styles) {
      var longhands = shorthandToLonghand[key] || [key];

      for (var i = 0; i < longhands.length; i++) {
        expanded[longhands[i]] = key;
      }
    }

    return expanded;
  }
  /**
   * When mixing shorthand and longhand property names, we warn during updates if
   * we expect an incorrect result to occur. In particular, we warn for:
   *
   * Updating a shorthand property (longhand gets overwritten):
   *   {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
   *   becomes .style.font = 'baz'
   * Removing a shorthand property (longhand gets lost too):
   *   {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
   *   becomes .style.font = ''
   * Removing a longhand property (should revert to shorthand; doesn't):
   *   {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
   *   becomes .style.fontVariant = ''
   */


  function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
    {
      if (!nextStyles) {
        return;
      }

      var expandedUpdates = expandShorthandMap(styleUpdates);
      var expandedStyles = expandShorthandMap(nextStyles);
      var warnedAbout = {};

      for (var key in expandedUpdates) {
        var originalKey = expandedUpdates[key];
        var correctOriginalKey = expandedStyles[key];

        if (correctOriginalKey && originalKey !== correctOriginalKey) {
          var warningKey = originalKey + ',' + correctOriginalKey;

          if (warnedAbout[warningKey]) {
            continue;
          }

          warnedAbout[warningKey] = true;

          error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
        }
      }
    }
  }

  // For HTML, certain tags should omit their close tag. We keep a list for
  // those special-case tags.
  var omittedCloseTags = {
    area: true,
    base: true,
    br: true,
    col: true,
    embed: true,
    hr: true,
    img: true,
    input: true,
    keygen: true,
    link: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.

  };

  // `omittedCloseTags` except that `menuitem` should still have its closing tag.

  var voidElementTags = assign({
    menuitem: true
  }, omittedCloseTags);

  var HTML = '__html';

  function assertValidProps(tag, props) {
    if (!props) {
      return;
    } // Note the use of `==` which checks for null or undefined.


    if (voidElementTags[tag]) {
      if (props.children != null || props.dangerouslySetInnerHTML != null) {
        throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
      }
    }

    if (props.dangerouslySetInnerHTML != null) {
      if (props.children != null) {
        throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      }

      if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) {
        throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
      }
    }

    {
      if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
        error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
      }
    }

    if (props.style != null && typeof props.style !== 'object') {
      throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
    }
  }

  function isCustomComponent(tagName, props) {
    if (tagName.indexOf('-') === -1) {
      return typeof props.is === 'string';
    }

    switch (tagName) {
      // These are reserved SVG and MathML elements.
      // We don't mind this list too much because we expect it to never grow.
      // The alternative is to track the namespace in a few places which is convoluted.
      // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
      case 'annotation-xml':
      case 'color-profile':
      case 'font-face':
      case 'font-face-src':
      case 'font-face-uri':
      case 'font-face-format':
      case 'font-face-name':
      case 'missing-glyph':
        return false;

      default:
        return true;
    }
  }

  // When adding attributes to the HTML or SVG allowed attribute list, be sure to
  // also add them to this module to ensure casing and incorrect name
  // warnings.
  var possibleStandardNames = {
    // HTML
    accept: 'accept',
    acceptcharset: 'acceptCharset',
    'accept-charset': 'acceptCharset',
    accesskey: 'accessKey',
    action: 'action',
    allowfullscreen: 'allowFullScreen',
    alt: 'alt',
    as: 'as',
    async: 'async',
    autocapitalize: 'autoCapitalize',
    autocomplete: 'autoComplete',
    autocorrect: 'autoCorrect',
    autofocus: 'autoFocus',
    autoplay: 'autoPlay',
    autosave: 'autoSave',
    capture: 'capture',
    cellpadding: 'cellPadding',
    cellspacing: 'cellSpacing',
    challenge: 'challenge',
    charset: 'charSet',
    checked: 'checked',
    children: 'children',
    cite: 'cite',
    class: 'className',
    classid: 'classID',
    classname: 'className',
    cols: 'cols',
    colspan: 'colSpan',
    content: 'content',
    contenteditable: 'contentEditable',
    contextmenu: 'contextMenu',
    controls: 'controls',
    controlslist: 'controlsList',
    coords: 'coords',
    crossorigin: 'crossOrigin',
    dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
    data: 'data',
    datetime: 'dateTime',
    default: 'default',
    defaultchecked: 'defaultChecked',
    defaultvalue: 'defaultValue',
    defer: 'defer',
    dir: 'dir',
    disabled: 'disabled',
    disablepictureinpicture: 'disablePictureInPicture',
    disableremoteplayback: 'disableRemotePlayback',
    download: 'download',
    draggable: 'draggable',
    enctype: 'encType',
    enterkeyhint: 'enterKeyHint',
    for: 'htmlFor',
    form: 'form',
    formmethod: 'formMethod',
    formaction: 'formAction',
    formenctype: 'formEncType',
    formnovalidate: 'formNoValidate',
    formtarget: 'formTarget',
    frameborder: 'frameBorder',
    headers: 'headers',
    height: 'height',
    hidden: 'hidden',
    high: 'high',
    href: 'href',
    hreflang: 'hrefLang',
    htmlfor: 'htmlFor',
    httpequiv: 'httpEquiv',
    'http-equiv': 'httpEquiv',
    icon: 'icon',
    id: 'id',
    imagesizes: 'imageSizes',
    imagesrcset: 'imageSrcSet',
    innerhtml: 'innerHTML',
    inputmode: 'inputMode',
    integrity: 'integrity',
    is: 'is',
    itemid: 'itemID',
    itemprop: 'itemProp',
    itemref: 'itemRef',
    itemscope: 'itemScope',
    itemtype: 'itemType',
    keyparams: 'keyParams',
    keytype: 'keyType',
    kind: 'kind',
    label: 'label',
    lang: 'lang',
    list: 'list',
    loop: 'loop',
    low: 'low',
    manifest: 'manifest',
    marginwidth: 'marginWidth',
    marginheight: 'marginHeight',
    max: 'max',
    maxlength: 'maxLength',
    media: 'media',
    mediagroup: 'mediaGroup',
    method: 'method',
    min: 'min',
    minlength: 'minLength',
    multiple: 'multiple',
    muted: 'muted',
    name: 'name',
    nomodule: 'noModule',
    nonce: 'nonce',
    novalidate: 'noValidate',
    open: 'open',
    optimum: 'optimum',
    pattern: 'pattern',
    placeholder: 'placeholder',
    playsinline: 'playsInline',
    poster: 'poster',
    preload: 'preload',
    profile: 'profile',
    radiogroup: 'radioGroup',
    readonly: 'readOnly',
    referrerpolicy: 'referrerPolicy',
    rel: 'rel',
    required: 'required',
    reversed: 'reversed',
    role: 'role',
    rows: 'rows',
    rowspan: 'rowSpan',
    sandbox: 'sandbox',
    scope: 'scope',
    scoped: 'scoped',
    scrolling: 'scrolling',
    seamless: 'seamless',
    selected: 'selected',
    shape: 'shape',
    size: 'size',
    sizes: 'sizes',
    span: 'span',
    spellcheck: 'spellCheck',
    src: 'src',
    srcdoc: 'srcDoc',
    srclang: 'srcLang',
    srcset: 'srcSet',
    start: 'start',
    step: 'step',
    style: 'style',
    summary: 'summary',
    tabindex: 'tabIndex',
    target: 'target',
    title: 'title',
    type: 'type',
    usemap: 'useMap',
    value: 'value',
    width: 'width',
    wmode: 'wmode',
    wrap: 'wrap',
    // SVG
    about: 'about',
    accentheight: 'accentHeight',
    'accent-height': 'accentHeight',
    accumulate: 'accumulate',
    additive: 'additive',
    alignmentbaseline: 'alignmentBaseline',
    'alignment-baseline': 'alignmentBaseline',
    allowreorder: 'allowReorder',
    alphabetic: 'alphabetic',
    amplitude: 'amplitude',
    arabicform: 'arabicForm',
    'arabic-form': 'arabicForm',
    ascent: 'ascent',
    attributename: 'attributeName',
    attributetype: 'attributeType',
    autoreverse: 'autoReverse',
    azimuth: 'azimuth',
    basefrequency: 'baseFrequency',
    baselineshift: 'baselineShift',
    'baseline-shift': 'baselineShift',
    baseprofile: 'baseProfile',
    bbox: 'bbox',
    begin: 'begin',
    bias: 'bias',
    by: 'by',
    calcmode: 'calcMode',
    capheight: 'capHeight',
    'cap-height': 'capHeight',
    clip: 'clip',
    clippath: 'clipPath',
    'clip-path': 'clipPath',
    clippathunits: 'clipPathUnits',
    cliprule: 'clipRule',
    'clip-rule': 'clipRule',
    color: 'color',
    colorinterpolation: 'colorInterpolation',
    'color-interpolation': 'colorInterpolation',
    colorinterpolationfilters: 'colorInterpolationFilters',
    'color-interpolation-filters': 'colorInterpolationFilters',
    colorprofile: 'colorProfile',
    'color-profile': 'colorProfile',
    colorrendering: 'colorRendering',
    'color-rendering': 'colorRendering',
    contentscripttype: 'contentScriptType',
    contentstyletype: 'contentStyleType',
    cursor: 'cursor',
    cx: 'cx',
    cy: 'cy',
    d: 'd',
    datatype: 'datatype',
    decelerate: 'decelerate',
    descent: 'descent',
    diffuseconstant: 'diffuseConstant',
    direction: 'direction',
    display: 'display',
    divisor: 'divisor',
    dominantbaseline: 'dominantBaseline',
    'dominant-baseline': 'dominantBaseline',
    dur: 'dur',
    dx: 'dx',
    dy: 'dy',
    edgemode: 'edgeMode',
    elevation: 'elevation',
    enablebackground: 'enableBackground',
    'enable-background': 'enableBackground',
    end: 'end',
    exponent: 'exponent',
    externalresourcesrequired: 'externalResourcesRequired',
    fill: 'fill',
    fillopacity: 'fillOpacity',
    'fill-opacity': 'fillOpacity',
    fillrule: 'fillRule',
    'fill-rule': 'fillRule',
    filter: 'filter',
    filterres: 'filterRes',
    filterunits: 'filterUnits',
    floodopacity: 'floodOpacity',
    'flood-opacity': 'floodOpacity',
    floodcolor: 'floodColor',
    'flood-color': 'floodColor',
    focusable: 'focusable',
    fontfamily: 'fontFamily',
    'font-family': 'fontFamily',
    fontsize: 'fontSize',
    'font-size': 'fontSize',
    fontsizeadjust: 'fontSizeAdjust',
    'font-size-adjust': 'fontSizeAdjust',
    fontstretch: 'fontStretch',
    'font-stretch': 'fontStretch',
    fontstyle: 'fontStyle',
    'font-style': 'fontStyle',
    fontvariant: 'fontVariant',
    'font-variant': 'fontVariant',
    fontweight: 'fontWeight',
    'font-weight': 'fontWeight',
    format: 'format',
    from: 'from',
    fx: 'fx',
    fy: 'fy',
    g1: 'g1',
    g2: 'g2',
    glyphname: 'glyphName',
    'glyph-name': 'glyphName',
    glyphorientationhorizontal: 'glyphOrientationHorizontal',
    'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
    glyphorientationvertical: 'glyphOrientationVertical',
    'glyph-orientation-vertical': 'glyphOrientationVertical',
    glyphref: 'glyphRef',
    gradienttransform: 'gradientTransform',
    gradientunits: 'gradientUnits',
    hanging: 'hanging',
    horizadvx: 'horizAdvX',
    'horiz-adv-x': 'horizAdvX',
    horizoriginx: 'horizOriginX',
    'horiz-origin-x': 'horizOriginX',
    ideographic: 'ideographic',
    imagerendering: 'imageRendering',
    'image-rendering': 'imageRendering',
    in2: 'in2',
    in: 'in',
    inlist: 'inlist',
    intercept: 'intercept',
    k1: 'k1',
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
    k: 'k',
    kernelmatrix: 'kernelMatrix',
    kernelunitlength: 'kernelUnitLength',
    kerning: 'kerning',
    keypoints: 'keyPoints',
    keysplines: 'keySplines',
    keytimes: 'keyTimes',
    lengthadjust: 'lengthAdjust',
    letterspacing: 'letterSpacing',
    'letter-spacing': 'letterSpacing',
    lightingcolor: 'lightingColor',
    'lighting-color': 'lightingColor',
    limitingconeangle: 'limitingConeAngle',
    local: 'local',
    markerend: 'markerEnd',
    'marker-end': 'markerEnd',
    markerheight: 'markerHeight',
    markermid: 'markerMid',
    'marker-mid': 'markerMid',
    markerstart: 'markerStart',
    'marker-start': 'markerStart',
    markerunits: 'markerUnits',
    markerwidth: 'markerWidth',
    mask: 'mask',
    maskcontentunits: 'maskContentUnits',
    maskunits: 'maskUnits',
    mathematical: 'mathematical',
    mode: 'mode',
    numoctaves: 'numOctaves',
    offset: 'offset',
    opacity: 'opacity',
    operator: 'operator',
    order: 'order',
    orient: 'orient',
    orientation: 'orientation',
    origin: 'origin',
    overflow: 'overflow',
    overlineposition: 'overlinePosition',
    'overline-position': 'overlinePosition',
    overlinethickness: 'overlineThickness',
    'overline-thickness': 'overlineThickness',
    paintorder: 'paintOrder',
    'paint-order': 'paintOrder',
    panose1: 'panose1',
    'panose-1': 'panose1',
    pathlength: 'pathLength',
    patterncontentunits: 'patternContentUnits',
    patterntransform: 'patternTransform',
    patternunits: 'patternUnits',
    pointerevents: 'pointerEvents',
    'pointer-events': 'pointerEvents',
    points: 'points',
    pointsatx: 'pointsAtX',
    pointsaty: 'pointsAtY',
    pointsatz: 'pointsAtZ',
    prefix: 'prefix',
    preservealpha: 'preserveAlpha',
    preserveaspectratio: 'preserveAspectRatio',
    primitiveunits: 'primitiveUnits',
    property: 'property',
    r: 'r',
    radius: 'radius',
    refx: 'refX',
    refy: 'refY',
    renderingintent: 'renderingIntent',
    'rendering-intent': 'renderingIntent',
    repeatcount: 'repeatCount',
    repeatdur: 'repeatDur',
    requiredextensions: 'requiredExtensions',
    requiredfeatures: 'requiredFeatures',
    resource: 'resource',
    restart: 'restart',
    result: 'result',
    results: 'results',
    rotate: 'rotate',
    rx: 'rx',
    ry: 'ry',
    scale: 'scale',
    security: 'security',
    seed: 'seed',
    shaperendering: 'shapeRendering',
    'shape-rendering': 'shapeRendering',
    slope: 'slope',
    spacing: 'spacing',
    specularconstant: 'specularConstant',
    specularexponent: 'specularExponent',
    speed: 'speed',
    spreadmethod: 'spreadMethod',
    startoffset: 'startOffset',
    stddeviation: 'stdDeviation',
    stemh: 'stemh',
    stemv: 'stemv',
    stitchtiles: 'stitchTiles',
    stopcolor: 'stopColor',
    'stop-color': 'stopColor',
    stopopacity: 'stopOpacity',
    'stop-opacity': 'stopOpacity',
    strikethroughposition: 'strikethroughPosition',
    'strikethrough-position': 'strikethroughPosition',
    strikethroughthickness: 'strikethroughThickness',
    'strikethrough-thickness': 'strikethroughThickness',
    string: 'string',
    stroke: 'stroke',
    strokedasharray: 'strokeDasharray',
    'stroke-dasharray': 'strokeDasharray',
    strokedashoffset: 'strokeDashoffset',
    'stroke-dashoffset': 'strokeDashoffset',
    strokelinecap: 'strokeLinecap',
    'stroke-linecap': 'strokeLinecap',
    strokelinejoin: 'strokeLinejoin',
    'stroke-linejoin': 'strokeLinejoin',
    strokemiterlimit: 'strokeMiterlimit',
    'stroke-miterlimit': 'strokeMiterlimit',
    strokewidth: 'strokeWidth',
    'stroke-width': 'strokeWidth',
    strokeopacity: 'strokeOpacity',
    'stroke-opacity': 'strokeOpacity',
    suppresscontenteditablewarning: 'suppressContentEditableWarning',
    suppresshydrationwarning: 'suppressHydrationWarning',
    surfacescale: 'surfaceScale',
    systemlanguage: 'systemLanguage',
    tablevalues: 'tableValues',
    targetx: 'targetX',
    targety: 'targetY',
    textanchor: 'textAnchor',
    'text-anchor': 'textAnchor',
    textdecoration: 'textDecoration',
    'text-decoration': 'textDecoration',
    textlength: 'textLength',
    textrendering: 'textRendering',
    'text-rendering': 'textRendering',
    to: 'to',
    transform: 'transform',
    typeof: 'typeof',
    u1: 'u1',
    u2: 'u2',
    underlineposition: 'underlinePosition',
    'underline-position': 'underlinePosition',
    underlinethickness: 'underlineThickness',
    'underline-thickness': 'underlineThickness',
    unicode: 'unicode',
    unicodebidi: 'unicodeBidi',
    'unicode-bidi': 'unicodeBidi',
    unicoderange: 'unicodeRange',
    'unicode-range': 'unicodeRange',
    unitsperem: 'unitsPerEm',
    'units-per-em': 'unitsPerEm',
    unselectable: 'unselectable',
    valphabetic: 'vAlphabetic',
    'v-alphabetic': 'vAlphabetic',
    values: 'values',
    vectoreffect: 'vectorEffect',
    'vector-effect': 'vectorEffect',
    version: 'version',
    vertadvy: 'vertAdvY',
    'vert-adv-y': 'vertAdvY',
    vertoriginx: 'vertOriginX',
    'vert-origin-x': 'vertOriginX',
    vertoriginy: 'vertOriginY',
    'vert-origin-y': 'vertOriginY',
    vhanging: 'vHanging',
    'v-hanging': 'vHanging',
    videographic: 'vIdeographic',
    'v-ideographic': 'vIdeographic',
    viewbox: 'viewBox',
    viewtarget: 'viewTarget',
    visibility: 'visibility',
    vmathematical: 'vMathematical',
    'v-mathematical': 'vMathematical',
    vocab: 'vocab',
    widths: 'widths',
    wordspacing: 'wordSpacing',
    'word-spacing': 'wordSpacing',
    writingmode: 'writingMode',
    'writing-mode': 'writingMode',
    x1: 'x1',
    x2: 'x2',
    x: 'x',
    xchannelselector: 'xChannelSelector',
    xheight: 'xHeight',
    'x-height': 'xHeight',
    xlinkactuate: 'xlinkActuate',
    'xlink:actuate': 'xlinkActuate',
    xlinkarcrole: 'xlinkArcrole',
    'xlink:arcrole': 'xlinkArcrole',
    xlinkhref: 'xlinkHref',
    'xlink:href': 'xlinkHref',
    xlinkrole: 'xlinkRole',
    'xlink:role': 'xlinkRole',
    xlinkshow: 'xlinkShow',
    'xlink:show': 'xlinkShow',
    xlinktitle: 'xlinkTitle',
    'xlink:title': 'xlinkTitle',
    xlinktype: 'xlinkType',
    'xlink:type': 'xlinkType',
    xmlbase: 'xmlBase',
    'xml:base': 'xmlBase',
    xmllang: 'xmlLang',
    'xml:lang': 'xmlLang',
    xmlns: 'xmlns',
    'xml:space': 'xmlSpace',
    xmlnsxlink: 'xmlnsXlink',
    'xmlns:xlink': 'xmlnsXlink',
    xmlspace: 'xmlSpace',
    y1: 'y1',
    y2: 'y2',
    y: 'y',
    ychannelselector: 'yChannelSelector',
    z: 'z',
    zoomandpan: 'zoomAndPan'
  };

  var ariaProperties = {
    'aria-current': 0,
    // state
    'aria-description': 0,
    'aria-details': 0,
    'aria-disabled': 0,
    // state
    'aria-hidden': 0,
    // state
    'aria-invalid': 0,
    // state
    'aria-keyshortcuts': 0,
    'aria-label': 0,
    'aria-roledescription': 0,
    // Widget Attributes
    'aria-autocomplete': 0,
    'aria-checked': 0,
    'aria-expanded': 0,
    'aria-haspopup': 0,
    'aria-level': 0,
    'aria-modal': 0,
    'aria-multiline': 0,
    'aria-multiselectable': 0,
    'aria-orientation': 0,
    'aria-placeholder': 0,
    'aria-pressed': 0,
    'aria-readonly': 0,
    'aria-required': 0,
    'aria-selected': 0,
    'aria-sort': 0,
    'aria-valuemax': 0,
    'aria-valuemin': 0,
    'aria-valuenow': 0,
    'aria-valuetext': 0,
    // Live Region Attributes
    'aria-atomic': 0,
    'aria-busy': 0,
    'aria-live': 0,
    'aria-relevant': 0,
    // Drag-and-Drop Attributes
    'aria-dropeffect': 0,
    'aria-grabbed': 0,
    // Relationship Attributes
    'aria-activedescendant': 0,
    'aria-colcount': 0,
    'aria-colindex': 0,
    'aria-colspan': 0,
    'aria-controls': 0,
    'aria-describedby': 0,
    'aria-errormessage': 0,
    'aria-flowto': 0,
    'aria-labelledby': 0,
    'aria-owns': 0,
    'aria-posinset': 0,
    'aria-rowcount': 0,
    'aria-rowindex': 0,
    'aria-rowspan': 0,
    'aria-setsize': 0
  };

  var warnedProperties = {};
  var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  function validateProperty(tagName, name) {
    {
      if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
        return true;
      }

      if (rARIACamel.test(name)) {
        var ariaName = 'aria-' + name.slice(4).toLowerCase();
        var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (correctName == null) {
          error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

          warnedProperties[name] = true;
          return true;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== correctName) {
          error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

          warnedProperties[name] = true;
          return true;
        }
      }

      if (rARIA.test(name)) {
        var lowerCasedName = name.toLowerCase();
        var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
        // DOM properties, then it is an invalid aria-* attribute.

        if (standardName == null) {
          warnedProperties[name] = true;
          return false;
        } // aria-* attributes should be lowercase; suggest the lowercase version.


        if (name !== standardName) {
          error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties[name] = true;
          return true;
        }
      }
    }

    return true;
  }

  function warnInvalidARIAProps(type, props) {
    {
      var invalidProps = [];

      for (var key in props) {
        var isValid = validateProperty(type, key);

        if (!isValid) {
          invalidProps.push(key);
        }
      }

      var unknownPropString = invalidProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (invalidProps.length === 1) {
        error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      } else if (invalidProps.length > 1) {
        error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
      }
    }
  }

  function validateProperties(type, props) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnInvalidARIAProps(type, props);
  }

  var didWarnValueNull = false;
  function validateProperties$1(type, props) {
    {
      if (type !== 'input' && type !== 'textarea' && type !== 'select') {
        return;
      }

      if (props != null && props.value === null && !didWarnValueNull) {
        didWarnValueNull = true;

        if (type === 'select' && props.multiple) {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
        } else {
          error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
        }
      }
    }
  }

  var validateProperty$1 = function () {};

  {
    var warnedProperties$1 = {};
    var EVENT_NAME_REGEX = /^on./;
    var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
    var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
    var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

    validateProperty$1 = function (tagName, name, value, eventRegistry) {
      if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
        return true;
      }

      var lowerCasedName = name.toLowerCase();

      if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
        error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

        warnedProperties$1[name] = true;
        return true;
      } // We can't rely on the event system being injected on the server.


      if (eventRegistry != null) {
        var registrationNameDependencies = eventRegistry.registrationNameDependencies,
            possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

        if (registrationNameDependencies.hasOwnProperty(name)) {
          return true;
        }

        var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

        if (registrationName != null) {
          error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

          warnedProperties$1[name] = true;
          return true;
        }

        if (EVENT_NAME_REGEX.test(name)) {
          error('Unknown event handler property `%s`. It will be ignored.', name);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (EVENT_NAME_REGEX.test(name)) {
        // If no event plugins have been injected, we are in a server environment.
        // So we can't tell if the event name is correct for sure, but we can filter
        // out known bad ones like `onclick`. We can't suggest a specific replacement though.
        if (INVALID_EVENT_NAME_REGEX.test(name)) {
          error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Let the ARIA attribute hook validate ARIA attributes


      if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
        return true;
      }

      if (lowerCasedName === 'innerhtml') {
        error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'aria') {
        error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

        warnedProperties$1[name] = true;
        return true;
      }

      if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
        error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'number' && isNaN(value)) {
        error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

        warnedProperties$1[name] = true;
        return true;
      }

      var propertyInfo = getPropertyInfo(name);
      var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        var standardName = possibleStandardNames[lowerCasedName];

        if (standardName !== name) {
          error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

          warnedProperties$1[name] = true;
          return true;
        }
      } else if (!isReserved && name !== lowerCasedName) {
        // Unknown attributes should have lowercase casing since that's how they
        // will be cased anyway with server rendering.
        error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        if (value) {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
        } else {
          error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
        }

        warnedProperties$1[name] = true;
        return true;
      } // Now that we've validated casing, do not validate
      // data types for reserved props


      if (isReserved) {
        return true;
      } // Warn when a known attribute is a bad type


      if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
        warnedProperties$1[name] = true;
        return false;
      } // Warn when passing the strings 'false' or 'true' into a boolean prop


      if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
        error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

        warnedProperties$1[name] = true;
        return true;
      }

      return true;
    };
  }

  var warnUnknownProperties = function (type, props, eventRegistry) {
    {
      var unknownProps = [];

      for (var key in props) {
        var isValid = validateProperty$1(type, key, props[key], eventRegistry);

        if (!isValid) {
          unknownProps.push(key);
        }
      }

      var unknownPropString = unknownProps.map(function (prop) {
        return '`' + prop + '`';
      }).join(', ');

      if (unknownProps.length === 1) {
        error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      } else if (unknownProps.length > 1) {
        error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
      }
    }
  };

  function validateProperties$2(type, props, eventRegistry) {
    if (isCustomComponent(type, props)) {
      return;
    }

    warnUnknownProperties(type, props, eventRegistry);
  }

  var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
  var IS_NON_DELEGATED = 1 << 1;
  var IS_CAPTURE_PHASE = 1 << 2;
  // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
  // we call willDeferLaterForLegacyFBSupport, thus not bailing out
  // will result in endless cycles like an infinite loop.
  // We also don't want to defer during event replaying.

  var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;

  // This exists to avoid circular dependency between ReactDOMEventReplaying
  // and DOMPluginEventSystem.
  var currentReplayingEvent = null;
  function setReplayingEvent(event) {
    {
      if (currentReplayingEvent !== null) {
        error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
      }
    }

    currentReplayingEvent = event;
  }
  function resetReplayingEvent() {
    {
      if (currentReplayingEvent === null) {
        error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
      }
    }

    currentReplayingEvent = null;
  }
  function isReplayingEvent(event) {
    return event === currentReplayingEvent;
  }

  /**
   * Gets the target node from a native browser event by accounting for
   * inconsistencies in browser DOM APIs.
   *
   * @param {object} nativeEvent Native browser event.
   * @return {DOMEventTarget} Target node.
   */

  function getEventTarget(nativeEvent) {
    // Fallback to nativeEvent.srcElement for IE9
    // https://github.com/facebook/react/issues/12506
    var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963

    if (target.correspondingUseElement) {
      target = target.correspondingUseElement;
    } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
    // @see http://www.quirksmode.org/js/events_properties.html


    return target.nodeType === TEXT_NODE ? target.parentNode : target;
  }

  var restoreImpl = null;
  var restoreTarget = null;
  var restoreQueue = null;

  function restoreStateOfTarget(target) {
    // We perform this translation at the end of the event loop so that we
    // always receive the correct fiber here
    var internalInstance = getInstanceFromNode(target);

    if (!internalInstance) {
      // Unmounted
      return;
    }

    if (typeof restoreImpl !== 'function') {
      throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.');
    }

    var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.

    if (stateNode) {
      var _props = getFiberCurrentPropsFromNode(stateNode);

      restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
    }
  }

  function setRestoreImplementation(impl) {
    restoreImpl = impl;
  }
  function enqueueStateRestore(target) {
    if (restoreTarget) {
      if (restoreQueue) {
        restoreQueue.push(target);
      } else {
        restoreQueue = [target];
      }
    } else {
      restoreTarget = target;
    }
  }
  function needsStateRestore() {
    return restoreTarget !== null || restoreQueue !== null;
  }
  function restoreStateIfNeeded() {
    if (!restoreTarget) {
      return;
    }

    var target = restoreTarget;
    var queuedTargets = restoreQueue;
    restoreTarget = null;
    restoreQueue = null;
    restoreStateOfTarget(target);

    if (queuedTargets) {
      for (var i = 0; i < queuedTargets.length; i++) {
        restoreStateOfTarget(queuedTargets[i]);
      }
    }
  }

  // the renderer. Such as when we're dispatching events or if third party
  // libraries need to call batchedUpdates. Eventually, this API will go away when
  // everything is batched by default. We'll then have a similar API to opt-out of
  // scheduled work and instead do synchronous work.
  // Defaults

  var batchedUpdatesImpl = function (fn, bookkeeping) {
    return fn(bookkeeping);
  };

  var flushSyncImpl = function () {};

  var isInsideEventHandler = false;

  function finishEventHandler() {
    // Here we wait until all updates have propagated, which is important
    // when using controlled components within layers:
    // https://github.com/facebook/react/issues/1698
    // Then we restore state of any controlled component.
    var controlledComponentsHavePendingUpdates = needsStateRestore();

    if (controlledComponentsHavePendingUpdates) {
      // If a controlled event was fired, we may need to restore the state of
      // the DOM node back to the controlled value. This is necessary when React
      // bails out of the update without touching the DOM.
      // TODO: Restore state in the microtask, after the discrete updates flush,
      // instead of early flushing them here.
      flushSyncImpl();
      restoreStateIfNeeded();
    }
  }

  function batchedUpdates(fn, a, b) {
    if (isInsideEventHandler) {
      // If we are currently inside another batch, we need to wait until it
      // fully completes before restoring state.
      return fn(a, b);
    }

    isInsideEventHandler = true;

    try {
      return batchedUpdatesImpl(fn, a, b);
    } finally {
      isInsideEventHandler = false;
      finishEventHandler();
    }
  } // TODO: Replace with flushSync
  function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
    batchedUpdatesImpl = _batchedUpdatesImpl;
    flushSyncImpl = _flushSyncImpl;
  }

  function isInteractive(tag) {
    return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
  }

  function shouldPreventMouseEvent(name, type, props) {
    switch (name) {
      case 'onClick':
      case 'onClickCapture':
      case 'onDoubleClick':
      case 'onDoubleClickCapture':
      case 'onMouseDown':
      case 'onMouseDownCapture':
      case 'onMouseMove':
      case 'onMouseMoveCapture':
      case 'onMouseUp':
      case 'onMouseUpCapture':
      case 'onMouseEnter':
        return !!(props.disabled && isInteractive(type));

      default:
        return false;
    }
  }
  /**
   * @param {object} inst The instance, which is the source of events.
   * @param {string} registrationName Name of listener (e.g. `onClick`).
   * @return {?function} The stored callback.
   */


  function getListener(inst, registrationName) {
    var stateNode = inst.stateNode;

    if (stateNode === null) {
      // Work in progress (ex: onload events in incremental mode).
      return null;
    }

    var props = getFiberCurrentPropsFromNode(stateNode);

    if (props === null) {
      // Work in progress.
      return null;
    }

    var listener = props[registrationName];

    if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
      return null;
    }

    if (listener && typeof listener !== 'function') {
      throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
    }

    return listener;
  }

  var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
  // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support

  if (canUseDOM) {
    try {
      var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value

      Object.defineProperty(options, 'passive', {
        get: function () {
          passiveBrowserEventsSupported = true;
        }
      });
      window.addEventListener('test', options, options);
      window.removeEventListener('test', options, options);
    } catch (e) {
      passiveBrowserEventsSupported = false;
    }
  }

  function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
    var funcArgs = Array.prototype.slice.call(arguments, 3);

    try {
      func.apply(context, funcArgs);
    } catch (error) {
      this.onError(error);
    }
  }

  var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;

  {
    // In DEV mode, we swap out invokeGuardedCallback for a special version
    // that plays more nicely with the browser's DevTools. The idea is to preserve
    // "Pause on exceptions" behavior. Because React wraps all user-provided
    // functions in invokeGuardedCallback, and the production version of
    // invokeGuardedCallback uses a try-catch, all user exceptions are treated
    // like caught exceptions, and the DevTools won't pause unless the developer
    // takes the extra step of enabling pause on caught exceptions. This is
    // unintuitive, though, because even though React has caught the error, from
    // the developer's perspective, the error is uncaught.
    //
    // To preserve the expected "Pause on exceptions" behavior, we don't use a
    // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
    // DOM node, and call the user-provided callback from inside an event handler
    // for that fake event. If the callback throws, the error is "captured" using
    // a global event handler. But because the error happens in a different
    // event loop context, it does not interrupt the normal program flow.
    // Effectively, this gives us try-catch behavior without actually using
    // try-catch. Neat!
    // Check that the browser supports the APIs we need to implement our special
    // DEV version of invokeGuardedCallback
    if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
      var fakeNode = document.createElement('react');

      invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
        // If document doesn't exist we know for sure we will crash in this method
        // when we call document.createEvent(). However this can cause confusing
        // errors: https://github.com/facebook/create-react-app/issues/3482
        // So we preemptively throw with a better message instead.
        if (typeof document === 'undefined' || document === null) {
          throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
        }

        var evt = document.createEvent('Event');
        var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
        // set this to true at the beginning, then set it to false right after
        // calling the function. If the function errors, `didError` will never be
        // set to false. This strategy works even if the browser is flaky and
        // fails to call our global error handler, because it doesn't rely on
        // the error event at all.

        var didError = true; // Keeps track of the value of window.event so that we can reset it
        // during the callback to let user code access window.event in the
        // browsers that support it.

        var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
        // dispatching: https://github.com/facebook/react/issues/13688

        var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');

        function restoreAfterDispatch() {
          // We immediately remove the callback from event listeners so that
          // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
          // nested call would trigger the fake event handlers of any call higher
          // in the stack.
          fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
          // window.event assignment in both IE <= 10 as they throw an error
          // "Member not found" in strict mode, and in Firefox which does not
          // support window.event.

          if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
            window.event = windowEvent;
          }
        } // Create an event handler for our fake event. We will synchronously
        // dispatch our fake event using `dispatchEvent`. Inside the handler, we
        // call the user-provided callback.


        var funcArgs = Array.prototype.slice.call(arguments, 3);

        function callCallback() {
          didCall = true;
          restoreAfterDispatch();
          func.apply(context, funcArgs);
          didError = false;
        } // Create a global error event handler. We use this to capture the value
        // that was thrown. It's possible that this error handler will fire more
        // than once; for example, if non-React code also calls `dispatchEvent`
        // and a handler for that event throws. We should be resilient to most of
        // those cases. Even if our error event handler fires more than once, the
        // last error event is always used. If the callback actually does error,
        // we know that the last error event is the correct one, because it's not
        // possible for anything else to have happened in between our callback
        // erroring and the code that follows the `dispatchEvent` call below. If
        // the callback doesn't error, but the error event was fired, we know to
        // ignore it because `didError` will be false, as described above.


        var error; // Use this to track whether the error event is ever called.

        var didSetError = false;
        var isCrossOriginError = false;

        function handleWindowError(event) {
          error = event.error;
          didSetError = true;

          if (error === null && event.colno === 0 && event.lineno === 0) {
            isCrossOriginError = true;
          }

          if (event.defaultPrevented) {
            // Some other error handler has prevented default.
            // Browsers silence the error report if this happens.
            // We'll remember this to later decide whether to log it or not.
            if (error != null && typeof error === 'object') {
              try {
                error._suppressLogging = true;
              } catch (inner) {// Ignore.
              }
            }
          }
        } // Create a fake event type.


        var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers

        window.addEventListener('error', handleWindowError);
        fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
        // errors, it will trigger our global error handler.

        evt.initEvent(evtType, false, false);
        fakeNode.dispatchEvent(evt);

        if (windowEventDescriptor) {
          Object.defineProperty(window, 'event', windowEventDescriptor);
        }

        if (didCall && didError) {
          if (!didSetError) {
            // The callback errored, but the error event never fired.
            // eslint-disable-next-line react-internal/prod-error-codes
            error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
          } else if (isCrossOriginError) {
            // eslint-disable-next-line react-internal/prod-error-codes
            error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
          }

          this.onError(error);
        } // Remove our event listeners


        window.removeEventListener('error', handleWindowError);

        if (!didCall) {
          // Something went really wrong, and our event was not dispatched.
          // https://github.com/facebook/react/issues/16734
          // https://github.com/facebook/react/issues/16585
          // Fall back to the production implementation.
          restoreAfterDispatch();
          return invokeGuardedCallbackProd.apply(this, arguments);
        }
      };
    }
  }

  var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;

  var hasError = false;
  var caughtError = null; // Used by event system to capture/rethrow the first error.

  var hasRethrowError = false;
  var rethrowError = null;
  var reporter = {
    onError: function (error) {
      hasError = true;
      caughtError = error;
    }
  };
  /**
   * Call a function while guarding against errors that happens within it.
   * Returns an error if it throws, otherwise null.
   *
   * In production, this is implemented using a try-catch. The reason we don't
   * use a try-catch directly is so that we can swap out a different
   * implementation in DEV mode.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */

  function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
    hasError = false;
    caughtError = null;
    invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  }
  /**
   * Same as invokeGuardedCallback, but instead of returning an error, it stores
   * it in a global so it can be rethrown by `rethrowCaughtError` later.
   * TODO: See if caughtError and rethrowError can be unified.
   *
   * @param {String} name of the guard to use for logging or debugging
   * @param {Function} func The function to invoke
   * @param {*} context The context to use when calling the function
   * @param {...*} args Arguments for function
   */

  function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
    invokeGuardedCallback.apply(this, arguments);

    if (hasError) {
      var error = clearCaughtError();

      if (!hasRethrowError) {
        hasRethrowError = true;
        rethrowError = error;
      }
    }
  }
  /**
   * During execution of guarded functions we will capture the first error which
   * we will rethrow to be handled by the top level error handler.
   */

  function rethrowCaughtError() {
    if (hasRethrowError) {
      var error = rethrowError;
      hasRethrowError = false;
      rethrowError = null;
      throw error;
    }
  }
  function hasCaughtError() {
    return hasError;
  }
  function clearCaughtError() {
    if (hasError) {
      var error = caughtError;
      hasError = false;
      caughtError = null;
      return error;
    } else {
      throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
    }
  }

  var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  var _ReactInternals$Sched = ReactInternals.Scheduler,
      unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
      unstable_now = _ReactInternals$Sched.unstable_now,
      unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
      unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
      unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
      unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
      unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
      unstable_next = _ReactInternals$Sched.unstable_next,
      unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
      unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
      unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
      unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
      unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
      unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
      unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
      unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
      unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
      unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting,
      unstable_yieldValue = _ReactInternals$Sched.unstable_yieldValue,
      unstable_setDisableYieldValue = _ReactInternals$Sched.unstable_setDisableYieldValue;

  /**
   * `ReactInstanceMap` maintains a mapping from a public facing stateful
   * instance (key) and the internal representation (value). This allows public
   * methods to accept the user facing instance as an argument and map them back
   * to internal methods.
   *
   * Note that this module is currently shared and assumed to be stateless.
   * If this becomes an actual Map, that will break.
   */
  function get(key) {
    return key._reactInternals;
  }
  function has(key) {
    return key._reactInternals !== undefined;
  }
  function set(key, value) {
    key._reactInternals = value;
  }

  // Don't change these two values. They're used by React Dev Tools.
  var NoFlags =
  /*                      */
  0;
  var PerformedWork =
  /*                */
  1; // You can change the rest (and add more).

  var Placement =
  /*                    */
  2;
  var Update =
  /*                       */
  4;
  var ChildDeletion =
  /*                */
  16;
  var ContentReset =
  /*                 */
  32;
  var Callback =
  /*                     */
  64;
  var DidCapture =
  /*                   */
  128;
  var ForceClientRender =
  /*            */
  256;
  var Ref =
  /*                          */
  512;
  var Snapshot =
  /*                     */
  1024;
  var Passive =
  /*                      */
  2048;
  var Hydrating =
  /*                    */
  4096;
  var Visibility =
  /*                   */
  8192;
  var StoreConsistency =
  /*             */
  16384;
  var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit)

  var HostEffectMask =
  /*               */
  32767; // These are not really side effects, but we still reuse this field.

  var Incomplete =
  /*                   */
  32768;
  var ShouldCapture =
  /*                */
  65536;
  var ForceUpdateForLegacySuspense =
  /* */
  131072;
  var Forked =
  /*                       */
  1048576; // Static tags describe aspects of a fiber that are not specific to a render,
  // e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
  // This enables us to defer more work in the unmount case,
  // since we can defer traversing the tree during layout to look for Passive effects,
  // and instead rely on the static flag as a signal that there may be cleanup work.

  var RefStatic =
  /*                    */
  2097152;
  var LayoutStatic =
  /*                 */
  4194304;
  var PassiveStatic =
  /*                */
  8388608; // These flags allow us to traverse to fibers that have effects on mount
  // without traversing the entire tree after every commit for
  // double invoking

  var MountLayoutDev =
  /*               */
  16777216;
  var MountPassiveDev =
  /*              */
  33554432; // Groups of flags that are used in the commit phase to skip over trees that
  // don't contain effects, by checking subtreeFlags.

  var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility
  // flag logic (see #20043)
  Update | Snapshot | ( 0);
  var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
  var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask

  var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones.
  // This allows certain concepts to persist without recalculating them,
  // e.g. whether a subtree contains passive effects or portals.

  var StaticMask = LayoutStatic | PassiveStatic | RefStatic;

  var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  function getNearestMountedFiber(fiber) {
    var node = fiber;
    var nearestMounted = fiber;

    if (!fiber.alternate) {
      // If there is no alternate, this might be a new tree that isn't inserted
      // yet. If it is, then it will have a pending insertion effect on it.
      var nextNode = node;

      do {
        node = nextNode;

        if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
          // This is an insertion or in-progress hydration. The nearest possible
          // mounted fiber is the parent but we need to continue to figure out
          // if that one is still mounted.
          nearestMounted = node.return;
        }

        nextNode = node.return;
      } while (nextNode);
    } else {
      while (node.return) {
        node = node.return;
      }
    }

    if (node.tag === HostRoot) {
      // TODO: Check if this was a nested HostRoot when used with
      // renderContainerIntoSubtree.
      return nearestMounted;
    } // If we didn't hit the root, that means that we're in an disconnected tree
    // that has been unmounted.


    return null;
  }
  function getSuspenseInstanceFromFiber(fiber) {
    if (fiber.tag === SuspenseComponent) {
      var suspenseState = fiber.memoizedState;

      if (suspenseState === null) {
        var current = fiber.alternate;

        if (current !== null) {
          suspenseState = current.memoizedState;
        }
      }

      if (suspenseState !== null) {
        return suspenseState.dehydrated;
      }
    }

    return null;
  }
  function getContainerFromFiber(fiber) {
    return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
  }
  function isFiberMounted(fiber) {
    return getNearestMountedFiber(fiber) === fiber;
  }
  function isMounted(component) {
    {
      var owner = ReactCurrentOwner.current;

      if (owner !== null && owner.tag === ClassComponent) {
        var ownerFiber = owner;
        var instance = ownerFiber.stateNode;

        if (!instance._warnedAboutRefsInRender) {
          error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component');
        }

        instance._warnedAboutRefsInRender = true;
      }
    }

    var fiber = get(component);

    if (!fiber) {
      return false;
    }

    return getNearestMountedFiber(fiber) === fiber;
  }

  function assertIsMounted(fiber) {
    if (getNearestMountedFiber(fiber) !== fiber) {
      throw new Error('Unable to find node on an unmounted component.');
    }
  }

  function findCurrentFiberUsingSlowPath(fiber) {
    var alternate = fiber.alternate;

    if (!alternate) {
      // If there is no alternate, then we only need to check if it is mounted.
      var nearestMounted = getNearestMountedFiber(fiber);

      if (nearestMounted === null) {
        throw new Error('Unable to find node on an unmounted component.');
      }

      if (nearestMounted !== fiber) {
        return null;
      }

      return fiber;
    } // If we have two possible branches, we'll walk backwards up to the root
    // to see what path the root points to. On the way we may hit one of the
    // special cases and we'll deal with them.


    var a = fiber;
    var b = alternate;

    while (true) {
      var parentA = a.return;

      if (parentA === null) {
        // We're at the root.
        break;
      }

      var parentB = parentA.alternate;

      if (parentB === null) {
        // There is no alternate. This is an unusual case. Currently, it only
        // happens when a Suspense component is hidden. An extra fragment fiber
        // is inserted in between the Suspense fiber and its children. Skip
        // over this extra fragment fiber and proceed to the next parent.
        var nextParent = parentA.return;

        if (nextParent !== null) {
          a = b = nextParent;
          continue;
        } // If there's no parent, we're at the root.


        break;
      } // If both copies of the parent fiber point to the same child, we can
      // assume that the child is current. This happens when we bailout on low
      // priority: the bailed out fiber's child reuses the current child.


      if (parentA.child === parentB.child) {
        var child = parentA.child;

        while (child) {
          if (child === a) {
            // We've determined that A is the current branch.
            assertIsMounted(parentA);
            return fiber;
          }

          if (child === b) {
            // We've determined that B is the current branch.
            assertIsMounted(parentA);
            return alternate;
          }

          child = child.sibling;
        } // We should never have an alternate for any mounting node. So the only
        // way this could possibly happen is if this was unmounted, if at all.


        throw new Error('Unable to find node on an unmounted component.');
      }

      if (a.return !== b.return) {
        // The return pointer of A and the return pointer of B point to different
        // fibers. We assume that return pointers never criss-cross, so A must
        // belong to the child set of A.return, and B must belong to the child
        // set of B.return.
        a = parentA;
        b = parentB;
      } else {
        // The return pointers point to the same fiber. We'll have to use the
        // default, slow path: scan the child sets of each parent alternate to see
        // which child belongs to which set.
        //
        // Search parent A's child set
        var didFindChild = false;
        var _child = parentA.child;

        while (_child) {
          if (_child === a) {
            didFindChild = true;
            a = parentA;
            b = parentB;
            break;
          }

          if (_child === b) {
            didFindChild = true;
            b = parentA;
            a = parentB;
            break;
          }

          _child = _child.sibling;
        }

        if (!didFindChild) {
          // Search parent B's child set
          _child = parentB.child;

          while (_child) {
            if (_child === a) {
              didFindChild = true;
              a = parentB;
              b = parentA;
              break;
            }

            if (_child === b) {
              didFindChild = true;
              b = parentB;
              a = parentA;
              break;
            }

            _child = _child.sibling;
          }

          if (!didFindChild) {
            throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
          }
        }
      }

      if (a.alternate !== b) {
        throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
      }
    } // If the root is not a host container, we're in a disconnected tree. I.e.
    // unmounted.


    if (a.tag !== HostRoot) {
      throw new Error('Unable to find node on an unmounted component.');
    }

    if (a.stateNode.current === a) {
      // We've determined that A is the current branch.
      return fiber;
    } // Otherwise B has to be current branch.


    return alternate;
  }
  function findCurrentHostFiber(parent) {
    var currentParent = findCurrentFiberUsingSlowPath(parent);
    return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
  }

  function findCurrentHostFiberImpl(node) {
    // Next we'll drill down this component to find the first HostComponent/Text.
    if (node.tag === HostComponent || node.tag === HostText) {
      return node;
    }

    var child = node.child;

    while (child !== null) {
      var match = findCurrentHostFiberImpl(child);

      if (match !== null) {
        return match;
      }

      child = child.sibling;
    }

    return null;
  }

  function findCurrentHostFiberWithNoPortals(parent) {
    var currentParent = findCurrentFiberUsingSlowPath(parent);
    return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
  }

  function findCurrentHostFiberWithNoPortalsImpl(node) {
    // Next we'll drill down this component to find the first HostComponent/Text.
    if (node.tag === HostComponent || node.tag === HostText) {
      return node;
    }

    var child = node.child;

    while (child !== null) {
      if (child.tag !== HostPortal) {
        var match = findCurrentHostFiberWithNoPortalsImpl(child);

        if (match !== null) {
          return match;
        }
      }

      child = child.sibling;
    }

    return null;
  }

  // This module only exists as an ESM wrapper around the external CommonJS
  var scheduleCallback = unstable_scheduleCallback;
  var cancelCallback = unstable_cancelCallback;
  var shouldYield = unstable_shouldYield;
  var requestPaint = unstable_requestPaint;
  var now = unstable_now;
  var getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
  var ImmediatePriority = unstable_ImmediatePriority;
  var UserBlockingPriority = unstable_UserBlockingPriority;
  var NormalPriority = unstable_NormalPriority;
  var LowPriority = unstable_LowPriority;
  var IdlePriority = unstable_IdlePriority;
  // this doesn't actually exist on the scheduler, but it *does*
  // on scheduler/unstable_mock, which we'll need for internal testing
  var unstable_yieldValue$1 = unstable_yieldValue;
  var unstable_setDisableYieldValue$1 = unstable_setDisableYieldValue;

  var rendererID = null;
  var injectedHook = null;
  var injectedProfilingHooks = null;
  var hasLoggedError = false;
  var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
  function injectInternals(internals) {
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
      // No DevTools
      return false;
    }

    var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;

    if (hook.isDisabled) {
      // This isn't a real property on the hook, but it can be set to opt out
      // of DevTools integration and associated warnings and logs.
      // https://github.com/facebook/react/issues/3877
      return true;
    }

    if (!hook.supportsFiber) {
      {
        error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools');
      } // DevTools exists, even though it doesn't support Fiber.


      return true;
    }

    try {
      if (enableSchedulingProfiler) {
        // Conditionally inject these hooks only if Timeline profiler is supported by this build.
        // This gives DevTools a way to feature detect that isn't tied to version number
        // (since profiling and timeline are controlled by different feature flags).
        internals = assign({}, internals, {
          getLaneLabelMap: getLaneLabelMap,
          injectProfilingHooks: injectProfilingHooks
        });
      }

      rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.

      injectedHook = hook;
    } catch (err) {
      // Catch all errors because it is unsafe to throw during initialization.
      {
        error('React instrumentation encountered an error: %s.', err);
      }
    }

    if (hook.checkDCE) {
      // This is the real DevTools.
      return true;
    } else {
      // This is likely a hook installed by Fast Refresh runtime.
      return false;
    }
  }
  function onScheduleRoot(root, children) {
    {
      if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
        try {
          injectedHook.onScheduleFiberRoot(rendererID, root, children);
        } catch (err) {
          if ( !hasLoggedError) {
            hasLoggedError = true;

            error('React instrumentation encountered an error: %s', err);
          }
        }
      }
    }
  }
  function onCommitRoot(root, eventPriority) {
    if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
      try {
        var didError = (root.current.flags & DidCapture) === DidCapture;

        if (enableProfilerTimer) {
          var schedulerPriority;

          switch (eventPriority) {
            case DiscreteEventPriority:
              schedulerPriority = ImmediatePriority;
              break;

            case ContinuousEventPriority:
              schedulerPriority = UserBlockingPriority;
              break;

            case DefaultEventPriority:
              schedulerPriority = NormalPriority;
              break;

            case IdleEventPriority:
              schedulerPriority = IdlePriority;
              break;

            default:
              schedulerPriority = NormalPriority;
              break;
          }

          injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError);
        } else {
          injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
        }
      } catch (err) {
        {
          if (!hasLoggedError) {
            hasLoggedError = true;

            error('React instrumentation encountered an error: %s', err);
          }
        }
      }
    }
  }
  function onPostCommitRoot(root) {
    if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') {
      try {
        injectedHook.onPostCommitFiberRoot(rendererID, root);
      } catch (err) {
        {
          if (!hasLoggedError) {
            hasLoggedError = true;

            error('React instrumentation encountered an error: %s', err);
          }
        }
      }
    }
  }
  function onCommitUnmount(fiber) {
    if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
      try {
        injectedHook.onCommitFiberUnmount(rendererID, fiber);
      } catch (err) {
        {
          if (!hasLoggedError) {
            hasLoggedError = true;

            error('React instrumentation encountered an error: %s', err);
          }
        }
      }
    }
  }
  function setIsStrictModeForDevtools(newIsStrictMode) {
    {
      if (typeof unstable_yieldValue$1 === 'function') {
        // We're in a test because Scheduler.unstable_yieldValue only exists
        // in SchedulerMock. To reduce the noise in strict mode tests,
        // suppress warnings and disable scheduler yielding during the double render
        unstable_setDisableYieldValue$1(newIsStrictMode);
        setSuppressWarning(newIsStrictMode);
      }

      if (injectedHook && typeof injectedHook.setStrictMode === 'function') {
        try {
          injectedHook.setStrictMode(rendererID, newIsStrictMode);
        } catch (err) {
          {
            if (!hasLoggedError) {
              hasLoggedError = true;

              error('React instrumentation encountered an error: %s', err);
            }
          }
        }
      }
    }
  } // Profiler API hooks

  function injectProfilingHooks(profilingHooks) {
    injectedProfilingHooks = profilingHooks;
  }

  function getLaneLabelMap() {
    {
      var map = new Map();
      var lane = 1;

      for (var index = 0; index < TotalLanes; index++) {
        var label = getLabelForLane(lane);
        map.set(lane, label);
        lane *= 2;
      }

      return map;
    }
  }

  function markCommitStarted(lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') {
        injectedProfilingHooks.markCommitStarted(lanes);
      }
    }
  }
  function markCommitStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') {
        injectedProfilingHooks.markCommitStopped();
      }
    }
  }
  function markComponentRenderStarted(fiber) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') {
        injectedProfilingHooks.markComponentRenderStarted(fiber);
      }
    }
  }
  function markComponentRenderStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') {
        injectedProfilingHooks.markComponentRenderStopped();
      }
    }
  }
  function markComponentPassiveEffectMountStarted(fiber) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') {
        injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
      }
    }
  }
  function markComponentPassiveEffectMountStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') {
        injectedProfilingHooks.markComponentPassiveEffectMountStopped();
      }
    }
  }
  function markComponentPassiveEffectUnmountStarted(fiber) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') {
        injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
      }
    }
  }
  function markComponentPassiveEffectUnmountStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') {
        injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
      }
    }
  }
  function markComponentLayoutEffectMountStarted(fiber) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') {
        injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
      }
    }
  }
  function markComponentLayoutEffectMountStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') {
        injectedProfilingHooks.markComponentLayoutEffectMountStopped();
      }
    }
  }
  function markComponentLayoutEffectUnmountStarted(fiber) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') {
        injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
      }
    }
  }
  function markComponentLayoutEffectUnmountStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') {
        injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
      }
    }
  }
  function markComponentErrored(fiber, thrownValue, lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') {
        injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
      }
    }
  }
  function markComponentSuspended(fiber, wakeable, lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') {
        injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
      }
    }
  }
  function markLayoutEffectsStarted(lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') {
        injectedProfilingHooks.markLayoutEffectsStarted(lanes);
      }
    }
  }
  function markLayoutEffectsStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') {
        injectedProfilingHooks.markLayoutEffectsStopped();
      }
    }
  }
  function markPassiveEffectsStarted(lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') {
        injectedProfilingHooks.markPassiveEffectsStarted(lanes);
      }
    }
  }
  function markPassiveEffectsStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') {
        injectedProfilingHooks.markPassiveEffectsStopped();
      }
    }
  }
  function markRenderStarted(lanes) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') {
        injectedProfilingHooks.markRenderStarted(lanes);
      }
    }
  }
  function markRenderYielded() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') {
        injectedProfilingHooks.markRenderYielded();
      }
    }
  }
  function markRenderStopped() {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') {
        injectedProfilingHooks.markRenderStopped();
      }
    }
  }
  function markRenderScheduled(lane) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') {
        injectedProfilingHooks.markRenderScheduled(lane);
      }
    }
  }
  function markForceUpdateScheduled(fiber, lane) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') {
        injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
      }
    }
  }
  function markStateUpdateScheduled(fiber, lane) {
    {
      if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') {
        injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
      }
    }
  }

  var NoMode =
  /*                         */
  0; // TODO: Remove ConcurrentMode by reading from the root tag instead

  var ConcurrentMode =
  /*                 */
  1;
  var ProfileMode =
  /*                    */
  2;
  var StrictLegacyMode =
  /*               */
  8;
  var StrictEffectsMode =
  /*              */
  16;

  // TODO: This is pretty well supported by browsers. Maybe we can drop it.
  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
  // Based on:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

  var log = Math.log;
  var LN2 = Math.LN2;

  function clz32Fallback(x) {
    var asUint = x >>> 0;

    if (asUint === 0) {
      return 32;
    }

    return 31 - (log(asUint) / LN2 | 0) | 0;
  }

  // If those values are changed that package should be rebuilt and redeployed.

  var TotalLanes = 31;
  var NoLanes =
  /*                        */
  0;
  var NoLane =
  /*                          */
  0;
  var SyncLane =
  /*                        */
  1;
  var InputContinuousHydrationLane =
  /*    */
  2;
  var InputContinuousLane =
  /*             */
  4;
  var DefaultHydrationLane =
  /*            */
  8;
  var DefaultLane =
  /*                     */
  16;
  var TransitionHydrationLane =
  /*                */
  32;
  var TransitionLanes =
  /*                       */
  4194240;
  var TransitionLane1 =
  /*                        */
  64;
  var TransitionLane2 =
  /*                        */
  128;
  var TransitionLane3 =
  /*                        */
  256;
  var TransitionLane4 =
  /*                        */
  512;
  var TransitionLane5 =
  /*                        */
  1024;
  var TransitionLane6 =
  /*                        */
  2048;
  var TransitionLane7 =
  /*                        */
  4096;
  var TransitionLane8 =
  /*                        */
  8192;
  var TransitionLane9 =
  /*                        */
  16384;
  var TransitionLane10 =
  /*                       */
  32768;
  var TransitionLane11 =
  /*                       */
  65536;
  var TransitionLane12 =
  /*                       */
  131072;
  var TransitionLane13 =
  /*                       */
  262144;
  var TransitionLane14 =
  /*                       */
  524288;
  var TransitionLane15 =
  /*                       */
  1048576;
  var TransitionLane16 =
  /*                       */
  2097152;
  var RetryLanes =
  /*                            */
  130023424;
  var RetryLane1 =
  /*                             */
  4194304;
  var RetryLane2 =
  /*                             */
  8388608;
  var RetryLane3 =
  /*                             */
  16777216;
  var RetryLane4 =
  /*                             */
  33554432;
  var RetryLane5 =
  /*                             */
  67108864;
  var SomeRetryLane = RetryLane1;
  var SelectiveHydrationLane =
  /*          */
  134217728;
  var NonIdleLanes =
  /*                          */
  268435455;
  var IdleHydrationLane =
  /*               */
  268435456;
  var IdleLane =
  /*                        */
  536870912;
  var OffscreenLane =
  /*                   */
  1073741824; // This function is used for the experimental timeline (react-devtools-timeline)
  // It should be kept in sync with the Lanes values above.

  function getLabelForLane(lane) {
    {
      if (lane & SyncLane) {
        return 'Sync';
      }

      if (lane & InputContinuousHydrationLane) {
        return 'InputContinuousHydration';
      }

      if (lane & InputContinuousLane) {
        return 'InputContinuous';
      }

      if (lane & DefaultHydrationLane) {
        return 'DefaultHydration';
      }

      if (lane & DefaultLane) {
        return 'Default';
      }

      if (lane & TransitionHydrationLane) {
        return 'TransitionHydration';
      }

      if (lane & TransitionLanes) {
        return 'Transition';
      }

      if (lane & RetryLanes) {
        return 'Retry';
      }

      if (lane & SelectiveHydrationLane) {
        return 'SelectiveHydration';
      }

      if (lane & IdleHydrationLane) {
        return 'IdleHydration';
      }

      if (lane & IdleLane) {
        return 'Idle';
      }

      if (lane & OffscreenLane) {
        return 'Offscreen';
      }
    }
  }
  var NoTimestamp = -1;
  var nextTransitionLane = TransitionLane1;
  var nextRetryLane = RetryLane1;

  function getHighestPriorityLanes(lanes) {
    switch (getHighestPriorityLane(lanes)) {
      case SyncLane:
        return SyncLane;

      case InputContinuousHydrationLane:
        return InputContinuousHydrationLane;

      case InputContinuousLane:
        return InputContinuousLane;

      case DefaultHydrationLane:
        return DefaultHydrationLane;

      case DefaultLane:
        return DefaultLane;

      case TransitionHydrationLane:
        return TransitionHydrationLane;

      case TransitionLane1:
      case TransitionLane2:
      case TransitionLane3:
      case TransitionLane4:
      case TransitionLane5:
      case TransitionLane6:
      case TransitionLane7:
      case TransitionLane8:
      case TransitionLane9:
      case TransitionLane10:
      case TransitionLane11:
      case TransitionLane12:
      case TransitionLane13:
      case TransitionLane14:
      case TransitionLane15:
      case TransitionLane16:
        return lanes & TransitionLanes;

      case RetryLane1:
      case RetryLane2:
      case RetryLane3:
      case RetryLane4:
      case RetryLane5:
        return lanes & RetryLanes;

      case SelectiveHydrationLane:
        return SelectiveHydrationLane;

      case IdleHydrationLane:
        return IdleHydrationLane;

      case IdleLane:
        return IdleLane;

      case OffscreenLane:
        return OffscreenLane;

      default:
        {
          error('Should have found matching lanes. This is a bug in React.');
        } // This shouldn't be reachable, but as a fallback, return the entire bitmask.


        return lanes;
    }
  }

  function getNextLanes(root, wipLanes) {
    // Early bailout if there's no pending work left.
    var pendingLanes = root.pendingLanes;

    if (pendingLanes === NoLanes) {
      return NoLanes;
    }

    var nextLanes = NoLanes;
    var suspendedLanes = root.suspendedLanes;
    var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished,
    // even if the work is suspended.

    var nonIdlePendingLanes = pendingLanes & NonIdleLanes;

    if (nonIdlePendingLanes !== NoLanes) {
      var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;

      if (nonIdleUnblockedLanes !== NoLanes) {
        nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
      } else {
        var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;

        if (nonIdlePingedLanes !== NoLanes) {
          nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
        }
      }
    } else {
      // The only remaining work is Idle.
      var unblockedLanes = pendingLanes & ~suspendedLanes;

      if (unblockedLanes !== NoLanes) {
        nextLanes = getHighestPriorityLanes(unblockedLanes);
      } else {
        if (pingedLanes !== NoLanes) {
          nextLanes = getHighestPriorityLanes(pingedLanes);
        }
      }
    }

    if (nextLanes === NoLanes) {
      // This should only be reachable if we're suspended
      // TODO: Consider warning in this path if a fallback timer is not scheduled.
      return NoLanes;
    } // If we're already in the middle of a render, switching lanes will interrupt
    // it and we'll lose our progress. We should only do this if the new lanes are
    // higher priority.


    if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
    // bother waiting until the root is complete.
    (wipLanes & suspendedLanes) === NoLanes) {
      var nextLane = getHighestPriorityLane(nextLanes);
      var wipLane = getHighestPriorityLane(wipLanes);

      if ( // Tests whether the next lane is equal or lower priority than the wip
      // one. This works because the bits decrease in priority as you go left.
      nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
      // only difference between default updates and transition updates is that
      // default updates do not support refresh transitions.
      nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) {
        // Keep working on the existing in-progress tree. Do not interrupt.
        return wipLanes;
      }
    }

    if ((nextLanes & InputContinuousLane) !== NoLanes) {
      // When updates are sync by default, we entangle continuous priority updates
      // and default updates, so they render in the same batch. The only reason
      // they use separate lanes is because continuous updates should interrupt
      // transitions, but default updates should not.
      nextLanes |= pendingLanes & DefaultLane;
    } // Check for entangled lanes and add them to the batch.
    //
    // A lane is said to be entangled with another when it's not allowed to render
    // in a batch that does not also include the other lane. Typically we do this
    // when multiple updates have the same source, and we only want to respond to
    // the most recent event from that source.
    //
    // Note that we apply entanglements *after* checking for partial work above.
    // This means that if a lane is entangled during an interleaved event while
    // it's already rendering, we won't interrupt it. This is intentional, since
    // entanglement is usually "best effort": we'll try our best to render the
    // lanes in the same batch, but it's not worth throwing out partially
    // completed work in order to do it.
    // TODO: Reconsider this. The counter-argument is that the partial work
    // represents an intermediate state, which we don't want to show to the user.
    // And by spending extra time finishing it, we're increasing the amount of
    // time it takes to show the final state, which is what they are actually
    // waiting for.
    //
    // For those exceptions where entanglement is semantically important, like
    // useMutableSource, we should ensure that there is no partial work at the
    // time we apply the entanglement.


    var entangledLanes = root.entangledLanes;

    if (entangledLanes !== NoLanes) {
      var entanglements = root.entanglements;
      var lanes = nextLanes & entangledLanes;

      while (lanes > 0) {
        var index = pickArbitraryLaneIndex(lanes);
        var lane = 1 << index;
        nextLanes |= entanglements[index];
        lanes &= ~lane;
      }
    }

    return nextLanes;
  }
  function getMostRecentEventTime(root, lanes) {
    var eventTimes = root.eventTimes;
    var mostRecentEventTime = NoTimestamp;

    while (lanes > 0) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;
      var eventTime = eventTimes[index];

      if (eventTime > mostRecentEventTime) {
        mostRecentEventTime = eventTime;
      }

      lanes &= ~lane;
    }

    return mostRecentEventTime;
  }

  function computeExpirationTime(lane, currentTime) {
    switch (lane) {
      case SyncLane:
      case InputContinuousHydrationLane:
      case InputContinuousLane:
        // User interactions should expire slightly more quickly.
        //
        // NOTE: This is set to the corresponding constant as in Scheduler.js.
        // When we made it larger, a product metric in www regressed, suggesting
        // there's a user interaction that's being starved by a series of
        // synchronous updates. If that theory is correct, the proper solution is
        // to fix the starvation. However, this scenario supports the idea that
        // expiration times are an important safeguard when starvation
        // does happen.
        return currentTime + 250;

      case DefaultHydrationLane:
      case DefaultLane:
      case TransitionHydrationLane:
      case TransitionLane1:
      case TransitionLane2:
      case TransitionLane3:
      case TransitionLane4:
      case TransitionLane5:
      case TransitionLane6:
      case TransitionLane7:
      case TransitionLane8:
      case TransitionLane9:
      case TransitionLane10:
      case TransitionLane11:
      case TransitionLane12:
      case TransitionLane13:
      case TransitionLane14:
      case TransitionLane15:
      case TransitionLane16:
        return currentTime + 5000;

      case RetryLane1:
      case RetryLane2:
      case RetryLane3:
      case RetryLane4:
      case RetryLane5:
        // TODO: Retries should be allowed to expire if they are CPU bound for
        // too long, but when I made this change it caused a spike in browser
        // crashes. There must be some other underlying bug; not super urgent but
        // ideally should figure out why and fix it. Unfortunately we don't have
        // a repro for the crashes, only detected via production metrics.
        return NoTimestamp;

      case SelectiveHydrationLane:
      case IdleHydrationLane:
      case IdleLane:
      case OffscreenLane:
        // Anything idle priority or lower should never expire.
        return NoTimestamp;

      default:
        {
          error('Should have found matching lanes. This is a bug in React.');
        }

        return NoTimestamp;
    }
  }

  function markStarvedLanesAsExpired(root, currentTime) {
    // TODO: This gets called every time we yield. We can optimize by storing
    // the earliest expiration time on the root. Then use that to quickly bail out
    // of this function.
    var pendingLanes = root.pendingLanes;
    var suspendedLanes = root.suspendedLanes;
    var pingedLanes = root.pingedLanes;
    var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
    // expiration time. If so, we'll assume the update is being starved and mark
    // it as expired to force it to finish.

    var lanes = pendingLanes;

    while (lanes > 0) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;
      var expirationTime = expirationTimes[index];

      if (expirationTime === NoTimestamp) {
        // Found a pending lane with no expiration time. If it's not suspended, or
        // if it's pinged, assume it's CPU-bound. Compute a new expiration time
        // using the current time.
        if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
          // Assumes timestamps are monotonically increasing.
          expirationTimes[index] = computeExpirationTime(lane, currentTime);
        }
      } else if (expirationTime <= currentTime) {
        // This lane expired
        root.expiredLanes |= lane;
      }

      lanes &= ~lane;
    }
  } // This returns the highest priority pending lanes regardless of whether they
  // are suspended.

  function getHighestPriorityPendingLanes(root) {
    return getHighestPriorityLanes(root.pendingLanes);
  }
  function getLanesToRetrySynchronouslyOnError(root) {
    var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;

    if (everythingButOffscreen !== NoLanes) {
      return everythingButOffscreen;
    }

    if (everythingButOffscreen & OffscreenLane) {
      return OffscreenLane;
    }

    return NoLanes;
  }
  function includesSyncLane(lanes) {
    return (lanes & SyncLane) !== NoLanes;
  }
  function includesNonIdleWork(lanes) {
    return (lanes & NonIdleLanes) !== NoLanes;
  }
  function includesOnlyRetries(lanes) {
    return (lanes & RetryLanes) === lanes;
  }
  function includesOnlyNonUrgentLanes(lanes) {
    var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
    return (lanes & UrgentLanes) === NoLanes;
  }
  function includesOnlyTransitions(lanes) {
    return (lanes & TransitionLanes) === lanes;
  }
  function includesBlockingLane(root, lanes) {

    var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
    return (lanes & SyncDefaultLanes) !== NoLanes;
  }
  function includesExpiredLane(root, lanes) {
    // This is a separate check from includesBlockingLane because a lane can
    // expire after a render has already started.
    return (lanes & root.expiredLanes) !== NoLanes;
  }
  function isTransitionLane(lane) {
    return (lane & TransitionLanes) !== NoLanes;
  }
  function claimNextTransitionLane() {
    // Cycle through the lanes, assigning each new transition to the next lane.
    // In most cases, this means every transition gets its own lane, until we
    // run out of lanes and cycle back to the beginning.
    var lane = nextTransitionLane;
    nextTransitionLane <<= 1;

    if ((nextTransitionLane & TransitionLanes) === NoLanes) {
      nextTransitionLane = TransitionLane1;
    }

    return lane;
  }
  function claimNextRetryLane() {
    var lane = nextRetryLane;
    nextRetryLane <<= 1;

    if ((nextRetryLane & RetryLanes) === NoLanes) {
      nextRetryLane = RetryLane1;
    }

    return lane;
  }
  function getHighestPriorityLane(lanes) {
    return lanes & -lanes;
  }
  function pickArbitraryLane(lanes) {
    // This wrapper function gets inlined. Only exists so to communicate that it
    // doesn't matter which bit is selected; you can pick any bit without
    // affecting the algorithms where its used. Here I'm using
    // getHighestPriorityLane because it requires the fewest operations.
    return getHighestPriorityLane(lanes);
  }

  function pickArbitraryLaneIndex(lanes) {
    return 31 - clz32(lanes);
  }

  function laneToIndex(lane) {
    return pickArbitraryLaneIndex(lane);
  }

  function includesSomeLane(a, b) {
    return (a & b) !== NoLanes;
  }
  function isSubsetOfLanes(set, subset) {
    return (set & subset) === subset;
  }
  function mergeLanes(a, b) {
    return a | b;
  }
  function removeLanes(set, subset) {
    return set & ~subset;
  }
  function intersectLanes(a, b) {
    return a & b;
  } // Seems redundant, but it changes the type from a single lane (used for
  // updates) to a group of lanes (used for flushing work).

  function laneToLanes(lane) {
    return lane;
  }
  function higherPriorityLane(a, b) {
    // This works because the bit ranges decrease in priority as you go left.
    return a !== NoLane && a < b ? a : b;
  }
  function createLaneMap(initial) {
    // Intentionally pushing one by one.
    // https://v8.dev/blog/elements-kinds#avoid-creating-holes
    var laneMap = [];

    for (var i = 0; i < TotalLanes; i++) {
      laneMap.push(initial);
    }

    return laneMap;
  }
  function markRootUpdated(root, updateLane, eventTime) {
    root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update
    // could unblock them. Clear the suspended lanes so that we can try rendering
    // them again.
    //
    // TODO: We really only need to unsuspend only lanes that are in the
    // `subtreeLanes` of the updated fiber, or the update lanes of the return
    // path. This would exclude suspended updates in an unrelated sibling tree,
    // since there's no way for this update to unblock it.
    //
    // We don't do this if the incoming update is idle, because we never process
    // idle updates until after all the regular updates have finished; there's no
    // way it could unblock a transition.

    if (updateLane !== IdleLane) {
      root.suspendedLanes = NoLanes;
      root.pingedLanes = NoLanes;
    }

    var eventTimes = root.eventTimes;
    var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
    // recent event, and we assume time is monotonically increasing.

    eventTimes[index] = eventTime;
  }
  function markRootSuspended(root, suspendedLanes) {
    root.suspendedLanes |= suspendedLanes;
    root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.

    var expirationTimes = root.expirationTimes;
    var lanes = suspendedLanes;

    while (lanes > 0) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;
      expirationTimes[index] = NoTimestamp;
      lanes &= ~lane;
    }
  }
  function markRootPinged(root, pingedLanes, eventTime) {
    root.pingedLanes |= root.suspendedLanes & pingedLanes;
  }
  function markRootFinished(root, remainingLanes) {
    var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
    root.pendingLanes = remainingLanes; // Let's try everything again

    root.suspendedLanes = NoLanes;
    root.pingedLanes = NoLanes;
    root.expiredLanes &= remainingLanes;
    root.mutableReadLanes &= remainingLanes;
    root.entangledLanes &= remainingLanes;
    var entanglements = root.entanglements;
    var eventTimes = root.eventTimes;
    var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work

    var lanes = noLongerPendingLanes;

    while (lanes > 0) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;
      entanglements[index] = NoLanes;
      eventTimes[index] = NoTimestamp;
      expirationTimes[index] = NoTimestamp;
      lanes &= ~lane;
    }
  }
  function markRootEntangled(root, entangledLanes) {
    // In addition to entangling each of the given lanes with each other, we also
    // have to consider _transitive_ entanglements. For each lane that is already
    // entangled with *any* of the given lanes, that lane is now transitively
    // entangled with *all* the given lanes.
    //
    // Translated: If C is entangled with A, then entangling A with B also
    // entangles C with B.
    //
    // If this is hard to grasp, it might help to intentionally break this
    // function and look at the tests that fail in ReactTransition-test.js. Try
    // commenting out one of the conditions below.
    var rootEntangledLanes = root.entangledLanes |= entangledLanes;
    var entanglements = root.entanglements;
    var lanes = rootEntangledLanes;

    while (lanes) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;

      if ( // Is this one of the newly entangled lanes?
      lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
      entanglements[index] & entangledLanes) {
        entanglements[index] |= entangledLanes;
      }

      lanes &= ~lane;
    }
  }
  function getBumpedLaneForHydration(root, renderLanes) {
    var renderLane = getHighestPriorityLane(renderLanes);
    var lane;

    switch (renderLane) {
      case InputContinuousLane:
        lane = InputContinuousHydrationLane;
        break;

      case DefaultLane:
        lane = DefaultHydrationLane;
        break;

      case TransitionLane1:
      case TransitionLane2:
      case TransitionLane3:
      case TransitionLane4:
      case TransitionLane5:
      case TransitionLane6:
      case TransitionLane7:
      case TransitionLane8:
      case TransitionLane9:
      case TransitionLane10:
      case TransitionLane11:
      case TransitionLane12:
      case TransitionLane13:
      case TransitionLane14:
      case TransitionLane15:
      case TransitionLane16:
      case RetryLane1:
      case RetryLane2:
      case RetryLane3:
      case RetryLane4:
      case RetryLane5:
        lane = TransitionHydrationLane;
        break;

      case IdleLane:
        lane = IdleHydrationLane;
        break;

      default:
        // Everything else is already either a hydration lane, or shouldn't
        // be retried at a hydration lane.
        lane = NoLane;
        break;
    } // Check if the lane we chose is suspended. If so, that indicates that we
    // already attempted and failed to hydrate at that level. Also check if we're
    // already rendering that lane, which is rare but could happen.


    if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) {
      // Give up trying to hydrate and fall back to client render.
      return NoLane;
    }

    return lane;
  }
  function addFiberToLanesMap(root, fiber, lanes) {

    if (!isDevToolsPresent) {
      return;
    }

    var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;

    while (lanes > 0) {
      var index = laneToIndex(lanes);
      var lane = 1 << index;
      var updaters = pendingUpdatersLaneMap[index];
      updaters.add(fiber);
      lanes &= ~lane;
    }
  }
  function movePendingFibersToMemoized(root, lanes) {

    if (!isDevToolsPresent) {
      return;
    }

    var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
    var memoizedUpdaters = root.memoizedUpdaters;

    while (lanes > 0) {
      var index = laneToIndex(lanes);
      var lane = 1 << index;
      var updaters = pendingUpdatersLaneMap[index];

      if (updaters.size > 0) {
        updaters.forEach(function (fiber) {
          var alternate = fiber.alternate;

          if (alternate === null || !memoizedUpdaters.has(alternate)) {
            memoizedUpdaters.add(fiber);
          }
        });
        updaters.clear();
      }

      lanes &= ~lane;
    }
  }
  function getTransitionsForLanes(root, lanes) {
    {
      return null;
    }
  }

  var DiscreteEventPriority = SyncLane;
  var ContinuousEventPriority = InputContinuousLane;
  var DefaultEventPriority = DefaultLane;
  var IdleEventPriority = IdleLane;
  var currentUpdatePriority = NoLane;
  function getCurrentUpdatePriority() {
    return currentUpdatePriority;
  }
  function setCurrentUpdatePriority(newPriority) {
    currentUpdatePriority = newPriority;
  }
  function runWithPriority(priority, fn) {
    var previousPriority = currentUpdatePriority;

    try {
      currentUpdatePriority = priority;
      return fn();
    } finally {
      currentUpdatePriority = previousPriority;
    }
  }
  function higherEventPriority(a, b) {
    return a !== 0 && a < b ? a : b;
  }
  function lowerEventPriority(a, b) {
    return a === 0 || a > b ? a : b;
  }
  function isHigherEventPriority(a, b) {
    return a !== 0 && a < b;
  }
  function lanesToEventPriority(lanes) {
    var lane = getHighestPriorityLane(lanes);

    if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
      return DiscreteEventPriority;
    }

    if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
      return ContinuousEventPriority;
    }

    if (includesNonIdleWork(lane)) {
      return DefaultEventPriority;
    }

    return IdleEventPriority;
  }

  // This is imported by the event replaying implementation in React DOM. It's
  // in a separate file to break a circular dependency between the renderer and
  // the reconciler.
  function isRootDehydrated(root) {
    var currentState = root.current.memoizedState;
    return currentState.isDehydrated;
  }

  var _attemptSynchronousHydration;

  function setAttemptSynchronousHydration(fn) {
    _attemptSynchronousHydration = fn;
  }
  function attemptSynchronousHydration(fiber) {
    _attemptSynchronousHydration(fiber);
  }
  var attemptContinuousHydration;
  function setAttemptContinuousHydration(fn) {
    attemptContinuousHydration = fn;
  }
  var attemptHydrationAtCurrentPriority;
  function setAttemptHydrationAtCurrentPriority(fn) {
    attemptHydrationAtCurrentPriority = fn;
  }
  var getCurrentUpdatePriority$1;
  function setGetCurrentUpdatePriority(fn) {
    getCurrentUpdatePriority$1 = fn;
  }
  var attemptHydrationAtPriority;
  function setAttemptHydrationAtPriority(fn) {
    attemptHydrationAtPriority = fn;
  } // TODO: Upgrade this definition once we're on a newer version of Flow that
  // has this definition built-in.

  var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.

  var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
  // if the last target was dehydrated.

  var queuedFocus = null;
  var queuedDrag = null;
  var queuedMouse = null; // For pointer events there can be one latest event per pointerId.

  var queuedPointers = new Map();
  var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.

  var queuedExplicitHydrationTargets = [];
  var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase
  'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit'];
  function isDiscreteEventThatRequiresHydration(eventType) {
    return discreteReplayableEvents.indexOf(eventType) > -1;
  }

  function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    return {
      blockedOn: blockedOn,
      domEventName: domEventName,
      eventSystemFlags: eventSystemFlags,
      nativeEvent: nativeEvent,
      targetContainers: [targetContainer]
    };
  }

  function clearIfContinuousEvent(domEventName, nativeEvent) {
    switch (domEventName) {
      case 'focusin':
      case 'focusout':
        queuedFocus = null;
        break;

      case 'dragenter':
      case 'dragleave':
        queuedDrag = null;
        break;

      case 'mouseover':
      case 'mouseout':
        queuedMouse = null;
        break;

      case 'pointerover':
      case 'pointerout':
        {
          var pointerId = nativeEvent.pointerId;
          queuedPointers.delete(pointerId);
          break;
        }

      case 'gotpointercapture':
      case 'lostpointercapture':
        {
          var _pointerId = nativeEvent.pointerId;
          queuedPointerCaptures.delete(_pointerId);
          break;
        }
    }
  }

  function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
      var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);

      if (blockedOn !== null) {
        var _fiber2 = getInstanceFromNode(blockedOn);

        if (_fiber2 !== null) {
          // Attempt to increase the priority of this target.
          attemptContinuousHydration(_fiber2);
        }
      }

      return queuedEvent;
    } // If we have already queued this exact event, then it's because
    // the different event systems have different DOM event listeners.
    // We can accumulate the flags, and the targetContainers, and
    // store a single event to be replayed.


    existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
    var targetContainers = existingQueuedEvent.targetContainers;

    if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
      targetContainers.push(targetContainer);
    }

    return existingQueuedEvent;
  }

  function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    // These set relatedTarget to null because the replayed event will be treated as if we
    // moved from outside the window (no target) onto the target once it hydrates.
    // Instead of mutating we could clone the event.
    switch (domEventName) {
      case 'focusin':
        {
          var focusEvent = nativeEvent;
          queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
          return true;
        }

      case 'dragenter':
        {
          var dragEvent = nativeEvent;
          queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
          return true;
        }

      case 'mouseover':
        {
          var mouseEvent = nativeEvent;
          queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
          return true;
        }

      case 'pointerover':
        {
          var pointerEvent = nativeEvent;
          var pointerId = pointerEvent.pointerId;
          queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
          return true;
        }

      case 'gotpointercapture':
        {
          var _pointerEvent = nativeEvent;
          var _pointerId2 = _pointerEvent.pointerId;
          queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
          return true;
        }
    }

    return false;
  } // Check if this target is unblocked. Returns true if it's unblocked.

  function attemptExplicitHydrationTarget(queuedTarget) {
    // TODO: This function shares a lot of logic with findInstanceBlockingEvent.
    // Try to unify them. It's a bit tricky since it would require two return
    // values.
    var targetInst = getClosestInstanceFromNode(queuedTarget.target);

    if (targetInst !== null) {
      var nearestMounted = getNearestMountedFiber(targetInst);

      if (nearestMounted !== null) {
        var tag = nearestMounted.tag;

        if (tag === SuspenseComponent) {
          var instance = getSuspenseInstanceFromFiber(nearestMounted);

          if (instance !== null) {
            // We're blocked on hydrating this boundary.
            // Increase its priority.
            queuedTarget.blockedOn = instance;
            attemptHydrationAtPriority(queuedTarget.priority, function () {
              attemptHydrationAtCurrentPriority(nearestMounted);
            });
            return;
          }
        } else if (tag === HostRoot) {
          var root = nearestMounted.stateNode;

          if (isRootDehydrated(root)) {
            queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
            // a root other than sync.

            return;
          }
        }
      }
    }

    queuedTarget.blockedOn = null;
  }

  function queueExplicitHydrationTarget(target) {
    // TODO: This will read the priority if it's dispatched by the React
    // event system but not native events. Should read window.event.type, like
    // we do for updates (getCurrentEventPriority).
    var updatePriority = getCurrentUpdatePriority$1();
    var queuedTarget = {
      blockedOn: null,
      target: target,
      priority: updatePriority
    };
    var i = 0;

    for (; i < queuedExplicitHydrationTargets.length; i++) {
      // Stop once we hit the first target with lower priority than
      if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) {
        break;
      }
    }

    queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);

    if (i === 0) {
      attemptExplicitHydrationTarget(queuedTarget);
    }
  }

  function attemptReplayContinuousQueuedEvent(queuedEvent) {
    if (queuedEvent.blockedOn !== null) {
      return false;
    }

    var targetContainers = queuedEvent.targetContainers;

    while (targetContainers.length > 0) {
      var targetContainer = targetContainers[0];
      var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);

      if (nextBlockedOn === null) {
        {
          var nativeEvent = queuedEvent.nativeEvent;
          var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
          setReplayingEvent(nativeEventClone);
          nativeEvent.target.dispatchEvent(nativeEventClone);
          resetReplayingEvent();
        }
      } else {
        // We're still blocked. Try again later.
        var _fiber3 = getInstanceFromNode(nextBlockedOn);

        if (_fiber3 !== null) {
          attemptContinuousHydration(_fiber3);
        }

        queuedEvent.blockedOn = nextBlockedOn;
        return false;
      } // This target container was successfully dispatched. Try the next.


      targetContainers.shift();
    }

    return true;
  }

  function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
    if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
      map.delete(key);
    }
  }

  function replayUnblockedEvents() {
    hasScheduledReplayAttempt = false;


    if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
      queuedFocus = null;
    }

    if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
      queuedDrag = null;
    }

    if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
      queuedMouse = null;
    }

    queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
    queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
  }

  function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
    if (queuedEvent.blockedOn === unblocked) {
      queuedEvent.blockedOn = null;

      if (!hasScheduledReplayAttempt) {
        hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
        // now unblocked. This first might not actually be unblocked yet.
        // We could check it early to avoid scheduling an unnecessary callback.

        unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
      }
    }
  }

  function retryIfBlockedOn(unblocked) {
    // Mark anything that was blocked on this as no longer blocked
    // and eligible for a replay.
    if (queuedDiscreteEvents.length > 0) {
      scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
      // worth it because we expect very few discrete events to queue up and once
      // we are actually fully unblocked it will be fast to replay them.

      for (var i = 1; i < queuedDiscreteEvents.length; i++) {
        var queuedEvent = queuedDiscreteEvents[i];

        if (queuedEvent.blockedOn === unblocked) {
          queuedEvent.blockedOn = null;
        }
      }
    }

    if (queuedFocus !== null) {
      scheduleCallbackIfUnblocked(queuedFocus, unblocked);
    }

    if (queuedDrag !== null) {
      scheduleCallbackIfUnblocked(queuedDrag, unblocked);
    }

    if (queuedMouse !== null) {
      scheduleCallbackIfUnblocked(queuedMouse, unblocked);
    }

    var unblock = function (queuedEvent) {
      return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
    };

    queuedPointers.forEach(unblock);
    queuedPointerCaptures.forEach(unblock);

    for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
      var queuedTarget = queuedExplicitHydrationTargets[_i];

      if (queuedTarget.blockedOn === unblocked) {
        queuedTarget.blockedOn = null;
      }
    }

    while (queuedExplicitHydrationTargets.length > 0) {
      var nextExplicitTarget = queuedExplicitHydrationTargets[0];

      if (nextExplicitTarget.blockedOn !== null) {
        // We're still blocked.
        break;
      } else {
        attemptExplicitHydrationTarget(nextExplicitTarget);

        if (nextExplicitTarget.blockedOn === null) {
          // We're unblocked.
          queuedExplicitHydrationTargets.shift();
        }
      }
    }
  }

  var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these?

  var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra.
  // We'd like to remove this but it's not clear if this is safe.

  function setEnabled(enabled) {
    _enabled = !!enabled;
  }
  function isEnabled() {
    return _enabled;
  }
  function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
    var eventPriority = getEventPriority(domEventName);
    var listenerWrapper;

    switch (eventPriority) {
      case DiscreteEventPriority:
        listenerWrapper = dispatchDiscreteEvent;
        break;

      case ContinuousEventPriority:
        listenerWrapper = dispatchContinuousEvent;
        break;

      case DefaultEventPriority:
      default:
        listenerWrapper = dispatchEvent;
        break;
    }

    return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
  }

  function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
    var previousPriority = getCurrentUpdatePriority();
    var prevTransition = ReactCurrentBatchConfig.transition;
    ReactCurrentBatchConfig.transition = null;

    try {
      setCurrentUpdatePriority(DiscreteEventPriority);
      dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig.transition = prevTransition;
    }
  }

  function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
    var previousPriority = getCurrentUpdatePriority();
    var prevTransition = ReactCurrentBatchConfig.transition;
    ReactCurrentBatchConfig.transition = null;

    try {
      setCurrentUpdatePriority(ContinuousEventPriority);
      dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig.transition = prevTransition;
    }
  }

  function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    if (!_enabled) {
      return;
    }

    {
      dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
    }
  }

  function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);

    if (blockedOn === null) {
      dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
      clearIfContinuousEvent(domEventName, nativeEvent);
      return;
    }

    if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
      nativeEvent.stopPropagation();
      return;
    } // We need to clear only if we didn't queue because
    // queueing is accumulative.


    clearIfContinuousEvent(domEventName, nativeEvent);

    if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
      while (blockedOn !== null) {
        var fiber = getInstanceFromNode(blockedOn);

        if (fiber !== null) {
          attemptSynchronousHydration(fiber);
        }

        var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);

        if (nextBlockedOn === null) {
          dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
        }

        if (nextBlockedOn === blockedOn) {
          break;
        }

        blockedOn = nextBlockedOn;
      }

      if (blockedOn !== null) {
        nativeEvent.stopPropagation();
      }

      return;
    } // This is not replayable so we'll invoke it but without a target,
    // in case the event system needs to trace it.


    dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
  }

  var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked.
  // The return_targetInst field above is conceptually part of the return value.

  function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    // TODO: Warn if _enabled is false.
    return_targetInst = null;
    var nativeEventTarget = getEventTarget(nativeEvent);
    var targetInst = getClosestInstanceFromNode(nativeEventTarget);

    if (targetInst !== null) {
      var nearestMounted = getNearestMountedFiber(targetInst);

      if (nearestMounted === null) {
        // This tree has been unmounted already. Dispatch without a target.
        targetInst = null;
      } else {
        var tag = nearestMounted.tag;

        if (tag === SuspenseComponent) {
          var instance = getSuspenseInstanceFromFiber(nearestMounted);

          if (instance !== null) {
            // Queue the event to be replayed later. Abort dispatching since we
            // don't want this event dispatched twice through the event system.
            // TODO: If this is the first discrete event in the queue. Schedule an increased
            // priority for this boundary.
            return instance;
          } // This shouldn't happen, something went wrong but to avoid blocking
          // the whole system, dispatch the event without a target.
          // TODO: Warn.


          targetInst = null;
        } else if (tag === HostRoot) {
          var root = nearestMounted.stateNode;

          if (isRootDehydrated(root)) {
            // If this happens during a replay something went wrong and it might block
            // the whole system.
            return getContainerFromFiber(nearestMounted);
          }

          targetInst = null;
        } else if (nearestMounted !== targetInst) {
          // If we get an event (ex: img onload) before committing that
          // component's mount, ignore it for now (that is, treat it as if it was an
          // event on a non-React tree). We might also consider queueing events and
          // dispatching them after the mount.
          targetInst = null;
        }
      }
    }

    return_targetInst = targetInst; // We're not blocked on anything.

    return null;
  }
  function getEventPriority(domEventName) {
    switch (domEventName) {
      // Used by SimpleEventPlugin:
      case 'cancel':
      case 'click':
      case 'close':
      case 'contextmenu':
      case 'copy':
      case 'cut':
      case 'auxclick':
      case 'dblclick':
      case 'dragend':
      case 'dragstart':
      case 'drop':
      case 'focusin':
      case 'focusout':
      case 'input':
      case 'invalid':
      case 'keydown':
      case 'keypress':
      case 'keyup':
      case 'mousedown':
      case 'mouseup':
      case 'paste':
      case 'pause':
      case 'play':
      case 'pointercancel':
      case 'pointerdown':
      case 'pointerup':
      case 'ratechange':
      case 'reset':
      case 'resize':
      case 'seeked':
      case 'submit':
      case 'touchcancel':
      case 'touchend':
      case 'touchstart':
      case 'volumechange': // Used by polyfills:
      // eslint-disable-next-line no-fallthrough

      case 'change':
      case 'selectionchange':
      case 'textInput':
      case 'compositionstart':
      case 'compositionend':
      case 'compositionupdate': // Only enableCreateEventHandleAPI:
      // eslint-disable-next-line no-fallthrough

      case 'beforeblur':
      case 'afterblur': // Not used by React but could be by user code:
      // eslint-disable-next-line no-fallthrough

      case 'beforeinput':
      case 'blur':
      case 'fullscreenchange':
      case 'focus':
      case 'hashchange':
      case 'popstate':
      case 'select':
      case 'selectstart':
        return DiscreteEventPriority;

      case 'drag':
      case 'dragenter':
      case 'dragexit':
      case 'dragleave':
      case 'dragover':
      case 'mousemove':
      case 'mouseout':
      case 'mouseover':
      case 'pointermove':
      case 'pointerout':
      case 'pointerover':
      case 'scroll':
      case 'toggle':
      case 'touchmove':
      case 'wheel': // Not used by React but could be by user code:
      // eslint-disable-next-line no-fallthrough

      case 'mouseenter':
      case 'mouseleave':
      case 'pointerenter':
      case 'pointerleave':
        return ContinuousEventPriority;

      case 'message':
        {
          // We might be in the Scheduler callback.
          // Eventually this mechanism will be replaced by a check
          // of the current priority on the native scheduler.
          var schedulerPriority = getCurrentPriorityLevel();

          switch (schedulerPriority) {
            case ImmediatePriority:
              return DiscreteEventPriority;

            case UserBlockingPriority:
              return ContinuousEventPriority;

            case NormalPriority:
            case LowPriority:
              // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
              return DefaultEventPriority;

            case IdlePriority:
              return IdleEventPriority;

            default:
              return DefaultEventPriority;
          }
        }

      default:
        return DefaultEventPriority;
    }
  }

  function addEventBubbleListener(target, eventType, listener) {
    target.addEventListener(eventType, listener, false);
    return listener;
  }
  function addEventCaptureListener(target, eventType, listener) {
    target.addEventListener(eventType, listener, true);
    return listener;
  }
  function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
    target.addEventListener(eventType, listener, {
      capture: true,
      passive: passive
    });
    return listener;
  }
  function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
    target.addEventListener(eventType, listener, {
      passive: passive
    });
    return listener;
  }

  /**
   * These variables store information about text content of a target node,
   * allowing comparison of content before and after a given event.
   *
   * Identify the node where selection currently begins, then observe
   * both its text content and its current position in the DOM. Since the
   * browser may natively replace the target node during composition, we can
   * use its position to find its replacement.
   *
   *
   */
  var root = null;
  var startText = null;
  var fallbackText = null;
  function initialize(nativeEventTarget) {
    root = nativeEventTarget;
    startText = getText();
    return true;
  }
  function reset() {
    root = null;
    startText = null;
    fallbackText = null;
  }
  function getData() {
    if (fallbackText) {
      return fallbackText;
    }

    var start;
    var startValue = startText;
    var startLength = startValue.length;
    var end;
    var endValue = getText();
    var endLength = endValue.length;

    for (start = 0; start < startLength; start++) {
      if (startValue[start] !== endValue[start]) {
        break;
      }
    }

    var minEnd = startLength - start;

    for (end = 1; end <= minEnd; end++) {
      if (startValue[startLength - end] !== endValue[endLength - end]) {
        break;
      }
    }

    var sliceTail = end > 1 ? 1 - end : undefined;
    fallbackText = endValue.slice(start, sliceTail);
    return fallbackText;
  }
  function getText() {
    if ('value' in root) {
      return root.value;
    }

    return root.textContent;
  }

  /**
   * `charCode` represents the actual "character code" and is safe to use with
   * `String.fromCharCode`. As such, only keys that correspond to printable
   * characters produce a valid `charCode`, the only exception to this is Enter.
   * The Tab-key is considered non-printable and does not have a `charCode`,
   * presumably because it does not produce a tab-character in browsers.
   *
   * @param {object} nativeEvent Native browser event.
   * @return {number} Normalized `charCode` property.
   */
  function getEventCharCode(nativeEvent) {
    var charCode;
    var keyCode = nativeEvent.keyCode;

    if ('charCode' in nativeEvent) {
      charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.

      if (charCode === 0 && keyCode === 13) {
        charCode = 13;
      }
    } else {
      // IE8 does not implement `charCode`, but `keyCode` has the correct value.
      charCode = keyCode;
    } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
    // report Enter as charCode 10 when ctrl is pressed.


    if (charCode === 10) {
      charCode = 13;
    } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
    // Must not discard the (non-)printable Enter-key.


    if (charCode >= 32 || charCode === 13) {
      return charCode;
    }

    return 0;
  }

  function functionThatReturnsTrue() {
    return true;
  }

  function functionThatReturnsFalse() {
    return false;
  } // This is intentionally a factory so that we have different returned constructors.
  // If we had a single constructor, it would be megamorphic and engines would deopt.


  function createSyntheticEvent(Interface) {
    /**
     * Synthetic events are dispatched by event plugins, typically in response to a
     * top-level event delegation handler.
     *
     * These systems should generally use pooling to reduce the frequency of garbage
     * collection. The system should check `isPersistent` to determine whether the
     * event should be released into the pool after being dispatched. Users that
     * need a persisted event should invoke `persist`.
     *
     * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
     * normalizing browser quirks. Subclasses do not necessarily have to implement a
     * DOM interface; custom application-specific events can also subclass this.
     */
    function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
      this._reactName = reactName;
      this._targetInst = targetInst;
      this.type = reactEventType;
      this.nativeEvent = nativeEvent;
      this.target = nativeEventTarget;
      this.currentTarget = null;

      for (var _propName in Interface) {
        if (!Interface.hasOwnProperty(_propName)) {
          continue;
        }

        var normalize = Interface[_propName];

        if (normalize) {
          this[_propName] = normalize(nativeEvent);
        } else {
          this[_propName] = nativeEvent[_propName];
        }
      }

      var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;

      if (defaultPrevented) {
        this.isDefaultPrevented = functionThatReturnsTrue;
      } else {
        this.isDefaultPrevented = functionThatReturnsFalse;
      }

      this.isPropagationStopped = functionThatReturnsFalse;
      return this;
    }

    assign(SyntheticBaseEvent.prototype, {
      preventDefault: function () {
        this.defaultPrevented = true;
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.preventDefault) {
          event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
        } else if (typeof event.returnValue !== 'unknown') {
          event.returnValue = false;
        }

        this.isDefaultPrevented = functionThatReturnsTrue;
      },
      stopPropagation: function () {
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.stopPropagation) {
          event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
        } else if (typeof event.cancelBubble !== 'unknown') {
          // The ChangeEventPlugin registers a "propertychange" event for
          // IE. This event does not support bubbling or cancelling, and
          // any references to cancelBubble throw "Member not found".  A
          // typeof check of "unknown" circumvents this issue (and is also
          // IE specific).
          event.cancelBubble = true;
        }

        this.isPropagationStopped = functionThatReturnsTrue;
      },

      /**
       * We release all dispatched `SyntheticEvent`s after each event loop, adding
       * them back into the pool. This allows a way to hold onto a reference that
       * won't be added back into the pool.
       */
      persist: function () {// Modern event system doesn't use pooling.
      },

      /**
       * Checks if this event should be released back into the pool.
       *
       * @return {boolean} True if this should not be released, false otherwise.
       */
      isPersistent: functionThatReturnsTrue
    });
    return SyntheticBaseEvent;
  }
  /**
   * @interface Event
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var EventInterface = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function (event) {
      return event.timeStamp || Date.now();
    },
    defaultPrevented: 0,
    isTrusted: 0
  };
  var SyntheticEvent = createSyntheticEvent(EventInterface);

  var UIEventInterface = assign({}, EventInterface, {
    view: 0,
    detail: 0
  });

  var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
  var lastMovementX;
  var lastMovementY;
  var lastMouseEvent;

  function updateMouseMovementPolyfillState(event) {
    if (event !== lastMouseEvent) {
      if (lastMouseEvent && event.type === 'mousemove') {
        lastMovementX = event.screenX - lastMouseEvent.screenX;
        lastMovementY = event.screenY - lastMouseEvent.screenY;
      } else {
        lastMovementX = 0;
        lastMovementY = 0;
      }

      lastMouseEvent = event;
    }
  }
  /**
   * @interface MouseEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var MouseEventInterface = assign({}, UIEventInterface, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: getEventModifierState,
    button: 0,
    buttons: 0,
    relatedTarget: function (event) {
      if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
      return event.relatedTarget;
    },
    movementX: function (event) {
      if ('movementX' in event) {
        return event.movementX;
      }

      updateMouseMovementPolyfillState(event);
      return lastMovementX;
    },
    movementY: function (event) {
      if ('movementY' in event) {
        return event.movementY;
      } // Don't need to call updateMouseMovementPolyfillState() here
      // because it's guaranteed to have already run when movementX
      // was copied.


      return lastMovementY;
    }
  });

  var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
  /**
   * @interface DragEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var DragEventInterface = assign({}, MouseEventInterface, {
    dataTransfer: 0
  });

  var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
  /**
   * @interface FocusEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var FocusEventInterface = assign({}, UIEventInterface, {
    relatedTarget: 0
  });

  var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
   * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
   */

  var AnimationEventInterface = assign({}, EventInterface, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  });

  var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/clipboard-apis/
   */

  var ClipboardEventInterface = assign({}, EventInterface, {
    clipboardData: function (event) {
      return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
    }
  });

  var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
   */

  var CompositionEventInterface = assign({}, EventInterface, {
    data: 0
  });

  var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
   *      /#events-inputevents
   */
  // Happens to share the same list for now.

  var SyntheticInputEvent = SyntheticCompositionEvent;
  /**
   * Normalization of deprecated HTML5 `key` values
   * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
   */

  var normalizeKey = {
    Esc: 'Escape',
    Spacebar: ' ',
    Left: 'ArrowLeft',
    Up: 'ArrowUp',
    Right: 'ArrowRight',
    Down: 'ArrowDown',
    Del: 'Delete',
    Win: 'OS',
    Menu: 'ContextMenu',
    Apps: 'ContextMenu',
    Scroll: 'ScrollLock',
    MozPrintableKey: 'Unidentified'
  };
  /**
   * Translation from legacy `keyCode` to HTML5 `key`
   * Only special keys supported, all others depend on keyboard layout or browser
   * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
   */

  var translateToKey = {
    '8': 'Backspace',
    '9': 'Tab',
    '12': 'Clear',
    '13': 'Enter',
    '16': 'Shift',
    '17': 'Control',
    '18': 'Alt',
    '19': 'Pause',
    '20': 'CapsLock',
    '27': 'Escape',
    '32': ' ',
    '33': 'PageUp',
    '34': 'PageDown',
    '35': 'End',
    '36': 'Home',
    '37': 'ArrowLeft',
    '38': 'ArrowUp',
    '39': 'ArrowRight',
    '40': 'ArrowDown',
    '45': 'Insert',
    '46': 'Delete',
    '112': 'F1',
    '113': 'F2',
    '114': 'F3',
    '115': 'F4',
    '116': 'F5',
    '117': 'F6',
    '118': 'F7',
    '119': 'F8',
    '120': 'F9',
    '121': 'F10',
    '122': 'F11',
    '123': 'F12',
    '144': 'NumLock',
    '145': 'ScrollLock',
    '224': 'Meta'
  };
  /**
   * @param {object} nativeEvent Native browser event.
   * @return {string} Normalized `key` property.
   */

  function getEventKey(nativeEvent) {
    if (nativeEvent.key) {
      // Normalize inconsistent values reported by browsers due to
      // implementations of a working draft specification.
      // FireFox implements `key` but returns `MozPrintableKey` for all
      // printable characters (normalized to `Unidentified`), ignore it.
      var key = normalizeKey[nativeEvent.key] || nativeEvent.key;

      if (key !== 'Unidentified') {
        return key;
      }
    } // Browser does not implement `key`, polyfill as much of it as we can.


    if (nativeEvent.type === 'keypress') {
      var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
      // thus be captured by `keypress`, no other non-printable key should.

      return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
    }

    if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
      // While user keyboard layout determines the actual meaning of each
      // `keyCode` value, almost all function keys have a universal value.
      return translateToKey[nativeEvent.keyCode] || 'Unidentified';
    }

    return '';
  }
  /**
   * Translation from modifier key to the associated property in the event.
   * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
   */


  var modifierKeyToProp = {
    Alt: 'altKey',
    Control: 'ctrlKey',
    Meta: 'metaKey',
    Shift: 'shiftKey'
  }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
  // getModifierState. If getModifierState is not supported, we map it to a set of
  // modifier keys exposed by the event. In this case, Lock-keys are not supported.

  function modifierStateGetter(keyArg) {
    var syntheticEvent = this;
    var nativeEvent = syntheticEvent.nativeEvent;

    if (nativeEvent.getModifierState) {
      return nativeEvent.getModifierState(keyArg);
    }

    var keyProp = modifierKeyToProp[keyArg];
    return keyProp ? !!nativeEvent[keyProp] : false;
  }

  function getEventModifierState(nativeEvent) {
    return modifierStateGetter;
  }
  /**
   * @interface KeyboardEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */


  var KeyboardEventInterface = assign({}, UIEventInterface, {
    key: getEventKey,
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: getEventModifierState,
    // Legacy Interface
    charCode: function (event) {
      // `charCode` is the result of a KeyPress event and represents the value of
      // the actual printable character.
      // KeyPress is deprecated, but its replacement is not yet final and not
      // implemented in any major browser. Only KeyPress has charCode.
      if (event.type === 'keypress') {
        return getEventCharCode(event);
      }

      return 0;
    },
    keyCode: function (event) {
      // `keyCode` is the result of a KeyDown/Up event and represents the value of
      // physical keyboard key.
      // The actual meaning of the value depends on the users' keyboard layout
      // which cannot be detected. Assuming that it is a US keyboard layout
      // provides a surprisingly accurate mapping for US and European users.
      // Due to this, it is left to the user to implement at this time.
      if (event.type === 'keydown' || event.type === 'keyup') {
        return event.keyCode;
      }

      return 0;
    },
    which: function (event) {
      // `which` is an alias for either `keyCode` or `charCode` depending on the
      // type of the event.
      if (event.type === 'keypress') {
        return getEventCharCode(event);
      }

      if (event.type === 'keydown' || event.type === 'keyup') {
        return event.keyCode;
      }

      return 0;
    }
  });

  var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
  /**
   * @interface PointerEvent
   * @see http://www.w3.org/TR/pointerevents/
   */

  var PointerEventInterface = assign({}, MouseEventInterface, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
  });

  var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
  /**
   * @interface TouchEvent
   * @see http://www.w3.org/TR/touch-events/
   */

  var TouchEventInterface = assign({}, UIEventInterface, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: getEventModifierState
  });

  var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
  /**
   * @interface Event
   * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
   * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
   */

  var TransitionEventInterface = assign({}, EventInterface, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  });

  var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
  /**
   * @interface WheelEvent
   * @see http://www.w3.org/TR/DOM-Level-3-Events/
   */

  var WheelEventInterface = assign({}, MouseEventInterface, {
    deltaX: function (event) {
      return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
      'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
    },
    deltaY: function (event) {
      return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
      'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
      'wheelDelta' in event ? -event.wheelDelta : 0;
    },
    deltaZ: 0,
    // Browsers without "deltaMode" is reporting in raw wheel delta where one
    // notch on the scroll is always +/- 120, roughly equivalent to pixels.
    // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
    // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
    deltaMode: 0
  });

  var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);

  var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space

  var START_KEYCODE = 229;
  var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
  var documentMode = null;

  if (canUseDOM && 'documentMode' in document) {
    documentMode = document.documentMode;
  } // Webkit offers a very useful `textInput` event that can be used to
  // directly represent `beforeInput`. The IE `textinput` event is not as
  // useful, so we don't use it.


  var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
  // by the native compositionend event may be incorrect. Japanese ideographic
  // spaces, for instance (\u3000) are not recorded correctly.

  var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
  var SPACEBAR_CODE = 32;
  var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);

  function registerEvents() {
    registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']);
    registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
    registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
    registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
  } // Track whether we've ever handled a keypress on the space key.


  var hasSpaceKeypress = false;
  /**
   * Return whether a native keypress event is assumed to be a command.
   * This is required because Firefox fires `keypress` events for key commands
   * (cut, copy, select-all, etc.) even though no character is inserted.
   */

  function isKeypressCommand(nativeEvent) {
    return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
    !(nativeEvent.ctrlKey && nativeEvent.altKey);
  }
  /**
   * Translate native top level events into event types.
   */


  function getCompositionEventType(domEventName) {
    switch (domEventName) {
      case 'compositionstart':
        return 'onCompositionStart';

      case 'compositionend':
        return 'onCompositionEnd';

      case 'compositionupdate':
        return 'onCompositionUpdate';
    }
  }
  /**
   * Does our fallback best-guess model think this event signifies that
   * composition has begun?
   */


  function isFallbackCompositionStart(domEventName, nativeEvent) {
    return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE;
  }
  /**
   * Does our fallback mode think that this event is the end of composition?
   */


  function isFallbackCompositionEnd(domEventName, nativeEvent) {
    switch (domEventName) {
      case 'keyup':
        // Command keys insert or clear IME input.
        return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;

      case 'keydown':
        // Expect IME keyCode on each keydown. If we get any other
        // code we must have exited earlier.
        return nativeEvent.keyCode !== START_KEYCODE;

      case 'keypress':
      case 'mousedown':
      case 'focusout':
        // Events are not possible without cancelling IME.
        return true;

      default:
        return false;
    }
  }
  /**
   * Google Input Tools provides composition data via a CustomEvent,
   * with the `data` property populated in the `detail` object. If this
   * is available on the event object, use it. If not, this is a plain
   * composition event and we have nothing special to extract.
   *
   * @param {object} nativeEvent
   * @return {?string}
   */


  function getDataFromCustomEvent(nativeEvent) {
    var detail = nativeEvent.detail;

    if (typeof detail === 'object' && 'data' in detail) {
      return detail.data;
    }

    return null;
  }
  /**
   * Check if a composition event was triggered by Korean IME.
   * Our fallback mode does not work well with IE's Korean IME,
   * so just use native composition events when Korean IME is used.
   * Although CompositionEvent.locale property is deprecated,
   * it is available in IE, where our fallback mode is enabled.
   *
   * @param {object} nativeEvent
   * @return {boolean}
   */


  function isUsingKoreanIME(nativeEvent) {
    return nativeEvent.locale === 'ko';
  } // Track the current IME composition status, if any.


  var isComposing = false;
  /**
   * @return {?object} A SyntheticCompositionEvent.
   */

  function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
    var eventType;
    var fallbackData;

    if (canUseCompositionEvent) {
      eventType = getCompositionEventType(domEventName);
    } else if (!isComposing) {
      if (isFallbackCompositionStart(domEventName, nativeEvent)) {
        eventType = 'onCompositionStart';
      }
    } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
      eventType = 'onCompositionEnd';
    }

    if (!eventType) {
      return null;
    }

    if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
      // The current composition is stored statically and must not be
      // overwritten while composition continues.
      if (!isComposing && eventType === 'onCompositionStart') {
        isComposing = initialize(nativeEventTarget);
      } else if (eventType === 'onCompositionEnd') {
        if (isComposing) {
          fallbackData = getData();
        }
      }
    }

    var listeners = accumulateTwoPhaseListeners(targetInst, eventType);

    if (listeners.length > 0) {
      var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
      dispatchQueue.push({
        event: event,
        listeners: listeners
      });

      if (fallbackData) {
        // Inject data generated from fallback path into the synthetic event.
        // This matches the property of native CompositionEventInterface.
        event.data = fallbackData;
      } else {
        var customData = getDataFromCustomEvent(nativeEvent);

        if (customData !== null) {
          event.data = customData;
        }
      }
    }
  }

  function getNativeBeforeInputChars(domEventName, nativeEvent) {
    switch (domEventName) {
      case 'compositionend':
        return getDataFromCustomEvent(nativeEvent);

      case 'keypress':
        /**
         * If native `textInput` events are available, our goal is to make
         * use of them. However, there is a special case: the spacebar key.
         * In Webkit, preventing default on a spacebar `textInput` event
         * cancels character insertion, but it *also* causes the browser
         * to fall back to its default spacebar behavior of scrolling the
         * page.
         *
         * Tracking at:
         * https://code.google.com/p/chromium/issues/detail?id=355103
         *
         * To avoid this issue, use the keypress event as if no `textInput`
         * event is available.
         */
        var which = nativeEvent.which;

        if (which !== SPACEBAR_CODE) {
          return null;
        }

        hasSpaceKeypress = true;
        return SPACEBAR_CHAR;

      case 'textInput':
        // Record the characters to be added to the DOM.
        var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
        // it at the keypress level and bail immediately. Android Chrome
        // doesn't give us keycodes, so we need to ignore it.

        if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
          return null;
        }

        return chars;

      default:
        // For other native event types, do nothing.
        return null;
    }
  }
  /**
   * For browsers that do not provide the `textInput` event, extract the
   * appropriate string to use for SyntheticInputEvent.
   */


  function getFallbackBeforeInputChars(domEventName, nativeEvent) {
    // If we are currently composing (IME) and using a fallback to do so,
    // try to extract the composed characters from the fallback object.
    // If composition event is available, we extract a string only at
    // compositionevent, otherwise extract it at fallback events.
    if (isComposing) {
      if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
        var chars = getData();
        reset();
        isComposing = false;
        return chars;
      }

      return null;
    }

    switch (domEventName) {
      case 'paste':
        // If a paste event occurs after a keypress, throw out the input
        // chars. Paste events should not lead to BeforeInput events.
        return null;

      case 'keypress':
        /**
         * As of v27, Firefox may fire keypress events even when no character
         * will be inserted. A few possibilities:
         *
         * - `which` is `0`. Arrow keys, Esc key, etc.
         *
         * - `which` is the pressed key code, but no char is available.
         *   Ex: 'AltGr + d` in Polish. There is no modified character for
         *   this key combination and no character is inserted into the
         *   document, but FF fires the keypress for char code `100` anyway.
         *   No `input` event will occur.
         *
         * - `which` is the pressed key code, but a command combination is
         *   being used. Ex: `Cmd+C`. No character is inserted, and no
         *   `input` event will occur.
         */
        if (!isKeypressCommand(nativeEvent)) {
          // IE fires the `keypress` event when a user types an emoji via
          // Touch keyboard of Windows.  In such a case, the `char` property
          // holds an emoji character like `\uD83D\uDE0A`.  Because its length
          // is 2, the property `which` does not represent an emoji correctly.
          // In such a case, we directly return the `char` property instead of
          // using `which`.
          if (nativeEvent.char && nativeEvent.char.length > 1) {
            return nativeEvent.char;
          } else if (nativeEvent.which) {
            return String.fromCharCode(nativeEvent.which);
          }
        }

        return null;

      case 'compositionend':
        return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;

      default:
        return null;
    }
  }
  /**
   * Extract a SyntheticInputEvent for `beforeInput`, based on either native
   * `textInput` or fallback behavior.
   *
   * @return {?object} A SyntheticInputEvent.
   */


  function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
    var chars;

    if (canUseTextInputEvent) {
      chars = getNativeBeforeInputChars(domEventName, nativeEvent);
    } else {
      chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
    } // If no characters are being inserted, no BeforeInput event should
    // be fired.


    if (!chars) {
      return null;
    }

    var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput');

    if (listeners.length > 0) {
      var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget);
      dispatchQueue.push({
        event: event,
        listeners: listeners
      });
      event.data = chars;
    }
  }
  /**
   * Create an `onBeforeInput` event to match
   * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
   *
   * This event plugin is based on the native `textInput` event
   * available in Chrome, Safari, Opera, and IE. This event fires after
   * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
   *
   * `beforeInput` is spec'd but not implemented in any browsers, and
   * the `input` event does not provide any useful information about what has
   * actually been added, contrary to the spec. Thus, `textInput` is the best
   * available event to identify the characters that have actually been inserted
   * into the target node.
   *
   * This plugin is also responsible for emitting `composition` events, thus
   * allowing us to share composition fallback code for both `beforeInput` and
   * `composition` event types.
   */


  function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
    extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
  }

  /**
   * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
   */
  var supportedInputTypes = {
    color: true,
    date: true,
    datetime: true,
    'datetime-local': true,
    email: true,
    month: true,
    number: true,
    password: true,
    range: true,
    search: true,
    tel: true,
    text: true,
    time: true,
    url: true,
    week: true
  };

  function isTextInputElement(elem) {
    var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();

    if (nodeName === 'input') {
      return !!supportedInputTypes[elem.type];
    }

    if (nodeName === 'textarea') {
      return true;
    }

    return false;
  }

  /**
   * Checks if an event is supported in the current execution environment.
   *
   * NOTE: This will not work correctly for non-generic events such as `change`,
   * `reset`, `load`, `error`, and `select`.
   *
   * Borrows from Modernizr.
   *
   * @param {string} eventNameSuffix Event name, e.g. "click".
   * @return {boolean} True if the event is supported.
   * @internal
   * @license Modernizr 3.0.0pre (Custom Build) | MIT
   */

  function isEventSupported(eventNameSuffix) {
    if (!canUseDOM) {
      return false;
    }

    var eventName = 'on' + eventNameSuffix;
    var isSupported = (eventName in document);

    if (!isSupported) {
      var element = document.createElement('div');
      element.setAttribute(eventName, 'return;');
      isSupported = typeof element[eventName] === 'function';
    }

    return isSupported;
  }

  function registerEvents$1() {
    registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']);
  }

  function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
    // Flag this event loop as needing state restore.
    enqueueStateRestore(target);
    var listeners = accumulateTwoPhaseListeners(inst, 'onChange');

    if (listeners.length > 0) {
      var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target);
      dispatchQueue.push({
        event: event,
        listeners: listeners
      });
    }
  }
  /**
   * For IE shims
   */


  var activeElement = null;
  var activeElementInst = null;
  /**
   * SECTION: handle `change` event
   */

  function shouldUseChangeEvent(elem) {
    var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
    return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
  }

  function manualDispatchChangeEvent(nativeEvent) {
    var dispatchQueue = [];
    createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
    // other events and have it go through ReactBrowserEventEmitter. Since it
    // doesn't, we manually listen for the events and so we have to enqueue and
    // process the abstract event manually.
    //
    // Batching is necessary here in order to ensure that all event handlers run
    // before the next rerender (including event handlers attached to ancestor
    // elements instead of directly on the input). Without this, controlled
    // components don't work properly in conjunction with event bubbling because
    // the component is rerendered and the value reverted before all the event
    // handlers can run. See https://github.com/facebook/react/issues/708.

    batchedUpdates(runEventInBatch, dispatchQueue);
  }

  function runEventInBatch(dispatchQueue) {
    processDispatchQueue(dispatchQueue, 0);
  }

  function getInstIfValueChanged(targetInst) {
    var targetNode = getNodeFromInstance(targetInst);

    if (updateValueIfChanged(targetNode)) {
      return targetInst;
    }
  }

  function getTargetInstForChangeEvent(domEventName, targetInst) {
    if (domEventName === 'change') {
      return targetInst;
    }
  }
  /**
   * SECTION: handle `input` event
   */


  var isInputEventSupported = false;

  if (canUseDOM) {
    // IE9 claims to support the input event but fails to trigger it when
    // deleting text, so we ignore its input events.
    isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
  }
  /**
   * (For IE <=9) Starts tracking propertychange events on the passed-in element
   * and override the value property so that we can distinguish user events from
   * value changes in JS.
   */


  function startWatchingForValueChange(target, targetInst) {
    activeElement = target;
    activeElementInst = targetInst;
    activeElement.attachEvent('onpropertychange', handlePropertyChange);
  }
  /**
   * (For IE <=9) Removes the event listeners from the currently-tracked element,
   * if any exists.
   */


  function stopWatchingForValueChange() {
    if (!activeElement) {
      return;
    }

    activeElement.detachEvent('onpropertychange', handlePropertyChange);
    activeElement = null;
    activeElementInst = null;
  }
  /**
   * (For IE <=9) Handles a propertychange event, sending a `change` event if
   * the value of the active element has changed.
   */


  function handlePropertyChange(nativeEvent) {
    if (nativeEvent.propertyName !== 'value') {
      return;
    }

    if (getInstIfValueChanged(activeElementInst)) {
      manualDispatchChangeEvent(nativeEvent);
    }
  }

  function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
    if (domEventName === 'focusin') {
      // In IE9, propertychange fires for most input events but is buggy and
      // doesn't fire when text is deleted, but conveniently, selectionchange
      // appears to fire in all of the remaining cases so we catch those and
      // forward the event if the value has changed
      // In either case, we don't want to call the event handler if the value
      // is changed from JS so we redefine a setter for `.value` that updates
      // our activeElementValue variable, allowing us to ignore those changes
      //
      // stopWatching() should be a noop here but we call it just in case we
      // missed a blur event somehow.
      stopWatchingForValueChange();
      startWatchingForValueChange(target, targetInst);
    } else if (domEventName === 'focusout') {
      stopWatchingForValueChange();
    }
  } // For IE8 and IE9.


  function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
    if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') {
      // On the selectionchange event, the target is just document which isn't
      // helpful for us so just check activeElement instead.
      //
      // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
      // propertychange on the first input event after setting `value` from a
      // script and fires only keydown, keypress, keyup. Catching keyup usually
      // gets it and catching keydown lets us fire an event for the first
      // keystroke if user does a key repeat (it'll be a little delayed: right
      // before the second keystroke). Other input methods (e.g., paste) seem to
      // fire selectionchange normally.
      return getInstIfValueChanged(activeElementInst);
    }
  }
  /**
   * SECTION: handle `click` event
   */


  function shouldUseClickEvent(elem) {
    // Use the `click` event to detect changes to checkbox and radio inputs.
    // This approach works across all browsers, whereas `change` does not fire
    // until `blur` in IE8.
    var nodeName = elem.nodeName;
    return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
  }

  function getTargetInstForClickEvent(domEventName, targetInst) {
    if (domEventName === 'click') {
      return getInstIfValueChanged(targetInst);
    }
  }

  function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
    if (domEventName === 'input' || domEventName === 'change') {
      return getInstIfValueChanged(targetInst);
    }
  }

  function handleControlledInputBlur(node) {
    var state = node._wrapperState;

    if (!state || !state.controlled || node.type !== 'number') {
      return;
    }

    {
      // If controlled, assign the value attribute to the current value on blur
      setDefaultValue(node, 'number', node.value);
    }
  }
  /**
   * This plugin creates an `onChange` event that normalizes change events
   * across form elements. This event fires at a time when it's possible to
   * change the element's value without seeing a flicker.
   *
   * Supported elements are:
   * - input (see `isTextInputElement`)
   * - textarea
   * - select
   */


  function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
    var getTargetInstFunc, handleEventFunc;

    if (shouldUseChangeEvent(targetNode)) {
      getTargetInstFunc = getTargetInstForChangeEvent;
    } else if (isTextInputElement(targetNode)) {
      if (isInputEventSupported) {
        getTargetInstFunc = getTargetInstForInputOrChangeEvent;
      } else {
        getTargetInstFunc = getTargetInstForInputEventPolyfill;
        handleEventFunc = handleEventsForInputEventPolyfill;
      }
    } else if (shouldUseClickEvent(targetNode)) {
      getTargetInstFunc = getTargetInstForClickEvent;
    }

    if (getTargetInstFunc) {
      var inst = getTargetInstFunc(domEventName, targetInst);

      if (inst) {
        createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
        return;
      }
    }

    if (handleEventFunc) {
      handleEventFunc(domEventName, targetNode, targetInst);
    } // When blurring, set the value attribute for number inputs


    if (domEventName === 'focusout') {
      handleControlledInputBlur(targetNode);
    }
  }

  function registerEvents$2() {
    registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']);
    registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']);
    registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']);
    registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']);
  }
  /**
   * For almost every interaction we care about, there will be both a top-level
   * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
   * we do not extract duplicate events. However, moving the mouse into the
   * browser from outside will not fire a `mouseout` event. In this case, we use
   * the `mouseover` top-level event.
   */


  function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover';
    var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout';

    if (isOverEvent && !isReplayingEvent(nativeEvent)) {
      // If this is an over event with a target, we might have already dispatched
      // the event in the out event of the other target. If this is replayed,
      // then it's because we couldn't dispatch against this target previously
      // so we have to do it now instead.
      var related = nativeEvent.relatedTarget || nativeEvent.fromElement;

      if (related) {
        // If the related node is managed by React, we can assume that we have
        // already dispatched the corresponding events during its mouseout.
        if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
          return;
        }
      }
    }

    if (!isOutEvent && !isOverEvent) {
      // Must not be a mouse or pointer in or out - ignoring.
      return;
    }

    var win; // TODO: why is this nullable in the types but we read from it?

    if (nativeEventTarget.window === nativeEventTarget) {
      // `nativeEventTarget` is probably a window object.
      win = nativeEventTarget;
    } else {
      // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
      var doc = nativeEventTarget.ownerDocument;

      if (doc) {
        win = doc.defaultView || doc.parentWindow;
      } else {
        win = window;
      }
    }

    var from;
    var to;

    if (isOutEvent) {
      var _related = nativeEvent.relatedTarget || nativeEvent.toElement;

      from = targetInst;
      to = _related ? getClosestInstanceFromNode(_related) : null;

      if (to !== null) {
        var nearestMounted = getNearestMountedFiber(to);

        if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
          to = null;
        }
      }
    } else {
      // Moving to a node from outside the window.
      from = null;
      to = targetInst;
    }

    if (from === to) {
      // Nothing pertains to our managed components.
      return;
    }

    var SyntheticEventCtor = SyntheticMouseEvent;
    var leaveEventType = 'onMouseLeave';
    var enterEventType = 'onMouseEnter';
    var eventTypePrefix = 'mouse';

    if (domEventName === 'pointerout' || domEventName === 'pointerover') {
      SyntheticEventCtor = SyntheticPointerEvent;
      leaveEventType = 'onPointerLeave';
      enterEventType = 'onPointerEnter';
      eventTypePrefix = 'pointer';
    }

    var fromNode = from == null ? win : getNodeFromInstance(from);
    var toNode = to == null ? win : getNodeFromInstance(to);
    var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget);
    leave.target = fromNode;
    leave.relatedTarget = toNode;
    var enter = null; // We should only process this nativeEvent if we are processing
    // the first ancestor. Next time, we will ignore the event.

    var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);

    if (nativeTargetInst === targetInst) {
      var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget);
      enterEvent.target = toNode;
      enterEvent.relatedTarget = fromNode;
      enter = enterEvent;
    }

    accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
  }

  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */
  function is(x, y) {
    return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
    ;
  }

  var objectIs = typeof Object.is === 'function' ? Object.is : is;

  /**
   * Performs equality by iterating through keys on an object and returning false
   * when any key has values which are not strictly equal between the arguments.
   * Returns true when the values of all keys are strictly equal.
   */

  function shallowEqual(objA, objB) {
    if (objectIs(objA, objB)) {
      return true;
    }

    if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
      return false;
    }

    var keysA = Object.keys(objA);
    var keysB = Object.keys(objB);

    if (keysA.length !== keysB.length) {
      return false;
    } // Test for A's keys different from B.


    for (var i = 0; i < keysA.length; i++) {
      var currentKey = keysA[i];

      if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
        return false;
      }
    }

    return true;
  }

  /**
   * Given any node return the first leaf node without children.
   *
   * @param {DOMElement|DOMTextNode} node
   * @return {DOMElement|DOMTextNode}
   */

  function getLeafNode(node) {
    while (node && node.firstChild) {
      node = node.firstChild;
    }

    return node;
  }
  /**
   * Get the next sibling within a container. This will walk up the
   * DOM if a node's siblings have been exhausted.
   *
   * @param {DOMElement|DOMTextNode} node
   * @return {?DOMElement|DOMTextNode}
   */


  function getSiblingNode(node) {
    while (node) {
      if (node.nextSibling) {
        return node.nextSibling;
      }

      node = node.parentNode;
    }
  }
  /**
   * Get object describing the nodes which contain characters at offset.
   *
   * @param {DOMElement|DOMTextNode} root
   * @param {number} offset
   * @return {?object}
   */


  function getNodeForCharacterOffset(root, offset) {
    var node = getLeafNode(root);
    var nodeStart = 0;
    var nodeEnd = 0;

    while (node) {
      if (node.nodeType === TEXT_NODE) {
        nodeEnd = nodeStart + node.textContent.length;

        if (nodeStart <= offset && nodeEnd >= offset) {
          return {
            node: node,
            offset: offset - nodeStart
          };
        }

        nodeStart = nodeEnd;
      }

      node = getLeafNode(getSiblingNode(node));
    }
  }

  /**
   * @param {DOMElement} outerNode
   * @return {?object}
   */

  function getOffsets(outerNode) {
    var ownerDocument = outerNode.ownerDocument;
    var win = ownerDocument && ownerDocument.defaultView || window;
    var selection = win.getSelection && win.getSelection();

    if (!selection || selection.rangeCount === 0) {
      return null;
    }

    var anchorNode = selection.anchorNode,
        anchorOffset = selection.anchorOffset,
        focusNode = selection.focusNode,
        focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
    // up/down buttons on an <input type="number">. Anonymous divs do not seem to
    // expose properties, triggering a "Permission denied error" if any of its
    // properties are accessed. The only seemingly possible way to avoid erroring
    // is to access a property that typically works for non-anonymous divs and
    // catch any error that may otherwise arise. See
    // https://bugzilla.mozilla.org/show_bug.cgi?id=208427

    try {
      /* eslint-disable no-unused-expressions */
      anchorNode.nodeType;
      focusNode.nodeType;
      /* eslint-enable no-unused-expressions */
    } catch (e) {
      return null;
    }

    return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
  }
  /**
   * Returns {start, end} where `start` is the character/codepoint index of
   * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
   * `end` is the index of (focusNode, focusOffset).
   *
   * Returns null if you pass in garbage input but we should probably just crash.
   *
   * Exported only for testing.
   */

  function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
    var length = 0;
    var start = -1;
    var end = -1;
    var indexWithinAnchor = 0;
    var indexWithinFocus = 0;
    var node = outerNode;
    var parentNode = null;

    outer: while (true) {
      var next = null;

      while (true) {
        if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
          start = length + anchorOffset;
        }

        if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
          end = length + focusOffset;
        }

        if (node.nodeType === TEXT_NODE) {
          length += node.nodeValue.length;
        }

        if ((next = node.firstChild) === null) {
          break;
        } // Moving from `node` to its first child `next`.


        parentNode = node;
        node = next;
      }

      while (true) {
        if (node === outerNode) {
          // If `outerNode` has children, this is always the second time visiting
          // it. If it has no children, this is still the first loop, and the only
          // valid selection is anchorNode and focusNode both equal to this node
          // and both offsets 0, in which case we will have handled above.
          break outer;
        }

        if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
          start = length;
        }

        if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
          end = length;
        }

        if ((next = node.nextSibling) !== null) {
          break;
        }

        node = parentNode;
        parentNode = node.parentNode;
      } // Moving from `node` to its next sibling `next`.


      node = next;
    }

    if (start === -1 || end === -1) {
      // This should never happen. (Would happen if the anchor/focus nodes aren't
      // actually inside the passed-in node.)
      return null;
    }

    return {
      start: start,
      end: end
    };
  }
  /**
   * In modern non-IE browsers, we can support both forward and backward
   * selections.
   *
   * Note: IE10+ supports the Selection object, but it does not support
   * the `extend` method, which means that even in modern IE, it's not possible
   * to programmatically create a backward selection. Thus, for all IE
   * versions, we use the old IE API to create our selections.
   *
   * @param {DOMElement|DOMTextNode} node
   * @param {object} offsets
   */

  function setOffsets(node, offsets) {
    var doc = node.ownerDocument || document;
    var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
    // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
    // fails when pasting 100+ items)

    if (!win.getSelection) {
      return;
    }

    var selection = win.getSelection();
    var length = node.textContent.length;
    var start = Math.min(offsets.start, length);
    var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
    // Flip backward selections, so we can set with a single range.

    if (!selection.extend && start > end) {
      var temp = end;
      end = start;
      start = temp;
    }

    var startMarker = getNodeForCharacterOffset(node, start);
    var endMarker = getNodeForCharacterOffset(node, end);

    if (startMarker && endMarker) {
      if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
        return;
      }

      var range = doc.createRange();
      range.setStart(startMarker.node, startMarker.offset);
      selection.removeAllRanges();

      if (start > end) {
        selection.addRange(range);
        selection.extend(endMarker.node, endMarker.offset);
      } else {
        range.setEnd(endMarker.node, endMarker.offset);
        selection.addRange(range);
      }
    }
  }

  function isTextNode(node) {
    return node && node.nodeType === TEXT_NODE;
  }

  function containsNode(outerNode, innerNode) {
    if (!outerNode || !innerNode) {
      return false;
    } else if (outerNode === innerNode) {
      return true;
    } else if (isTextNode(outerNode)) {
      return false;
    } else if (isTextNode(innerNode)) {
      return containsNode(outerNode, innerNode.parentNode);
    } else if ('contains' in outerNode) {
      return outerNode.contains(innerNode);
    } else if (outerNode.compareDocumentPosition) {
      return !!(outerNode.compareDocumentPosition(innerNode) & 16);
    } else {
      return false;
    }
  }

  function isInDocument(node) {
    return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
  }

  function isSameOriginFrame(iframe) {
    try {
      // Accessing the contentDocument of a HTMLIframeElement can cause the browser
      // to throw, e.g. if it has a cross-origin src attribute.
      // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
      // iframe.contentDocument.defaultView;
      // A safety way is to access one of the cross origin properties: Window or Location
      // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
      // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
      return typeof iframe.contentWindow.location.href === 'string';
    } catch (err) {
      return false;
    }
  }

  function getActiveElementDeep() {
    var win = window;
    var element = getActiveElement();

    while (element instanceof win.HTMLIFrameElement) {
      if (isSameOriginFrame(element)) {
        win = element.contentWindow;
      } else {
        return element;
      }

      element = getActiveElement(win.document);
    }

    return element;
  }
  /**
   * @ReactInputSelection: React input selection module. Based on Selection.js,
   * but modified to be suitable for react and has a couple of bug fixes (doesn't
   * assume buttons have range selections allowed).
   * Input selection module for React.
   */

  /**
   * @hasSelectionCapabilities: we get the element types that support selection
   * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
   * and `selectionEnd` rows.
   */


  function hasSelectionCapabilities(elem) {
    var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
    return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
  }
  function getSelectionInformation() {
    var focusedElem = getActiveElementDeep();
    return {
      focusedElem: focusedElem,
      selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
    };
  }
  /**
   * @restoreSelection: If any selection information was potentially lost,
   * restore it. This is useful when performing operations that could remove dom
   * nodes and place them back in, resulting in focus being lost.
   */

  function restoreSelection(priorSelectionInformation) {
    var curFocusedElem = getActiveElementDeep();
    var priorFocusedElem = priorSelectionInformation.focusedElem;
    var priorSelectionRange = priorSelectionInformation.selectionRange;

    if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
      if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
        setSelection(priorFocusedElem, priorSelectionRange);
      } // Focusing a node can change the scroll position, which is undesirable


      var ancestors = [];
      var ancestor = priorFocusedElem;

      while (ancestor = ancestor.parentNode) {
        if (ancestor.nodeType === ELEMENT_NODE) {
          ancestors.push({
            element: ancestor,
            left: ancestor.scrollLeft,
            top: ancestor.scrollTop
          });
        }
      }

      if (typeof priorFocusedElem.focus === 'function') {
        priorFocusedElem.focus();
      }

      for (var i = 0; i < ancestors.length; i++) {
        var info = ancestors[i];
        info.element.scrollLeft = info.left;
        info.element.scrollTop = info.top;
      }
    }
  }
  /**
   * @getSelection: Gets the selection bounds of a focused textarea, input or
   * contentEditable node.
   * -@input: Look up selection bounds of this input
   * -@return {start: selectionStart, end: selectionEnd}
   */

  function getSelection(input) {
    var selection;

    if ('selectionStart' in input) {
      // Modern browser with input or textarea.
      selection = {
        start: input.selectionStart,
        end: input.selectionEnd
      };
    } else {
      // Content editable or old IE textarea.
      selection = getOffsets(input);
    }

    return selection || {
      start: 0,
      end: 0
    };
  }
  /**
   * @setSelection: Sets the selection bounds of a textarea or input and focuses
   * the input.
   * -@input     Set selection bounds of this input or textarea
   * -@offsets   Object of same form that is returned from get*
   */

  function setSelection(input, offsets) {
    var start = offsets.start;
    var end = offsets.end;

    if (end === undefined) {
      end = start;
    }

    if ('selectionStart' in input) {
      input.selectionStart = start;
      input.selectionEnd = Math.min(end, input.value.length);
    } else {
      setOffsets(input, offsets);
    }
  }

  var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;

  function registerEvents$3() {
    registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']);
  }

  var activeElement$1 = null;
  var activeElementInst$1 = null;
  var lastSelection = null;
  var mouseDown = false;
  /**
   * Get an object which is a unique representation of the current selection.
   *
   * The return value will not be consistent across nodes or browsers, but
   * two identical selections on the same node will return identical objects.
   */

  function getSelection$1(node) {
    if ('selectionStart' in node && hasSelectionCapabilities(node)) {
      return {
        start: node.selectionStart,
        end: node.selectionEnd
      };
    } else {
      var win = node.ownerDocument && node.ownerDocument.defaultView || window;
      var selection = win.getSelection();
      return {
        anchorNode: selection.anchorNode,
        anchorOffset: selection.anchorOffset,
        focusNode: selection.focusNode,
        focusOffset: selection.focusOffset
      };
    }
  }
  /**
   * Get document associated with the event target.
   */


  function getEventTargetDocument(eventTarget) {
    return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
  }
  /**
   * Poll selection to see whether it's changed.
   *
   * @param {object} nativeEvent
   * @param {object} nativeEventTarget
   * @return {?SyntheticEvent}
   */


  function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
    // Ensure we have the right element, and that the user is not dragging a
    // selection (this matches native `select` event behavior). In HTML5, select
    // fires only on input and textarea thus if there's no focused element we
    // won't dispatch.
    var doc = getEventTargetDocument(nativeEventTarget);

    if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
      return;
    } // Only fire when selection has actually changed.


    var currentSelection = getSelection$1(activeElement$1);

    if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
      lastSelection = currentSelection;
      var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect');

      if (listeners.length > 0) {
        var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget);
        dispatchQueue.push({
          event: event,
          listeners: listeners
        });
        event.target = activeElement$1;
      }
    }
  }
  /**
   * This plugin creates an `onSelect` event that normalizes select events
   * across form elements.
   *
   * Supported elements are:
   * - input (see `isTextInputElement`)
   * - textarea
   * - contentEditable
   *
   * This differs from native browser implementations in the following ways:
   * - Fires on contentEditable fields as well as inputs.
   * - Fires for collapsed selection.
   * - Fires after user input.
   */


  function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;

    switch (domEventName) {
      // Track the input node that has focus.
      case 'focusin':
        if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
          activeElement$1 = targetNode;
          activeElementInst$1 = targetInst;
          lastSelection = null;
        }

        break;

      case 'focusout':
        activeElement$1 = null;
        activeElementInst$1 = null;
        lastSelection = null;
        break;
      // Don't fire the event while the user is dragging. This matches the
      // semantics of the native select event.

      case 'mousedown':
        mouseDown = true;
        break;

      case 'contextmenu':
      case 'mouseup':
      case 'dragend':
        mouseDown = false;
        constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
        break;
      // Chrome and IE fire non-standard event when selection is changed (and
      // sometimes when it hasn't). IE's event fires out of order with respect
      // to key and input events on deletion, so we discard it.
      //
      // Firefox doesn't support selectionchange, so check selection status
      // after each key entry. The selection changes after keydown and before
      // keyup, but we check on keydown as well in the case of holding down a
      // key, when multiple keydown events are fired but only one keyup is.
      // This is also our approach for IE handling, for the reason above.

      case 'selectionchange':
        if (skipSelectionChangeEvent) {
          break;
        }

      // falls through

      case 'keydown':
      case 'keyup':
        constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
    }
  }

  /**
   * Generate a mapping of standard vendor prefixes using the defined style property and event name.
   *
   * @param {string} styleProp
   * @param {string} eventName
   * @returns {object}
   */

  function makePrefixMap(styleProp, eventName) {
    var prefixes = {};
    prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
    prefixes['Webkit' + styleProp] = 'webkit' + eventName;
    prefixes['Moz' + styleProp] = 'moz' + eventName;
    return prefixes;
  }
  /**
   * A list of event names to a configurable list of vendor prefixes.
   */


  var vendorPrefixes = {
    animationend: makePrefixMap('Animation', 'AnimationEnd'),
    animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
    animationstart: makePrefixMap('Animation', 'AnimationStart'),
    transitionend: makePrefixMap('Transition', 'TransitionEnd')
  };
  /**
   * Event names that have already been detected and prefixed (if applicable).
   */

  var prefixedEventNames = {};
  /**
   * Element to check for prefixes on.
   */

  var style = {};
  /**
   * Bootstrap if a DOM exists.
   */

  if (canUseDOM) {
    style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
    // the un-prefixed "animation" and "transition" properties are defined on the
    // style object but the events that fire will still be prefixed, so we need
    // to check if the un-prefixed events are usable, and if not remove them from the map.

    if (!('AnimationEvent' in window)) {
      delete vendorPrefixes.animationend.animation;
      delete vendorPrefixes.animationiteration.animation;
      delete vendorPrefixes.animationstart.animation;
    } // Same as above


    if (!('TransitionEvent' in window)) {
      delete vendorPrefixes.transitionend.transition;
    }
  }
  /**
   * Attempts to determine the correct vendor prefixed event name.
   *
   * @param {string} eventName
   * @returns {string}
   */


  function getVendorPrefixedEventName(eventName) {
    if (prefixedEventNames[eventName]) {
      return prefixedEventNames[eventName];
    } else if (!vendorPrefixes[eventName]) {
      return eventName;
    }

    var prefixMap = vendorPrefixes[eventName];

    for (var styleProp in prefixMap) {
      if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
        return prefixedEventNames[eventName] = prefixMap[styleProp];
      }
    }

    return eventName;
  }

  var ANIMATION_END = getVendorPrefixedEventName('animationend');
  var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration');
  var ANIMATION_START = getVendorPrefixedEventName('animationstart');
  var TRANSITION_END = getVendorPrefixedEventName('transitionend');

  var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list!
  //
  // E.g. it needs "pointerDown", not "pointerdown".
  // This is because we derive both React name ("onPointerDown")
  // and DOM name ("pointerdown") from the same list.
  //
  // Exceptions that don't match this convention are listed separately.
  //
  // prettier-ignore

  var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel'];

  function registerSimpleEvent(domEventName, reactName) {
    topLevelEventsToReactNames.set(domEventName, reactName);
    registerTwoPhaseEvent(reactName, [domEventName]);
  }

  function registerSimpleEvents() {
    for (var i = 0; i < simpleEventPluginEvents.length; i++) {
      var eventName = simpleEventPluginEvents[i];
      var domEventName = eventName.toLowerCase();
      var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
      registerSimpleEvent(domEventName, 'on' + capitalizedEvent);
    } // Special cases where event names don't match.


    registerSimpleEvent(ANIMATION_END, 'onAnimationEnd');
    registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration');
    registerSimpleEvent(ANIMATION_START, 'onAnimationStart');
    registerSimpleEvent('dblclick', 'onDoubleClick');
    registerSimpleEvent('focusin', 'onFocus');
    registerSimpleEvent('focusout', 'onBlur');
    registerSimpleEvent(TRANSITION_END, 'onTransitionEnd');
  }

  function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    var reactName = topLevelEventsToReactNames.get(domEventName);

    if (reactName === undefined) {
      return;
    }

    var SyntheticEventCtor = SyntheticEvent;
    var reactEventType = domEventName;

    switch (domEventName) {
      case 'keypress':
        // Firefox creates a keypress event for function keys too. This removes
        // the unwanted keypress events. Enter is however both printable and
        // non-printable. One would expect Tab to be as well (but it isn't).
        if (getEventCharCode(nativeEvent) === 0) {
          return;
        }

      /* falls through */

      case 'keydown':
      case 'keyup':
        SyntheticEventCtor = SyntheticKeyboardEvent;
        break;

      case 'focusin':
        reactEventType = 'focus';
        SyntheticEventCtor = SyntheticFocusEvent;
        break;

      case 'focusout':
        reactEventType = 'blur';
        SyntheticEventCtor = SyntheticFocusEvent;
        break;

      case 'beforeblur':
      case 'afterblur':
        SyntheticEventCtor = SyntheticFocusEvent;
        break;

      case 'click':
        // Firefox creates a click event on right mouse clicks. This removes the
        // unwanted click events.
        if (nativeEvent.button === 2) {
          return;
        }

      /* falls through */

      case 'auxclick':
      case 'dblclick':
      case 'mousedown':
      case 'mousemove':
      case 'mouseup': // TODO: Disabled elements should not respond to mouse events

      /* falls through */

      case 'mouseout':
      case 'mouseover':
      case 'contextmenu':
        SyntheticEventCtor = SyntheticMouseEvent;
        break;

      case 'drag':
      case 'dragend':
      case 'dragenter':
      case 'dragexit':
      case 'dragleave':
      case 'dragover':
      case 'dragstart':
      case 'drop':
        SyntheticEventCtor = SyntheticDragEvent;
        break;

      case 'touchcancel':
      case 'touchend':
      case 'touchmove':
      case 'touchstart':
        SyntheticEventCtor = SyntheticTouchEvent;
        break;

      case ANIMATION_END:
      case ANIMATION_ITERATION:
      case ANIMATION_START:
        SyntheticEventCtor = SyntheticAnimationEvent;
        break;

      case TRANSITION_END:
        SyntheticEventCtor = SyntheticTransitionEvent;
        break;

      case 'scroll':
        SyntheticEventCtor = SyntheticUIEvent;
        break;

      case 'wheel':
        SyntheticEventCtor = SyntheticWheelEvent;
        break;

      case 'copy':
      case 'cut':
      case 'paste':
        SyntheticEventCtor = SyntheticClipboardEvent;
        break;

      case 'gotpointercapture':
      case 'lostpointercapture':
      case 'pointercancel':
      case 'pointerdown':
      case 'pointermove':
      case 'pointerout':
      case 'pointerover':
      case 'pointerup':
        SyntheticEventCtor = SyntheticPointerEvent;
        break;
    }

    var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;

    {
      // Some events don't bubble in the browser.
      // In the past, React has always bubbled them, but this can be surprising.
      // We're going to try aligning closer to the browser behavior by not bubbling
      // them in React either. We'll start by not bubbling onScroll, and then expand.
      var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
      // nonDelegatedEvents list in DOMPluginEventSystem.
      // Then we can remove this special list.
      // This is a breaking change that can wait until React 18.
      domEventName === 'scroll';

      var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);

      if (_listeners.length > 0) {
        // Intentionally create event lazily.
        var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);

        dispatchQueue.push({
          event: _event,
          listeners: _listeners
        });
      }
    }
  }

  // TODO: remove top-level side effect.
  registerSimpleEvents();
  registerEvents$2();
  registerEvents$1();
  registerEvents$3();
  registerEvents();

  function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
    // TODO: we should remove the concept of a "SimpleEventPlugin".
    // This is the basic functionality of the event system. All
    // the other plugins are essentially polyfills. So the plugin
    // should probably be inlined somewhere and have its logic
    // be core the to event system. This would potentially allow
    // us to ship builds of React without the polyfilled plugins below.
    extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
    var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the
    // event's native "bubble" phase, which means that we're
    // not in the capture phase. That's because we emulate
    // the capture phase here still. This is a trade-off,
    // because in an ideal world we would not emulate and use
    // the phases properly, like we do with the SimpleEvent
    // plugin. However, the plugins below either expect
    // emulation (EnterLeave) or use state localized to that
    // plugin (BeforeInput, Change, Select). The state in
    // these modules complicates things, as you'll essentially
    // get the case where the capture phase event might change
    // state, only for the following bubble event to come in
    // later and not trigger anything as the state now
    // invalidates the heuristics of the event plugin. We
    // could alter all these plugins to work in such ways, but
    // that might cause other unknown side-effects that we
    // can't foresee right now.

    if (shouldProcessPolyfillPlugins) {
      extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
      extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
      extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
      extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
    }
  } // List of events that need to be individually attached to media elements.


  var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather
  // set them on the actual target element itself. This is primarily
  // because these events do not consistently bubble in the DOM.

  var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes));

  function executeDispatch(event, listener, currentTarget) {
    var type = event.type || 'unknown-event';
    event.currentTarget = currentTarget;
    invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
    event.currentTarget = null;
  }

  function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
    var previousInstance;

    if (inCapturePhase) {
      for (var i = dispatchListeners.length - 1; i >= 0; i--) {
        var _dispatchListeners$i = dispatchListeners[i],
            instance = _dispatchListeners$i.instance,
            currentTarget = _dispatchListeners$i.currentTarget,
            listener = _dispatchListeners$i.listener;

        if (instance !== previousInstance && event.isPropagationStopped()) {
          return;
        }

        executeDispatch(event, listener, currentTarget);
        previousInstance = instance;
      }
    } else {
      for (var _i = 0; _i < dispatchListeners.length; _i++) {
        var _dispatchListeners$_i = dispatchListeners[_i],
            _instance = _dispatchListeners$_i.instance,
            _currentTarget = _dispatchListeners$_i.currentTarget,
            _listener = _dispatchListeners$_i.listener;

        if (_instance !== previousInstance && event.isPropagationStopped()) {
          return;
        }

        executeDispatch(event, _listener, _currentTarget);
        previousInstance = _instance;
      }
    }
  }

  function processDispatchQueue(dispatchQueue, eventSystemFlags) {
    var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;

    for (var i = 0; i < dispatchQueue.length; i++) {
      var _dispatchQueue$i = dispatchQueue[i],
          event = _dispatchQueue$i.event,
          listeners = _dispatchQueue$i.listeners;
      processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); //  event system doesn't use pooling.
    } // This would be a good time to rethrow if any of the event handlers threw.


    rethrowCaughtError();
  }

  function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
    var nativeEventTarget = getEventTarget(nativeEvent);
    var dispatchQueue = [];
    extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
    processDispatchQueue(dispatchQueue, eventSystemFlags);
  }

  function listenToNonDelegatedEvent(domEventName, targetElement) {
    {
      if (!nonDelegatedEvents.has(domEventName)) {
        error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName);
      }
    }

    var isCapturePhaseListener = false;
    var listenerSet = getEventListenerSet(targetElement);
    var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);

    if (!listenerSet.has(listenerSetKey)) {
      addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
      listenerSet.add(listenerSetKey);
    }
  }
  function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
    {
      if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
        error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName);
      }
    }

    var eventSystemFlags = 0;

    if (isCapturePhaseListener) {
      eventSystemFlags |= IS_CAPTURE_PHASE;
    }

    addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
  } // This is only used by createEventHandle when the
  var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2);
  function listenToAllSupportedEvents(rootContainerElement) {
    if (!rootContainerElement[listeningMarker]) {
      rootContainerElement[listeningMarker] = true;
      allNativeEvents.forEach(function (domEventName) {
        // We handle selectionchange separately because it
        // doesn't bubble and needs to be on the document.
        if (domEventName !== 'selectionchange') {
          if (!nonDelegatedEvents.has(domEventName)) {
            listenToNativeEvent(domEventName, false, rootContainerElement);
          }

          listenToNativeEvent(domEventName, true, rootContainerElement);
        }
      });
      var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;

      if (ownerDocument !== null) {
        // The selectionchange event also needs deduplication
        // but it is attached to the document.
        if (!ownerDocument[listeningMarker]) {
          ownerDocument[listeningMarker] = true;
          listenToNativeEvent('selectionchange', false, ownerDocument);
        }
      }
    }
  }

  function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
    var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be
    // active and not passive.

    var isPassiveListener = undefined;

    if (passiveBrowserEventsSupported) {
      // Browsers introduced an intervention, making these events
      // passive by default on document. React doesn't bind them
      // to document anymore, but changing this now would undo
      // the performance wins from the change. So we emulate
      // the existing behavior manually on the roots now.
      // https://github.com/facebook/react/issues/19651
      if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') {
        isPassiveListener = true;
      }
    }

    targetContainer =  targetContainer;
    var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we


    if (isCapturePhaseListener) {
      if (isPassiveListener !== undefined) {
        unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
      } else {
        unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
      }
    } else {
      if (isPassiveListener !== undefined) {
        unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
      } else {
        unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
      }
    }
  }

  function isMatchingRootContainer(grandContainer, targetContainer) {
    return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
  }

  function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
    var ancestorInst = targetInst;

    if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
      var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we

      if (targetInst !== null) {
        // The below logic attempts to work out if we need to change
        // the target fiber to a different ancestor. We had similar logic
        // in the legacy event system, except the big difference between
        // systems is that the modern event system now has an event listener
        // attached to each React Root and React Portal Root. Together,
        // the DOM nodes representing these roots are the "rootContainer".
        // To figure out which ancestor instance we should use, we traverse
        // up the fiber tree from the target instance and attempt to find
        // root boundaries that match that of our current "rootContainer".
        // If we find that "rootContainer", we find the parent fiber
        // sub-tree for that root and make that our ancestor instance.
        var node = targetInst;

        mainLoop: while (true) {
          if (node === null) {
            return;
          }

          var nodeTag = node.tag;

          if (nodeTag === HostRoot || nodeTag === HostPortal) {
            var container = node.stateNode.containerInfo;

            if (isMatchingRootContainer(container, targetContainerNode)) {
              break;
            }

            if (nodeTag === HostPortal) {
              // The target is a portal, but it's not the rootContainer we're looking for.
              // Normally portals handle their own events all the way down to the root.
              // So we should be able to stop now. However, we don't know if this portal
              // was part of *our* root.
              var grandNode = node.return;

              while (grandNode !== null) {
                var grandTag = grandNode.tag;

                if (grandTag === HostRoot || grandTag === HostPortal) {
                  var grandContainer = grandNode.stateNode.containerInfo;

                  if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
                    // This is the rootContainer we're looking for and we found it as
                    // a parent of the Portal. That means we can ignore it because the
                    // Portal will bubble through to us.
                    return;
                  }
                }

                grandNode = grandNode.return;
              }
            } // Now we need to find it's corresponding host fiber in the other
            // tree. To do this we can use getClosestInstanceFromNode, but we
            // need to validate that the fiber is a host instance, otherwise
            // we need to traverse up through the DOM till we find the correct
            // node that is from the other tree.


            while (container !== null) {
              var parentNode = getClosestInstanceFromNode(container);

              if (parentNode === null) {
                return;
              }

              var parentTag = parentNode.tag;

              if (parentTag === HostComponent || parentTag === HostText) {
                node = ancestorInst = parentNode;
                continue mainLoop;
              }

              container = container.parentNode;
            }
          }

          node = node.return;
        }
      }
    }

    batchedUpdates(function () {
      return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
    });
  }

  function createDispatchListener(instance, listener, currentTarget) {
    return {
      instance: instance,
      listener: listener,
      currentTarget: currentTarget
    };
  }

  function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
    var captureName = reactName !== null ? reactName + 'Capture' : null;
    var reactEventName = inCapturePhase ? captureName : reactName;
    var listeners = [];
    var instance = targetFiber;
    var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path.

    while (instance !== null) {
      var _instance2 = instance,
          stateNode = _instance2.stateNode,
          tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>)

      if (tag === HostComponent && stateNode !== null) {
        lastHostComponent = stateNode; // createEventHandle listeners


        if (reactEventName !== null) {
          var listener = getListener(instance, reactEventName);

          if (listener != null) {
            listeners.push(createDispatchListener(instance, listener, lastHostComponent));
          }
        }
      } // If we are only accumulating events for the target, then we don't
      // continue to propagate through the React fiber tree to find other
      // listeners.


      if (accumulateTargetOnly) {
        break;
      } // If we are processing the onBeforeBlur event, then we need to take

      instance = instance.return;
    }

    return listeners;
  } // We should only use this function for:
  // - BeforeInputEventPlugin
  // - ChangeEventPlugin
  // - SelectEventPlugin
  // This is because we only process these plugins
  // in the bubble phase, so we need to accumulate two
  // phase event listeners (via emulation).

  function accumulateTwoPhaseListeners(targetFiber, reactName) {
    var captureName = reactName + 'Capture';
    var listeners = [];
    var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path.

    while (instance !== null) {
      var _instance3 = instance,
          stateNode = _instance3.stateNode,
          tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>)

      if (tag === HostComponent && stateNode !== null) {
        var currentTarget = stateNode;
        var captureListener = getListener(instance, captureName);

        if (captureListener != null) {
          listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
        }

        var bubbleListener = getListener(instance, reactName);

        if (bubbleListener != null) {
          listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
        }
      }

      instance = instance.return;
    }

    return listeners;
  }

  function getParent(inst) {
    if (inst === null) {
      return null;
    }

    do {
      inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
      // That is depending on if we want nested subtrees (layers) to bubble
      // events to their parent. We could also go through parentNode on the
      // host node but that wouldn't work for React Native and doesn't let us
      // do the portal feature.
    } while (inst && inst.tag !== HostComponent);

    if (inst) {
      return inst;
    }

    return null;
  }
  /**
   * Return the lowest common ancestor of A and B, or null if they are in
   * different trees.
   */


  function getLowestCommonAncestor(instA, instB) {
    var nodeA = instA;
    var nodeB = instB;
    var depthA = 0;

    for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
      depthA++;
    }

    var depthB = 0;

    for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
      depthB++;
    } // If A is deeper, crawl up.


    while (depthA - depthB > 0) {
      nodeA = getParent(nodeA);
      depthA--;
    } // If B is deeper, crawl up.


    while (depthB - depthA > 0) {
      nodeB = getParent(nodeB);
      depthB--;
    } // Walk in lockstep until we find a match.


    var depth = depthA;

    while (depth--) {
      if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
        return nodeA;
      }

      nodeA = getParent(nodeA);
      nodeB = getParent(nodeB);
    }

    return null;
  }

  function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
    var registrationName = event._reactName;
    var listeners = [];
    var instance = target;

    while (instance !== null) {
      if (instance === common) {
        break;
      }

      var _instance4 = instance,
          alternate = _instance4.alternate,
          stateNode = _instance4.stateNode,
          tag = _instance4.tag;

      if (alternate !== null && alternate === common) {
        break;
      }

      if (tag === HostComponent && stateNode !== null) {
        var currentTarget = stateNode;

        if (inCapturePhase) {
          var captureListener = getListener(instance, registrationName);

          if (captureListener != null) {
            listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
          }
        } else if (!inCapturePhase) {
          var bubbleListener = getListener(instance, registrationName);

          if (bubbleListener != null) {
            listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
          }
        }
      }

      instance = instance.return;
    }

    if (listeners.length !== 0) {
      dispatchQueue.push({
        event: event,
        listeners: listeners
      });
    }
  } // We should only use this function for:
  // - EnterLeaveEventPlugin
  // This is because we only process this plugin
  // in the bubble phase, so we need to accumulate two
  // phase event listeners.


  function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
    var common = from && to ? getLowestCommonAncestor(from, to) : null;

    if (from !== null) {
      accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
    }

    if (to !== null && enterEvent !== null) {
      accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
    }
  }
  function getListenerSetKey(domEventName, capture) {
    return domEventName + "__" + (capture ? 'capture' : 'bubble');
  }

  var didWarnInvalidHydration = false;
  var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
  var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
  var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
  var AUTOFOCUS = 'autoFocus';
  var CHILDREN = 'children';
  var STYLE = 'style';
  var HTML$1 = '__html';
  var warnedUnknownTags;
  var validatePropertiesInDevelopment;
  var warnForPropDifference;
  var warnForExtraAttributes;
  var warnForInvalidEventListener;
  var canDiffStyleForHydrationWarning;
  var normalizeHTML;

  {
    warnedUnknownTags = {
      // There are working polyfills for <dialog>. Let people use it.
      dialog: true,
      // Electron ships a custom <webview> tag to display external web content in
      // an isolated frame and process.
      // This tag is not present in non Electron environments such as JSDom which
      // is often used for testing purposes.
      // @see https://electronjs.org/docs/api/webview-tag
      webview: true
    };

    validatePropertiesInDevelopment = function (type, props) {
      validateProperties(type, props);
      validateProperties$1(type, props);
      validateProperties$2(type, props, {
        registrationNameDependencies: registrationNameDependencies,
        possibleRegistrationNames: possibleRegistrationNames
      });
    }; // IE 11 parses & normalizes the style attribute as opposed to other
    // browsers. It adds spaces and sorts the properties in some
    // non-alphabetical order. Handling that would require sorting CSS
    // properties in the client & server versions or applying
    // `expectedStyle` to a temporary DOM node to read its `style` attribute
    // normalized. Since it only affects IE, we're skipping style warnings
    // in that browser completely in favor of doing all that work.
    // See https://github.com/facebook/react/issues/11807


    canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;

    warnForPropDifference = function (propName, serverValue, clientValue) {
      if (didWarnInvalidHydration) {
        return;
      }

      var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
      var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);

      if (normalizedServerValue === normalizedClientValue) {
        return;
      }

      didWarnInvalidHydration = true;

      error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
    };

    warnForExtraAttributes = function (attributeNames) {
      if (didWarnInvalidHydration) {
        return;
      }

      didWarnInvalidHydration = true;
      var names = [];
      attributeNames.forEach(function (name) {
        names.push(name);
      });

      error('Extra attributes from the server: %s', names);
    };

    warnForInvalidEventListener = function (registrationName, listener) {
      if (listener === false) {
        error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
      } else {
        error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
      }
    }; // Parse the HTML and read it back to normalize the HTML string so that it
    // can be used for comparison.


    normalizeHTML = function (parent, html) {
      // We could have created a separate document here to avoid
      // re-initializing custom elements if they exist. But this breaks
      // how <noscript> is being handled. So we use the same document.
      // See the discussion in https://github.com/facebook/react/pull/11157.
      var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
      testElement.innerHTML = html;
      return testElement.innerHTML;
    };
  } // HTML parsing normalizes CR and CRLF to LF.
  // It also can turn \u0000 into \uFFFD inside attributes.
  // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
  // If we have a mismatch, it might be caused by that.
  // We will still patch up in this case but not fire the warning.


  var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
  var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;

  function normalizeMarkupForTextOrAttribute(markup) {
    {
      checkHtmlStringCoercion(markup);
    }

    var markupString = typeof markup === 'string' ? markup : '' + markup;
    return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
  }

  function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
    var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
    var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);

    if (normalizedServerText === normalizedClientText) {
      return;
    }

    if (shouldWarnDev) {
      {
        if (!didWarnInvalidHydration) {
          didWarnInvalidHydration = true;

          error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
        }
      }
    }

    if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
      // In concurrent roots, we throw when there's a text mismatch and revert to
      // client rendering, up to the nearest Suspense boundary.
      throw new Error('Text content does not match server-rendered HTML.');
    }
  }

  function getOwnerDocumentFromRootContainer(rootContainerElement) {
    return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
  }

  function noop() {}

  function trapClickOnNonInteractiveElement(node) {
    // Mobile Safari does not fire properly bubble click events on
    // non-interactive elements, which means delegated click listeners do not
    // fire. The workaround for this bug involves attaching an empty click
    // listener on the target node.
    // https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
    // Just set it using the onclick property so that we don't have to manage any
    // bookkeeping for it. Not sure if we need to clear it when the listener is
    // removed.
    // TODO: Only do this for the relevant Safaris maybe?
    node.onclick = noop;
  }

  function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
    for (var propKey in nextProps) {
      if (!nextProps.hasOwnProperty(propKey)) {
        continue;
      }

      var nextProp = nextProps[propKey];

      if (propKey === STYLE) {
        {
          if (nextProp) {
            // Freeze the next style object so that we can assume it won't be
            // mutated. We have already warned for this in the past.
            Object.freeze(nextProp);
          }
        } // Relies on `updateStylesByID` not mutating `styleUpdates`.


        setValueForStyles(domElement, nextProp);
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
        var nextHtml = nextProp ? nextProp[HTML$1] : undefined;

        if (nextHtml != null) {
          setInnerHTML(domElement, nextHtml);
        }
      } else if (propKey === CHILDREN) {
        if (typeof nextProp === 'string') {
          // Avoid setting initial textContent when the text is empty. In IE11 setting
          // textContent on a <textarea> will cause the placeholder to not
          // show within the <textarea> until it has been focused and blurred again.
          // https://github.com/facebook/react/issues/6731#issuecomment-254874553
          var canSetTextContent = tag !== 'textarea' || nextProp !== '';

          if (canSetTextContent) {
            setTextContent(domElement, nextProp);
          }
        } else if (typeof nextProp === 'number') {
          setTextContent(domElement, '' + nextProp);
        }
      } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
        if (nextProp != null) {
          if ( typeof nextProp !== 'function') {
            warnForInvalidEventListener(propKey, nextProp);
          }

          if (propKey === 'onScroll') {
            listenToNonDelegatedEvent('scroll', domElement);
          }
        }
      } else if (nextProp != null) {
        setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
      }
    }
  }

  function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
    // TODO: Handle wasCustomComponentTag
    for (var i = 0; i < updatePayload.length; i += 2) {
      var propKey = updatePayload[i];
      var propValue = updatePayload[i + 1];

      if (propKey === STYLE) {
        setValueForStyles(domElement, propValue);
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
        setInnerHTML(domElement, propValue);
      } else if (propKey === CHILDREN) {
        setTextContent(domElement, propValue);
      } else {
        setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
      }
    }
  }

  function createElement(type, props, rootContainerElement, parentNamespace) {
    var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
    // tags get no namespace.

    var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
    var domElement;
    var namespaceURI = parentNamespace;

    if (namespaceURI === HTML_NAMESPACE) {
      namespaceURI = getIntrinsicNamespace(type);
    }

    if (namespaceURI === HTML_NAMESPACE) {
      {
        isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
        // allow <SVG> or <mATH>.

        if (!isCustomComponentTag && type !== type.toLowerCase()) {
          error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
        }
      }

      if (type === 'script') {
        // Create the script via .innerHTML so its "parser-inserted" flag is
        // set to true and it does not execute
        var div = ownerDocument.createElement('div');

        div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
        // This is guaranteed to yield a script element.

        var firstChild = div.firstChild;
        domElement = div.removeChild(firstChild);
      } else if (typeof props.is === 'string') {
        // $FlowIssue `createElement` should be updated for Web Components
        domElement = ownerDocument.createElement(type, {
          is: props.is
        });
      } else {
        // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
        // See discussion in https://github.com/facebook/react/pull/6896
        // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
        domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
        // attributes on `select`s needs to be added before `option`s are inserted.
        // This prevents:
        // - a bug where the `select` does not scroll to the correct option because singular
        //  `select` elements automatically pick the first item #13222
        // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
        // See https://github.com/facebook/react/issues/13222
        // and https://github.com/facebook/react/issues/14239

        if (type === 'select') {
          var node = domElement;

          if (props.multiple) {
            node.multiple = true;
          } else if (props.size) {
            // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
            // it is possible that no option is selected.
            //
            // This is only necessary when a select in "single selection mode".
            node.size = props.size;
          }
        }
      }
    } else {
      domElement = ownerDocument.createElementNS(namespaceURI, type);
    }

    {
      if (namespaceURI === HTML_NAMESPACE) {
        if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) {
          warnedUnknownTags[type] = true;

          error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
        }
      }
    }

    return domElement;
  }
  function createTextNode(text, rootContainerElement) {
    return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
  }
  function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
    var isCustomComponentTag = isCustomComponent(tag, rawProps);

    {
      validatePropertiesInDevelopment(tag, rawProps);
    } // TODO: Make sure that we check isMounted before firing any of these events.


    var props;

    switch (tag) {
      case 'dialog':
        listenToNonDelegatedEvent('cancel', domElement);
        listenToNonDelegatedEvent('close', domElement);
        props = rawProps;
        break;

      case 'iframe':
      case 'object':
      case 'embed':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the load event.
        listenToNonDelegatedEvent('load', domElement);
        props = rawProps;
        break;

      case 'video':
      case 'audio':
        // We listen to these events in case to ensure emulated bubble
        // listeners still fire for all the media events.
        for (var i = 0; i < mediaEventTypes.length; i++) {
          listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
        }

        props = rawProps;
        break;

      case 'source':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the error event.
        listenToNonDelegatedEvent('error', domElement);
        props = rawProps;
        break;

      case 'img':
      case 'image':
      case 'link':
        // We listen to these events in case to ensure emulated bubble
        // listeners still fire for error and load events.
        listenToNonDelegatedEvent('error', domElement);
        listenToNonDelegatedEvent('load', domElement);
        props = rawProps;
        break;

      case 'details':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the toggle event.
        listenToNonDelegatedEvent('toggle', domElement);
        props = rawProps;
        break;

      case 'input':
        initWrapperState(domElement, rawProps);
        props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;

      case 'option':
        validateProps(domElement, rawProps);
        props = rawProps;
        break;

      case 'select':
        initWrapperState$1(domElement, rawProps);
        props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;

      case 'textarea':
        initWrapperState$2(domElement, rawProps);
        props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;

      default:
        props = rawProps;
    }

    assertValidProps(tag, props);
    setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);

    switch (tag) {
      case 'input':
        // TODO: Make sure we check if this is still unmounted or do any clean
        // up necessary since we never stop tracking anymore.
        track(domElement);
        postMountWrapper(domElement, rawProps, false);
        break;

      case 'textarea':
        // TODO: Make sure we check if this is still unmounted or do any clean
        // up necessary since we never stop tracking anymore.
        track(domElement);
        postMountWrapper$3(domElement);
        break;

      case 'option':
        postMountWrapper$1(domElement, rawProps);
        break;

      case 'select':
        postMountWrapper$2(domElement, rawProps);
        break;

      default:
        if (typeof props.onClick === 'function') {
          // TODO: This cast may not be sound for SVG, MathML or custom elements.
          trapClickOnNonInteractiveElement(domElement);
        }

        break;
    }
  } // Calculate the diff between the two objects.

  function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
    {
      validatePropertiesInDevelopment(tag, nextRawProps);
    }

    var updatePayload = null;
    var lastProps;
    var nextProps;

    switch (tag) {
      case 'input':
        lastProps = getHostProps(domElement, lastRawProps);
        nextProps = getHostProps(domElement, nextRawProps);
        updatePayload = [];
        break;

      case 'select':
        lastProps = getHostProps$1(domElement, lastRawProps);
        nextProps = getHostProps$1(domElement, nextRawProps);
        updatePayload = [];
        break;

      case 'textarea':
        lastProps = getHostProps$2(domElement, lastRawProps);
        nextProps = getHostProps$2(domElement, nextRawProps);
        updatePayload = [];
        break;

      default:
        lastProps = lastRawProps;
        nextProps = nextRawProps;

        if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
          // TODO: This cast may not be sound for SVG, MathML or custom elements.
          trapClickOnNonInteractiveElement(domElement);
        }

        break;
    }

    assertValidProps(tag, nextProps);
    var propKey;
    var styleName;
    var styleUpdates = null;

    for (propKey in lastProps) {
      if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
        continue;
      }

      if (propKey === STYLE) {
        var lastStyle = lastProps[propKey];

        for (styleName in lastStyle) {
          if (lastStyle.hasOwnProperty(styleName)) {
            if (!styleUpdates) {
              styleUpdates = {};
            }

            styleUpdates[styleName] = '';
          }
        }
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
        // This is a special case. If any listener updates we need to ensure
        // that the "current" fiber pointer gets updated so we need a commit
        // to update this element.
        if (!updatePayload) {
          updatePayload = [];
        }
      } else {
        // For all other deleted properties we add it to the queue. We use
        // the allowed property list in the commit phase instead.
        (updatePayload = updatePayload || []).push(propKey, null);
      }
    }

    for (propKey in nextProps) {
      var nextProp = nextProps[propKey];
      var lastProp = lastProps != null ? lastProps[propKey] : undefined;

      if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
        continue;
      }

      if (propKey === STYLE) {
        {
          if (nextProp) {
            // Freeze the next style object so that we can assume it won't be
            // mutated. We have already warned for this in the past.
            Object.freeze(nextProp);
          }
        }

        if (lastProp) {
          // Unset styles on `lastProp` but not on `nextProp`.
          for (styleName in lastProp) {
            if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
              if (!styleUpdates) {
                styleUpdates = {};
              }

              styleUpdates[styleName] = '';
            }
          } // Update styles that changed since `lastProp`.


          for (styleName in nextProp) {
            if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
              if (!styleUpdates) {
                styleUpdates = {};
              }

              styleUpdates[styleName] = nextProp[styleName];
            }
          }
        } else {
          // Relies on `updateStylesByID` not mutating `styleUpdates`.
          if (!styleUpdates) {
            if (!updatePayload) {
              updatePayload = [];
            }

            updatePayload.push(propKey, styleUpdates);
          }

          styleUpdates = nextProp;
        }
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
        var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
        var lastHtml = lastProp ? lastProp[HTML$1] : undefined;

        if (nextHtml != null) {
          if (lastHtml !== nextHtml) {
            (updatePayload = updatePayload || []).push(propKey, nextHtml);
          }
        }
      } else if (propKey === CHILDREN) {
        if (typeof nextProp === 'string' || typeof nextProp === 'number') {
          (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
        }
      } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
        if (nextProp != null) {
          // We eagerly listen to this even though we haven't committed yet.
          if ( typeof nextProp !== 'function') {
            warnForInvalidEventListener(propKey, nextProp);
          }

          if (propKey === 'onScroll') {
            listenToNonDelegatedEvent('scroll', domElement);
          }
        }

        if (!updatePayload && lastProp !== nextProp) {
          // This is a special case. If any listener updates we need to ensure
          // that the "current" props pointer gets updated so we need a commit
          // to update this element.
          updatePayload = [];
        }
      } else {
        // For any other property we always add it to the queue and then we
        // filter it out using the allowed property list during the commit.
        (updatePayload = updatePayload || []).push(propKey, nextProp);
      }
    }

    if (styleUpdates) {
      {
        validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
      }

      (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
    }

    return updatePayload;
  } // Apply the diff.

  function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
    // Update checked *before* name.
    // In the middle of an update, it is possible to have multiple checked.
    // When a checked radio tries to change name, browser makes another radio's checked false.
    if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
      updateChecked(domElement, nextRawProps);
    }

    var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
    var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.

    updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
    // changed.

    switch (tag) {
      case 'input':
        // Update the wrapper around inputs *after* updating props. This has to
        // happen after `updateDOMProperties`. Otherwise HTML5 input validations
        // raise warnings and prevent the new value from being assigned.
        updateWrapper(domElement, nextRawProps);
        break;

      case 'textarea':
        updateWrapper$1(domElement, nextRawProps);
        break;

      case 'select':
        // <select> value update needs to occur after <option> children
        // reconciliation
        postUpdateWrapper(domElement, nextRawProps);
        break;
    }
  }

  function getPossibleStandardName(propName) {
    {
      var lowerCasedName = propName.toLowerCase();

      if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        return null;
      }

      return possibleStandardNames[lowerCasedName] || null;
    }
  }

  function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
    var isCustomComponentTag;
    var extraAttributeNames;

    {
      isCustomComponentTag = isCustomComponent(tag, rawProps);
      validatePropertiesInDevelopment(tag, rawProps);
    } // TODO: Make sure that we check isMounted before firing any of these events.


    switch (tag) {
      case 'dialog':
        listenToNonDelegatedEvent('cancel', domElement);
        listenToNonDelegatedEvent('close', domElement);
        break;

      case 'iframe':
      case 'object':
      case 'embed':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the load event.
        listenToNonDelegatedEvent('load', domElement);
        break;

      case 'video':
      case 'audio':
        // We listen to these events in case to ensure emulated bubble
        // listeners still fire for all the media events.
        for (var i = 0; i < mediaEventTypes.length; i++) {
          listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
        }

        break;

      case 'source':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the error event.
        listenToNonDelegatedEvent('error', domElement);
        break;

      case 'img':
      case 'image':
      case 'link':
        // We listen to these events in case to ensure emulated bubble
        // listeners still fire for error and load events.
        listenToNonDelegatedEvent('error', domElement);
        listenToNonDelegatedEvent('load', domElement);
        break;

      case 'details':
        // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the toggle event.
        listenToNonDelegatedEvent('toggle', domElement);
        break;

      case 'input':
        initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;

      case 'option':
        validateProps(domElement, rawProps);
        break;

      case 'select':
        initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;

      case 'textarea':
        initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
        // listeners still fire for the invalid event.

        listenToNonDelegatedEvent('invalid', domElement);
        break;
    }

    assertValidProps(tag, rawProps);

    {
      extraAttributeNames = new Set();
      var attributes = domElement.attributes;

      for (var _i = 0; _i < attributes.length; _i++) {
        var name = attributes[_i].name.toLowerCase();

        switch (name) {
          // Controlled attributes are not validated
          // TODO: Only ignore them on controlled tags.
          case 'value':
            break;

          case 'checked':
            break;

          case 'selected':
            break;

          default:
            // Intentionally use the original name.
            // See discussion in https://github.com/facebook/react/pull/10676.
            extraAttributeNames.add(attributes[_i].name);
        }
      }
    }

    var updatePayload = null;

    for (var propKey in rawProps) {
      if (!rawProps.hasOwnProperty(propKey)) {
        continue;
      }

      var nextProp = rawProps[propKey];

      if (propKey === CHILDREN) {
        // For text content children we compare against textContent. This
        // might match additional HTML that is hidden when we read it using
        // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
        // satisfies our requirement. Our requirement is not to produce perfect
        // HTML and attributes. Ideally we should preserve structure but it's
        // ok not to if the visible content is still enough to indicate what
        // even listeners these nodes might be wired up to.
        // TODO: Warn if there is more than a single textNode as a child.
        // TODO: Should we use domElement.firstChild.nodeValue to compare?
        if (typeof nextProp === 'string') {
          if (domElement.textContent !== nextProp) {
            if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
              checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
            }

            updatePayload = [CHILDREN, nextProp];
          }
        } else if (typeof nextProp === 'number') {
          if (domElement.textContent !== '' + nextProp) {
            if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
              checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
            }

            updatePayload = [CHILDREN, '' + nextProp];
          }
        }
      } else if (registrationNameDependencies.hasOwnProperty(propKey)) {
        if (nextProp != null) {
          if ( typeof nextProp !== 'function') {
            warnForInvalidEventListener(propKey, nextProp);
          }

          if (propKey === 'onScroll') {
            listenToNonDelegatedEvent('scroll', domElement);
          }
        }
      } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
      typeof isCustomComponentTag === 'boolean') {
        // Validate that the properties correspond to their expected values.
        var serverValue = void 0;
        var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey);

        if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
        // TODO: Only ignore them on controlled tags.
        propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
          var serverHTML = domElement.innerHTML;
          var nextHtml = nextProp ? nextProp[HTML$1] : undefined;

          if (nextHtml != null) {
            var expectedHTML = normalizeHTML(domElement, nextHtml);

            if (expectedHTML !== serverHTML) {
              warnForPropDifference(propKey, serverHTML, expectedHTML);
            }
          }
        } else if (propKey === STYLE) {
          // $FlowFixMe - Should be inferred as not undefined.
          extraAttributeNames.delete(propKey);

          if (canDiffStyleForHydrationWarning) {
            var expectedStyle = createDangerousStringForStyles(nextProp);
            serverValue = domElement.getAttribute('style');

            if (expectedStyle !== serverValue) {
              warnForPropDifference(propKey, serverValue, expectedStyle);
            }
          }
        } else if (isCustomComponentTag && !enableCustomElementPropertySupport) {
          // $FlowFixMe - Should be inferred as not undefined.
          extraAttributeNames.delete(propKey.toLowerCase());
          serverValue = getValueForAttribute(domElement, propKey, nextProp);

          if (nextProp !== serverValue) {
            warnForPropDifference(propKey, serverValue, nextProp);
          }
        } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
          var isMismatchDueToBadCasing = false;

          if (propertyInfo !== null) {
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propertyInfo.attributeName);
            serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
          } else {
            var ownNamespace = parentNamespace;

            if (ownNamespace === HTML_NAMESPACE) {
              ownNamespace = getIntrinsicNamespace(tag);
            }

            if (ownNamespace === HTML_NAMESPACE) {
              // $FlowFixMe - Should be inferred as not undefined.
              extraAttributeNames.delete(propKey.toLowerCase());
            } else {
              var standardName = getPossibleStandardName(propKey);

              if (standardName !== null && standardName !== propKey) {
                // If an SVG prop is supplied with bad casing, it will
                // be successfully parsed from HTML, but will produce a mismatch
                // (and would be incorrectly rendered on the client).
                // However, we already warn about bad casing elsewhere.
                // So we'll skip the misleading extra mismatch warning in this case.
                isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.

                extraAttributeNames.delete(standardName);
              } // $FlowFixMe - Should be inferred as not undefined.


              extraAttributeNames.delete(propKey);
            }

            serverValue = getValueForAttribute(domElement, propKey, nextProp);
          }

          var dontWarnCustomElement = enableCustomElementPropertySupport  ;

          if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
            warnForPropDifference(propKey, serverValue, nextProp);
          }
        }
      }
    }

    {
      if (shouldWarnDev) {
        if ( // $FlowFixMe - Should be inferred as not undefined.
        extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
          // $FlowFixMe - Should be inferred as not undefined.
          warnForExtraAttributes(extraAttributeNames);
        }
      }
    }

    switch (tag) {
      case 'input':
        // TODO: Make sure we check if this is still unmounted or do any clean
        // up necessary since we never stop tracking anymore.
        track(domElement);
        postMountWrapper(domElement, rawProps, true);
        break;

      case 'textarea':
        // TODO: Make sure we check if this is still unmounted or do any clean
        // up necessary since we never stop tracking anymore.
        track(domElement);
        postMountWrapper$3(domElement);
        break;

      case 'select':
      case 'option':
        // For input and textarea we current always set the value property at
        // post mount to force it to diverge from attributes. However, for
        // option and select we don't quite do the same thing and select
        // is not resilient to the DOM state changing so we don't do that here.
        // TODO: Consider not doing this for input and textarea.
        break;

      default:
        if (typeof rawProps.onClick === 'function') {
          // TODO: This cast may not be sound for SVG, MathML or custom elements.
          trapClickOnNonInteractiveElement(domElement);
        }

        break;
    }

    return updatePayload;
  }
  function diffHydratedText(textNode, text, isConcurrentMode) {
    var isDifferent = textNode.nodeValue !== text;
    return isDifferent;
  }
  function warnForDeletedHydratableElement(parentNode, child) {
    {
      if (didWarnInvalidHydration) {
        return;
      }

      didWarnInvalidHydration = true;

      error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
    }
  }
  function warnForDeletedHydratableText(parentNode, child) {
    {
      if (didWarnInvalidHydration) {
        return;
      }

      didWarnInvalidHydration = true;

      error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
    }
  }
  function warnForInsertedHydratedElement(parentNode, tag, props) {
    {
      if (didWarnInvalidHydration) {
        return;
      }

      didWarnInvalidHydration = true;

      error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
    }
  }
  function warnForInsertedHydratedText(parentNode, text) {
    {
      if (text === '') {
        // We expect to insert empty text nodes since they're not represented in
        // the HTML.
        // TODO: Remove this special case if we can just avoid inserting empty
        // text nodes.
        return;
      }

      if (didWarnInvalidHydration) {
        return;
      }

      didWarnInvalidHydration = true;

      error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
    }
  }
  function restoreControlledState$3(domElement, tag, props) {
    switch (tag) {
      case 'input':
        restoreControlledState(domElement, props);
        return;

      case 'textarea':
        restoreControlledState$2(domElement, props);
        return;

      case 'select':
        restoreControlledState$1(domElement, props);
        return;
    }
  }

  var validateDOMNesting = function () {};

  var updatedAncestorInfo = function () {};

  {
    // This validation code was written based on the HTML5 parsing spec:
    // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
    //
    // Note: this does not catch all invalid nesting, nor does it try to (as it's
    // not clear what practical benefit doing so provides); instead, we warn only
    // for cases where the parser will give a parse tree differing from what React
    // intended. For example, <b><div></div></b> is invalid but we don't warn
    // because it still parses correctly; we do warn for other cases like nested
    // <p> tags where the beginning of the second element implicitly closes the
    // first, causing a confusing mess.
    // https://html.spec.whatwg.org/multipage/syntax.html#special
    var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope

    var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
    // TODO: Distinguish by namespace here -- for <title>, including it here
    // errs on the side of fewer warnings
    'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope

    var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags

    var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
    var emptyAncestorInfo = {
      current: null,
      formTag: null,
      aTagInScope: null,
      buttonTagInScope: null,
      nobrTagInScope: null,
      pTagInButtonScope: null,
      listItemTagAutoclosing: null,
      dlItemTagAutoclosing: null
    };

    updatedAncestorInfo = function (oldInfo, tag) {
      var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);

      var info = {
        tag: tag
      };

      if (inScopeTags.indexOf(tag) !== -1) {
        ancestorInfo.aTagInScope = null;
        ancestorInfo.buttonTagInScope = null;
        ancestorInfo.nobrTagInScope = null;
      }

      if (buttonScopeTags.indexOf(tag) !== -1) {
        ancestorInfo.pTagInButtonScope = null;
      } // See rules for 'li', 'dd', 'dt' start tags in
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


      if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
        ancestorInfo.listItemTagAutoclosing = null;
        ancestorInfo.dlItemTagAutoclosing = null;
      }

      ancestorInfo.current = info;

      if (tag === 'form') {
        ancestorInfo.formTag = info;
      }

      if (tag === 'a') {
        ancestorInfo.aTagInScope = info;
      }

      if (tag === 'button') {
        ancestorInfo.buttonTagInScope = info;
      }

      if (tag === 'nobr') {
        ancestorInfo.nobrTagInScope = info;
      }

      if (tag === 'p') {
        ancestorInfo.pTagInButtonScope = info;
      }

      if (tag === 'li') {
        ancestorInfo.listItemTagAutoclosing = info;
      }

      if (tag === 'dd' || tag === 'dt') {
        ancestorInfo.dlItemTagAutoclosing = info;
      }

      return ancestorInfo;
    };
    /**
     * Returns whether
     */


    var isTagValidWithParent = function (tag, parentTag) {
      // First, let's check if we're in an unusual parsing mode...
      switch (parentTag) {
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
        case 'select':
          return tag === 'option' || tag === 'optgroup' || tag === '#text';

        case 'optgroup':
          return tag === 'option' || tag === '#text';
        // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
        // but

        case 'option':
          return tag === '#text';
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
        // No special behavior since these rules fall back to "in body" mode for
        // all except special table nodes which cause bad parsing behavior anyway.
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr

        case 'tr':
          return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody

        case 'tbody':
        case 'thead':
        case 'tfoot':
          return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup

        case 'colgroup':
          return tag === 'col' || tag === 'template';
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable

        case 'table':
          return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead

        case 'head':
          return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
        // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element

        case 'html':
          return tag === 'head' || tag === 'body' || tag === 'frameset';

        case 'frameset':
          return tag === 'frame';

        case '#document':
          return tag === 'html';
      } // Probably in the "in body" parsing mode, so we outlaw only tag combos
      // where the parsing rules cause implicit opens or closes to be added.
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


      switch (tag) {
        case 'h1':
        case 'h2':
        case 'h3':
        case 'h4':
        case 'h5':
        case 'h6':
          return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';

        case 'rp':
        case 'rt':
          return impliedEndTags.indexOf(parentTag) === -1;

        case 'body':
        case 'caption':
        case 'col':
        case 'colgroup':
        case 'frameset':
        case 'frame':
        case 'head':
        case 'html':
        case 'tbody':
        case 'td':
        case 'tfoot':
        case 'th':
        case 'thead':
        case 'tr':
          // These tags are only valid with a few parents that have special child
          // parsing rules -- if we're down here, then none of those matched and
          // so we allow it only if we don't know what the parent is, as all other
          // cases are invalid.
          return parentTag == null;
      }

      return true;
    };
    /**
     * Returns whether
     */


    var findInvalidAncestorForTag = function (tag, ancestorInfo) {
      switch (tag) {
        case 'address':
        case 'article':
        case 'aside':
        case 'blockquote':
        case 'center':
        case 'details':
        case 'dialog':
        case 'dir':
        case 'div':
        case 'dl':
        case 'fieldset':
        case 'figcaption':
        case 'figure':
        case 'footer':
        case 'header':
        case 'hgroup':
        case 'main':
        case 'menu':
        case 'nav':
        case 'ol':
        case 'p':
        case 'section':
        case 'summary':
        case 'ul':
        case 'pre':
        case 'listing':
        case 'table':
        case 'hr':
        case 'xmp':
        case 'h1':
        case 'h2':
        case 'h3':
        case 'h4':
        case 'h5':
        case 'h6':
          return ancestorInfo.pTagInButtonScope;

        case 'form':
          return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;

        case 'li':
          return ancestorInfo.listItemTagAutoclosing;

        case 'dd':
        case 'dt':
          return ancestorInfo.dlItemTagAutoclosing;

        case 'button':
          return ancestorInfo.buttonTagInScope;

        case 'a':
          // Spec says something about storing a list of markers, but it sounds
          // equivalent to this check.
          return ancestorInfo.aTagInScope;

        case 'nobr':
          return ancestorInfo.nobrTagInScope;
      }

      return null;
    };

    var didWarn$1 = {};

    validateDOMNesting = function (childTag, childText, ancestorInfo) {
      ancestorInfo = ancestorInfo || emptyAncestorInfo;
      var parentInfo = ancestorInfo.current;
      var parentTag = parentInfo && parentInfo.tag;

      if (childText != null) {
        if (childTag != null) {
          error('validateDOMNesting: when childText is passed, childTag should be null');
        }

        childTag = '#text';
      }

      var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
      var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
      var invalidParentOrAncestor = invalidParent || invalidAncestor;

      if (!invalidParentOrAncestor) {
        return;
      }

      var ancestorTag = invalidParentOrAncestor.tag;
      var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag;

      if (didWarn$1[warnKey]) {
        return;
      }

      didWarn$1[warnKey] = true;
      var tagDisplayName = childTag;
      var whitespaceInfo = '';

      if (childTag === '#text') {
        if (/\S/.test(childText)) {
          tagDisplayName = 'Text nodes';
        } else {
          tagDisplayName = 'Whitespace text nodes';
          whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
        }
      } else {
        tagDisplayName = '<' + childTag + '>';
      }

      if (invalidParent) {
        var info = '';

        if (ancestorTag === 'table' && childTag === 'tr') {
          info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
        }

        error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
      } else {
        error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
      }
    };
  }

  var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
  var SUSPENSE_START_DATA = '$';
  var SUSPENSE_END_DATA = '/$';
  var SUSPENSE_PENDING_START_DATA = '$?';
  var SUSPENSE_FALLBACK_START_DATA = '$!';
  var STYLE$1 = 'style';
  var eventsEnabled = null;
  var selectionInformation = null;
  function getRootHostContext(rootContainerInstance) {
    var type;
    var namespace;
    var nodeType = rootContainerInstance.nodeType;

    switch (nodeType) {
      case DOCUMENT_NODE:
      case DOCUMENT_FRAGMENT_NODE:
        {
          type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
          var root = rootContainerInstance.documentElement;
          namespace = root ? root.namespaceURI : getChildNamespace(null, '');
          break;
        }

      default:
        {
          var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
          var ownNamespace = container.namespaceURI || null;
          type = container.tagName;
          namespace = getChildNamespace(ownNamespace, type);
          break;
        }
    }

    {
      var validatedTag = type.toLowerCase();
      var ancestorInfo = updatedAncestorInfo(null, validatedTag);
      return {
        namespace: namespace,
        ancestorInfo: ancestorInfo
      };
    }
  }
  function getChildHostContext(parentHostContext, type, rootContainerInstance) {
    {
      var parentHostContextDev = parentHostContext;
      var namespace = getChildNamespace(parentHostContextDev.namespace, type);
      var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
      return {
        namespace: namespace,
        ancestorInfo: ancestorInfo
      };
    }
  }
  function getPublicInstance(instance) {
    return instance;
  }
  function prepareForCommit(containerInfo) {
    eventsEnabled = isEnabled();
    selectionInformation = getSelectionInformation();
    var activeInstance = null;

    setEnabled(false);
    return activeInstance;
  }
  function resetAfterCommit(containerInfo) {
    restoreSelection(selectionInformation);
    setEnabled(eventsEnabled);
    eventsEnabled = null;
    selectionInformation = null;
  }
  function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
    var parentNamespace;

    {
      // TODO: take namespace into account when validating.
      var hostContextDev = hostContext;
      validateDOMNesting(type, null, hostContextDev.ancestorInfo);

      if (typeof props.children === 'string' || typeof props.children === 'number') {
        var string = '' + props.children;
        var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
        validateDOMNesting(null, string, ownAncestorInfo);
      }

      parentNamespace = hostContextDev.namespace;
    }

    var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
    precacheFiberNode(internalInstanceHandle, domElement);
    updateFiberProps(domElement, props);
    return domElement;
  }
  function appendInitialChild(parentInstance, child) {
    parentInstance.appendChild(child);
  }
  function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
    setInitialProperties(domElement, type, props, rootContainerInstance);

    switch (type) {
      case 'button':
      case 'input':
      case 'select':
      case 'textarea':
        return !!props.autoFocus;

      case 'img':
        return true;

      default:
        return false;
    }
  }
  function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
    {
      var hostContextDev = hostContext;

      if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
        var string = '' + newProps.children;
        var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
        validateDOMNesting(null, string, ownAncestorInfo);
      }
    }

    return diffProperties(domElement, type, oldProps, newProps);
  }
  function shouldSetTextContent(type, props) {
    return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
  }
  function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
    {
      var hostContextDev = hostContext;
      validateDOMNesting(null, text, hostContextDev.ancestorInfo);
    }

    var textNode = createTextNode(text, rootContainerInstance);
    precacheFiberNode(internalInstanceHandle, textNode);
    return textNode;
  }
  function getCurrentEventPriority() {
    var currentEvent = window.event;

    if (currentEvent === undefined) {
      return DefaultEventPriority;
    }

    return getEventPriority(currentEvent.type);
  }
  // if a component just imports ReactDOM (e.g. for findDOMNode).
  // Some environments might not have setTimeout or clearTimeout.

  var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
  var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
  var noTimeout = -1;
  var localPromise = typeof Promise === 'function' ? Promise : undefined; // -------------------
  var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) {
    return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
  } : scheduleTimeout; // TODO: Determine the best fallback here.

  function handleErrorInNextTick(error) {
    setTimeout(function () {
      throw error;
    });
  } // -------------------
  function commitMount(domElement, type, newProps, internalInstanceHandle) {
    // Despite the naming that might imply otherwise, this method only
    // fires if there is an `Update` effect scheduled during mounting.
    // This happens if `finalizeInitialChildren` returns `true` (which it
    // does to implement the `autoFocus` attribute on the client). But
    // there are also other cases when this might happen (such as patching
    // up text content during hydration mismatch). So we'll check this again.
    switch (type) {
      case 'button':
      case 'input':
      case 'select':
      case 'textarea':
        if (newProps.autoFocus) {
          domElement.focus();
        }

        return;

      case 'img':
        {
          if (newProps.src) {
            domElement.src = newProps.src;
          }

          return;
        }
    }
  }
  function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
    // Apply the diff to the DOM node.
    updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with
    // with current event handlers.

    updateFiberProps(domElement, newProps);
  }
  function resetTextContent(domElement) {
    setTextContent(domElement, '');
  }
  function commitTextUpdate(textInstance, oldText, newText) {
    textInstance.nodeValue = newText;
  }
  function appendChild(parentInstance, child) {
    parentInstance.appendChild(child);
  }
  function appendChildToContainer(container, child) {
    var parentNode;

    if (container.nodeType === COMMENT_NODE) {
      parentNode = container.parentNode;
      parentNode.insertBefore(child, container);
    } else {
      parentNode = container;
      parentNode.appendChild(child);
    } // This container might be used for a portal.
    // If something inside a portal is clicked, that click should bubble
    // through the React tree. However, on Mobile Safari the click would
    // never bubble through the *DOM* tree unless an ancestor with onclick
    // event exists. So we wouldn't see it and dispatch it.
    // This is why we ensure that non React root containers have inline onclick
    // defined.
    // https://github.com/facebook/react/issues/11918


    var reactRootContainer = container._reactRootContainer;

    if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
      // TODO: This cast may not be sound for SVG, MathML or custom elements.
      trapClickOnNonInteractiveElement(parentNode);
    }
  }
  function insertBefore(parentInstance, child, beforeChild) {
    parentInstance.insertBefore(child, beforeChild);
  }
  function insertInContainerBefore(container, child, beforeChild) {
    if (container.nodeType === COMMENT_NODE) {
      container.parentNode.insertBefore(child, beforeChild);
    } else {
      container.insertBefore(child, beforeChild);
    }
  }

  function removeChild(parentInstance, child) {
    parentInstance.removeChild(child);
  }
  function removeChildFromContainer(container, child) {
    if (container.nodeType === COMMENT_NODE) {
      container.parentNode.removeChild(child);
    } else {
      container.removeChild(child);
    }
  }
  function clearSuspenseBoundary(parentInstance, suspenseInstance) {
    var node = suspenseInstance; // Delete all nodes within this suspense boundary.
    // There might be nested nodes so we need to keep track of how
    // deep we are and only break out when we're back on top.

    var depth = 0;

    do {
      var nextNode = node.nextSibling;
      parentInstance.removeChild(node);

      if (nextNode && nextNode.nodeType === COMMENT_NODE) {
        var data = nextNode.data;

        if (data === SUSPENSE_END_DATA) {
          if (depth === 0) {
            parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.

            retryIfBlockedOn(suspenseInstance);
            return;
          } else {
            depth--;
          }
        } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
          depth++;
        }
      }

      node = nextNode;
    } while (node); // TODO: Warn, we didn't find the end comment boundary.
    // Retry if any event replaying was blocked on this.


    retryIfBlockedOn(suspenseInstance);
  }
  function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
    if (container.nodeType === COMMENT_NODE) {
      clearSuspenseBoundary(container.parentNode, suspenseInstance);
    } else if (container.nodeType === ELEMENT_NODE) {
      clearSuspenseBoundary(container, suspenseInstance);
    } // Retry if any event replaying was blocked on this.


    retryIfBlockedOn(container);
  }
  function hideInstance(instance) {
    // TODO: Does this work for all element types? What about MathML? Should we
    // pass host context to this method?
    instance = instance;
    var style = instance.style;

    if (typeof style.setProperty === 'function') {
      style.setProperty('display', 'none', 'important');
    } else {
      style.display = 'none';
    }
  }
  function hideTextInstance(textInstance) {
    textInstance.nodeValue = '';
  }
  function unhideInstance(instance, props) {
    instance = instance;
    var styleProp = props[STYLE$1];
    var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
    instance.style.display = dangerousStyleValue('display', display);
  }
  function unhideTextInstance(textInstance, text) {
    textInstance.nodeValue = text;
  }
  function clearContainer(container) {
    if (container.nodeType === ELEMENT_NODE) {
      container.textContent = '';
    } else if (container.nodeType === DOCUMENT_NODE) {
      if (container.documentElement) {
        container.removeChild(container.documentElement);
      }
    }
  } // -------------------
  function canHydrateInstance(instance, type, props) {
    if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
      return null;
    } // This has now been refined to an element node.


    return instance;
  }
  function canHydrateTextInstance(instance, text) {
    if (text === '' || instance.nodeType !== TEXT_NODE) {
      // Empty strings are not parsed by HTML so there won't be a correct match here.
      return null;
    } // This has now been refined to a text node.


    return instance;
  }
  function canHydrateSuspenseInstance(instance) {
    if (instance.nodeType !== COMMENT_NODE) {
      // Empty strings are not parsed by HTML so there won't be a correct match here.
      return null;
    } // This has now been refined to a suspense node.


    return instance;
  }
  function isSuspenseInstancePending(instance) {
    return instance.data === SUSPENSE_PENDING_START_DATA;
  }
  function isSuspenseInstanceFallback(instance) {
    return instance.data === SUSPENSE_FALLBACK_START_DATA;
  }
  function getSuspenseInstanceFallbackErrorDetails(instance) {
    var dataset = instance.nextSibling && instance.nextSibling.dataset;
    var digest, message, stack;

    if (dataset) {
      digest = dataset.dgst;

      {
        message = dataset.msg;
        stack = dataset.stck;
      }
    }

    {
      return {
        message: message,
        digest: digest,
        stack: stack
      };
    } // let value = {message: undefined, hash: undefined};
    // const nextSibling = instance.nextSibling;
    // if (nextSibling) {
    //   const dataset = ((nextSibling: any): HTMLTemplateElement).dataset;
    //   value.message = dataset.msg;
    //   value.hash = dataset.hash;
    //   if (true) {
    //     value.stack = dataset.stack;
    //   }
    // }
    // return value;

  }
  function registerSuspenseInstanceRetry(instance, callback) {
    instance._reactRetry = callback;
  }

  function getNextHydratable(node) {
    // Skip non-hydratable nodes.
    for (; node != null; node = node.nextSibling) {
      var nodeType = node.nodeType;

      if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
        break;
      }

      if (nodeType === COMMENT_NODE) {
        var nodeData = node.data;

        if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
          break;
        }

        if (nodeData === SUSPENSE_END_DATA) {
          return null;
        }
      }
    }

    return node;
  }

  function getNextHydratableSibling(instance) {
    return getNextHydratable(instance.nextSibling);
  }
  function getFirstHydratableChild(parentInstance) {
    return getNextHydratable(parentInstance.firstChild);
  }
  function getFirstHydratableChildWithinContainer(parentContainer) {
    return getNextHydratable(parentContainer.firstChild);
  }
  function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
    return getNextHydratable(parentInstance.nextSibling);
  }
  function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
    precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
    // get attached.

    updateFiberProps(instance, props);
    var parentNamespace;

    {
      var hostContextDev = hostContext;
      parentNamespace = hostContextDev.namespace;
    } // TODO: Temporary hack to check if we're in a concurrent root. We can delete
    // when the legacy root API is removed.


    var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
    return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
  }
  function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
    precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete
    // when the legacy root API is removed.

    var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
    return diffHydratedText(textInstance, text);
  }
  function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
    precacheFiberNode(internalInstanceHandle, suspenseInstance);
  }
  function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
    var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
    // There might be nested nodes so we need to keep track of how
    // deep we are and only break out when we're back on top.

    var depth = 0;

    while (node) {
      if (node.nodeType === COMMENT_NODE) {
        var data = node.data;

        if (data === SUSPENSE_END_DATA) {
          if (depth === 0) {
            return getNextHydratableSibling(node);
          } else {
            depth--;
          }
        } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
          depth++;
        }
      }

      node = node.nextSibling;
    } // TODO: Warn, we didn't find the end comment boundary.


    return null;
  } // Returns the SuspenseInstance if this node is a direct child of a
  // SuspenseInstance. I.e. if its previous sibling is a Comment with
  // SUSPENSE_x_START_DATA. Otherwise, null.

  function getParentSuspenseInstance(targetInstance) {
    var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
    // There might be nested nodes so we need to keep track of how
    // deep we are and only break out when we're back on top.

    var depth = 0;

    while (node) {
      if (node.nodeType === COMMENT_NODE) {
        var data = node.data;

        if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
          if (depth === 0) {
            return node;
          } else {
            depth--;
          }
        } else if (data === SUSPENSE_END_DATA) {
          depth++;
        }
      }

      node = node.previousSibling;
    }

    return null;
  }
  function commitHydratedContainer(container) {
    // Retry if any event replaying was blocked on this.
    retryIfBlockedOn(container);
  }
  function commitHydratedSuspenseInstance(suspenseInstance) {
    // Retry if any event replaying was blocked on this.
    retryIfBlockedOn(suspenseInstance);
  }
  function shouldDeleteUnhydratedTailInstances(parentType) {
    return parentType !== 'head' && parentType !== 'body';
  }
  function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
    var shouldWarnDev = true;
    checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
  }
  function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
    if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
      var shouldWarnDev = true;
      checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
    }
  }
  function didNotHydrateInstanceWithinContainer(parentContainer, instance) {
    {
      if (instance.nodeType === ELEMENT_NODE) {
        warnForDeletedHydratableElement(parentContainer, instance);
      } else if (instance.nodeType === COMMENT_NODE) ; else {
        warnForDeletedHydratableText(parentContainer, instance);
      }
    }
  }
  function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) {
    {
      // $FlowFixMe: Only Element or Document can be parent nodes.
      var parentNode = parentInstance.parentNode;

      if (parentNode !== null) {
        if (instance.nodeType === ELEMENT_NODE) {
          warnForDeletedHydratableElement(parentNode, instance);
        } else if (instance.nodeType === COMMENT_NODE) ; else {
          warnForDeletedHydratableText(parentNode, instance);
        }
      }
    }
  }
  function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) {
    {
      if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        if (instance.nodeType === ELEMENT_NODE) {
          warnForDeletedHydratableElement(parentInstance, instance);
        } else if (instance.nodeType === COMMENT_NODE) ; else {
          warnForDeletedHydratableText(parentInstance, instance);
        }
      }
    }
  }
  function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) {
    {
      warnForInsertedHydratedElement(parentContainer, type);
    }
  }
  function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
    {
      warnForInsertedHydratedText(parentContainer, text);
    }
  }
  function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) {
    {
      // $FlowFixMe: Only Element or Document can be parent nodes.
      var parentNode = parentInstance.parentNode;
      if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type);
    }
  }
  function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
    {
      // $FlowFixMe: Only Element or Document can be parent nodes.
      var parentNode = parentInstance.parentNode;
      if (parentNode !== null) warnForInsertedHydratedText(parentNode, text);
    }
  }
  function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) {
    {
      if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        warnForInsertedHydratedElement(parentInstance, type);
      }
    }
  }
  function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
    {
      if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        warnForInsertedHydratedText(parentInstance, text);
      }
    }
  }
  function errorHydratingContainer(parentContainer) {
    {
      // TODO: This gets logged by onRecoverableError, too, so we should be
      // able to remove it.
      error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase());
    }
  }
  function preparePortalMount(portalInstance) {
    listenToAllSupportedEvents(portalInstance);
  }

  var randomKey = Math.random().toString(36).slice(2);
  var internalInstanceKey = '__reactFiber$' + randomKey;
  var internalPropsKey = '__reactProps$' + randomKey;
  var internalContainerInstanceKey = '__reactContainer$' + randomKey;
  var internalEventHandlersKey = '__reactEvents$' + randomKey;
  var internalEventHandlerListenersKey = '__reactListeners$' + randomKey;
  var internalEventHandlesSetKey = '__reactHandles$' + randomKey;
  function detachDeletedInstance(node) {
    // TODO: This function is only called on host components. I don't think all of
    // these fields are relevant.
    delete node[internalInstanceKey];
    delete node[internalPropsKey];
    delete node[internalEventHandlersKey];
    delete node[internalEventHandlerListenersKey];
    delete node[internalEventHandlesSetKey];
  }
  function precacheFiberNode(hostInst, node) {
    node[internalInstanceKey] = hostInst;
  }
  function markContainerAsRoot(hostRoot, node) {
    node[internalContainerInstanceKey] = hostRoot;
  }
  function unmarkContainerAsRoot(node) {
    node[internalContainerInstanceKey] = null;
  }
  function isContainerMarkedAsRoot(node) {
    return !!node[internalContainerInstanceKey];
  } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
  // If the target node is part of a hydrated or not yet rendered subtree, then
  // this may also return a SuspenseComponent or HostRoot to indicate that.
  // Conceptually the HostRoot fiber is a child of the Container node. So if you
  // pass the Container node as the targetNode, you will not actually get the
  // HostRoot back. To get to the HostRoot, you need to pass a child of it.
  // The same thing applies to Suspense boundaries.

  function getClosestInstanceFromNode(targetNode) {
    var targetInst = targetNode[internalInstanceKey];

    if (targetInst) {
      // Don't return HostRoot or SuspenseComponent here.
      return targetInst;
    } // If the direct event target isn't a React owned DOM node, we need to look
    // to see if one of its parents is a React owned DOM node.


    var parentNode = targetNode.parentNode;

    while (parentNode) {
      // We'll check if this is a container root that could include
      // React nodes in the future. We need to check this first because
      // if we're a child of a dehydrated container, we need to first
      // find that inner container before moving on to finding the parent
      // instance. Note that we don't check this field on  the targetNode
      // itself because the fibers are conceptually between the container
      // node and the first child. It isn't surrounding the container node.
      // If it's not a container, we check if it's an instance.
      targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];

      if (targetInst) {
        // Since this wasn't the direct target of the event, we might have
        // stepped past dehydrated DOM nodes to get here. However they could
        // also have been non-React nodes. We need to answer which one.
        // If we the instance doesn't have any children, then there can't be
        // a nested suspense boundary within it. So we can use this as a fast
        // bailout. Most of the time, when people add non-React children to
        // the tree, it is using a ref to a child-less DOM node.
        // Normally we'd only need to check one of the fibers because if it
        // has ever gone from having children to deleting them or vice versa
        // it would have deleted the dehydrated boundary nested inside already.
        // However, since the HostRoot starts out with an alternate it might
        // have one on the alternate so we need to check in case this was a
        // root.
        var alternate = targetInst.alternate;

        if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
          // Next we need to figure out if the node that skipped past is
          // nested within a dehydrated boundary and if so, which one.
          var suspenseInstance = getParentSuspenseInstance(targetNode);

          while (suspenseInstance !== null) {
            // We found a suspense instance. That means that we haven't
            // hydrated it yet. Even though we leave the comments in the
            // DOM after hydrating, and there are boundaries in the DOM
            // that could already be hydrated, we wouldn't have found them
            // through this pass since if the target is hydrated it would
            // have had an internalInstanceKey on it.
            // Let's get the fiber associated with the SuspenseComponent
            // as the deepest instance.
            var targetSuspenseInst = suspenseInstance[internalInstanceKey];

            if (targetSuspenseInst) {
              return targetSuspenseInst;
            } // If we don't find a Fiber on the comment, it might be because
            // we haven't gotten to hydrate it yet. There might still be a
            // parent boundary that hasn't above this one so we need to find
            // the outer most that is known.


            suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
            // host component also hasn't hydrated yet. We can return it
            // below since it will bail out on the isMounted check later.
          }
        }

        return targetInst;
      }

      targetNode = parentNode;
      parentNode = targetNode.parentNode;
    }

    return null;
  }
  /**
   * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
   * instance, or null if the node was not rendered by this React.
   */

  function getInstanceFromNode(node) {
    var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];

    if (inst) {
      if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
        return inst;
      } else {
        return null;
      }
    }

    return null;
  }
  /**
   * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
   * DOM node.
   */

  function getNodeFromInstance(inst) {
    if (inst.tag === HostComponent || inst.tag === HostText) {
      // In Fiber this, is just the state node right now. We assume it will be
      // a host component or host text.
      return inst.stateNode;
    } // Without this first invariant, passing a non-DOM-component triggers the next
    // invariant for a missing parent, which is super confusing.


    throw new Error('getNodeFromInstance: Invalid argument.');
  }
  function getFiberCurrentPropsFromNode(node) {
    return node[internalPropsKey] || null;
  }
  function updateFiberProps(node, props) {
    node[internalPropsKey] = props;
  }
  function getEventListenerSet(node) {
    var elementListenerSet = node[internalEventHandlersKey];

    if (elementListenerSet === undefined) {
      elementListenerSet = node[internalEventHandlersKey] = new Set();
    }

    return elementListenerSet;
  }

  var loggedTypeFailures = {};
  var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

  function setCurrentlyValidatingElement(element) {
    {
      if (element) {
        var owner = element._owner;
        var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
        ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
      } else {
        ReactDebugCurrentFrame$1.setExtraStackFrame(null);
      }
    }
  }

  function checkPropTypes(typeSpecs, values, location, componentName, element) {
    {
      // $FlowFixMe This is okay but Flow doesn't know it.
      var has = Function.call.bind(hasOwnProperty);

      for (var typeSpecName in typeSpecs) {
        if (has(typeSpecs, typeSpecName)) {
          var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
          // fail the render phase where it didn't fail before. So we log it.
          // After these have been cleaned up, we'll let them throw.

          try {
            // This is intentionally an invariant that gets caught. It's the same
            // behavior as without this statement except with a better message.
            if (typeof typeSpecs[typeSpecName] !== 'function') {
              // eslint-disable-next-line react-internal/prod-error-codes
              var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
              err.name = 'Invariant Violation';
              throw err;
            }

            error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
          } catch (ex) {
            error$1 = ex;
          }

          if (error$1 && !(error$1 instanceof Error)) {
            setCurrentlyValidatingElement(element);

            error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

            setCurrentlyValidatingElement(null);
          }

          if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
            // Only monitor this failure once because there tends to be a lot of the
            // same error.
            loggedTypeFailures[error$1.message] = true;
            setCurrentlyValidatingElement(element);

            error('Failed %s type: %s', location, error$1.message);

            setCurrentlyValidatingElement(null);
          }
        }
      }
    }
  }

  var valueStack = [];
  var fiberStack;

  {
    fiberStack = [];
  }

  var index = -1;

  function createCursor(defaultValue) {
    return {
      current: defaultValue
    };
  }

  function pop(cursor, fiber) {
    if (index < 0) {
      {
        error('Unexpected pop.');
      }

      return;
    }

    {
      if (fiber !== fiberStack[index]) {
        error('Unexpected Fiber popped.');
      }
    }

    cursor.current = valueStack[index];
    valueStack[index] = null;

    {
      fiberStack[index] = null;
    }

    index--;
  }

  function push(cursor, value, fiber) {
    index++;
    valueStack[index] = cursor.current;

    {
      fiberStack[index] = fiber;
    }

    cursor.current = value;
  }

  var warnedAboutMissingGetChildContext;

  {
    warnedAboutMissingGetChildContext = {};
  }

  var emptyContextObject = {};

  {
    Object.freeze(emptyContextObject);
  } // A cursor to the current merged context object on the stack.


  var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.

  var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
  // We use this to get access to the parent context after we have already
  // pushed the next context provider, and now need to merge their contexts.

  var previousContext = emptyContextObject;

  function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
    {
      if (didPushOwnContextIfProvider && isContextProvider(Component)) {
        // If the fiber is a context provider itself, when we read its context
        // we may have already pushed its own child context on the stack. A context
        // provider should not "see" its own child context. Therefore we read the
        // previous (parent) context instead for a context provider.
        return previousContext;
      }

      return contextStackCursor.current;
    }
  }

  function cacheContext(workInProgress, unmaskedContext, maskedContext) {
    {
      var instance = workInProgress.stateNode;
      instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
      instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
    }
  }

  function getMaskedContext(workInProgress, unmaskedContext) {
    {
      var type = workInProgress.type;
      var contextTypes = type.contextTypes;

      if (!contextTypes) {
        return emptyContextObject;
      } // Avoid recreating masked context unless unmasked context has changed.
      // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
      // This may trigger infinite loops if componentWillReceiveProps calls setState.


      var instance = workInProgress.stateNode;

      if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
        return instance.__reactInternalMemoizedMaskedChildContext;
      }

      var context = {};

      for (var key in contextTypes) {
        context[key] = unmaskedContext[key];
      }

      {
        var name = getComponentNameFromFiber(workInProgress) || 'Unknown';
        checkPropTypes(contextTypes, context, 'context', name);
      } // Cache unmasked context so we can avoid recreating masked context unless necessary.
      // Context is created before the class component is instantiated so check for instance.


      if (instance) {
        cacheContext(workInProgress, unmaskedContext, context);
      }

      return context;
    }
  }

  function hasContextChanged() {
    {
      return didPerformWorkStackCursor.current;
    }
  }

  function isContextProvider(type) {
    {
      var childContextTypes = type.childContextTypes;
      return childContextTypes !== null && childContextTypes !== undefined;
    }
  }

  function popContext(fiber) {
    {
      pop(didPerformWorkStackCursor, fiber);
      pop(contextStackCursor, fiber);
    }
  }

  function popTopLevelContextObject(fiber) {
    {
      pop(didPerformWorkStackCursor, fiber);
      pop(contextStackCursor, fiber);
    }
  }

  function pushTopLevelContextObject(fiber, context, didChange) {
    {
      if (contextStackCursor.current !== emptyContextObject) {
        throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      }

      push(contextStackCursor, context, fiber);
      push(didPerformWorkStackCursor, didChange, fiber);
    }
  }

  function processChildContext(fiber, type, parentContext) {
    {
      var instance = fiber.stateNode;
      var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
      // It has only been added in Fiber to match the (unintentional) behavior in Stack.

      if (typeof instance.getChildContext !== 'function') {
        {
          var componentName = getComponentNameFromFiber(fiber) || 'Unknown';

          if (!warnedAboutMissingGetChildContext[componentName]) {
            warnedAboutMissingGetChildContext[componentName] = true;

            error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
          }
        }

        return parentContext;
      }

      var childContext = instance.getChildContext();

      for (var contextKey in childContext) {
        if (!(contextKey in childContextTypes)) {
          throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
        }
      }

      {
        var name = getComponentNameFromFiber(fiber) || 'Unknown';
        checkPropTypes(childContextTypes, childContext, 'child context', name);
      }

      return assign({}, parentContext, childContext);
    }
  }

  function pushContextProvider(workInProgress) {
    {
      var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
      // If the instance does not exist yet, we will push null at first,
      // and replace it on the stack later when invalidating the context.

      var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
      // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.

      previousContext = contextStackCursor.current;
      push(contextStackCursor, memoizedMergedChildContext, workInProgress);
      push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
      return true;
    }
  }

  function invalidateContextProvider(workInProgress, type, didChange) {
    {
      var instance = workInProgress.stateNode;

      if (!instance) {
        throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      }

      if (didChange) {
        // Merge parent and own context.
        // Skip this if we're not updating due to sCU.
        // This avoids unnecessarily recomputing memoized values.
        var mergedContext = processChildContext(workInProgress, type, previousContext);
        instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
        // It is important to unwind the context in the reverse order.

        pop(didPerformWorkStackCursor, workInProgress);
        pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.

        push(contextStackCursor, mergedContext, workInProgress);
        push(didPerformWorkStackCursor, didChange, workInProgress);
      } else {
        pop(didPerformWorkStackCursor, workInProgress);
        push(didPerformWorkStackCursor, didChange, workInProgress);
      }
    }
  }

  function findCurrentUnmaskedContext(fiber) {
    {
      // Currently this is only used with renderSubtreeIntoContainer; not sure if it
      // makes sense elsewhere
      if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
        throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      }

      var node = fiber;

      do {
        switch (node.tag) {
          case HostRoot:
            return node.stateNode.context;

          case ClassComponent:
            {
              var Component = node.type;

              if (isContextProvider(Component)) {
                return node.stateNode.__reactInternalMemoizedMergedChildContext;
              }

              break;
            }
        }

        node = node.return;
      } while (node !== null);

      throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }
  }

  var LegacyRoot = 0;
  var ConcurrentRoot = 1;

  var syncQueue = null;
  var includesLegacySyncCallbacks = false;
  var isFlushingSyncQueue = false;
  function scheduleSyncCallback(callback) {
    // Push this callback into an internal queue. We'll flush these either in
    // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
    if (syncQueue === null) {
      syncQueue = [callback];
    } else {
      // Push onto existing queue. Don't need to schedule a callback because
      // we already scheduled one when we created the queue.
      syncQueue.push(callback);
    }
  }
  function scheduleLegacySyncCallback(callback) {
    includesLegacySyncCallbacks = true;
    scheduleSyncCallback(callback);
  }
  function flushSyncCallbacksOnlyInLegacyMode() {
    // Only flushes the queue if there's a legacy sync callback scheduled.
    // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
    // it might make more sense for the queue to be a list of roots instead of a
    // list of generic callbacks. Then we can have two: one for legacy roots, one
    // for concurrent roots. And this method would only flush the legacy ones.
    if (includesLegacySyncCallbacks) {
      flushSyncCallbacks();
    }
  }
  function flushSyncCallbacks() {
    if (!isFlushingSyncQueue && syncQueue !== null) {
      // Prevent re-entrance.
      isFlushingSyncQueue = true;
      var i = 0;
      var previousUpdatePriority = getCurrentUpdatePriority();

      try {
        var isSync = true;
        var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this
        // queue is in the render or commit phases.

        setCurrentUpdatePriority(DiscreteEventPriority);

        for (; i < queue.length; i++) {
          var callback = queue[i];

          do {
            callback = callback(isSync);
          } while (callback !== null);
        }

        syncQueue = null;
        includesLegacySyncCallbacks = false;
      } catch (error) {
        // If something throws, leave the remaining callbacks on the queue.
        if (syncQueue !== null) {
          syncQueue = syncQueue.slice(i + 1);
        } // Resume flushing in the next tick


        scheduleCallback(ImmediatePriority, flushSyncCallbacks);
        throw error;
      } finally {
        setCurrentUpdatePriority(previousUpdatePriority);
        isFlushingSyncQueue = false;
      }
    }

    return null;
  }

  // TODO: Use the unified fiber stack module instead of this local one?
  // Intentionally not using it yet to derisk the initial implementation, because
  // the way we push/pop these values is a bit unusual. If there's a mistake, I'd
  // rather the ids be wrong than crash the whole reconciler.
  var forkStack = [];
  var forkStackIndex = 0;
  var treeForkProvider = null;
  var treeForkCount = 0;
  var idStack = [];
  var idStackIndex = 0;
  var treeContextProvider = null;
  var treeContextId = 1;
  var treeContextOverflow = '';
  function isForkedChild(workInProgress) {
    warnIfNotHydrating();
    return (workInProgress.flags & Forked) !== NoFlags;
  }
  function getForksAtLevel(workInProgress) {
    warnIfNotHydrating();
    return treeForkCount;
  }
  function getTreeId() {
    var overflow = treeContextOverflow;
    var idWithLeadingBit = treeContextId;
    var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
    return id.toString(32) + overflow;
  }
  function pushTreeFork(workInProgress, totalChildren) {
    // This is called right after we reconcile an array (or iterator) of child
    // fibers, because that's the only place where we know how many children in
    // the whole set without doing extra work later, or storing addtional
    // information on the fiber.
    //
    // That's why this function is separate from pushTreeId â€” it's called during
    // the render phase of the fork parent, not the child, which is where we push
    // the other context values.
    //
    // In the Fizz implementation this is much simpler because the child is
    // rendered in the same callstack as the parent.
    //
    // It might be better to just add a `forks` field to the Fiber type. It would
    // make this module simpler.
    warnIfNotHydrating();
    forkStack[forkStackIndex++] = treeForkCount;
    forkStack[forkStackIndex++] = treeForkProvider;
    treeForkProvider = workInProgress;
    treeForkCount = totalChildren;
  }
  function pushTreeId(workInProgress, totalChildren, index) {
    warnIfNotHydrating();
    idStack[idStackIndex++] = treeContextId;
    idStack[idStackIndex++] = treeContextOverflow;
    idStack[idStackIndex++] = treeContextProvider;
    treeContextProvider = workInProgress;
    var baseIdWithLeadingBit = treeContextId;
    var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
    // of the id; we use it to account for leading 0s.

    var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
    var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
    var slot = index + 1;
    var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
    // consideration the leading 1 we use to mark the end of the sequence.

    if (length > 30) {
      // We overflowed the bitwise-safe range. Fall back to slower algorithm.
      // This branch assumes the length of the base id is greater than 5; it won't
      // work for smaller ids, because you need 5 bits per character.
      //
      // We encode the id in multiple steps: first the base id, then the
      // remaining digits.
      //
      // Each 5 bit sequence corresponds to a single base 32 character. So for
      // example, if the current id is 23 bits long, we can convert 20 of those
      // bits into a string of 4 characters, with 3 bits left over.
      //
      // First calculate how many bits in the base id represent a complete
      // sequence of characters.
      var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

      var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

      var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

      var restOfBaseId = baseId >> numberOfOverflowBits;
      var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
      // we made more room, this time it won't overflow.

      var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
      var restOfNewBits = slot << restOfBaseLength;
      var id = restOfNewBits | restOfBaseId;
      var overflow = newOverflow + baseOverflow;
      treeContextId = 1 << restOfLength | id;
      treeContextOverflow = overflow;
    } else {
      // Normal path
      var newBits = slot << baseLength;

      var _id = newBits | baseId;

      var _overflow = baseOverflow;
      treeContextId = 1 << length | _id;
      treeContextOverflow = _overflow;
    }
  }
  function pushMaterializedTreeId(workInProgress) {
    warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear
    // in its children.

    var returnFiber = workInProgress.return;

    if (returnFiber !== null) {
      var numberOfForks = 1;
      var slotIndex = 0;
      pushTreeFork(workInProgress, numberOfForks);
      pushTreeId(workInProgress, numberOfForks, slotIndex);
    }
  }

  function getBitLength(number) {
    return 32 - clz32(number);
  }

  function getLeadingBit(id) {
    return 1 << getBitLength(id) - 1;
  }

  function popTreeContext(workInProgress) {
    // Restore the previous values.
    // This is a bit more complicated than other context-like modules in Fiber
    // because the same Fiber may appear on the stack multiple times and for
    // different reasons. We have to keep popping until the work-in-progress is
    // no longer at the top of the stack.
    while (workInProgress === treeForkProvider) {
      treeForkProvider = forkStack[--forkStackIndex];
      forkStack[forkStackIndex] = null;
      treeForkCount = forkStack[--forkStackIndex];
      forkStack[forkStackIndex] = null;
    }

    while (workInProgress === treeContextProvider) {
      treeContextProvider = idStack[--idStackIndex];
      idStack[idStackIndex] = null;
      treeContextOverflow = idStack[--idStackIndex];
      idStack[idStackIndex] = null;
      treeContextId = idStack[--idStackIndex];
      idStack[idStackIndex] = null;
    }
  }
  function getSuspendedTreeContext() {
    warnIfNotHydrating();

    if (treeContextProvider !== null) {
      return {
        id: treeContextId,
        overflow: treeContextOverflow
      };
    } else {
      return null;
    }
  }
  function restoreSuspendedTreeContext(workInProgress, suspendedContext) {
    warnIfNotHydrating();
    idStack[idStackIndex++] = treeContextId;
    idStack[idStackIndex++] = treeContextOverflow;
    idStack[idStackIndex++] = treeContextProvider;
    treeContextId = suspendedContext.id;
    treeContextOverflow = suspendedContext.overflow;
    treeContextProvider = workInProgress;
  }

  function warnIfNotHydrating() {
    {
      if (!getIsHydrating()) {
        error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.');
      }
    }
  }

  // This may have been an insertion or a hydration.

  var hydrationParentFiber = null;
  var nextHydratableInstance = null;
  var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches
  // due to earlier mismatches or a suspended fiber.

  var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary

  var hydrationErrors = null;

  function warnIfHydrating() {
    {
      if (isHydrating) {
        error('We should not be hydrating here. This is a bug in React. Please file a bug.');
      }
    }
  }

  function markDidThrowWhileHydratingDEV() {
    {
      didSuspendOrErrorDEV = true;
    }
  }
  function didSuspendOrErrorWhileHydratingDEV() {
    {
      return didSuspendOrErrorDEV;
    }
  }

  function enterHydrationState(fiber) {

    var parentInstance = fiber.stateNode.containerInfo;
    nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
    hydrationParentFiber = fiber;
    isHydrating = true;
    hydrationErrors = null;
    didSuspendOrErrorDEV = false;
    return true;
  }

  function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {

    nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
    hydrationParentFiber = fiber;
    isHydrating = true;
    hydrationErrors = null;
    didSuspendOrErrorDEV = false;

    if (treeContext !== null) {
      restoreSuspendedTreeContext(fiber, treeContext);
    }

    return true;
  }

  function warnUnhydratedInstance(returnFiber, instance) {
    {
      switch (returnFiber.tag) {
        case HostRoot:
          {
            didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance);
            break;
          }

        case HostComponent:
          {
            var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
            didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API.
            isConcurrentMode);
            break;
          }

        case SuspenseComponent:
          {
            var suspenseState = returnFiber.memoizedState;
            if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance);
            break;
          }
      }
    }
  }

  function deleteHydratableInstance(returnFiber, instance) {
    warnUnhydratedInstance(returnFiber, instance);
    var childToDelete = createFiberFromHostInstanceForDeletion();
    childToDelete.stateNode = instance;
    childToDelete.return = returnFiber;
    var deletions = returnFiber.deletions;

    if (deletions === null) {
      returnFiber.deletions = [childToDelete];
      returnFiber.flags |= ChildDeletion;
    } else {
      deletions.push(childToDelete);
    }
  }

  function warnNonhydratedInstance(returnFiber, fiber) {
    {
      if (didSuspendOrErrorDEV) {
        // Inside a boundary that already suspended. We're currently rendering the
        // siblings of a suspended node. The mismatch may be due to the missing
        // data, so it's probably a false positive.
        return;
      }

      switch (returnFiber.tag) {
        case HostRoot:
          {
            var parentContainer = returnFiber.stateNode.containerInfo;

            switch (fiber.tag) {
              case HostComponent:
                var type = fiber.type;
                var props = fiber.pendingProps;
                didNotFindHydratableInstanceWithinContainer(parentContainer, type);
                break;

              case HostText:
                var text = fiber.pendingProps;
                didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
                break;
            }

            break;
          }

        case HostComponent:
          {
            var parentType = returnFiber.type;
            var parentProps = returnFiber.memoizedProps;
            var parentInstance = returnFiber.stateNode;

            switch (fiber.tag) {
              case HostComponent:
                {
                  var _type = fiber.type;
                  var _props = fiber.pendingProps;
                  var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                  didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API.
                  isConcurrentMode);
                  break;
                }

              case HostText:
                {
                  var _text = fiber.pendingProps;

                  var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;

                  didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API.
                  _isConcurrentMode);
                  break;
                }
            }

            break;
          }

        case SuspenseComponent:
          {
            var suspenseState = returnFiber.memoizedState;
            var _parentInstance = suspenseState.dehydrated;
            if (_parentInstance !== null) switch (fiber.tag) {
              case HostComponent:
                var _type2 = fiber.type;
                var _props2 = fiber.pendingProps;
                didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
                break;

              case HostText:
                var _text2 = fiber.pendingProps;
                didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
                break;
            }
            break;
          }

        default:
          return;
      }
    }
  }

  function insertNonHydratedInstance(returnFiber, fiber) {
    fiber.flags = fiber.flags & ~Hydrating | Placement;
    warnNonhydratedInstance(returnFiber, fiber);
  }

  function tryHydrate(fiber, nextInstance) {
    switch (fiber.tag) {
      case HostComponent:
        {
          var type = fiber.type;
          var props = fiber.pendingProps;
          var instance = canHydrateInstance(nextInstance, type);

          if (instance !== null) {
            fiber.stateNode = instance;
            hydrationParentFiber = fiber;
            nextHydratableInstance = getFirstHydratableChild(instance);
            return true;
          }

          return false;
        }

      case HostText:
        {
          var text = fiber.pendingProps;
          var textInstance = canHydrateTextInstance(nextInstance, text);

          if (textInstance !== null) {
            fiber.stateNode = textInstance;
            hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate.

            nextHydratableInstance = null;
            return true;
          }

          return false;
        }

      case SuspenseComponent:
        {
          var suspenseInstance = canHydrateSuspenseInstance(nextInstance);

          if (suspenseInstance !== null) {
            var suspenseState = {
              dehydrated: suspenseInstance,
              treeContext: getSuspendedTreeContext(),
              retryLane: OffscreenLane
            };
            fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
            // This simplifies the code for getHostSibling and deleting nodes,
            // since it doesn't have to consider all Suspense boundaries and
            // check if they're dehydrated ones or not.

            var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
            dehydratedFragment.return = fiber;
            fiber.child = dehydratedFragment;
            hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into
            // it during the first pass. Instead, we'll reenter it later.

            nextHydratableInstance = null;
            return true;
          }

          return false;
        }

      default:
        return false;
    }
  }

  function shouldClientRenderOnMismatch(fiber) {
    return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
  }

  function throwOnHydrationMismatch(fiber) {
    throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.');
  }

  function tryToClaimNextHydratableInstance(fiber) {
    if (!isHydrating) {
      return;
    }

    var nextInstance = nextHydratableInstance;

    if (!nextInstance) {
      if (shouldClientRenderOnMismatch(fiber)) {
        warnNonhydratedInstance(hydrationParentFiber, fiber);
        throwOnHydrationMismatch();
      } // Nothing to hydrate. Make it an insertion.


      insertNonHydratedInstance(hydrationParentFiber, fiber);
      isHydrating = false;
      hydrationParentFiber = fiber;
      return;
    }

    var firstAttemptedInstance = nextInstance;

    if (!tryHydrate(fiber, nextInstance)) {
      if (shouldClientRenderOnMismatch(fiber)) {
        warnNonhydratedInstance(hydrationParentFiber, fiber);
        throwOnHydrationMismatch();
      } // If we can't hydrate this instance let's try the next one.
      // We use this as a heuristic. It's based on intuition and not data so it
      // might be flawed or unnecessary.


      nextInstance = getNextHydratableSibling(firstAttemptedInstance);
      var prevHydrationParentFiber = hydrationParentFiber;

      if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
        // Nothing to hydrate. Make it an insertion.
        insertNonHydratedInstance(hydrationParentFiber, fiber);
        isHydrating = false;
        hydrationParentFiber = fiber;
        return;
      } // We matched the next one, we'll now assume that the first one was
      // superfluous and we'll delete it. Since we can't eagerly delete it
      // we'll have to schedule a deletion. To do that, this node needs a dummy
      // fiber associated with it.


      deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
    }
  }

  function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {

    var instance = fiber.stateNode;
    var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
    var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component.

    fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
    // is a new ref we mark this as an update.

    if (updatePayload !== null) {
      return true;
    }

    return false;
  }

  function prepareToHydrateHostTextInstance(fiber) {

    var textInstance = fiber.stateNode;
    var textContent = fiber.memoizedProps;
    var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);

    if (shouldUpdate) {
      // We assume that prepareToHydrateHostTextInstance is called in a context where the
      // hydration parent is the parent host component of this host text.
      var returnFiber = hydrationParentFiber;

      if (returnFiber !== null) {
        switch (returnFiber.tag) {
          case HostRoot:
            {
              var parentContainer = returnFiber.stateNode.containerInfo;
              var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
              didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
              isConcurrentMode);
              break;
            }

          case HostComponent:
            {
              var parentType = returnFiber.type;
              var parentProps = returnFiber.memoizedProps;
              var parentInstance = returnFiber.stateNode;

              var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;

              didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
              _isConcurrentMode2);
              break;
            }
        }
      }
    }

    return shouldUpdate;
  }

  function prepareToHydrateHostSuspenseInstance(fiber) {

    var suspenseState = fiber.memoizedState;
    var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;

    if (!suspenseInstance) {
      throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    hydrateSuspenseInstance(suspenseInstance, fiber);
  }

  function skipPastDehydratedSuspenseInstance(fiber) {

    var suspenseState = fiber.memoizedState;
    var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;

    if (!suspenseInstance) {
      throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
  }

  function popToNextHostParent(fiber) {
    var parent = fiber.return;

    while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
      parent = parent.return;
    }

    hydrationParentFiber = parent;
  }

  function popHydrationState(fiber) {

    if (fiber !== hydrationParentFiber) {
      // We're deeper than the current hydration context, inside an inserted
      // tree.
      return false;
    }

    if (!isHydrating) {
      // If we're not currently hydrating but we're in a hydration context, then
      // we were an insertion and now need to pop up reenter hydration of our
      // siblings.
      popToNextHostParent(fiber);
      isHydrating = true;
      return false;
    } // If we have any remaining hydratable nodes, we need to delete them now.
    // We only do this deeper than head and body since they tend to have random
    // other nodes in them. We also ignore components with pure text content in
    // side of them. We also don't delete anything inside the root container.


    if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
      var nextInstance = nextHydratableInstance;

      if (nextInstance) {
        if (shouldClientRenderOnMismatch(fiber)) {
          warnIfUnhydratedTailNodes(fiber);
          throwOnHydrationMismatch();
        } else {
          while (nextInstance) {
            deleteHydratableInstance(fiber, nextInstance);
            nextInstance = getNextHydratableSibling(nextInstance);
          }
        }
      }
    }

    popToNextHostParent(fiber);

    if (fiber.tag === SuspenseComponent) {
      nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
    } else {
      nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
    }

    return true;
  }

  function hasUnhydratedTailNodes() {
    return isHydrating && nextHydratableInstance !== null;
  }

  function warnIfUnhydratedTailNodes(fiber) {
    var nextInstance = nextHydratableInstance;

    while (nextInstance) {
      warnUnhydratedInstance(fiber, nextInstance);
      nextInstance = getNextHydratableSibling(nextInstance);
    }
  }

  function resetHydrationState() {

    hydrationParentFiber = null;
    nextHydratableInstance = null;
    isHydrating = false;
    didSuspendOrErrorDEV = false;
  }

  function upgradeHydrationErrorsToRecoverable() {
    if (hydrationErrors !== null) {
      // Successfully completed a forced client render. The errors that occurred
      // during the hydration attempt are now recovered. We will log them in
      // commit phase, once the entire tree has finished.
      queueRecoverableErrors(hydrationErrors);
      hydrationErrors = null;
    }
  }

  function getIsHydrating() {
    return isHydrating;
  }

  function queueHydrationError(error) {
    if (hydrationErrors === null) {
      hydrationErrors = [error];
    } else {
      hydrationErrors.push(error);
    }
  }

  var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
  var NoTransition = null;
  function requestCurrentTransition() {
    return ReactCurrentBatchConfig$1.transition;
  }

  var ReactStrictModeWarnings = {
    recordUnsafeLifecycleWarnings: function (fiber, instance) {},
    flushPendingUnsafeLifecycleWarnings: function () {},
    recordLegacyContextWarning: function (fiber, instance) {},
    flushLegacyContextWarning: function () {},
    discardPendingWarnings: function () {}
  };

  {
    var findStrictRoot = function (fiber) {
      var maybeStrictRoot = null;
      var node = fiber;

      while (node !== null) {
        if (node.mode & StrictLegacyMode) {
          maybeStrictRoot = node;
        }

        node = node.return;
      }

      return maybeStrictRoot;
    };

    var setToSortedString = function (set) {
      var array = [];
      set.forEach(function (value) {
        array.push(value);
      });
      return array.sort().join(', ');
    };

    var pendingComponentWillMountWarnings = [];
    var pendingUNSAFE_ComponentWillMountWarnings = [];
    var pendingComponentWillReceivePropsWarnings = [];
    var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
    var pendingComponentWillUpdateWarnings = [];
    var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.

    var didWarnAboutUnsafeLifecycles = new Set();

    ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
      // Dedupe strategy: Warn once per component.
      if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
        return;
      }

      if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
      instance.componentWillMount.__suppressDeprecationWarning !== true) {
        pendingComponentWillMountWarnings.push(fiber);
      }

      if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') {
        pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        pendingComponentWillReceivePropsWarnings.push(fiber);
      }

      if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        pendingComponentWillUpdateWarnings.push(fiber);
      }

      if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
        pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
      }
    };

    ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
      // We do an initial pass to gather component names
      var componentWillMountUniqueNames = new Set();

      if (pendingComponentWillMountWarnings.length > 0) {
        pendingComponentWillMountWarnings.forEach(function (fiber) {
          componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingComponentWillMountWarnings = [];
      }

      var UNSAFE_componentWillMountUniqueNames = new Set();

      if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
        pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
          UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingUNSAFE_ComponentWillMountWarnings = [];
      }

      var componentWillReceivePropsUniqueNames = new Set();

      if (pendingComponentWillReceivePropsWarnings.length > 0) {
        pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
          componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingComponentWillReceivePropsWarnings = [];
      }

      var UNSAFE_componentWillReceivePropsUniqueNames = new Set();

      if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
        pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
          UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
      }

      var componentWillUpdateUniqueNames = new Set();

      if (pendingComponentWillUpdateWarnings.length > 0) {
        pendingComponentWillUpdateWarnings.forEach(function (fiber) {
          componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingComponentWillUpdateWarnings = [];
      }

      var UNSAFE_componentWillUpdateUniqueNames = new Set();

      if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
        pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
          UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        });
        pendingUNSAFE_ComponentWillUpdateWarnings = [];
      } // Finally, we flush all the warnings
      // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'


      if (UNSAFE_componentWillMountUniqueNames.size > 0) {
        var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);

        error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
      }

      if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
        var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);

        error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
      }

      if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
        var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);

        error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
      }

      if (componentWillMountUniqueNames.size > 0) {
        var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);

        warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
      }

      if (componentWillReceivePropsUniqueNames.size > 0) {
        var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

        warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
      }

      if (componentWillUpdateUniqueNames.size > 0) {
        var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);

        warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
      }
    };

    var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.

    var didWarnAboutLegacyContext = new Set();

    ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
      var strictRoot = findStrictRoot(fiber);

      if (strictRoot === null) {
        error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');

        return;
      } // Dedup strategy: Warn once per component.


      if (didWarnAboutLegacyContext.has(fiber.type)) {
        return;
      }

      var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);

      if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
        if (warningsForRoot === undefined) {
          warningsForRoot = [];
          pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
        }

        warningsForRoot.push(fiber);
      }
    };

    ReactStrictModeWarnings.flushLegacyContextWarning = function () {
      pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
        if (fiberArray.length === 0) {
          return;
        }

        var firstFiber = fiberArray[0];
        var uniqueNames = new Set();
        fiberArray.forEach(function (fiber) {
          uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
          didWarnAboutLegacyContext.add(fiber.type);
        });
        var sortedNames = setToSortedString(uniqueNames);

        try {
          setCurrentFiber(firstFiber);

          error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames);
        } finally {
          resetCurrentFiber();
        }
      });
    };

    ReactStrictModeWarnings.discardPendingWarnings = function () {
      pendingComponentWillMountWarnings = [];
      pendingUNSAFE_ComponentWillMountWarnings = [];
      pendingComponentWillReceivePropsWarnings = [];
      pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
      pendingComponentWillUpdateWarnings = [];
      pendingUNSAFE_ComponentWillUpdateWarnings = [];
      pendingLegacyContextWarning = new Map();
    };
  }

  var didWarnAboutMaps;
  var didWarnAboutGenerators;
  var didWarnAboutStringRefs;
  var ownerHasKeyUseWarning;
  var ownerHasFunctionTypeWarning;

  var warnForMissingKey = function (child, returnFiber) {};

  {
    didWarnAboutMaps = false;
    didWarnAboutGenerators = false;
    didWarnAboutStringRefs = {};
    /**
     * Warn if there's no key explicitly set on dynamic arrays of children or
     * object keys are not valid. This allows us to keep track of children between
     * updates.
     */

    ownerHasKeyUseWarning = {};
    ownerHasFunctionTypeWarning = {};

    warnForMissingKey = function (child, returnFiber) {
      if (child === null || typeof child !== 'object') {
        return;
      }

      if (!child._store || child._store.validated || child.key != null) {
        return;
      }

      if (typeof child._store !== 'object') {
        throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      }

      child._store.validated = true;
      var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

      if (ownerHasKeyUseWarning[componentName]) {
        return;
      }

      ownerHasKeyUseWarning[componentName] = true;

      error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
    };
  }

  function isReactClass(type) {
    return type.prototype && type.prototype.isReactComponent;
  }

  function coerceRef(returnFiber, current, element) {
    var mixedRef = element.ref;

    if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
      {
        // TODO: Clean this up once we turn on the string ref warning for
        // everyone, because the strict mode case will no longer be relevant
        if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
        // because these cannot be automatically converted to an arrow function
        // using a codemod. Therefore, we don't have to warn about string refs again.
        !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs"
        !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs"
        !(typeof element.type === 'function' && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set"
        element._owner) {
          var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

          if (!didWarnAboutStringRefs[componentName]) {
            {
              error('Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef);
            }

            didWarnAboutStringRefs[componentName] = true;
          }
        }
      }

      if (element._owner) {
        var owner = element._owner;
        var inst;

        if (owner) {
          var ownerFiber = owner;

          if (ownerFiber.tag !== ClassComponent) {
            throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref');
          }

          inst = ownerFiber.stateNode;
        }

        if (!inst) {
          throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.');
        } // Assigning this to a const so Flow knows it won't change in the closure


        var resolvedInst = inst;

        {
          checkPropStringCoercion(mixedRef, 'ref');
        }

        var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref

        if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
          return current.ref;
        }

        var ref = function (value) {
          var refs = resolvedInst.refs;

          if (value === null) {
            delete refs[stringRef];
          } else {
            refs[stringRef] = value;
          }
        };

        ref._stringRef = stringRef;
        return ref;
      } else {
        if (typeof mixedRef !== 'string') {
          throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
        }

        if (!element._owner) {
          throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.');
        }
      }
    }

    return mixedRef;
  }

  function throwOnInvalidObjectType(returnFiber, newChild) {
    var childString = Object.prototype.toString.call(newChild);
    throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
  }

  function warnOnFunctionType(returnFiber) {
    {
      var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

      if (ownerHasFunctionTypeWarning[componentName]) {
        return;
      }

      ownerHasFunctionTypeWarning[componentName] = true;

      error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
    }
  }

  function resolveLazy(lazyType) {
    var payload = lazyType._payload;
    var init = lazyType._init;
    return init(payload);
  } // This wrapper function exists because I expect to clone the code in each path
  // to be able to optimize each path individually by branching early. This needs
  // a compiler or we can do it manually. Helpers that don't need this branching
  // live outside of this function.


  function ChildReconciler(shouldTrackSideEffects) {
    function deleteChild(returnFiber, childToDelete) {
      if (!shouldTrackSideEffects) {
        // Noop.
        return;
      }

      var deletions = returnFiber.deletions;

      if (deletions === null) {
        returnFiber.deletions = [childToDelete];
        returnFiber.flags |= ChildDeletion;
      } else {
        deletions.push(childToDelete);
      }
    }

    function deleteRemainingChildren(returnFiber, currentFirstChild) {
      if (!shouldTrackSideEffects) {
        // Noop.
        return null;
      } // TODO: For the shouldClone case, this could be micro-optimized a bit by
      // assuming that after the first child we've already added everything.


      var childToDelete = currentFirstChild;

      while (childToDelete !== null) {
        deleteChild(returnFiber, childToDelete);
        childToDelete = childToDelete.sibling;
      }

      return null;
    }

    function mapRemainingChildren(returnFiber, currentFirstChild) {
      // Add the remaining children to a temporary map so that we can find them by
      // keys quickly. Implicit (null) keys get added to this set with their index
      // instead.
      var existingChildren = new Map();
      var existingChild = currentFirstChild;

      while (existingChild !== null) {
        if (existingChild.key !== null) {
          existingChildren.set(existingChild.key, existingChild);
        } else {
          existingChildren.set(existingChild.index, existingChild);
        }

        existingChild = existingChild.sibling;
      }

      return existingChildren;
    }

    function useFiber(fiber, pendingProps) {
      // We currently set sibling to null and index to 0 here because it is easy
      // to forget to do before returning it. E.g. for the single child case.
      var clone = createWorkInProgress(fiber, pendingProps);
      clone.index = 0;
      clone.sibling = null;
      return clone;
    }

    function placeChild(newFiber, lastPlacedIndex, newIndex) {
      newFiber.index = newIndex;

      if (!shouldTrackSideEffects) {
        // During hydration, the useId algorithm needs to know which fibers are
        // part of a list of children (arrays, iterators).
        newFiber.flags |= Forked;
        return lastPlacedIndex;
      }

      var current = newFiber.alternate;

      if (current !== null) {
        var oldIndex = current.index;

        if (oldIndex < lastPlacedIndex) {
          // This is a move.
          newFiber.flags |= Placement;
          return lastPlacedIndex;
        } else {
          // This item can stay in place.
          return oldIndex;
        }
      } else {
        // This is an insertion.
        newFiber.flags |= Placement;
        return lastPlacedIndex;
      }
    }

    function placeSingleChild(newFiber) {
      // This is simpler for the single child case. We only need to do a
      // placement for inserting new children.
      if (shouldTrackSideEffects && newFiber.alternate === null) {
        newFiber.flags |= Placement;
      }

      return newFiber;
    }

    function updateTextNode(returnFiber, current, textContent, lanes) {
      if (current === null || current.tag !== HostText) {
        // Insert
        var created = createFiberFromText(textContent, returnFiber.mode, lanes);
        created.return = returnFiber;
        return created;
      } else {
        // Update
        var existing = useFiber(current, textContent);
        existing.return = returnFiber;
        return existing;
      }
    }

    function updateElement(returnFiber, current, element, lanes) {
      var elementType = element.type;

      if (elementType === REACT_FRAGMENT_TYPE) {
        return updateFragment(returnFiber, current, element.props.children, lanes, element.key);
      }

      if (current !== null) {
        if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
         isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type.
        // We need to do this after the Hot Reloading check above,
        // because hot reloading has different semantics than prod because
        // it doesn't resuspend. So we can't let the call below suspend.
        typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) {
          // Move based on index
          var existing = useFiber(current, element.props);
          existing.ref = coerceRef(returnFiber, current, element);
          existing.return = returnFiber;

          {
            existing._debugSource = element._source;
            existing._debugOwner = element._owner;
          }

          return existing;
        }
      } // Insert


      var created = createFiberFromElement(element, returnFiber.mode, lanes);
      created.ref = coerceRef(returnFiber, current, element);
      created.return = returnFiber;
      return created;
    }

    function updatePortal(returnFiber, current, portal, lanes) {
      if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
        // Insert
        var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
        created.return = returnFiber;
        return created;
      } else {
        // Update
        var existing = useFiber(current, portal.children || []);
        existing.return = returnFiber;
        return existing;
      }
    }

    function updateFragment(returnFiber, current, fragment, lanes, key) {
      if (current === null || current.tag !== Fragment) {
        // Insert
        var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
        created.return = returnFiber;
        return created;
      } else {
        // Update
        var existing = useFiber(current, fragment);
        existing.return = returnFiber;
        return existing;
      }
    }

    function createChild(returnFiber, newChild, lanes) {
      if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
        // Text nodes don't have keys. If the previous node is implicitly keyed
        // we can continue to replace it without aborting even if it is not a text
        // node.
        var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
        created.return = returnFiber;
        return created;
      }

      if (typeof newChild === 'object' && newChild !== null) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            {
              var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);

              _created.ref = coerceRef(returnFiber, null, newChild);
              _created.return = returnFiber;
              return _created;
            }

          case REACT_PORTAL_TYPE:
            {
              var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);

              _created2.return = returnFiber;
              return _created2;
            }

          case REACT_LAZY_TYPE:
            {
              var payload = newChild._payload;
              var init = newChild._init;
              return createChild(returnFiber, init(payload), lanes);
            }
        }

        if (isArray(newChild) || getIteratorFn(newChild)) {
          var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);

          _created3.return = returnFiber;
          return _created3;
        }

        throwOnInvalidObjectType(returnFiber, newChild);
      }

      {
        if (typeof newChild === 'function') {
          warnOnFunctionType(returnFiber);
        }
      }

      return null;
    }

    function updateSlot(returnFiber, oldFiber, newChild, lanes) {
      // Update the fiber if the keys match, otherwise return null.
      var key = oldFiber !== null ? oldFiber.key : null;

      if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
        // Text nodes don't have keys. If the previous node is implicitly keyed
        // we can continue to replace it without aborting even if it is not a text
        // node.
        if (key !== null) {
          return null;
        }

        return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
      }

      if (typeof newChild === 'object' && newChild !== null) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            {
              if (newChild.key === key) {
                return updateElement(returnFiber, oldFiber, newChild, lanes);
              } else {
                return null;
              }
            }

          case REACT_PORTAL_TYPE:
            {
              if (newChild.key === key) {
                return updatePortal(returnFiber, oldFiber, newChild, lanes);
              } else {
                return null;
              }
            }

          case REACT_LAZY_TYPE:
            {
              var payload = newChild._payload;
              var init = newChild._init;
              return updateSlot(returnFiber, oldFiber, init(payload), lanes);
            }
        }

        if (isArray(newChild) || getIteratorFn(newChild)) {
          if (key !== null) {
            return null;
          }

          return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
        }

        throwOnInvalidObjectType(returnFiber, newChild);
      }

      {
        if (typeof newChild === 'function') {
          warnOnFunctionType(returnFiber);
        }
      }

      return null;
    }

    function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
      if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
        // Text nodes don't have keys, so we neither have to check the old nor
        // new node for the key. If both are text nodes, they match.
        var matchedFiber = existingChildren.get(newIdx) || null;
        return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
      }

      if (typeof newChild === 'object' && newChild !== null) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            {
              var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

              return updateElement(returnFiber, _matchedFiber, newChild, lanes);
            }

          case REACT_PORTAL_TYPE:
            {
              var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

              return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
            }

          case REACT_LAZY_TYPE:
            var payload = newChild._payload;
            var init = newChild._init;
            return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes);
        }

        if (isArray(newChild) || getIteratorFn(newChild)) {
          var _matchedFiber3 = existingChildren.get(newIdx) || null;

          return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
        }

        throwOnInvalidObjectType(returnFiber, newChild);
      }

      {
        if (typeof newChild === 'function') {
          warnOnFunctionType(returnFiber);
        }
      }

      return null;
    }
    /**
     * Warns if there is a duplicate or missing key
     */


    function warnOnInvalidKey(child, knownKeys, returnFiber) {
      {
        if (typeof child !== 'object' || child === null) {
          return knownKeys;
        }

        switch (child.$$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            warnForMissingKey(child, returnFiber);
            var key = child.key;

            if (typeof key !== 'string') {
              break;
            }

            if (knownKeys === null) {
              knownKeys = new Set();
              knownKeys.add(key);
              break;
            }

            if (!knownKeys.has(key)) {
              knownKeys.add(key);
              break;
            }

            error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted â€” the behavior is unsupported and ' + 'could change in a future version.', key);

            break;

          case REACT_LAZY_TYPE:
            var payload = child._payload;
            var init = child._init;
            warnOnInvalidKey(init(payload), knownKeys, returnFiber);
            break;
        }
      }

      return knownKeys;
    }

    function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
      // This algorithm can't optimize by searching from both ends since we
      // don't have backpointers on fibers. I'm trying to see how far we can get
      // with that model. If it ends up not being worth the tradeoffs, we can
      // add it later.
      // Even with a two ended optimization, we'd want to optimize for the case
      // where there are few changes and brute force the comparison instead of
      // going for the Map. It'd like to explore hitting that path first in
      // forward-only mode and only go for the Map once we notice that we need
      // lots of look ahead. This doesn't handle reversal as well as two ended
      // search but that's unusual. Besides, for the two ended optimization to
      // work on Iterables, we'd need to copy the whole set.
      // In this first iteration, we'll just live with hitting the bad case
      // (adding everything to a Map) in for every insert/move.
      // If you change this code, also update reconcileChildrenIterator() which
      // uses the same algorithm.
      {
        // First, validate keys.
        var knownKeys = null;

        for (var i = 0; i < newChildren.length; i++) {
          var child = newChildren[i];
          knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
        }
      }

      var resultingFirstChild = null;
      var previousNewFiber = null;
      var oldFiber = currentFirstChild;
      var lastPlacedIndex = 0;
      var newIdx = 0;
      var nextOldFiber = null;

      for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
        if (oldFiber.index > newIdx) {
          nextOldFiber = oldFiber;
          oldFiber = null;
        } else {
          nextOldFiber = oldFiber.sibling;
        }

        var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);

        if (newFiber === null) {
          // TODO: This breaks on empty slots like null children. That's
          // unfortunate because it triggers the slow path all the time. We need
          // a better way to communicate whether this was a miss or null,
          // boolean, undefined, etc.
          if (oldFiber === null) {
            oldFiber = nextOldFiber;
          }

          break;
        }

        if (shouldTrackSideEffects) {
          if (oldFiber && newFiber.alternate === null) {
            // We matched the slot, but we didn't reuse the existing fiber, so we
            // need to delete the existing child.
            deleteChild(returnFiber, oldFiber);
          }
        }

        lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = newFiber;
        } else {
          // TODO: Defer siblings if we're not at the right index for this slot.
          // I.e. if we had null values before, then we want to defer this
          // for each null value. However, we also don't want to call updateSlot
          // with the previous one.
          previousNewFiber.sibling = newFiber;
        }

        previousNewFiber = newFiber;
        oldFiber = nextOldFiber;
      }

      if (newIdx === newChildren.length) {
        // We've reached the end of the new children. We can delete the rest.
        deleteRemainingChildren(returnFiber, oldFiber);

        if (getIsHydrating()) {
          var numberOfForks = newIdx;
          pushTreeFork(returnFiber, numberOfForks);
        }

        return resultingFirstChild;
      }

      if (oldFiber === null) {
        // If we don't have any more existing children we can choose a fast path
        // since the rest will all be insertions.
        for (; newIdx < newChildren.length; newIdx++) {
          var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);

          if (_newFiber === null) {
            continue;
          }

          lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            // TODO: Move out of the loop. This only happens for the first run.
            resultingFirstChild = _newFiber;
          } else {
            previousNewFiber.sibling = _newFiber;
          }

          previousNewFiber = _newFiber;
        }

        if (getIsHydrating()) {
          var _numberOfForks = newIdx;
          pushTreeFork(returnFiber, _numberOfForks);
        }

        return resultingFirstChild;
      } // Add all children to a key map for quick lookups.


      var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

      for (; newIdx < newChildren.length; newIdx++) {
        var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);

        if (_newFiber2 !== null) {
          if (shouldTrackSideEffects) {
            if (_newFiber2.alternate !== null) {
              // The new fiber is a work in progress, but if there exists a
              // current, that means that we reused the fiber. We need to delete
              // it from the child list so that we don't add it to the deletion
              // list.
              existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
            }
          }

          lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            resultingFirstChild = _newFiber2;
          } else {
            previousNewFiber.sibling = _newFiber2;
          }

          previousNewFiber = _newFiber2;
        }
      }

      if (shouldTrackSideEffects) {
        // Any existing children that weren't consumed above were deleted. We need
        // to add them to the deletion list.
        existingChildren.forEach(function (child) {
          return deleteChild(returnFiber, child);
        });
      }

      if (getIsHydrating()) {
        var _numberOfForks2 = newIdx;
        pushTreeFork(returnFiber, _numberOfForks2);
      }

      return resultingFirstChild;
    }

    function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
      // This is the same implementation as reconcileChildrenArray(),
      // but using the iterator instead.
      var iteratorFn = getIteratorFn(newChildrenIterable);

      if (typeof iteratorFn !== 'function') {
        throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.');
      }

      {
        // We don't support rendering Generators because it's a mutation.
        // See https://github.com/facebook/react/issues/12995
        if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
        newChildrenIterable[Symbol.toStringTag] === 'Generator') {
          if (!didWarnAboutGenerators) {
            error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
          }

          didWarnAboutGenerators = true;
        } // Warn about using Maps as children


        if (newChildrenIterable.entries === iteratorFn) {
          if (!didWarnAboutMaps) {
            error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
          }

          didWarnAboutMaps = true;
        } // First, validate keys.
        // We'll get a different iterator later for the main pass.


        var _newChildren = iteratorFn.call(newChildrenIterable);

        if (_newChildren) {
          var knownKeys = null;

          var _step = _newChildren.next();

          for (; !_step.done; _step = _newChildren.next()) {
            var child = _step.value;
            knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
          }
        }
      }

      var newChildren = iteratorFn.call(newChildrenIterable);

      if (newChildren == null) {
        throw new Error('An iterable object provided no iterator.');
      }

      var resultingFirstChild = null;
      var previousNewFiber = null;
      var oldFiber = currentFirstChild;
      var lastPlacedIndex = 0;
      var newIdx = 0;
      var nextOldFiber = null;
      var step = newChildren.next();

      for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
        if (oldFiber.index > newIdx) {
          nextOldFiber = oldFiber;
          oldFiber = null;
        } else {
          nextOldFiber = oldFiber.sibling;
        }

        var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);

        if (newFiber === null) {
          // TODO: This breaks on empty slots like null children. That's
          // unfortunate because it triggers the slow path all the time. We need
          // a better way to communicate whether this was a miss or null,
          // boolean, undefined, etc.
          if (oldFiber === null) {
            oldFiber = nextOldFiber;
          }

          break;
        }

        if (shouldTrackSideEffects) {
          if (oldFiber && newFiber.alternate === null) {
            // We matched the slot, but we didn't reuse the existing fiber, so we
            // need to delete the existing child.
            deleteChild(returnFiber, oldFiber);
          }
        }

        lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = newFiber;
        } else {
          // TODO: Defer siblings if we're not at the right index for this slot.
          // I.e. if we had null values before, then we want to defer this
          // for each null value. However, we also don't want to call updateSlot
          // with the previous one.
          previousNewFiber.sibling = newFiber;
        }

        previousNewFiber = newFiber;
        oldFiber = nextOldFiber;
      }

      if (step.done) {
        // We've reached the end of the new children. We can delete the rest.
        deleteRemainingChildren(returnFiber, oldFiber);

        if (getIsHydrating()) {
          var numberOfForks = newIdx;
          pushTreeFork(returnFiber, numberOfForks);
        }

        return resultingFirstChild;
      }

      if (oldFiber === null) {
        // If we don't have any more existing children we can choose a fast path
        // since the rest will all be insertions.
        for (; !step.done; newIdx++, step = newChildren.next()) {
          var _newFiber3 = createChild(returnFiber, step.value, lanes);

          if (_newFiber3 === null) {
            continue;
          }

          lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            // TODO: Move out of the loop. This only happens for the first run.
            resultingFirstChild = _newFiber3;
          } else {
            previousNewFiber.sibling = _newFiber3;
          }

          previousNewFiber = _newFiber3;
        }

        if (getIsHydrating()) {
          var _numberOfForks3 = newIdx;
          pushTreeFork(returnFiber, _numberOfForks3);
        }

        return resultingFirstChild;
      } // Add all children to a key map for quick lookups.


      var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

      for (; !step.done; newIdx++, step = newChildren.next()) {
        var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);

        if (_newFiber4 !== null) {
          if (shouldTrackSideEffects) {
            if (_newFiber4.alternate !== null) {
              // The new fiber is a work in progress, but if there exists a
              // current, that means that we reused the fiber. We need to delete
              // it from the child list so that we don't add it to the deletion
              // list.
              existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
            }
          }

          lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            resultingFirstChild = _newFiber4;
          } else {
            previousNewFiber.sibling = _newFiber4;
          }

          previousNewFiber = _newFiber4;
        }
      }

      if (shouldTrackSideEffects) {
        // Any existing children that weren't consumed above were deleted. We need
        // to add them to the deletion list.
        existingChildren.forEach(function (child) {
          return deleteChild(returnFiber, child);
        });
      }

      if (getIsHydrating()) {
        var _numberOfForks4 = newIdx;
        pushTreeFork(returnFiber, _numberOfForks4);
      }

      return resultingFirstChild;
    }

    function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
      // There's no need to check for keys on text nodes since we don't have a
      // way to define them.
      if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
        // We already have an existing node so let's just update it and delete
        // the rest.
        deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
        var existing = useFiber(currentFirstChild, textContent);
        existing.return = returnFiber;
        return existing;
      } // The existing first child is not a text node so we need to create one
      // and delete the existing ones.


      deleteRemainingChildren(returnFiber, currentFirstChild);
      var created = createFiberFromText(textContent, returnFiber.mode, lanes);
      created.return = returnFiber;
      return created;
    }

    function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
      var key = element.key;
      var child = currentFirstChild;

      while (child !== null) {
        // TODO: If key === null and child.key === null, then this only applies to
        // the first item in the list.
        if (child.key === key) {
          var elementType = element.type;

          if (elementType === REACT_FRAGMENT_TYPE) {
            if (child.tag === Fragment) {
              deleteRemainingChildren(returnFiber, child.sibling);
              var existing = useFiber(child, element.props.children);
              existing.return = returnFiber;

              {
                existing._debugSource = element._source;
                existing._debugOwner = element._owner;
              }

              return existing;
            }
          } else {
            if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
             isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type.
            // We need to do this after the Hot Reloading check above,
            // because hot reloading has different semantics than prod because
            // it doesn't resuspend. So we can't let the call below suspend.
            typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
              deleteRemainingChildren(returnFiber, child.sibling);

              var _existing = useFiber(child, element.props);

              _existing.ref = coerceRef(returnFiber, child, element);
              _existing.return = returnFiber;

              {
                _existing._debugSource = element._source;
                _existing._debugOwner = element._owner;
              }

              return _existing;
            }
          } // Didn't match.


          deleteRemainingChildren(returnFiber, child);
          break;
        } else {
          deleteChild(returnFiber, child);
        }

        child = child.sibling;
      }

      if (element.type === REACT_FRAGMENT_TYPE) {
        var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
        created.return = returnFiber;
        return created;
      } else {
        var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);

        _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
        _created4.return = returnFiber;
        return _created4;
      }
    }

    function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
      var key = portal.key;
      var child = currentFirstChild;

      while (child !== null) {
        // TODO: If key === null and child.key === null, then this only applies to
        // the first item in the list.
        if (child.key === key) {
          if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
            deleteRemainingChildren(returnFiber, child.sibling);
            var existing = useFiber(child, portal.children || []);
            existing.return = returnFiber;
            return existing;
          } else {
            deleteRemainingChildren(returnFiber, child);
            break;
          }
        } else {
          deleteChild(returnFiber, child);
        }

        child = child.sibling;
      }

      var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
      created.return = returnFiber;
      return created;
    } // This API will tag the children with the side-effect of the reconciliation
    // itself. They will be added to the side-effect list as we pass through the
    // children and the parent.


    function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
      // This function is not recursive.
      // If the top level item is an array, we treat it as a set of children,
      // not as a fragment. Nested arrays on the other hand will be treated as
      // fragment nodes. Recursion happens at the normal flow.
      // Handle top level unkeyed fragments as if they were arrays.
      // This leads to an ambiguity between <>{[...]}</> and <>...</>.
      // We treat the ambiguous cases above the same.
      var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;

      if (isUnkeyedTopLevelFragment) {
        newChild = newChild.props.children;
      } // Handle object types


      if (typeof newChild === 'object' && newChild !== null) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));

          case REACT_PORTAL_TYPE:
            return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));

          case REACT_LAZY_TYPE:
            var payload = newChild._payload;
            var init = newChild._init; // TODO: This function is supposed to be non-recursive.

            return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes);
        }

        if (isArray(newChild)) {
          return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
        }

        if (getIteratorFn(newChild)) {
          return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
        }

        throwOnInvalidObjectType(returnFiber, newChild);
      }

      if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
        return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
      }

      {
        if (typeof newChild === 'function') {
          warnOnFunctionType(returnFiber);
        }
      } // Remaining cases are all treated as empty.


      return deleteRemainingChildren(returnFiber, currentFirstChild);
    }

    return reconcileChildFibers;
  }

  var reconcileChildFibers = ChildReconciler(true);
  var mountChildFibers = ChildReconciler(false);
  function cloneChildFibers(current, workInProgress) {
    if (current !== null && workInProgress.child !== current.child) {
      throw new Error('Resuming work not yet implemented.');
    }

    if (workInProgress.child === null) {
      return;
    }

    var currentChild = workInProgress.child;
    var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
    workInProgress.child = newChild;
    newChild.return = workInProgress;

    while (currentChild.sibling !== null) {
      currentChild = currentChild.sibling;
      newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
      newChild.return = workInProgress;
    }

    newChild.sibling = null;
  } // Reset a workInProgress child set to prepare it for a second pass.

  function resetChildFibers(workInProgress, lanes) {
    var child = workInProgress.child;

    while (child !== null) {
      resetWorkInProgress(child, lanes);
      child = child.sibling;
    }
  }

  var valueCursor = createCursor(null);
  var rendererSigil;

  {
    // Use this to detect multiple renderers using the same context
    rendererSigil = {};
  }

  var currentlyRenderingFiber = null;
  var lastContextDependency = null;
  var lastFullyObservedContext = null;
  var isDisallowedContextReadInDEV = false;
  function resetContextDependencies() {
    // This is called right before React yields execution, to ensure `readContext`
    // cannot be called outside the render phase.
    currentlyRenderingFiber = null;
    lastContextDependency = null;
    lastFullyObservedContext = null;

    {
      isDisallowedContextReadInDEV = false;
    }
  }
  function enterDisallowedContextReadInDEV() {
    {
      isDisallowedContextReadInDEV = true;
    }
  }
  function exitDisallowedContextReadInDEV() {
    {
      isDisallowedContextReadInDEV = false;
    }
  }
  function pushProvider(providerFiber, context, nextValue) {
    {
      push(valueCursor, context._currentValue, providerFiber);
      context._currentValue = nextValue;

      {
        if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
          error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
        }

        context._currentRenderer = rendererSigil;
      }
    }
  }
  function popProvider(context, providerFiber) {
    var currentValue = valueCursor.current;
    pop(valueCursor, providerFiber);

    {
      {
        context._currentValue = currentValue;
      }
    }
  }
  function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {
    // Update the child lanes of all the ancestors, including the alternates.
    var node = parent;

    while (node !== null) {
      var alternate = node.alternate;

      if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
        node.childLanes = mergeLanes(node.childLanes, renderLanes);

        if (alternate !== null) {
          alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
        }
      } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
        alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
      }

      if (node === propagationRoot) {
        break;
      }

      node = node.return;
    }

    {
      if (node !== propagationRoot) {
        error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.');
      }
    }
  }
  function propagateContextChange(workInProgress, context, renderLanes) {
    {
      propagateContextChange_eager(workInProgress, context, renderLanes);
    }
  }

  function propagateContextChange_eager(workInProgress, context, renderLanes) {

    var fiber = workInProgress.child;

    if (fiber !== null) {
      // Set the return pointer of the child to the work-in-progress fiber.
      fiber.return = workInProgress;
    }

    while (fiber !== null) {
      var nextFiber = void 0; // Visit this fiber.

      var list = fiber.dependencies;

      if (list !== null) {
        nextFiber = fiber.child;
        var dependency = list.firstContext;

        while (dependency !== null) {
          // Check if the context matches.
          if (dependency.context === context) {
            // Match! Schedule an update on this fiber.
            if (fiber.tag === ClassComponent) {
              // Schedule a force update on the work-in-progress.
              var lane = pickArbitraryLane(renderLanes);
              var update = createUpdate(NoTimestamp, lane);
              update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
              // update to the current fiber, too, which means it will persist even if
              // this render is thrown away. Since it's a race condition, not sure it's
              // worth fixing.
              // Inlined `enqueueUpdate` to remove interleaved update check

              var updateQueue = fiber.updateQueue;

              if (updateQueue === null) ; else {
                var sharedQueue = updateQueue.shared;
                var pending = sharedQueue.pending;

                if (pending === null) {
                  // This is the first update. Create a circular list.
                  update.next = update;
                } else {
                  update.next = pending.next;
                  pending.next = update;
                }

                sharedQueue.pending = update;
              }
            }

            fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
            var alternate = fiber.alternate;

            if (alternate !== null) {
              alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
            }

            scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too.

            list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
            // dependency list.

            break;
          }

          dependency = dependency.next;
        }
      } else if (fiber.tag === ContextProvider) {
        // Don't scan deeper if this is a matching provider
        nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
      } else if (fiber.tag === DehydratedFragment) {
        // If a dehydrated suspense boundary is in this subtree, we don't know
        // if it will have any context consumers in it. The best we can do is
        // mark it as having updates.
        var parentSuspense = fiber.return;

        if (parentSuspense === null) {
          throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.');
        }

        parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
        var _alternate = parentSuspense.alternate;

        if (_alternate !== null) {
          _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes);
        } // This is intentionally passing this fiber as the parent
        // because we want to schedule this fiber as having work
        // on its children. We'll use the childLanes on
        // this fiber to indicate that a context has changed.


        scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress);
        nextFiber = fiber.sibling;
      } else {
        // Traverse down.
        nextFiber = fiber.child;
      }

      if (nextFiber !== null) {
        // Set the return pointer of the child to the work-in-progress fiber.
        nextFiber.return = fiber;
      } else {
        // No child. Traverse to next sibling.
        nextFiber = fiber;

        while (nextFiber !== null) {
          if (nextFiber === workInProgress) {
            // We're back to the root of this subtree. Exit.
            nextFiber = null;
            break;
          }

          var sibling = nextFiber.sibling;

          if (sibling !== null) {
            // Set the return pointer of the sibling to the work-in-progress fiber.
            sibling.return = nextFiber.return;
            nextFiber = sibling;
            break;
          } // No more siblings. Traverse up.


          nextFiber = nextFiber.return;
        }
      }

      fiber = nextFiber;
    }
  }
  function prepareToReadContext(workInProgress, renderLanes) {
    currentlyRenderingFiber = workInProgress;
    lastContextDependency = null;
    lastFullyObservedContext = null;
    var dependencies = workInProgress.dependencies;

    if (dependencies !== null) {
      {
        var firstContext = dependencies.firstContext;

        if (firstContext !== null) {
          if (includesSomeLane(dependencies.lanes, renderLanes)) {
            // Context list has a pending update. Mark that this fiber performed work.
            markWorkInProgressReceivedUpdate();
          } // Reset the work-in-progress list


          dependencies.firstContext = null;
        }
      }
    }
  }
  function readContext(context) {
    {
      // This warning would fire if you read context inside a Hook like useMemo.
      // Unlike the class check below, it's not enforced in production for perf.
      if (isDisallowedContextReadInDEV) {
        error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
      }
    }

    var value =  context._currentValue ;

    if (lastFullyObservedContext === context) ; else {
      var contextItem = {
        context: context,
        memoizedValue: value,
        next: null
      };

      if (lastContextDependency === null) {
        if (currentlyRenderingFiber === null) {
          throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
        } // This is the first dependency for this component. Create a new list.


        lastContextDependency = contextItem;
        currentlyRenderingFiber.dependencies = {
          lanes: NoLanes,
          firstContext: contextItem
        };
      } else {
        // Append a new context item.
        lastContextDependency = lastContextDependency.next = contextItem;
      }
    }

    return value;
  }

  // render. When this render exits, either because it finishes or because it is
  // interrupted, the interleaved updates will be transferred onto the main part
  // of the queue.

  var concurrentQueues = null;
  function pushConcurrentUpdateQueue(queue) {
    if (concurrentQueues === null) {
      concurrentQueues = [queue];
    } else {
      concurrentQueues.push(queue);
    }
  }
  function finishQueueingConcurrentUpdates() {
    // Transfer the interleaved updates onto the main queue. Each queue has a
    // `pending` field and an `interleaved` field. When they are not null, they
    // point to the last node in a circular linked list. We need to append the
    // interleaved list to the end of the pending list by joining them into a
    // single, circular list.
    if (concurrentQueues !== null) {
      for (var i = 0; i < concurrentQueues.length; i++) {
        var queue = concurrentQueues[i];
        var lastInterleavedUpdate = queue.interleaved;

        if (lastInterleavedUpdate !== null) {
          queue.interleaved = null;
          var firstInterleavedUpdate = lastInterleavedUpdate.next;
          var lastPendingUpdate = queue.pending;

          if (lastPendingUpdate !== null) {
            var firstPendingUpdate = lastPendingUpdate.next;
            lastPendingUpdate.next = firstInterleavedUpdate;
            lastInterleavedUpdate.next = firstPendingUpdate;
          }

          queue.pending = lastInterleavedUpdate;
        }
      }

      concurrentQueues = null;
    }
  }
  function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
    var interleaved = queue.interleaved;

    if (interleaved === null) {
      // This is the first update. Create a circular list.
      update.next = update; // At the end of the current render, this queue's interleaved updates will
      // be transferred to the pending queue.

      pushConcurrentUpdateQueue(queue);
    } else {
      update.next = interleaved.next;
      interleaved.next = update;
    }

    queue.interleaved = update;
    return markUpdateLaneFromFiberToRoot(fiber, lane);
  }
  function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) {
    var interleaved = queue.interleaved;

    if (interleaved === null) {
      // This is the first update. Create a circular list.
      update.next = update; // At the end of the current render, this queue's interleaved updates will
      // be transferred to the pending queue.

      pushConcurrentUpdateQueue(queue);
    } else {
      update.next = interleaved.next;
      interleaved.next = update;
    }

    queue.interleaved = update;
  }
  function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
    var interleaved = queue.interleaved;

    if (interleaved === null) {
      // This is the first update. Create a circular list.
      update.next = update; // At the end of the current render, this queue's interleaved updates will
      // be transferred to the pending queue.

      pushConcurrentUpdateQueue(queue);
    } else {
      update.next = interleaved.next;
      interleaved.next = update;
    }

    queue.interleaved = update;
    return markUpdateLaneFromFiberToRoot(fiber, lane);
  }
  function enqueueConcurrentRenderForLane(fiber, lane) {
    return markUpdateLaneFromFiberToRoot(fiber, lane);
  } // Calling this function outside this module should only be done for backwards
  // compatibility and should always be accompanied by a warning.

  var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;

  function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
    // Update the source fiber's lanes
    sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
    var alternate = sourceFiber.alternate;

    if (alternate !== null) {
      alternate.lanes = mergeLanes(alternate.lanes, lane);
    }

    {
      if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
        warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
      }
    } // Walk the parent path to the root and update the child lanes.


    var node = sourceFiber;
    var parent = sourceFiber.return;

    while (parent !== null) {
      parent.childLanes = mergeLanes(parent.childLanes, lane);
      alternate = parent.alternate;

      if (alternate !== null) {
        alternate.childLanes = mergeLanes(alternate.childLanes, lane);
      } else {
        {
          if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
            warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
          }
        }
      }

      node = parent;
      parent = parent.return;
    }

    if (node.tag === HostRoot) {
      var root = node.stateNode;
      return root;
    } else {
      return null;
    }
  }

  var UpdateState = 0;
  var ReplaceState = 1;
  var ForceUpdate = 2;
  var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
  // It should only be read right after calling `processUpdateQueue`, via
  // `checkHasForceUpdateAfterProcessing`.

  var hasForceUpdate = false;
  var didWarnUpdateInsideUpdate;
  var currentlyProcessingQueue;

  {
    didWarnUpdateInsideUpdate = false;
    currentlyProcessingQueue = null;
  }

  function initializeUpdateQueue(fiber) {
    var queue = {
      baseState: fiber.memoizedState,
      firstBaseUpdate: null,
      lastBaseUpdate: null,
      shared: {
        pending: null,
        interleaved: null,
        lanes: NoLanes
      },
      effects: null
    };
    fiber.updateQueue = queue;
  }
  function cloneUpdateQueue(current, workInProgress) {
    // Clone the update queue from current. Unless it's already a clone.
    var queue = workInProgress.updateQueue;
    var currentQueue = current.updateQueue;

    if (queue === currentQueue) {
      var clone = {
        baseState: currentQueue.baseState,
        firstBaseUpdate: currentQueue.firstBaseUpdate,
        lastBaseUpdate: currentQueue.lastBaseUpdate,
        shared: currentQueue.shared,
        effects: currentQueue.effects
      };
      workInProgress.updateQueue = clone;
    }
  }
  function createUpdate(eventTime, lane) {
    var update = {
      eventTime: eventTime,
      lane: lane,
      tag: UpdateState,
      payload: null,
      callback: null,
      next: null
    };
    return update;
  }
  function enqueueUpdate(fiber, update, lane) {
    var updateQueue = fiber.updateQueue;

    if (updateQueue === null) {
      // Only occurs if the fiber has been unmounted.
      return null;
    }

    var sharedQueue = updateQueue.shared;

    {
      if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
        error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');

        didWarnUpdateInsideUpdate = true;
      }
    }

    if (isUnsafeClassRenderPhaseUpdate()) {
      // This is an unsafe render phase update. Add directly to the update
      // queue so we can process it immediately during the current render.
      var pending = sharedQueue.pending;

      if (pending === null) {
        // This is the first update. Create a circular list.
        update.next = update;
      } else {
        update.next = pending.next;
        pending.next = update;
      }

      sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering
      // this fiber. This is for backwards compatibility in the case where you
      // update a different component during render phase than the one that is
      // currently renderings (a pattern that is accompanied by a warning).

      return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
    } else {
      return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
    }
  }
  function entangleTransitions(root, fiber, lane) {
    var updateQueue = fiber.updateQueue;

    if (updateQueue === null) {
      // Only occurs if the fiber has been unmounted.
      return;
    }

    var sharedQueue = updateQueue.shared;

    if (isTransitionLane(lane)) {
      var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must
      // have finished. We can remove them from the shared queue, which represents
      // a superset of the actually pending lanes. In some cases we may entangle
      // more than we need to, but that's OK. In fact it's worse if we *don't*
      // entangle when we should.

      queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.

      var newQueueLanes = mergeLanes(queueLanes, lane);
      sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
      // the lane finished since the last time we entangled it. So we need to
      // entangle it again, just to be sure.

      markRootEntangled(root, newQueueLanes);
    }
  }
  function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
    // Captured updates are updates that are thrown by a child during the render
    // phase. They should be discarded if the render is aborted. Therefore,
    // we should only put them on the work-in-progress queue, not the current one.
    var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.

    var current = workInProgress.alternate;

    if (current !== null) {
      var currentQueue = current.updateQueue;

      if (queue === currentQueue) {
        // The work-in-progress queue is the same as current. This happens when
        // we bail out on a parent fiber that then captures an error thrown by
        // a child. Since we want to append the update only to the work-in
        // -progress queue, we need to clone the updates. We usually clone during
        // processUpdateQueue, but that didn't happen in this case because we
        // skipped over the parent when we bailed out.
        var newFirst = null;
        var newLast = null;
        var firstBaseUpdate = queue.firstBaseUpdate;

        if (firstBaseUpdate !== null) {
          // Loop through the updates and clone them.
          var update = firstBaseUpdate;

          do {
            var clone = {
              eventTime: update.eventTime,
              lane: update.lane,
              tag: update.tag,
              payload: update.payload,
              callback: update.callback,
              next: null
            };

            if (newLast === null) {
              newFirst = newLast = clone;
            } else {
              newLast.next = clone;
              newLast = clone;
            }

            update = update.next;
          } while (update !== null); // Append the captured update the end of the cloned list.


          if (newLast === null) {
            newFirst = newLast = capturedUpdate;
          } else {
            newLast.next = capturedUpdate;
            newLast = capturedUpdate;
          }
        } else {
          // There are no base updates.
          newFirst = newLast = capturedUpdate;
        }

        queue = {
          baseState: currentQueue.baseState,
          firstBaseUpdate: newFirst,
          lastBaseUpdate: newLast,
          shared: currentQueue.shared,
          effects: currentQueue.effects
        };
        workInProgress.updateQueue = queue;
        return;
      }
    } // Append the update to the end of the list.


    var lastBaseUpdate = queue.lastBaseUpdate;

    if (lastBaseUpdate === null) {
      queue.firstBaseUpdate = capturedUpdate;
    } else {
      lastBaseUpdate.next = capturedUpdate;
    }

    queue.lastBaseUpdate = capturedUpdate;
  }

  function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
    switch (update.tag) {
      case ReplaceState:
        {
          var payload = update.payload;

          if (typeof payload === 'function') {
            // Updater function
            {
              enterDisallowedContextReadInDEV();
            }

            var nextState = payload.call(instance, prevState, nextProps);

            {
              if ( workInProgress.mode & StrictLegacyMode) {
                setIsStrictModeForDevtools(true);

                try {
                  payload.call(instance, prevState, nextProps);
                } finally {
                  setIsStrictModeForDevtools(false);
                }
              }

              exitDisallowedContextReadInDEV();
            }

            return nextState;
          } // State object


          return payload;
        }

      case CaptureUpdate:
        {
          workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
        }
      // Intentional fallthrough

      case UpdateState:
        {
          var _payload = update.payload;
          var partialState;

          if (typeof _payload === 'function') {
            // Updater function
            {
              enterDisallowedContextReadInDEV();
            }

            partialState = _payload.call(instance, prevState, nextProps);

            {
              if ( workInProgress.mode & StrictLegacyMode) {
                setIsStrictModeForDevtools(true);

                try {
                  _payload.call(instance, prevState, nextProps);
                } finally {
                  setIsStrictModeForDevtools(false);
                }
              }

              exitDisallowedContextReadInDEV();
            }
          } else {
            // Partial state object
            partialState = _payload;
          }

          if (partialState === null || partialState === undefined) {
            // Null and undefined are treated as no-ops.
            return prevState;
          } // Merge the partial state and the previous state.


          return assign({}, prevState, partialState);
        }

      case ForceUpdate:
        {
          hasForceUpdate = true;
          return prevState;
        }
    }

    return prevState;
  }

  function processUpdateQueue(workInProgress, props, instance, renderLanes) {
    // This is always non-null on a ClassComponent or HostRoot
    var queue = workInProgress.updateQueue;
    hasForceUpdate = false;

    {
      currentlyProcessingQueue = queue.shared;
    }

    var firstBaseUpdate = queue.firstBaseUpdate;
    var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.

    var pendingQueue = queue.shared.pending;

    if (pendingQueue !== null) {
      queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
      // and last so that it's non-circular.

      var lastPendingUpdate = pendingQueue;
      var firstPendingUpdate = lastPendingUpdate.next;
      lastPendingUpdate.next = null; // Append pending updates to base queue

      if (lastBaseUpdate === null) {
        firstBaseUpdate = firstPendingUpdate;
      } else {
        lastBaseUpdate.next = firstPendingUpdate;
      }

      lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
      // we need to transfer the updates to that queue, too. Because the base
      // queue is a singly-linked list with no cycles, we can append to both
      // lists and take advantage of structural sharing.
      // TODO: Pass `current` as argument

      var current = workInProgress.alternate;

      if (current !== null) {
        // This is always non-null on a ClassComponent or HostRoot
        var currentQueue = current.updateQueue;
        var currentLastBaseUpdate = currentQueue.lastBaseUpdate;

        if (currentLastBaseUpdate !== lastBaseUpdate) {
          if (currentLastBaseUpdate === null) {
            currentQueue.firstBaseUpdate = firstPendingUpdate;
          } else {
            currentLastBaseUpdate.next = firstPendingUpdate;
          }

          currentQueue.lastBaseUpdate = lastPendingUpdate;
        }
      }
    } // These values may change as we process the queue.


    if (firstBaseUpdate !== null) {
      // Iterate through the list of updates to compute the result.
      var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
      // from the original lanes.

      var newLanes = NoLanes;
      var newBaseState = null;
      var newFirstBaseUpdate = null;
      var newLastBaseUpdate = null;
      var update = firstBaseUpdate;

      do {
        var updateLane = update.lane;
        var updateEventTime = update.eventTime;

        if (!isSubsetOfLanes(renderLanes, updateLane)) {
          // Priority is insufficient. Skip this update. If this is the first
          // skipped update, the previous update/state is the new base
          // update/state.
          var clone = {
            eventTime: updateEventTime,
            lane: updateLane,
            tag: update.tag,
            payload: update.payload,
            callback: update.callback,
            next: null
          };

          if (newLastBaseUpdate === null) {
            newFirstBaseUpdate = newLastBaseUpdate = clone;
            newBaseState = newState;
          } else {
            newLastBaseUpdate = newLastBaseUpdate.next = clone;
          } // Update the remaining priority in the queue.


          newLanes = mergeLanes(newLanes, updateLane);
        } else {
          // This update does have sufficient priority.
          if (newLastBaseUpdate !== null) {
            var _clone = {
              eventTime: updateEventTime,
              // This update is going to be committed so we never want uncommit
              // it. Using NoLane works because 0 is a subset of all bitmasks, so
              // this will never be skipped by the check above.
              lane: NoLane,
              tag: update.tag,
              payload: update.payload,
              callback: update.callback,
              next: null
            };
            newLastBaseUpdate = newLastBaseUpdate.next = _clone;
          } // Process this update.


          newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
          var callback = update.callback;

          if (callback !== null && // If the update was already committed, we should not queue its
          // callback again.
          update.lane !== NoLane) {
            workInProgress.flags |= Callback;
            var effects = queue.effects;

            if (effects === null) {
              queue.effects = [update];
            } else {
              effects.push(update);
            }
          }
        }

        update = update.next;

        if (update === null) {
          pendingQueue = queue.shared.pending;

          if (pendingQueue === null) {
            break;
          } else {
            // An update was scheduled from inside a reducer. Add the new
            // pending updates to the end of the list and keep processing.
            var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
            // unravel them when transferring them to the base queue.

            var _firstPendingUpdate = _lastPendingUpdate.next;
            _lastPendingUpdate.next = null;
            update = _firstPendingUpdate;
            queue.lastBaseUpdate = _lastPendingUpdate;
            queue.shared.pending = null;
          }
        }
      } while (true);

      if (newLastBaseUpdate === null) {
        newBaseState = newState;
      }

      queue.baseState = newBaseState;
      queue.firstBaseUpdate = newFirstBaseUpdate;
      queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to
      // process them during this render, but we do need to track which lanes
      // are remaining.

      var lastInterleaved = queue.shared.interleaved;

      if (lastInterleaved !== null) {
        var interleaved = lastInterleaved;

        do {
          newLanes = mergeLanes(newLanes, interleaved.lane);
          interleaved = interleaved.next;
        } while (interleaved !== lastInterleaved);
      } else if (firstBaseUpdate === null) {
        // `queue.lanes` is used for entangling transitions. We can set it back to
        // zero once the queue is empty.
        queue.shared.lanes = NoLanes;
      } // Set the remaining expiration time to be whatever is remaining in the queue.
      // This should be fine because the only two other things that contribute to
      // expiration time are props and context. We're already in the middle of the
      // begin phase by the time we start processing the queue, so we've already
      // dealt with the props. Context in components that specify
      // shouldComponentUpdate is tricky; but we'll have to account for
      // that regardless.


      markSkippedUpdateLanes(newLanes);
      workInProgress.lanes = newLanes;
      workInProgress.memoizedState = newState;
    }

    {
      currentlyProcessingQueue = null;
    }
  }

  function callCallback(callback, context) {
    if (typeof callback !== 'function') {
      throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback));
    }

    callback.call(context);
  }

  function resetHasForceUpdateBeforeProcessing() {
    hasForceUpdate = false;
  }
  function checkHasForceUpdateAfterProcessing() {
    return hasForceUpdate;
  }
  function commitUpdateQueue(finishedWork, finishedQueue, instance) {
    // Commit the effects
    var effects = finishedQueue.effects;
    finishedQueue.effects = null;

    if (effects !== null) {
      for (var i = 0; i < effects.length; i++) {
        var effect = effects[i];
        var callback = effect.callback;

        if (callback !== null) {
          effect.callback = null;
          callCallback(callback, instance);
        }
      }
    }
  }

  var NO_CONTEXT = {};
  var contextStackCursor$1 = createCursor(NO_CONTEXT);
  var contextFiberStackCursor = createCursor(NO_CONTEXT);
  var rootInstanceStackCursor = createCursor(NO_CONTEXT);

  function requiredContext(c) {
    if (c === NO_CONTEXT) {
      throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.');
    }

    return c;
  }

  function getRootHostContainer() {
    var rootInstance = requiredContext(rootInstanceStackCursor.current);
    return rootInstance;
  }

  function pushHostContainer(fiber, nextRootInstance) {
    // Push current root instance onto the stack;
    // This allows us to reset root when portals are popped.
    push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
    // This enables us to pop only Fibers that provide unique contexts.

    push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
    // However, we can't just call getRootHostContext() and push it because
    // we'd have a different number of entries on the stack depending on
    // whether getRootHostContext() throws somewhere in renderer code or not.
    // So we push an empty value first. This lets us safely unwind on errors.

    push(contextStackCursor$1, NO_CONTEXT, fiber);
    var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.

    pop(contextStackCursor$1, fiber);
    push(contextStackCursor$1, nextRootContext, fiber);
  }

  function popHostContainer(fiber) {
    pop(contextStackCursor$1, fiber);
    pop(contextFiberStackCursor, fiber);
    pop(rootInstanceStackCursor, fiber);
  }

  function getHostContext() {
    var context = requiredContext(contextStackCursor$1.current);
    return context;
  }

  function pushHostContext(fiber) {
    var rootInstance = requiredContext(rootInstanceStackCursor.current);
    var context = requiredContext(contextStackCursor$1.current);
    var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.

    if (context === nextContext) {
      return;
    } // Track the context and the Fiber that provided it.
    // This enables us to pop only Fibers that provide unique contexts.


    push(contextFiberStackCursor, fiber, fiber);
    push(contextStackCursor$1, nextContext, fiber);
  }

  function popHostContext(fiber) {
    // Do not pop unless this Fiber provided the current context.
    // pushHostContext() only pushes Fibers that provide unique contexts.
    if (contextFiberStackCursor.current !== fiber) {
      return;
    }

    pop(contextStackCursor$1, fiber);
    pop(contextFiberStackCursor, fiber);
  }

  var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
  // inherited deeply down the subtree. The upper bits only affect
  // this immediate suspense boundary and gets reset each new
  // boundary or suspense list.

  var SubtreeSuspenseContextMask = 1; // Subtree Flags:
  // InvisibleParentSuspenseContext indicates that one of our parent Suspense
  // boundaries is not currently showing visible main content.
  // Either because it is already showing a fallback or is not mounted at all.
  // We can use this to determine if it is desirable to trigger a fallback at
  // the parent. If not, then we might need to trigger undesirable boundaries
  // and/or suspend the commit to avoid hiding the parent content.

  var InvisibleParentSuspenseContext = 1; // Shallow Flags:
  // ForceSuspenseFallback can be used by SuspenseList to force newly added
  // items into their fallback state during one of the render passes.

  var ForceSuspenseFallback = 2;
  var suspenseStackCursor = createCursor(DefaultSuspenseContext);
  function hasSuspenseContext(parentContext, flag) {
    return (parentContext & flag) !== 0;
  }
  function setDefaultShallowSuspenseContext(parentContext) {
    return parentContext & SubtreeSuspenseContextMask;
  }
  function setShallowSuspenseContext(parentContext, shallowContext) {
    return parentContext & SubtreeSuspenseContextMask | shallowContext;
  }
  function addSubtreeSuspenseContext(parentContext, subtreeContext) {
    return parentContext | subtreeContext;
  }
  function pushSuspenseContext(fiber, newContext) {
    push(suspenseStackCursor, newContext, fiber);
  }
  function popSuspenseContext(fiber) {
    pop(suspenseStackCursor, fiber);
  }

  function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
    // If it was the primary children that just suspended, capture and render the
    // fallback. Otherwise, don't capture and bubble to the next boundary.
    var nextState = workInProgress.memoizedState;

    if (nextState !== null) {
      if (nextState.dehydrated !== null) {
        // A dehydrated boundary always captures.
        return true;
      }

      return false;
    }

    var props = workInProgress.memoizedProps; // Regular boundaries always capture.

    {
      return true;
    } // If it's a boundary we should avoid, then we prefer to bubble up to the
  }
  function findFirstSuspended(row) {
    var node = row;

    while (node !== null) {
      if (node.tag === SuspenseComponent) {
        var state = node.memoizedState;

        if (state !== null) {
          var dehydrated = state.dehydrated;

          if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
            return node;
          }
        }
      } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
      // keep track of whether it suspended or not.
      node.memoizedProps.revealOrder !== undefined) {
        var didSuspend = (node.flags & DidCapture) !== NoFlags;

        if (didSuspend) {
          return node;
        }
      } else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === row) {
        return null;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === row) {
          return null;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }

    return null;
  }

  var NoFlags$1 =
  /*   */
  0; // Represents whether effect should fire.

  var HasEffect =
  /* */
  1; // Represents the phase in which the effect (not the clean-up) fires.

  var Insertion =
  /*  */
  2;
  var Layout =
  /*    */
  4;
  var Passive$1 =
  /*   */
  8;

  // and should be reset before starting a new render.
  // This tracks which mutable sources need to be reset after a render.

  var workInProgressSources = [];
  function resetWorkInProgressVersions() {
    for (var i = 0; i < workInProgressSources.length; i++) {
      var mutableSource = workInProgressSources[i];

      {
        mutableSource._workInProgressVersionPrimary = null;
      }
    }

    workInProgressSources.length = 0;
  }
  // This ensures that the version used for server rendering matches the one
  // that is eventually read during hydration.
  // If they don't match there's a potential tear and a full deopt render is required.

  function registerMutableSourceForHydration(root, mutableSource) {
    var getVersion = mutableSource._getVersion;
    var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished.
    // Retaining it forever may interfere with GC.

    if (root.mutableSourceEagerHydrationData == null) {
      root.mutableSourceEagerHydrationData = [mutableSource, version];
    } else {
      root.mutableSourceEagerHydrationData.push(mutableSource, version);
    }
  }

  var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
      ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
  var didWarnAboutMismatchedHooksForComponent;
  var didWarnUncachedGetSnapshot;

  {
    didWarnAboutMismatchedHooksForComponent = new Set();
  }

  // These are set right before calling the component.
  var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
  // the work-in-progress hook.

  var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
  // current hook list is the list that belongs to the current fiber. The
  // work-in-progress hook list is a new list that will be added to the
  // work-in-progress fiber.

  var currentHook = null;
  var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
  // does not get reset if we do another render pass; only when we're completely
  // finished evaluating this component. This is an optimization so we know
  // whether we need to clear render phase updates after a throw.

  var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
  // gets reset after each attempt.
  // TODO: Maybe there's some way to consolidate this with
  // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.

  var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component.

  var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during
  // hydration). This counter is global, so client ids are not stable across
  // render attempts.

  var globalClientIdCounter = 0;
  var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook

  var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
  // The list stores the order of hooks used during the initial render (mount).
  // Subsequent renders (updates) reference this list.

  var hookTypesDev = null;
  var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
  // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
  // When true, such Hooks will always be "remounted". Only used during hot reload.

  var ignorePreviousDependencies = false;

  function mountHookTypesDev() {
    {
      var hookName = currentHookNameInDev;

      if (hookTypesDev === null) {
        hookTypesDev = [hookName];
      } else {
        hookTypesDev.push(hookName);
      }
    }
  }

  function updateHookTypesDev() {
    {
      var hookName = currentHookNameInDev;

      if (hookTypesDev !== null) {
        hookTypesUpdateIndexDev++;

        if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
          warnOnHookMismatchInDev(hookName);
        }
      }
    }
  }

  function checkDepsAreArrayDev(deps) {
    {
      if (deps !== undefined && deps !== null && !isArray(deps)) {
        // Verify deps, but only on mount to avoid extra checks.
        // It's unlikely their type would change as usually you define them inline.
        error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
      }
    }
  }

  function warnOnHookMismatchInDev(currentHookName) {
    {
      var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);

      if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
        didWarnAboutMismatchedHooksForComponent.add(componentName);

        if (hookTypesDev !== null) {
          var table = '';
          var secondColumnStart = 30;

          for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
            var oldHookName = hookTypesDev[i];
            var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
            var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
            // lol @ IE not supporting String#repeat

            while (row.length < secondColumnStart) {
              row += ' ';
            }

            row += newHookName + '\n';
            table += row;
          }

          error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + '   Previous render            Next render\n' + '   ------------------------------------------------------\n' + '%s' + '   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
        }
      }
    }
  }

  function throwInvalidHookError() {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
  }

  function areHookInputsEqual(nextDeps, prevDeps) {
    {
      if (ignorePreviousDependencies) {
        // Only true when this component is being hot reloaded.
        return false;
      }
    }

    if (prevDeps === null) {
      {
        error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
      }

      return false;
    }

    {
      // Don't bother comparing lengths in prod because these arrays should be
      // passed inline.
      if (nextDeps.length !== prevDeps.length) {
        error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
      }
    }

    for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
      if (objectIs(nextDeps[i], prevDeps[i])) {
        continue;
      }

      return false;
    }

    return true;
  }

  function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
    renderLanes = nextRenderLanes;
    currentlyRenderingFiber$1 = workInProgress;

    {
      hookTypesDev = current !== null ? current._debugHookTypes : null;
      hookTypesUpdateIndexDev = -1; // Used for hot reloading:

      ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
    }

    workInProgress.memoizedState = null;
    workInProgress.updateQueue = null;
    workInProgress.lanes = NoLanes; // The following should have already been reset
    // currentHook = null;
    // workInProgressHook = null;
    // didScheduleRenderPhaseUpdate = false;
    // localIdCounter = 0;
    // TODO Warn if no hooks are used at all during mount, then some are used during update.
    // Currently we will identify the update render as a mount because memoizedState === null.
    // This is tricky because it's valid for certain types of components (e.g. React.lazy)
    // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
    // Non-stateful hooks (e.g. context) don't get added to memoizedState,
    // so memoizedState would be null during updates and mounts.

    {
      if (current !== null && current.memoizedState !== null) {
        ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
      } else if (hookTypesDev !== null) {
        // This dispatcher handles an edge case where a component is updating,
        // but no stateful hooks have been used.
        // We want to match the production code behavior (which will use HooksDispatcherOnMount),
        // but with the extra DEV validation to ensure hooks ordering hasn't changed.
        // This dispatcher does that.
        ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
      } else {
        ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
      }
    }

    var children = Component(props, secondArg); // Check if there was a render phase update

    if (didScheduleRenderPhaseUpdateDuringThisPass) {
      // Keep rendering in a loop for as long as render phase updates continue to
      // be scheduled. Use a counter to prevent infinite loops.
      var numberOfReRenders = 0;

      do {
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        localIdCounter = 0;

        if (numberOfReRenders >= RE_RENDER_LIMIT) {
          throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
        }

        numberOfReRenders += 1;

        {
          // Even when hot reloading, allow dependencies to stabilize
          // after first render to prevent infinite render phase updates.
          ignorePreviousDependencies = false;
        } // Start over from the beginning of the list


        currentHook = null;
        workInProgressHook = null;
        workInProgress.updateQueue = null;

        {
          // Also validate hook order for cascading updates.
          hookTypesUpdateIndexDev = -1;
        }

        ReactCurrentDispatcher$1.current =  HooksDispatcherOnRerenderInDEV ;
        children = Component(props, secondArg);
      } while (didScheduleRenderPhaseUpdateDuringThisPass);
    } // We can assume the previous dispatcher is always this one, since we set it
    // at the beginning of the render phase and there's no re-entrance.


    ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;

    {
      workInProgress._debugHookTypes = hookTypesDev;
    } // This check uses currentHook so that it works the same in DEV and prod bundles.
    // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.


    var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
    renderLanes = NoLanes;
    currentlyRenderingFiber$1 = null;
    currentHook = null;
    workInProgressHook = null;

    {
      currentHookNameInDev = null;
      hookTypesDev = null;
      hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last
      // render. If this fires, it suggests that we incorrectly reset the static
      // flags in some other part of the codebase. This has happened before, for
      // example, in the SuspenseList implementation.

      if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
      // and creates false positives. To make this work in legacy mode, we'd
      // need to mark fibers that commit in an incomplete state, somehow. For
      // now I'll disable the warning that most of the bugs that would trigger
      // it are either exclusive to concurrent mode or exist in both.
      (current.mode & ConcurrentMode) !== NoMode) {
        error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.');
      }
    }

    didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook
    // localIdCounter = 0;

    if (didRenderTooFewHooks) {
      throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.');
    }

    return children;
  }
  function checkDidRenderIdHook() {
    // This should be called immediately after every renderWithHooks call.
    // Conceptually, it's part of the return value of renderWithHooks; it's only a
    // separate function to avoid using an array tuple.
    var didRenderIdHook = localIdCounter !== 0;
    localIdCounter = 0;
    return didRenderIdHook;
  }
  function bailoutHooks(current, workInProgress, lanes) {
    workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the
    // complete phase (bubbleProperties).

    if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
      workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update);
    } else {
      workInProgress.flags &= ~(Passive | Update);
    }

    current.lanes = removeLanes(current.lanes, lanes);
  }
  function resetHooksAfterThrow() {
    // We can assume the previous dispatcher is always this one, since we set it
    // at the beginning of the render phase and there's no re-entrance.
    ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;

    if (didScheduleRenderPhaseUpdate) {
      // There were render phase updates. These are only valid for this render
      // phase, which we are now aborting. Remove the updates from the queues so
      // they do not persist to the next render. Do not remove updates from hooks
      // that weren't processed.
      //
      // Only reset the updates from the queue if it has a clone. If it does
      // not have a clone, that means it wasn't processed, and the updates were
      // scheduled before we entered the render phase.
      var hook = currentlyRenderingFiber$1.memoizedState;

      while (hook !== null) {
        var queue = hook.queue;

        if (queue !== null) {
          queue.pending = null;
        }

        hook = hook.next;
      }

      didScheduleRenderPhaseUpdate = false;
    }

    renderLanes = NoLanes;
    currentlyRenderingFiber$1 = null;
    currentHook = null;
    workInProgressHook = null;

    {
      hookTypesDev = null;
      hookTypesUpdateIndexDev = -1;
      currentHookNameInDev = null;
      isUpdatingOpaqueValueInRenderPhase = false;
    }

    didScheduleRenderPhaseUpdateDuringThisPass = false;
    localIdCounter = 0;
  }

  function mountWorkInProgressHook() {
    var hook = {
      memoizedState: null,
      baseState: null,
      baseQueue: null,
      queue: null,
      next: null
    };

    if (workInProgressHook === null) {
      // This is the first hook in the list
      currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
    } else {
      // Append to the end of the list
      workInProgressHook = workInProgressHook.next = hook;
    }

    return workInProgressHook;
  }

  function updateWorkInProgressHook() {
    // This function is used both for updates and for re-renders triggered by a
    // render phase update. It assumes there is either a current hook we can
    // clone, or a work-in-progress hook from a previous render pass that we can
    // use as a base. When we reach the end of the base list, we must switch to
    // the dispatcher used for mounts.
    var nextCurrentHook;

    if (currentHook === null) {
      var current = currentlyRenderingFiber$1.alternate;

      if (current !== null) {
        nextCurrentHook = current.memoizedState;
      } else {
        nextCurrentHook = null;
      }
    } else {
      nextCurrentHook = currentHook.next;
    }

    var nextWorkInProgressHook;

    if (workInProgressHook === null) {
      nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
    } else {
      nextWorkInProgressHook = workInProgressHook.next;
    }

    if (nextWorkInProgressHook !== null) {
      // There's already a work-in-progress. Reuse it.
      workInProgressHook = nextWorkInProgressHook;
      nextWorkInProgressHook = workInProgressHook.next;
      currentHook = nextCurrentHook;
    } else {
      // Clone from the current hook.
      if (nextCurrentHook === null) {
        throw new Error('Rendered more hooks than during the previous render.');
      }

      currentHook = nextCurrentHook;
      var newHook = {
        memoizedState: currentHook.memoizedState,
        baseState: currentHook.baseState,
        baseQueue: currentHook.baseQueue,
        queue: currentHook.queue,
        next: null
      };

      if (workInProgressHook === null) {
        // This is the first hook in the list.
        currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
      } else {
        // Append to the end of the list.
        workInProgressHook = workInProgressHook.next = newHook;
      }
    }

    return workInProgressHook;
  }

  function createFunctionComponentUpdateQueue() {
    return {
      lastEffect: null,
      stores: null
    };
  }

  function basicStateReducer(state, action) {
    // $FlowFixMe: Flow doesn't like mixed types
    return typeof action === 'function' ? action(state) : action;
  }

  function mountReducer(reducer, initialArg, init) {
    var hook = mountWorkInProgressHook();
    var initialState;

    if (init !== undefined) {
      initialState = init(initialArg);
    } else {
      initialState = initialArg;
    }

    hook.memoizedState = hook.baseState = initialState;
    var queue = {
      pending: null,
      interleaved: null,
      lanes: NoLanes,
      dispatch: null,
      lastRenderedReducer: reducer,
      lastRenderedState: initialState
    };
    hook.queue = queue;
    var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue);
    return [hook.memoizedState, dispatch];
  }

  function updateReducer(reducer, initialArg, init) {
    var hook = updateWorkInProgressHook();
    var queue = hook.queue;

    if (queue === null) {
      throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
    }

    queue.lastRenderedReducer = reducer;
    var current = currentHook; // The last rebase update that is NOT part of the base state.

    var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.

    var pendingQueue = queue.pending;

    if (pendingQueue !== null) {
      // We have new updates that haven't been processed yet.
      // We'll add them to the base queue.
      if (baseQueue !== null) {
        // Merge the pending queue and the base queue.
        var baseFirst = baseQueue.next;
        var pendingFirst = pendingQueue.next;
        baseQueue.next = pendingFirst;
        pendingQueue.next = baseFirst;
      }

      {
        if (current.baseQueue !== baseQueue) {
          // Internal invariant that should never happen, but feasibly could in
          // the future if we implement resuming, or some form of that.
          error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
        }
      }

      current.baseQueue = baseQueue = pendingQueue;
      queue.pending = null;
    }

    if (baseQueue !== null) {
      // We have a queue to process.
      var first = baseQueue.next;
      var newState = current.baseState;
      var newBaseState = null;
      var newBaseQueueFirst = null;
      var newBaseQueueLast = null;
      var update = first;

      do {
        var updateLane = update.lane;

        if (!isSubsetOfLanes(renderLanes, updateLane)) {
          // Priority is insufficient. Skip this update. If this is the first
          // skipped update, the previous update/state is the new base
          // update/state.
          var clone = {
            lane: updateLane,
            action: update.action,
            hasEagerState: update.hasEagerState,
            eagerState: update.eagerState,
            next: null
          };

          if (newBaseQueueLast === null) {
            newBaseQueueFirst = newBaseQueueLast = clone;
            newBaseState = newState;
          } else {
            newBaseQueueLast = newBaseQueueLast.next = clone;
          } // Update the remaining priority in the queue.
          // TODO: Don't need to accumulate this. Instead, we can remove
          // renderLanes from the original lanes.


          currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
          markSkippedUpdateLanes(updateLane);
        } else {
          // This update does have sufficient priority.
          if (newBaseQueueLast !== null) {
            var _clone = {
              // This update is going to be committed so we never want uncommit
              // it. Using NoLane works because 0 is a subset of all bitmasks, so
              // this will never be skipped by the check above.
              lane: NoLane,
              action: update.action,
              hasEagerState: update.hasEagerState,
              eagerState: update.eagerState,
              next: null
            };
            newBaseQueueLast = newBaseQueueLast.next = _clone;
          } // Process this update.


          if (update.hasEagerState) {
            // If this update is a state update (not a reducer) and was processed eagerly,
            // we can use the eagerly computed state
            newState = update.eagerState;
          } else {
            var action = update.action;
            newState = reducer(newState, action);
          }
        }

        update = update.next;
      } while (update !== null && update !== first);

      if (newBaseQueueLast === null) {
        newBaseState = newState;
      } else {
        newBaseQueueLast.next = newBaseQueueFirst;
      } // Mark that the fiber performed work, but only if the new state is
      // different from the current state.


      if (!objectIs(newState, hook.memoizedState)) {
        markWorkInProgressReceivedUpdate();
      }

      hook.memoizedState = newState;
      hook.baseState = newBaseState;
      hook.baseQueue = newBaseQueueLast;
      queue.lastRenderedState = newState;
    } // Interleaved updates are stored on a separate queue. We aren't going to
    // process them during this render, but we do need to track which lanes
    // are remaining.


    var lastInterleaved = queue.interleaved;

    if (lastInterleaved !== null) {
      var interleaved = lastInterleaved;

      do {
        var interleavedLane = interleaved.lane;
        currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
        markSkippedUpdateLanes(interleavedLane);
        interleaved = interleaved.next;
      } while (interleaved !== lastInterleaved);
    } else if (baseQueue === null) {
      // `queue.lanes` is used for entangling transitions. We can set it back to
      // zero once the queue is empty.
      queue.lanes = NoLanes;
    }

    var dispatch = queue.dispatch;
    return [hook.memoizedState, dispatch];
  }

  function rerenderReducer(reducer, initialArg, init) {
    var hook = updateWorkInProgressHook();
    var queue = hook.queue;

    if (queue === null) {
      throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
    }

    queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
    // work-in-progress hook.

    var dispatch = queue.dispatch;
    var lastRenderPhaseUpdate = queue.pending;
    var newState = hook.memoizedState;

    if (lastRenderPhaseUpdate !== null) {
      // The queue doesn't persist past this render pass.
      queue.pending = null;
      var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      var update = firstRenderPhaseUpdate;

      do {
        // Process this render phase update. We don't have to check the
        // priority because it will always be the same as the current
        // render's.
        var action = update.action;
        newState = reducer(newState, action);
        update = update.next;
      } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
      // different from the current state.


      if (!objectIs(newState, hook.memoizedState)) {
        markWorkInProgressReceivedUpdate();
      }

      hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
      // the base state unless the queue is empty.
      // TODO: Not sure if this is the desired semantics, but it's what we
      // do for gDSFP. I can't remember why.

      if (hook.baseQueue === null) {
        hook.baseState = newState;
      }

      queue.lastRenderedState = newState;
    }

    return [newState, dispatch];
  }

  function mountMutableSource(source, getSnapshot, subscribe) {
    {
      return undefined;
    }
  }

  function updateMutableSource(source, getSnapshot, subscribe) {
    {
      return undefined;
    }
  }

  function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    var fiber = currentlyRenderingFiber$1;
    var hook = mountWorkInProgressHook();
    var nextSnapshot;
    var isHydrating = getIsHydrating();

    if (isHydrating) {
      if (getServerSnapshot === undefined) {
        throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
      }

      nextSnapshot = getServerSnapshot();

      {
        if (!didWarnUncachedGetSnapshot) {
          if (nextSnapshot !== getServerSnapshot()) {
            error('The result of getServerSnapshot should be cached to avoid an infinite loop');

            didWarnUncachedGetSnapshot = true;
          }
        }
      }
    } else {
      nextSnapshot = getSnapshot();

      {
        if (!didWarnUncachedGetSnapshot) {
          var cachedSnapshot = getSnapshot();

          if (!objectIs(nextSnapshot, cachedSnapshot)) {
            error('The result of getSnapshot should be cached to avoid an infinite loop');

            didWarnUncachedGetSnapshot = true;
          }
        }
      } // Unless we're rendering a blocking lane, schedule a consistency check.
      // Right before committing, we will walk the tree and check if any of the
      // stores were mutated.
      //
      // We won't do this if we're hydrating server-rendered content, because if
      // the content is stale, it's already visible anyway. Instead we'll patch
      // it up in a passive effect.


      var root = getWorkInProgressRoot();

      if (root === null) {
        throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
      }

      if (!includesBlockingLane(root, renderLanes)) {
        pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
      }
    } // Read the current snapshot from the store on every render. This breaks the
    // normal rules of React, and only works because store updates are
    // always synchronous.


    hook.memoizedState = nextSnapshot;
    var inst = {
      value: nextSnapshot,
      getSnapshot: getSnapshot
    };
    hook.queue = inst; // Schedule an effect to subscribe to the store.

    mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update
    // this whenever subscribe, getSnapshot, or value changes. Because there's no
    // clean-up function, and we track the deps correctly, we can call pushEffect
    // directly, without storing any additional state. For the same reason, we
    // don't need to set a static flag, either.
    // TODO: We can move this to the passive phase once we add a pre-commit
    // consistency check. See the next comment.

    fiber.flags |= Passive;
    pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null);
    return nextSnapshot;
  }

  function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    var fiber = currentlyRenderingFiber$1;
    var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the
    // normal rules of React, and only works because store updates are
    // always synchronous.

    var nextSnapshot = getSnapshot();

    {
      if (!didWarnUncachedGetSnapshot) {
        var cachedSnapshot = getSnapshot();

        if (!objectIs(nextSnapshot, cachedSnapshot)) {
          error('The result of getSnapshot should be cached to avoid an infinite loop');

          didWarnUncachedGetSnapshot = true;
        }
      }
    }

    var prevSnapshot = hook.memoizedState;
    var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);

    if (snapshotChanged) {
      hook.memoizedState = nextSnapshot;
      markWorkInProgressReceivedUpdate();
    }

    var inst = hook.queue;
    updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the
    // commit phase if there was an interleaved mutation. In concurrent mode
    // this can happen all the time, but even in synchronous mode, an earlier
    // effect may have mutated the store.

    if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
    // checking whether we scheduled a subscription effect above.
    workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
      fiber.flags |= Passive;
      pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check.
      // Right before committing, we will walk the tree and check if any of the
      // stores were mutated.

      var root = getWorkInProgressRoot();

      if (root === null) {
        throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
      }

      if (!includesBlockingLane(root, renderLanes)) {
        pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
      }
    }

    return nextSnapshot;
  }

  function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
    fiber.flags |= StoreConsistency;
    var check = {
      getSnapshot: getSnapshot,
      value: renderedSnapshot
    };
    var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;

    if (componentUpdateQueue === null) {
      componentUpdateQueue = createFunctionComponentUpdateQueue();
      currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
      componentUpdateQueue.stores = [check];
    } else {
      var stores = componentUpdateQueue.stores;

      if (stores === null) {
        componentUpdateQueue.stores = [check];
      } else {
        stores.push(check);
      }
    }
  }

  function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
    // These are updated in the passive phase
    inst.value = nextSnapshot;
    inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could
    // have been in an event that fired before the passive effects, or it could
    // have been in a layout effect. In that case, we would have used the old
    // snapsho and getSnapshot values to bail out. We need to check one more time.

    if (checkIfSnapshotChanged(inst)) {
      // Force a re-render.
      forceStoreRerender(fiber);
    }
  }

  function subscribeToStore(fiber, inst, subscribe) {
    var handleStoreChange = function () {
      // The store changed. Check if the snapshot changed since the last time we
      // read from the store.
      if (checkIfSnapshotChanged(inst)) {
        // Force a re-render.
        forceStoreRerender(fiber);
      }
    }; // Subscribe to the store and return a clean-up function.


    return subscribe(handleStoreChange);
  }

  function checkIfSnapshotChanged(inst) {
    var latestGetSnapshot = inst.getSnapshot;
    var prevValue = inst.value;

    try {
      var nextValue = latestGetSnapshot();
      return !objectIs(prevValue, nextValue);
    } catch (error) {
      return true;
    }
  }

  function forceStoreRerender(fiber) {
    var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
    }
  }

  function mountState(initialState) {
    var hook = mountWorkInProgressHook();

    if (typeof initialState === 'function') {
      // $FlowFixMe: Flow doesn't like mixed types
      initialState = initialState();
    }

    hook.memoizedState = hook.baseState = initialState;
    var queue = {
      pending: null,
      interleaved: null,
      lanes: NoLanes,
      dispatch: null,
      lastRenderedReducer: basicStateReducer,
      lastRenderedState: initialState
    };
    hook.queue = queue;
    var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
    return [hook.memoizedState, dispatch];
  }

  function updateState(initialState) {
    return updateReducer(basicStateReducer);
  }

  function rerenderState(initialState) {
    return rerenderReducer(basicStateReducer);
  }

  function pushEffect(tag, create, destroy, deps) {
    var effect = {
      tag: tag,
      create: create,
      destroy: destroy,
      deps: deps,
      // Circular
      next: null
    };
    var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;

    if (componentUpdateQueue === null) {
      componentUpdateQueue = createFunctionComponentUpdateQueue();
      currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
      componentUpdateQueue.lastEffect = effect.next = effect;
    } else {
      var lastEffect = componentUpdateQueue.lastEffect;

      if (lastEffect === null) {
        componentUpdateQueue.lastEffect = effect.next = effect;
      } else {
        var firstEffect = lastEffect.next;
        lastEffect.next = effect;
        effect.next = firstEffect;
        componentUpdateQueue.lastEffect = effect;
      }
    }

    return effect;
  }

  function mountRef(initialValue) {
    var hook = mountWorkInProgressHook();

    {
      var _ref2 = {
        current: initialValue
      };
      hook.memoizedState = _ref2;
      return _ref2;
    }
  }

  function updateRef(initialValue) {
    var hook = updateWorkInProgressHook();
    return hook.memoizedState;
  }

  function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
    var hook = mountWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    currentlyRenderingFiber$1.flags |= fiberFlags;
    hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
  }

  function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
    var hook = updateWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    var destroy = undefined;

    if (currentHook !== null) {
      var prevEffect = currentHook.memoizedState;
      destroy = prevEffect.destroy;

      if (nextDeps !== null) {
        var prevDeps = prevEffect.deps;

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps);
          return;
        }
      }
    }

    currentlyRenderingFiber$1.flags |= fiberFlags;
    hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
  }

  function mountEffect(create, deps) {
    if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
      return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps);
    } else {
      return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps);
    }
  }

  function updateEffect(create, deps) {
    return updateEffectImpl(Passive, Passive$1, create, deps);
  }

  function mountInsertionEffect(create, deps) {
    return mountEffectImpl(Update, Insertion, create, deps);
  }

  function updateInsertionEffect(create, deps) {
    return updateEffectImpl(Update, Insertion, create, deps);
  }

  function mountLayoutEffect(create, deps) {
    var fiberFlags = Update;

    {
      fiberFlags |= LayoutStatic;
    }

    if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
      fiberFlags |= MountLayoutDev;
    }

    return mountEffectImpl(fiberFlags, Layout, create, deps);
  }

  function updateLayoutEffect(create, deps) {
    return updateEffectImpl(Update, Layout, create, deps);
  }

  function imperativeHandleEffect(create, ref) {
    if (typeof ref === 'function') {
      var refCallback = ref;

      var _inst = create();

      refCallback(_inst);
      return function () {
        refCallback(null);
      };
    } else if (ref !== null && ref !== undefined) {
      var refObject = ref;

      {
        if (!refObject.hasOwnProperty('current')) {
          error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
        }
      }

      var _inst2 = create();

      refObject.current = _inst2;
      return function () {
        refObject.current = null;
      };
    }
  }

  function mountImperativeHandle(ref, create, deps) {
    {
      if (typeof create !== 'function') {
        error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
      }
    } // TODO: If deps are provided, should we skip comparing the ref itself?


    var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
    var fiberFlags = Update;

    {
      fiberFlags |= LayoutStatic;
    }

    if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
      fiberFlags |= MountLayoutDev;
    }

    return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
  }

  function updateImperativeHandle(ref, create, deps) {
    {
      if (typeof create !== 'function') {
        error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
      }
    } // TODO: If deps are provided, should we skip comparing the ref itself?


    var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
    return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
  }

  function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
    // The react-debug-hooks package injects its own implementation
    // so that e.g. DevTools can display custom hook values.
  }

  var updateDebugValue = mountDebugValue;

  function mountCallback(callback, deps) {
    var hook = mountWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    hook.memoizedState = [callback, nextDeps];
    return callback;
  }

  function updateCallback(callback, deps) {
    var hook = updateWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    var prevState = hook.memoizedState;

    if (prevState !== null) {
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }

    hook.memoizedState = [callback, nextDeps];
    return callback;
  }

  function mountMemo(nextCreate, deps) {
    var hook = mountWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    var nextValue = nextCreate();
    hook.memoizedState = [nextValue, nextDeps];
    return nextValue;
  }

  function updateMemo(nextCreate, deps) {
    var hook = updateWorkInProgressHook();
    var nextDeps = deps === undefined ? null : deps;
    var prevState = hook.memoizedState;

    if (prevState !== null) {
      // Assume these are defined. If they're not, areHookInputsEqual will warn.
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }

    var nextValue = nextCreate();
    hook.memoizedState = [nextValue, nextDeps];
    return nextValue;
  }

  function mountDeferredValue(value) {
    var hook = mountWorkInProgressHook();
    hook.memoizedState = value;
    return value;
  }

  function updateDeferredValue(value) {
    var hook = updateWorkInProgressHook();
    var resolvedCurrentHook = currentHook;
    var prevValue = resolvedCurrentHook.memoizedState;
    return updateDeferredValueImpl(hook, prevValue, value);
  }

  function rerenderDeferredValue(value) {
    var hook = updateWorkInProgressHook();

    if (currentHook === null) {
      // This is a rerender during a mount.
      hook.memoizedState = value;
      return value;
    } else {
      // This is a rerender during an update.
      var prevValue = currentHook.memoizedState;
      return updateDeferredValueImpl(hook, prevValue, value);
    }
  }

  function updateDeferredValueImpl(hook, prevValue, value) {
    var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);

    if (shouldDeferValue) {
      // This is an urgent update. If the value has changed, keep using the
      // previous value and spawn a deferred render to update it later.
      if (!objectIs(value, prevValue)) {
        // Schedule a deferred render
        var deferredLane = claimNextTransitionLane();
        currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
        markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent
        // from the latest value. The name "baseState" doesn't really match how we
        // use it because we're reusing a state hook field instead of creating a
        // new one.

        hook.baseState = true;
      } // Reuse the previous value


      return prevValue;
    } else {
      // This is not an urgent update, so we can use the latest value regardless
      // of what it is. No need to defer it.
      // However, if we're currently inside a spawned render, then we need to mark
      // this as an update to prevent the fiber from bailing out.
      //
      // `baseState` is true when the current value is different from the rendered
      // value. The name doesn't really match how we use it because we're reusing
      // a state hook field instead of creating a new one.
      if (hook.baseState) {
        // Flip this back to false.
        hook.baseState = false;
        markWorkInProgressReceivedUpdate();
      }

      hook.memoizedState = value;
      return value;
    }
  }

  function startTransition(setPending, callback, options) {
    var previousPriority = getCurrentUpdatePriority();
    setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
    setPending(true);
    var prevTransition = ReactCurrentBatchConfig$2.transition;
    ReactCurrentBatchConfig$2.transition = {};
    var currentTransition = ReactCurrentBatchConfig$2.transition;

    {
      ReactCurrentBatchConfig$2.transition._updatedFibers = new Set();
    }

    try {
      setPending(false);
      callback();
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig$2.transition = prevTransition;

      {
        if (prevTransition === null && currentTransition._updatedFibers) {
          var updatedFibersCount = currentTransition._updatedFibers.size;

          if (updatedFibersCount > 10) {
            warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
          }

          currentTransition._updatedFibers.clear();
        }
      }
    }
  }

  function mountTransition() {
    var _mountState = mountState(false),
        isPending = _mountState[0],
        setPending = _mountState[1]; // The `start` method never changes.


    var start = startTransition.bind(null, setPending);
    var hook = mountWorkInProgressHook();
    hook.memoizedState = start;
    return [isPending, start];
  }

  function updateTransition() {
    var _updateState = updateState(),
        isPending = _updateState[0];

    var hook = updateWorkInProgressHook();
    var start = hook.memoizedState;
    return [isPending, start];
  }

  function rerenderTransition() {
    var _rerenderState = rerenderState(),
        isPending = _rerenderState[0];

    var hook = updateWorkInProgressHook();
    var start = hook.memoizedState;
    return [isPending, start];
  }

  var isUpdatingOpaqueValueInRenderPhase = false;
  function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
    {
      return isUpdatingOpaqueValueInRenderPhase;
    }
  }

  function mountId() {
    var hook = mountWorkInProgressHook();
    var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we
    // should do this in Fiber, too? Deferring this decision for now because
    // there's no other place to store the prefix except for an internal field on
    // the public createRoot object, which the fiber tree does not currently have
    // a reference to.

    var identifierPrefix = root.identifierPrefix;
    var id;

    if (getIsHydrating()) {
      var treeId = getTreeId(); // Use a captial R prefix for server-generated ids.

      id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
      // that represents the position of this useId hook among all the useId
      // hooks for this fiber.

      var localId = localIdCounter++;

      if (localId > 0) {
        id += 'H' + localId.toString(32);
      }

      id += ':';
    } else {
      // Use a lowercase r prefix for client-generated ids.
      var globalClientId = globalClientIdCounter++;
      id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':';
    }

    hook.memoizedState = id;
    return id;
  }

  function updateId() {
    var hook = updateWorkInProgressHook();
    var id = hook.memoizedState;
    return id;
  }

  function dispatchReducerAction(fiber, queue, action) {
    {
      if (typeof arguments[3] === 'function') {
        error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
      }
    }

    var lane = requestUpdateLane(fiber);
    var update = {
      lane: lane,
      action: action,
      hasEagerState: false,
      eagerState: null,
      next: null
    };

    if (isRenderPhaseUpdate(fiber)) {
      enqueueRenderPhaseUpdate(queue, update);
    } else {
      var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);

      if (root !== null) {
        var eventTime = requestEventTime();
        scheduleUpdateOnFiber(root, fiber, lane, eventTime);
        entangleTransitionUpdate(root, queue, lane);
      }
    }

    markUpdateInDevTools(fiber, lane);
  }

  function dispatchSetState(fiber, queue, action) {
    {
      if (typeof arguments[3] === 'function') {
        error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
      }
    }

    var lane = requestUpdateLane(fiber);
    var update = {
      lane: lane,
      action: action,
      hasEagerState: false,
      eagerState: null,
      next: null
    };

    if (isRenderPhaseUpdate(fiber)) {
      enqueueRenderPhaseUpdate(queue, update);
    } else {
      var alternate = fiber.alternate;

      if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
        // The queue is currently empty, which means we can eagerly compute the
        // next state before entering the render phase. If the new state is the
        // same as the current state, we may be able to bail out entirely.
        var lastRenderedReducer = queue.lastRenderedReducer;

        if (lastRenderedReducer !== null) {
          var prevDispatcher;

          {
            prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
          }

          try {
            var currentState = queue.lastRenderedState;
            var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
            // it, on the update object. If the reducer hasn't changed by the
            // time we enter the render phase, then the eager state can be used
            // without calling the reducer again.

            update.hasEagerState = true;
            update.eagerState = eagerState;

            if (objectIs(eagerState, currentState)) {
              // Fast path. We can bail out without scheduling React to re-render.
              // It's still possible that we'll need to rebase this update later,
              // if the component re-renders for a different reason and by that
              // time the reducer has changed.
              // TODO: Do we still need to entangle transitions in this case?
              enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane);
              return;
            }
          } catch (error) {// Suppress the error. It will throw again in the render phase.
          } finally {
            {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          }
        }
      }

      var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);

      if (root !== null) {
        var eventTime = requestEventTime();
        scheduleUpdateOnFiber(root, fiber, lane, eventTime);
        entangleTransitionUpdate(root, queue, lane);
      }
    }

    markUpdateInDevTools(fiber, lane);
  }

  function isRenderPhaseUpdate(fiber) {
    var alternate = fiber.alternate;
    return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
  }

  function enqueueRenderPhaseUpdate(queue, update) {
    // This is a render phase update. Stash it in a lazily-created map of
    // queue -> linked list of updates. After this render pass, we'll restart
    // and apply the stashed updates on top of the work-in-progress hook.
    didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
    var pending = queue.pending;

    if (pending === null) {
      // This is the first update. Create a circular list.
      update.next = update;
    } else {
      update.next = pending.next;
      pending.next = update;
    }

    queue.pending = update;
  } // TODO: Move to ReactFiberConcurrentUpdates?


  function entangleTransitionUpdate(root, queue, lane) {
    if (isTransitionLane(lane)) {
      var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they
      // must have finished. We can remove them from the shared queue, which
      // represents a superset of the actually pending lanes. In some cases we
      // may entangle more than we need to, but that's OK. In fact it's worse if
      // we *don't* entangle when we should.

      queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.

      var newQueueLanes = mergeLanes(queueLanes, lane);
      queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
      // the lane finished since the last time we entangled it. So we need to
      // entangle it again, just to be sure.

      markRootEntangled(root, newQueueLanes);
    }
  }

  function markUpdateInDevTools(fiber, lane, action) {

    {
      markStateUpdateScheduled(fiber, lane);
    }
  }

  var ContextOnlyDispatcher = {
    readContext: readContext,
    useCallback: throwInvalidHookError,
    useContext: throwInvalidHookError,
    useEffect: throwInvalidHookError,
    useImperativeHandle: throwInvalidHookError,
    useInsertionEffect: throwInvalidHookError,
    useLayoutEffect: throwInvalidHookError,
    useMemo: throwInvalidHookError,
    useReducer: throwInvalidHookError,
    useRef: throwInvalidHookError,
    useState: throwInvalidHookError,
    useDebugValue: throwInvalidHookError,
    useDeferredValue: throwInvalidHookError,
    useTransition: throwInvalidHookError,
    useMutableSource: throwInvalidHookError,
    useSyncExternalStore: throwInvalidHookError,
    useId: throwInvalidHookError,
    unstable_isNewReconciler: enableNewReconciler
  };

  var HooksDispatcherOnMountInDEV = null;
  var HooksDispatcherOnMountWithHookTypesInDEV = null;
  var HooksDispatcherOnUpdateInDEV = null;
  var HooksDispatcherOnRerenderInDEV = null;
  var InvalidNestedHooksDispatcherOnMountInDEV = null;
  var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
  var InvalidNestedHooksDispatcherOnRerenderInDEV = null;

  {
    var warnInvalidContextAccess = function () {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    };

    var warnInvalidHookAccess = function () {
      error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
    };

    HooksDispatcherOnMountInDEV = {
      readContext: function (context) {
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        mountHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        mountHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        mountHookTypesDev();
        return mountDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        mountHookTypesDev();
        return mountDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        mountHookTypesDev();
        return mountTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        mountHookTypesDev();
        return mountMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        mountHookTypesDev();
        return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        mountHookTypesDev();
        return mountId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    HooksDispatcherOnMountWithHookTypesInDEV = {
      readContext: function (context) {
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        updateHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        updateHookTypesDev();
        return mountEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        updateHookTypesDev();
        return mountImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        updateHookTypesDev();
        return mountInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        updateHookTypesDev();
        return mountLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        updateHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        updateHookTypesDev();
        return mountDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        updateHookTypesDev();
        return mountDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        updateHookTypesDev();
        return mountTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        updateHookTypesDev();
        return mountMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        updateHookTypesDev();
        return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        updateHookTypesDev();
        return mountId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    HooksDispatcherOnUpdateInDEV = {
      readContext: function (context) {
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        updateHookTypesDev();
        return updateEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        updateHookTypesDev();
        return updateImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        updateHookTypesDev();
        return updateInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        updateHookTypesDev();
        return updateLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        updateHookTypesDev();
        return updateRef();
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        updateHookTypesDev();
        return updateDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        updateHookTypesDev();
        return updateDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        updateHookTypesDev();
        return updateTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        updateHookTypesDev();
        return updateMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        updateHookTypesDev();
        return updateSyncExternalStore(subscribe, getSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        updateHookTypesDev();
        return updateId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    HooksDispatcherOnRerenderInDEV = {
      readContext: function (context) {
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        updateHookTypesDev();
        return updateEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        updateHookTypesDev();
        return updateImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        updateHookTypesDev();
        return updateInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        updateHookTypesDev();
        return updateLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

        try {
          return updateMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

        try {
          return rerenderReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        updateHookTypesDev();
        return updateRef();
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

        try {
          return rerenderState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        updateHookTypesDev();
        return updateDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        updateHookTypesDev();
        return rerenderDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        updateHookTypesDev();
        return rerenderTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        updateHookTypesDev();
        return updateMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        updateHookTypesDev();
        return updateSyncExternalStore(subscribe, getSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        updateHookTypesDev();
        return updateId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    InvalidNestedHooksDispatcherOnMountInDEV = {
      readContext: function (context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

        try {
          return mountState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    InvalidNestedHooksDispatcherOnUpdateInDEV = {
      readContext: function (context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateRef();
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(subscribe, getSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };

    InvalidNestedHooksDispatcherOnRerenderInDEV = {
      readContext: function (context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      useCallback: function (callback, deps) {
        currentHookNameInDev = 'useCallback';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function (context) {
        currentHookNameInDev = 'useContext';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function (create, deps) {
        currentHookNameInDev = 'useEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffect(create, deps);
      },
      useImperativeHandle: function (ref, create, deps) {
        currentHookNameInDev = 'useImperativeHandle';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref, create, deps);
      },
      useInsertionEffect: function (create, deps) {
        currentHookNameInDev = 'useInsertionEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateInsertionEffect(create, deps);
      },
      useLayoutEffect: function (create, deps) {
        currentHookNameInDev = 'useLayoutEffect';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateLayoutEffect(create, deps);
      },
      useMemo: function (create, deps) {
        currentHookNameInDev = 'useMemo';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return updateMemo(create, deps);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useReducer: function (reducer, initialArg, init) {
        currentHookNameInDev = 'useReducer';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return rerenderReducer(reducer, initialArg, init);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useRef: function (initialValue) {
        currentHookNameInDev = 'useRef';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateRef();
      },
      useState: function (initialState) {
        currentHookNameInDev = 'useState';
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactCurrentDispatcher$1.current;
        ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

        try {
          return rerenderState(initialState);
        } finally {
          ReactCurrentDispatcher$1.current = prevDispatcher;
        }
      },
      useDebugValue: function (value, formatterFn) {
        currentHookNameInDev = 'useDebugValue';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateDebugValue();
      },
      useDeferredValue: function (value) {
        currentHookNameInDev = 'useDeferredValue';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderDeferredValue(value);
      },
      useTransition: function () {
        currentHookNameInDev = 'useTransition';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderTransition();
      },
      useMutableSource: function (source, getSnapshot, subscribe) {
        currentHookNameInDev = 'useMutableSource';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateMutableSource();
      },
      useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = 'useSyncExternalStore';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(subscribe, getSnapshot);
      },
      useId: function () {
        currentHookNameInDev = 'useId';
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateId();
      },
      unstable_isNewReconciler: enableNewReconciler
    };
  }

  var now$1 = unstable_now;
  var commitTime = 0;
  var layoutEffectStartTime = -1;
  var profilerStartTime = -1;
  var passiveEffectStartTime = -1;
  /**
   * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
   *
   * The overall sequence is:
   *   1. render
   *   2. commit (and call `onRender`, `onCommit`)
   *   3. check for nested updates
   *   4. flush passive effects (and call `onPostCommit`)
   *
   * Nested updates are identified in step 3 above,
   * but step 4 still applies to the work that was just committed.
   * We use two flags to track nested updates then:
   * one tracks whether the upcoming update is a nested update,
   * and the other tracks whether the current update was a nested update.
   * The first value gets synced to the second at the start of the render phase.
   */

  var currentUpdateIsNested = false;
  var nestedUpdateScheduled = false;

  function isCurrentUpdateNested() {
    return currentUpdateIsNested;
  }

  function markNestedUpdateScheduled() {
    {
      nestedUpdateScheduled = true;
    }
  }

  function resetNestedUpdateFlag() {
    {
      currentUpdateIsNested = false;
      nestedUpdateScheduled = false;
    }
  }

  function syncNestedUpdateFlag() {
    {
      currentUpdateIsNested = nestedUpdateScheduled;
      nestedUpdateScheduled = false;
    }
  }

  function getCommitTime() {
    return commitTime;
  }

  function recordCommitTime() {

    commitTime = now$1();
  }

  function startProfilerTimer(fiber) {

    profilerStartTime = now$1();

    if (fiber.actualStartTime < 0) {
      fiber.actualStartTime = now$1();
    }
  }

  function stopProfilerTimerIfRunning(fiber) {

    profilerStartTime = -1;
  }

  function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {

    if (profilerStartTime >= 0) {
      var elapsedTime = now$1() - profilerStartTime;
      fiber.actualDuration += elapsedTime;

      if (overrideBaseTime) {
        fiber.selfBaseDuration = elapsedTime;
      }

      profilerStartTime = -1;
    }
  }

  function recordLayoutEffectDuration(fiber) {

    if (layoutEffectStartTime >= 0) {
      var elapsedTime = now$1() - layoutEffectStartTime;
      layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
      // Or the root (for the DevTools Profiler to read)

      var parentFiber = fiber.return;

      while (parentFiber !== null) {
        switch (parentFiber.tag) {
          case HostRoot:
            var root = parentFiber.stateNode;
            root.effectDuration += elapsedTime;
            return;

          case Profiler:
            var parentStateNode = parentFiber.stateNode;
            parentStateNode.effectDuration += elapsedTime;
            return;
        }

        parentFiber = parentFiber.return;
      }
    }
  }

  function recordPassiveEffectDuration(fiber) {

    if (passiveEffectStartTime >= 0) {
      var elapsedTime = now$1() - passiveEffectStartTime;
      passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
      // Or the root (for the DevTools Profiler to read)

      var parentFiber = fiber.return;

      while (parentFiber !== null) {
        switch (parentFiber.tag) {
          case HostRoot:
            var root = parentFiber.stateNode;

            if (root !== null) {
              root.passiveEffectDuration += elapsedTime;
            }

            return;

          case Profiler:
            var parentStateNode = parentFiber.stateNode;

            if (parentStateNode !== null) {
              // Detached fibers have their state node cleared out.
              // In this case, the return pointer is also cleared out,
              // so we won't be able to report the time spent in this Profiler's subtree.
              parentStateNode.passiveEffectDuration += elapsedTime;
            }

            return;
        }

        parentFiber = parentFiber.return;
      }
    }
  }

  function startLayoutEffectTimer() {

    layoutEffectStartTime = now$1();
  }

  function startPassiveEffectTimer() {

    passiveEffectStartTime = now$1();
  }

  function transferActualDuration(fiber) {
    // Transfer time spent rendering these children so we don't lose it
    // after we rerender. This is used as a helper in special cases
    // where we should count the work of multiple passes.
    var child = fiber.child;

    while (child) {
      fiber.actualDuration += child.actualDuration;
      child = child.sibling;
    }
  }

  function resolveDefaultProps(Component, baseProps) {
    if (Component && Component.defaultProps) {
      // Resolve default props. Taken from ReactElement
      var props = assign({}, baseProps);
      var defaultProps = Component.defaultProps;

      for (var propName in defaultProps) {
        if (props[propName] === undefined) {
          props[propName] = defaultProps[propName];
        }
      }

      return props;
    }

    return baseProps;
  }

  var fakeInternalInstance = {};
  var didWarnAboutStateAssignmentForComponent;
  var didWarnAboutUninitializedState;
  var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
  var didWarnAboutLegacyLifecyclesAndDerivedState;
  var didWarnAboutUndefinedDerivedState;
  var warnOnUndefinedDerivedState;
  var warnOnInvalidCallback;
  var didWarnAboutDirectlyAssigningPropsToState;
  var didWarnAboutContextTypeAndContextTypes;
  var didWarnAboutInvalidateContextType;
  var didWarnAboutLegacyContext$1;

  {
    didWarnAboutStateAssignmentForComponent = new Set();
    didWarnAboutUninitializedState = new Set();
    didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
    didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
    didWarnAboutDirectlyAssigningPropsToState = new Set();
    didWarnAboutUndefinedDerivedState = new Set();
    didWarnAboutContextTypeAndContextTypes = new Set();
    didWarnAboutInvalidateContextType = new Set();
    didWarnAboutLegacyContext$1 = new Set();
    var didWarnOnInvalidCallback = new Set();

    warnOnInvalidCallback = function (callback, callerName) {
      if (callback === null || typeof callback === 'function') {
        return;
      }

      var key = callerName + '_' + callback;

      if (!didWarnOnInvalidCallback.has(key)) {
        didWarnOnInvalidCallback.add(key);

        error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
      }
    };

    warnOnUndefinedDerivedState = function (type, partialState) {
      if (partialState === undefined) {
        var componentName = getComponentNameFromType(type) || 'Component';

        if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
          didWarnAboutUndefinedDerivedState.add(componentName);

          error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
        }
      }
    }; // This is so gross but it's at least non-critical and can be removed if
    // it causes problems. This is meant to give a nicer error message for
    // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
    // ...)) which otherwise throws a "_processChildContext is not a function"
    // exception.


    Object.defineProperty(fakeInternalInstance, '_processChildContext', {
      enumerable: false,
      value: function () {
        throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).');
      }
    });
    Object.freeze(fakeInternalInstance);
  }

  function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
    var prevState = workInProgress.memoizedState;
    var partialState = getDerivedStateFromProps(nextProps, prevState);

    {
      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          // Invoke the function an extra time to help detect side-effects.
          partialState = getDerivedStateFromProps(nextProps, prevState);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }

      warnOnUndefinedDerivedState(ctor, partialState);
    } // Merge the partial state and the previous state.


    var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
    workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
    // base state.

    if (workInProgress.lanes === NoLanes) {
      // Queue is always non-null for classes
      var updateQueue = workInProgress.updateQueue;
      updateQueue.baseState = memoizedState;
    }
  }

  var classComponentUpdater = {
    isMounted: isMounted,
    enqueueSetState: function (inst, payload, callback) {
      var fiber = get(inst);
      var eventTime = requestEventTime();
      var lane = requestUpdateLane(fiber);
      var update = createUpdate(eventTime, lane);
      update.payload = payload;

      if (callback !== undefined && callback !== null) {
        {
          warnOnInvalidCallback(callback, 'setState');
        }

        update.callback = callback;
      }

      var root = enqueueUpdate(fiber, update, lane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, lane, eventTime);
        entangleTransitions(root, fiber, lane);
      }

      {
        markStateUpdateScheduled(fiber, lane);
      }
    },
    enqueueReplaceState: function (inst, payload, callback) {
      var fiber = get(inst);
      var eventTime = requestEventTime();
      var lane = requestUpdateLane(fiber);
      var update = createUpdate(eventTime, lane);
      update.tag = ReplaceState;
      update.payload = payload;

      if (callback !== undefined && callback !== null) {
        {
          warnOnInvalidCallback(callback, 'replaceState');
        }

        update.callback = callback;
      }

      var root = enqueueUpdate(fiber, update, lane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, lane, eventTime);
        entangleTransitions(root, fiber, lane);
      }

      {
        markStateUpdateScheduled(fiber, lane);
      }
    },
    enqueueForceUpdate: function (inst, callback) {
      var fiber = get(inst);
      var eventTime = requestEventTime();
      var lane = requestUpdateLane(fiber);
      var update = createUpdate(eventTime, lane);
      update.tag = ForceUpdate;

      if (callback !== undefined && callback !== null) {
        {
          warnOnInvalidCallback(callback, 'forceUpdate');
        }

        update.callback = callback;
      }

      var root = enqueueUpdate(fiber, update, lane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, lane, eventTime);
        entangleTransitions(root, fiber, lane);
      }

      {
        markForceUpdateScheduled(fiber, lane);
      }
    }
  };

  function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
    var instance = workInProgress.stateNode;

    if (typeof instance.shouldComponentUpdate === 'function') {
      var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);

      {
        if ( workInProgress.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);

          try {
            // Invoke the function an extra time to help detect side-effects.
            shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }

        if (shouldUpdate === undefined) {
          error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component');
        }
      }

      return shouldUpdate;
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent) {
      return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
    }

    return true;
  }

  function checkClassInstance(workInProgress, ctor, newProps) {
    var instance = workInProgress.stateNode;

    {
      var name = getComponentNameFromType(ctor) || 'Component';
      var renderPresent = instance.render;

      if (!renderPresent) {
        if (ctor.prototype && typeof ctor.prototype.render === 'function') {
          error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
        } else {
          error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
        }
      }

      if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
        error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
      }

      if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
        error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
      }

      if (instance.propTypes) {
        error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
      }

      if (instance.contextType) {
        error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
      }

      {
        if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
        // this one.
        (workInProgress.mode & StrictLegacyMode) === NoMode) {
          didWarnAboutLegacyContext$1.add(ctor);

          error('%s uses the legacy childContextTypes API which is no longer ' + 'supported and will be removed in the next major release. Use ' + 'React.createContext() instead\n\n.' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
        }

        if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
        // this one.
        (workInProgress.mode & StrictLegacyMode) === NoMode) {
          didWarnAboutLegacyContext$1.add(ctor);

          error('%s uses the legacy contextTypes API which is no longer supported ' + 'and will be removed in the next major release. Use ' + 'React.createContext() with static contextType instead.\n\n' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
        }

        if (instance.contextTypes) {
          error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
        }

        if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
          didWarnAboutContextTypeAndContextTypes.add(ctor);

          error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
        }
      }

      if (typeof instance.componentShouldUpdate === 'function') {
        error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
      }

      if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
        error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
      }

      if (typeof instance.componentDidUnmount === 'function') {
        error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
      }

      if (typeof instance.componentDidReceiveProps === 'function') {
        error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
      }

      if (typeof instance.componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
      }

      if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
        error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
      }

      var hasMutatedProps = instance.props !== newProps;

      if (instance.props !== undefined && hasMutatedProps) {
        error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
      }

      if (instance.defaultProps) {
        error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
        didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

        error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
      }

      if (typeof instance.getDerivedStateFromProps === 'function') {
        error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof instance.getDerivedStateFromError === 'function') {
        error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
      }

      if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
        error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
      }

      var _state = instance.state;

      if (_state && (typeof _state !== 'object' || isArray(_state))) {
        error('%s.state: must be set to an object or null', name);
      }

      if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
        error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
      }
    }
  }

  function adoptClassInstance(workInProgress, instance) {
    instance.updater = classComponentUpdater;
    workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates

    set(instance, workInProgress);

    {
      instance._reactInternalInstance = fakeInternalInstance;
    }
  }

  function constructClassInstance(workInProgress, ctor, props) {
    var isLegacyContextConsumer = false;
    var unmaskedContext = emptyContextObject;
    var context = emptyContextObject;
    var contextType = ctor.contextType;

    {
      if ('contextType' in ctor) {
        var isValid = // Allow null for conditional declaration
        contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

        if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
          didWarnAboutInvalidateContextType.add(ctor);
          var addendum = '';

          if (contextType === undefined) {
            addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
          } else if (typeof contextType !== 'object') {
            addendum = ' However, it is set to a ' + typeof contextType + '.';
          } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
            addendum = ' Did you accidentally pass the Context.Provider instead?';
          } else if (contextType._context !== undefined) {
            // <Context.Consumer>
            addendum = ' Did you accidentally pass the Context.Consumer instead?';
          } else {
            addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
          }

          error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
        }
      }
    }

    if (typeof contextType === 'object' && contextType !== null) {
      context = readContext(contextType);
    } else {
      unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
      var contextTypes = ctor.contextTypes;
      isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
      context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
    }

    var instance = new ctor(props, context); // Instantiate twice to help detect side-effects.

    {
      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          instance = new ctor(props, context); // eslint-disable-line no-new
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
    }

    var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
    adoptClassInstance(workInProgress, instance);

    {
      if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutUninitializedState.has(componentName)) {
          didWarnAboutUninitializedState.add(componentName);

          error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
        }
      } // If new component APIs are defined, "unsafe" lifecycles won't be called.
      // Warn about these lifecycles if they are present.
      // Don't warn about react-lifecycles-compat polyfilled methods though.


      if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
        var foundWillMountName = null;
        var foundWillReceivePropsName = null;
        var foundWillUpdateName = null;

        if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
          foundWillMountName = 'componentWillMount';
        } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
          foundWillMountName = 'UNSAFE_componentWillMount';
        }

        if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
          foundWillReceivePropsName = 'componentWillReceiveProps';
        } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
          foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
        }

        if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
          foundWillUpdateName = 'componentWillUpdate';
        } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
          foundWillUpdateName = 'UNSAFE_componentWillUpdate';
        }

        if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
          var _componentName = getComponentNameFromType(ctor) || 'Component';

          var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

          if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
            didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

            error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
          }
        }
      }
    } // Cache unmasked context so we can avoid recreating masked context unless necessary.
    // ReactFiberContext usually updates this cache but can't for newly-created instances.


    if (isLegacyContextConsumer) {
      cacheContext(workInProgress, unmaskedContext, context);
    }

    return instance;
  }

  function callComponentWillMount(workInProgress, instance) {
    var oldState = instance.state;

    if (typeof instance.componentWillMount === 'function') {
      instance.componentWillMount();
    }

    if (typeof instance.UNSAFE_componentWillMount === 'function') {
      instance.UNSAFE_componentWillMount();
    }

    if (oldState !== instance.state) {
      {
        error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component');
      }

      classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
    }
  }

  function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
    var oldState = instance.state;

    if (typeof instance.componentWillReceiveProps === 'function') {
      instance.componentWillReceiveProps(newProps, nextContext);
    }

    if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
      instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
    }

    if (instance.state !== oldState) {
      {
        var componentName = getComponentNameFromFiber(workInProgress) || 'Component';

        if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
          didWarnAboutStateAssignmentForComponent.add(componentName);

          error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
        }
      }

      classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
    }
  } // Invokes the mount life-cycles on a previously never rendered instance.


  function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
    {
      checkClassInstance(workInProgress, ctor, newProps);
    }

    var instance = workInProgress.stateNode;
    instance.props = newProps;
    instance.state = workInProgress.memoizedState;
    instance.refs = {};
    initializeUpdateQueue(workInProgress);
    var contextType = ctor.contextType;

    if (typeof contextType === 'object' && contextType !== null) {
      instance.context = readContext(contextType);
    } else {
      var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
      instance.context = getMaskedContext(workInProgress, unmaskedContext);
    }

    {
      if (instance.state === newProps) {
        var componentName = getComponentNameFromType(ctor) || 'Component';

        if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
          didWarnAboutDirectlyAssigningPropsToState.add(componentName);

          error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
        }
      }

      if (workInProgress.mode & StrictLegacyMode) {
        ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
      }

      {
        ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
      }
    }

    instance.state = workInProgress.memoizedState;
    var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

    if (typeof getDerivedStateFromProps === 'function') {
      applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
      instance.state = workInProgress.memoizedState;
    } // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.


    if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
      callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
      // process them now.

      processUpdateQueue(workInProgress, newProps, instance, renderLanes);
      instance.state = workInProgress.memoizedState;
    }

    if (typeof instance.componentDidMount === 'function') {
      var fiberFlags = Update;

      {
        fiberFlags |= LayoutStatic;
      }

      if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
        fiberFlags |= MountLayoutDev;
      }

      workInProgress.flags |= fiberFlags;
    }
  }

  function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
    var instance = workInProgress.stateNode;
    var oldProps = workInProgress.memoizedProps;
    instance.props = oldProps;
    var oldContext = instance.context;
    var contextType = ctor.contextType;
    var nextContext = emptyContextObject;

    if (typeof contextType === 'object' && contextType !== null) {
      nextContext = readContext(contextType);
    } else {
      var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
      nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
    }

    var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
    var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
    // ever the previously attempted to render - not the "current". However,
    // during componentDidUpdate we pass the "current" props.
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.

    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
      if (oldProps !== newProps || oldContext !== nextContext) {
        callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
      }
    }

    resetHasForceUpdateBeforeProcessing();
    var oldState = workInProgress.memoizedState;
    var newState = instance.state = oldState;
    processUpdateQueue(workInProgress, newProps, instance, renderLanes);
    newState = workInProgress.memoizedState;

    if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
      // If an update was already in progress, we should schedule an Update
      // effect even though we're bailing out, so that cWU/cDU are called.
      if (typeof instance.componentDidMount === 'function') {
        var fiberFlags = Update;

        {
          fiberFlags |= LayoutStatic;
        }

        if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
          fiberFlags |= MountLayoutDev;
        }

        workInProgress.flags |= fiberFlags;
      }

      return false;
    }

    if (typeof getDerivedStateFromProps === 'function') {
      applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
      newState = workInProgress.memoizedState;
    }

    var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);

    if (shouldUpdate) {
      // In order to support react-lifecycles-compat polyfilled components,
      // Unsafe lifecycles should not be invoked for components using the new APIs.
      if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
        if (typeof instance.componentWillMount === 'function') {
          instance.componentWillMount();
        }

        if (typeof instance.UNSAFE_componentWillMount === 'function') {
          instance.UNSAFE_componentWillMount();
        }
      }

      if (typeof instance.componentDidMount === 'function') {
        var _fiberFlags = Update;

        {
          _fiberFlags |= LayoutStatic;
        }

        if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
          _fiberFlags |= MountLayoutDev;
        }

        workInProgress.flags |= _fiberFlags;
      }
    } else {
      // If an update was already in progress, we should schedule an Update
      // effect even though we're bailing out, so that cWU/cDU are called.
      if (typeof instance.componentDidMount === 'function') {
        var _fiberFlags2 = Update;

        {
          _fiberFlags2 |= LayoutStatic;
        }

        if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
          _fiberFlags2 |= MountLayoutDev;
        }

        workInProgress.flags |= _fiberFlags2;
      } // If shouldComponentUpdate returned false, we should still update the
      // memoized state to indicate that this work can be reused.


      workInProgress.memoizedProps = newProps;
      workInProgress.memoizedState = newState;
    } // Update the existing instance's state, props, and context pointers even
    // if shouldComponentUpdate returns false.


    instance.props = newProps;
    instance.state = newState;
    instance.context = nextContext;
    return shouldUpdate;
  } // Invokes the update life-cycles and returns false if it shouldn't rerender.


  function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
    var instance = workInProgress.stateNode;
    cloneUpdateQueue(current, workInProgress);
    var unresolvedOldProps = workInProgress.memoizedProps;
    var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
    instance.props = oldProps;
    var unresolvedNewProps = workInProgress.pendingProps;
    var oldContext = instance.context;
    var contextType = ctor.contextType;
    var nextContext = emptyContextObject;

    if (typeof contextType === 'object' && contextType !== null) {
      nextContext = readContext(contextType);
    } else {
      var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
      nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
    }

    var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
    var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
    // ever the previously attempted to render - not the "current". However,
    // during componentDidUpdate we pass the "current" props.
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.

    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
      if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
        callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
      }
    }

    resetHasForceUpdateBeforeProcessing();
    var oldState = workInProgress.memoizedState;
    var newState = instance.state = oldState;
    processUpdateQueue(workInProgress, newProps, instance, renderLanes);
    newState = workInProgress.memoizedState;

    if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation   )) {
      // If an update was already in progress, we should schedule an Update
      // effect even though we're bailing out, so that cWU/cDU are called.
      if (typeof instance.componentDidUpdate === 'function') {
        if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
          workInProgress.flags |= Update;
        }
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function') {
        if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
          workInProgress.flags |= Snapshot;
        }
      }

      return false;
    }

    if (typeof getDerivedStateFromProps === 'function') {
      applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
      newState = workInProgress.memoizedState;
    }

    var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
    // both before and after `shouldComponentUpdate` has been called. Not ideal,
    // but I'm loath to refactor this function. This only happens for memoized
    // components so it's not that common.
    enableLazyContextPropagation   ;

    if (shouldUpdate) {
      // In order to support react-lifecycles-compat polyfilled components,
      // Unsafe lifecycles should not be invoked for components using the new APIs.
      if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
        if (typeof instance.componentWillUpdate === 'function') {
          instance.componentWillUpdate(newProps, newState, nextContext);
        }

        if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
          instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
        }
      }

      if (typeof instance.componentDidUpdate === 'function') {
        workInProgress.flags |= Update;
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function') {
        workInProgress.flags |= Snapshot;
      }
    } else {
      // If an update was already in progress, we should schedule an Update
      // effect even though we're bailing out, so that cWU/cDU are called.
      if (typeof instance.componentDidUpdate === 'function') {
        if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
          workInProgress.flags |= Update;
        }
      }

      if (typeof instance.getSnapshotBeforeUpdate === 'function') {
        if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
          workInProgress.flags |= Snapshot;
        }
      } // If shouldComponentUpdate returned false, we should still update the
      // memoized props/state to indicate that this work can be reused.


      workInProgress.memoizedProps = newProps;
      workInProgress.memoizedState = newState;
    } // Update the existing instance's state, props, and context pointers even
    // if shouldComponentUpdate returns false.


    instance.props = newProps;
    instance.state = newState;
    instance.context = nextContext;
    return shouldUpdate;
  }

  function createCapturedValueAtFiber(value, source) {
    // If the value is an error, call this function immediately after it is thrown
    // so the stack is accurate.
    return {
      value: value,
      source: source,
      stack: getStackByFiberInDevAndProd(source),
      digest: null
    };
  }
  function createCapturedValue(value, digest, stack) {
    return {
      value: value,
      source: null,
      stack: stack != null ? stack : null,
      digest: digest != null ? digest : null
    };
  }

  // This module is forked in different environments.
  // By default, return `true` to log errors to the console.
  // Forks can return `false` if this isn't desirable.
  function showErrorDialog(boundary, errorInfo) {
    return true;
  }

  function logCapturedError(boundary, errorInfo) {
    try {
      var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
      // This enables renderers like ReactNative to better manage redbox behavior.

      if (logError === false) {
        return;
      }

      var error = errorInfo.value;

      if (true) {
        var source = errorInfo.source;
        var stack = errorInfo.stack;
        var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
        // `preventDefault()` in window `error` handler.
        // We record this information as an expando on the error.

        if (error != null && error._suppressLogging) {
          if (boundary.tag === ClassComponent) {
            // The error is recoverable and was silenced.
            // Ignore it and don't print the stack addendum.
            // This is handy for testing error boundaries without noise.
            return;
          } // The error is fatal. Since the silencing might have
          // been accidental, we'll surface it anyway.
          // However, the browser would have silenced the original error
          // so we'll print it first, and then print the stack addendum.


          console['error'](error); // Don't transform to our wrapper
          // For a more detailed description of this block, see:
          // https://github.com/facebook/react/pull/13384
        }

        var componentName = source ? getComponentNameFromFiber(source) : null;
        var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
        var errorBoundaryMessage;

        if (boundary.tag === HostRoot) {
          errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';
        } else {
          var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous';
          errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
        }

        var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
        // We don't include the original error message and JS stack because the browser
        // has already printed it. Even if the application swallows the error, it is still
        // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.

        console['error'](combinedMessage); // Don't transform to our wrapper
      } else {
        // In production, we print the error directly.
        // This will include the message, the JS stack, and anything the browser wants to show.
        // We pass the error object instead of custom message so that the browser displays the error natively.
        console['error'](error); // Don't transform to our wrapper
      }
    } catch (e) {
      // This method must not throw, or React internal state will get messed up.
      // If console.error is overridden, or logCapturedError() shows a dialog that throws,
      // we want to report this error outside of the normal stack as a last resort.
      // https://github.com/facebook/react/issues/13188
      setTimeout(function () {
        throw e;
      });
    }
  }

  var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;

  function createRootErrorUpdate(fiber, errorInfo, lane) {
    var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.

    update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
    // being called "element".

    update.payload = {
      element: null
    };
    var error = errorInfo.value;

    update.callback = function () {
      onUncaughtError(error);
      logCapturedError(fiber, errorInfo);
    };

    return update;
  }

  function createClassErrorUpdate(fiber, errorInfo, lane) {
    var update = createUpdate(NoTimestamp, lane);
    update.tag = CaptureUpdate;
    var getDerivedStateFromError = fiber.type.getDerivedStateFromError;

    if (typeof getDerivedStateFromError === 'function') {
      var error$1 = errorInfo.value;

      update.payload = function () {
        return getDerivedStateFromError(error$1);
      };

      update.callback = function () {
        {
          markFailedErrorBoundaryForHotReloading(fiber);
        }

        logCapturedError(fiber, errorInfo);
      };
    }

    var inst = fiber.stateNode;

    if (inst !== null && typeof inst.componentDidCatch === 'function') {
      update.callback = function callback() {
        {
          markFailedErrorBoundaryForHotReloading(fiber);
        }

        logCapturedError(fiber, errorInfo);

        if (typeof getDerivedStateFromError !== 'function') {
          // To preserve the preexisting retry behavior of error boundaries,
          // we keep track of which ones already failed during this batch.
          // This gets reset before we yield back to the browser.
          // TODO: Warn in strict mode if getDerivedStateFromError is
          // not defined.
          markLegacyErrorBoundaryAsFailed(this);
        }

        var error$1 = errorInfo.value;
        var stack = errorInfo.stack;
        this.componentDidCatch(error$1, {
          componentStack: stack !== null ? stack : ''
        });

        {
          if (typeof getDerivedStateFromError !== 'function') {
            // If componentDidCatch is the only error boundary method defined,
            // then it needs to call setState to recover from errors.
            // If no state update is scheduled then the boundary will swallow the error.
            if (!includesSomeLane(fiber.lanes, SyncLane)) {
              error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown');
            }
          }
        }
      };
    }

    return update;
  }

  function attachPingListener(root, wakeable, lanes) {
    // Attach a ping listener
    //
    // The data might resolve before we have a chance to commit the fallback. Or,
    // in the case of a refresh, we'll never commit a fallback. So we need to
    // attach a listener now. When it resolves ("pings"), we can decide whether to
    // try rendering the tree again.
    //
    // Only attach a listener if one does not already exist for the lanes
    // we're currently rendering (which acts like a "thread ID" here).
    //
    // We only need to do this in concurrent mode. Legacy Suspense always
    // commits fallbacks synchronously, so there are no pings.
    var pingCache = root.pingCache;
    var threadIDs;

    if (pingCache === null) {
      pingCache = root.pingCache = new PossiblyWeakMap$1();
      threadIDs = new Set();
      pingCache.set(wakeable, threadIDs);
    } else {
      threadIDs = pingCache.get(wakeable);

      if (threadIDs === undefined) {
        threadIDs = new Set();
        pingCache.set(wakeable, threadIDs);
      }
    }

    if (!threadIDs.has(lanes)) {
      // Memoize using the thread ID to prevent redundant listeners.
      threadIDs.add(lanes);
      var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);

      {
        if (isDevToolsPresent) {
          // If we have pending work still, restore the original updaters
          restorePendingUpdaters(root, lanes);
        }
      }

      wakeable.then(ping, ping);
    }
  }

  function attachRetryListener(suspenseBoundary, root, wakeable, lanes) {
    // Retry listener
    //
    // If the fallback does commit, we need to attach a different type of
    // listener. This one schedules an update on the Suspense boundary to turn
    // the fallback state off.
    //
    // Stash the wakeable on the boundary fiber so we can access it in the
    // commit phase.
    //
    // When the wakeable resolves, we'll attempt to render the boundary
    // again ("retry").
    var wakeables = suspenseBoundary.updateQueue;

    if (wakeables === null) {
      var updateQueue = new Set();
      updateQueue.add(wakeable);
      suspenseBoundary.updateQueue = updateQueue;
    } else {
      wakeables.add(wakeable);
    }
  }

  function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
    // A legacy mode Suspense quirk, only relevant to hook components.


    var tag = sourceFiber.tag;

    if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
      var currentSource = sourceFiber.alternate;

      if (currentSource) {
        sourceFiber.updateQueue = currentSource.updateQueue;
        sourceFiber.memoizedState = currentSource.memoizedState;
        sourceFiber.lanes = currentSource.lanes;
      } else {
        sourceFiber.updateQueue = null;
        sourceFiber.memoizedState = null;
      }
    }
  }

  function getNearestSuspenseBoundaryToCapture(returnFiber) {
    var node = returnFiber;

    do {
      if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) {
        return node;
      } // This boundary already captured during this render. Continue to the next
      // boundary.


      node = node.return;
    } while (node !== null);

    return null;
  }

  function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) {
    // This marks a Suspense boundary so that when we're unwinding the stack,
    // it captures the suspended "exception" and does a second (fallback) pass.
    if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
      // Legacy Mode Suspense
      //
      // If the boundary is in legacy mode, we should *not*
      // suspend the commit. Pretend as if the suspended component rendered
      // null and keep rendering. When the Suspense boundary completes,
      // we'll do a second pass to render the fallback.
      if (suspenseBoundary === returnFiber) {
        // Special case where we suspended while reconciling the children of
        // a Suspense boundary's inner Offscreen wrapper fiber. This happens
        // when a React.lazy component is a direct child of a
        // Suspense boundary.
        //
        // Suspense boundaries are implemented as multiple fibers, but they
        // are a single conceptual unit. The legacy mode behavior where we
        // pretend the suspended fiber committed as `null` won't work,
        // because in this case the "suspended" fiber is the inner
        // Offscreen wrapper.
        //
        // Because the contents of the boundary haven't started rendering
        // yet (i.e. nothing in the tree has partially rendered) we can
        // switch to the regular, concurrent mode behavior: mark the
        // boundary with ShouldCapture and enter the unwind phase.
        suspenseBoundary.flags |= ShouldCapture;
      } else {
        suspenseBoundary.flags |= DidCapture;
        sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
        // But we shouldn't call any lifecycle methods or callbacks. Remove
        // all lifecycle effect tags.

        sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);

        if (sourceFiber.tag === ClassComponent) {
          var currentSourceFiber = sourceFiber.alternate;

          if (currentSourceFiber === null) {
            // This is a new mount. Change the tag so it's not mistaken for a
            // completed class component. For example, we should not call
            // componentWillUnmount if it is deleted.
            sourceFiber.tag = IncompleteClassComponent;
          } else {
            // When we try rendering again, we should not reuse the current fiber,
            // since it's known to be in an inconsistent state. Use a force update to
            // prevent a bail out.
            var update = createUpdate(NoTimestamp, SyncLane);
            update.tag = ForceUpdate;
            enqueueUpdate(sourceFiber, update, SyncLane);
          }
        } // The source fiber did not complete. Mark it with Sync priority to
        // indicate that it still has pending work.


        sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
      }

      return suspenseBoundary;
    } // Confirmed that the boundary is in a concurrent mode tree. Continue
    // with the normal suspend path.
    //
    // After this we'll use a set of heuristics to determine whether this
    // render pass will run to completion or restart or "suspend" the commit.
    // The actual logic for this is spread out in different places.
    //
    // This first principle is that if we're going to suspend when we complete
    // a root, then we should also restart if we get an update or ping that
    // might unsuspend it, and vice versa. The only reason to suspend is
    // because you think you might want to restart before committing. However,
    // it doesn't make sense to restart only while in the period we're suspended.
    //
    // Restarting too aggressively is also not good because it starves out any
    // intermediate loading state. So we use heuristics to determine when.
    // Suspense Heuristics
    //
    // If nothing threw a Promise or all the same fallbacks are already showing,
    // then don't suspend/restart.
    //
    // If this is an initial render of a new tree of Suspense boundaries and
    // those trigger a fallback, then don't suspend/restart. We want to ensure
    // that we can show the initial loading state as quickly as possible.
    //
    // If we hit a "Delayed" case, such as when we'd switch from content back into
    // a fallback, then we should always suspend/restart. Transitions apply
    // to this case. If none is defined, JND is used instead.
    //
    // If we're already showing a fallback and it gets "retried", allowing us to show
    // another level, but there's still an inner boundary that would show a fallback,
    // then we suspend/restart for 500ms since the last time we showed a fallback
    // anywhere in the tree. This effectively throttles progressive loading into a
    // consistent train of commits. This also gives us an opportunity to restart to
    // get to the completed state slightly earlier.
    //
    // If there's ambiguity due to batching it's resolved in preference of:
    // 1) "delayed", 2) "initial render", 3) "retry".
    //
    // We want to ensure that a "busy" state doesn't get force committed. We want to
    // ensure that new initial loading states can commit as soon as possible.


    suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in
    // the begin phase to prevent an early bailout.

    suspenseBoundary.lanes = rootRenderLanes;
    return suspenseBoundary;
  }

  function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
    // The source fiber did not complete.
    sourceFiber.flags |= Incomplete;

    {
      if (isDevToolsPresent) {
        // If we have pending work still, restore the original updaters
        restorePendingUpdaters(root, rootRenderLanes);
      }
    }

    if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
      // This is a wakeable. The component suspended.
      var wakeable = value;
      resetSuspendedComponent(sourceFiber);

      {
        if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
          markDidThrowWhileHydratingDEV();
        }
      }


      var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);

      if (suspenseBoundary !== null) {
        suspenseBoundary.flags &= ~ForceClientRender;
        markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always
        // commits fallbacks synchronously, so there are no pings.

        if (suspenseBoundary.mode & ConcurrentMode) {
          attachPingListener(root, wakeable, rootRenderLanes);
        }

        attachRetryListener(suspenseBoundary, root, wakeable);
        return;
      } else {
        // No boundary was found. Unless this is a sync update, this is OK.
        // We can suspend and wait for more data to arrive.
        if (!includesSyncLane(rootRenderLanes)) {
          // This is not a sync update. Suspend. Since we're not activating a
          // Suspense boundary, this will unwind all the way to the root without
          // performing a second pass to render a fallback. (This is arguably how
          // refresh transitions should work, too, since we're not going to commit
          // the fallbacks anyway.)
          //
          // This case also applies to initial hydration.
          attachPingListener(root, wakeable, rootRenderLanes);
          renderDidSuspendDelayIfPossible();
          return;
        } // This is a sync/discrete update. We treat this case like an error
        // because discrete renders are expected to produce a complete tree
        // synchronously to maintain consistency with external state.


        var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path.
        // The error will be caught by the nearest suspense boundary.

        value = uncaughtSuspenseError;
      }
    } else {
      // This is a regular error, not a Suspense wakeable.
      if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
        markDidThrowWhileHydratingDEV();

        var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by
        // discarding the dehydrated content and switching to a client render.
        // Instead of surfacing the error, find the nearest Suspense boundary
        // and render it again without hydration.


        if (_suspenseBoundary !== null) {
          if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
            // Set a flag to indicate that we should try rendering the normal
            // children again, not the fallback.
            _suspenseBoundary.flags |= ForceClientRender;
          }

          markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should
          // still log it so it can be fixed.

          queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
          return;
        }
      }
    }

    value = createCapturedValueAtFiber(value, sourceFiber);
    renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start
    // over and traverse parent path again, this time treating the exception
    // as an error.

    var workInProgress = returnFiber;

    do {
      switch (workInProgress.tag) {
        case HostRoot:
          {
            var _errorInfo = value;
            workInProgress.flags |= ShouldCapture;
            var lane = pickArbitraryLane(rootRenderLanes);
            workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
            var update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
            enqueueCapturedUpdate(workInProgress, update);
            return;
          }

        case ClassComponent:
          // Capture and retry
          var errorInfo = value;
          var ctor = workInProgress.type;
          var instance = workInProgress.stateNode;

          if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
            workInProgress.flags |= ShouldCapture;

            var _lane = pickArbitraryLane(rootRenderLanes);

            workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state

            var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane);

            enqueueCapturedUpdate(workInProgress, _update);
            return;
          }

          break;
      }

      workInProgress = workInProgress.return;
    } while (workInProgress !== null);
  }

  function getSuspendedCache() {
    {
      return null;
    } // This function is called when a Suspense boundary suspends. It returns the
  }

  var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
  var didReceiveUpdate = false;
  var didWarnAboutBadClass;
  var didWarnAboutModulePatternComponent;
  var didWarnAboutContextTypeOnFunctionComponent;
  var didWarnAboutGetDerivedStateOnFunctionComponent;
  var didWarnAboutFunctionRefs;
  var didWarnAboutReassigningProps;
  var didWarnAboutRevealOrder;
  var didWarnAboutTailOptions;
  var didWarnAboutDefaultPropsOnFunctionComponent;

  {
    didWarnAboutBadClass = {};
    didWarnAboutModulePatternComponent = {};
    didWarnAboutContextTypeOnFunctionComponent = {};
    didWarnAboutGetDerivedStateOnFunctionComponent = {};
    didWarnAboutFunctionRefs = {};
    didWarnAboutReassigningProps = false;
    didWarnAboutRevealOrder = {};
    didWarnAboutTailOptions = {};
    didWarnAboutDefaultPropsOnFunctionComponent = {};
  }

  function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
    if (current === null) {
      // If this is a fresh new component that hasn't been rendered yet, we
      // won't update its child set by applying minimal side-effects. Instead,
      // we will add them all to the child before it gets rendered. That means
      // we can optimize this reconciliation pass by not tracking side-effects.
      workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
    } else {
      // If the current child is the same as the work in progress, it means that
      // we haven't yet started any work on these children. Therefore, we use
      // the clone algorithm to create a copy of all the current children.
      // If we had any progressed work already, that is invalid at this point so
      // let's throw it out.
      workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
    }
  }

  function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
    // This function is fork of reconcileChildren. It's used in cases where we
    // want to reconcile without matching against the existing set. This has the
    // effect of all current children being unmounted; even if the type and key
    // are the same, the old child is unmounted and a new child is created.
    //
    // To do this, we're going to go through the reconcile algorithm twice. In
    // the first pass, we schedule a deletion for all the current children by
    // passing null.
    workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
    // pass null in place of where we usually pass the current child set. This has
    // the effect of remounting all children regardless of whether their
    // identities match.

    workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
  }

  function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
    // TODO: current can be non-null here even if the component
    // hasn't yet mounted. This happens after the first render suspends.
    // We'll need to figure out if this is fine or can cause issues.
    {
      if (workInProgress.type !== workInProgress.elementType) {
        // Lazy component props can't be validated in createElement
        // because they're only guaranteed to be resolved here.
        var innerPropTypes = Component.propTypes;

        if (innerPropTypes) {
          checkPropTypes(innerPropTypes, nextProps, // Resolved props
          'prop', getComponentNameFromType(Component));
        }
      }
    }

    var render = Component.render;
    var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent

    var nextChildren;
    var hasId;
    prepareToReadContext(workInProgress, renderLanes);

    {
      markComponentRenderStarted(workInProgress);
    }

    {
      ReactCurrentOwner$1.current = workInProgress;
      setIsRendering(true);
      nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
      hasId = checkDidRenderIdHook();

      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
          hasId = checkDidRenderIdHook();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }

      setIsRendering(false);
    }

    {
      markComponentRenderStopped();
    }

    if (current !== null && !didReceiveUpdate) {
      bailoutHooks(current, workInProgress, renderLanes);
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }

    if (getIsHydrating() && hasId) {
      pushMaterializedTreeId(workInProgress);
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
    if (current === null) {
      var type = Component.type;

      if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
      Component.defaultProps === undefined) {
        var resolvedType = type;

        {
          resolvedType = resolveFunctionForHotReloading(type);
        } // If this is a plain function component without default props,
        // and with only the default shallow comparison, we upgrade it
        // to a SimpleMemoComponent to allow fast path updates.


        workInProgress.tag = SimpleMemoComponent;
        workInProgress.type = resolvedType;

        {
          validateFunctionComponentInDev(workInProgress, type);
        }

        return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes);
      }

      {
        var innerPropTypes = type.propTypes;

        if (innerPropTypes) {
          // Inner memo component props aren't currently validated in createElement.
          // We could move it there, but we'd still need this for lazy code path.
          checkPropTypes(innerPropTypes, nextProps, // Resolved props
          'prop', getComponentNameFromType(type));
        }

        if ( Component.defaultProps !== undefined) {
          var componentName = getComponentNameFromType(type) || 'Unknown';

          if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
            error('%s: Support for defaultProps will be removed from memo components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

            didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
          }
        }
      }

      var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
      child.ref = workInProgress.ref;
      child.return = workInProgress;
      workInProgress.child = child;
      return child;
    }

    {
      var _type = Component.type;
      var _innerPropTypes = _type.propTypes;

      if (_innerPropTypes) {
        // Inner memo component props aren't currently validated in createElement.
        // We could move it there, but we'd still need this for lazy code path.
        checkPropTypes(_innerPropTypes, nextProps, // Resolved props
        'prop', getComponentNameFromType(_type));
      }
    }

    var currentChild = current.child; // This is always exactly one child

    var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);

    if (!hasScheduledUpdateOrContext) {
      // This will be the props with resolved defaultProps,
      // unlike current.memoizedProps which will be the unresolved ones.
      var prevProps = currentChild.memoizedProps; // Default to shallow comparison

      var compare = Component.compare;
      compare = compare !== null ? compare : shallowEqual;

      if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
      }
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;
    var newChild = createWorkInProgress(currentChild, nextProps);
    newChild.ref = workInProgress.ref;
    newChild.return = workInProgress;
    workInProgress.child = newChild;
    return newChild;
  }

  function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
    // TODO: current can be non-null here even if the component
    // hasn't yet mounted. This happens when the inner render suspends.
    // We'll need to figure out if this is fine or can cause issues.
    {
      if (workInProgress.type !== workInProgress.elementType) {
        // Lazy component props can't be validated in createElement
        // because they're only guaranteed to be resolved here.
        var outerMemoType = workInProgress.elementType;

        if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
          // We warn when you define propTypes on lazy()
          // so let's just skip over it to find memo() outer wrapper.
          // Inner props for memo are validated later.
          var lazyComponent = outerMemoType;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            outerMemoType = init(payload);
          } catch (x) {
            outerMemoType = null;
          } // Inner propTypes will be validated in the function component path.


          var outerPropTypes = outerMemoType && outerMemoType.propTypes;

          if (outerPropTypes) {
            checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
            'prop', getComponentNameFromType(outerMemoType));
          }
        }
      }
    }

    if (current !== null) {
      var prevProps = current.memoizedProps;

      if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
       workInProgress.type === current.type )) {
        didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we
        // would during a normal fiber bailout.
        //
        // We don't have strong guarantees that the props object is referentially
        // equal during updates where we can't bail out anyway â€” like if the props
        // are shallowly equal, but there's a local state or context update in the
        // same batch.
        //
        // However, as a principle, we should aim to make the behavior consistent
        // across different ways of memoizing a component. For example, React.memo
        // has a different internal Fiber layout if you pass a normal function
        // component (SimpleMemoComponent) versus if you pass a different type
        // like forwardRef (MemoComponent). But this is an implementation detail.
        // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
        // affect whether the props object is reused during a bailout.

        workInProgress.pendingProps = nextProps = prevProps;

        if (!checkScheduledUpdateOrContext(current, renderLanes)) {
          // The pending lanes were cleared at the beginning of beginWork. We're
          // about to bail out, but there might be other lanes that weren't
          // included in the current render. Usually, the priority level of the
          // remaining updates is accumulated during the evaluation of the
          // component (i.e. when processing the update queue). But since since
          // we're bailing out early *without* evaluating the component, we need
          // to account for it here, too. Reset to the value of the current fiber.
          // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
          // because a MemoComponent fiber does not have hooks or an update queue;
          // rather, it wraps around an inner component, which may or may not
          // contains hooks.
          // TODO: Move the reset at in beginWork out of the common path so that
          // this is no longer necessary.
          workInProgress.lanes = current.lanes;
          return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
        } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
          // This is a special case that only exists for legacy mode.
          // See https://github.com/facebook/react/pull/19216.
          didReceiveUpdate = true;
        }
      }
    }

    return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
  }

  function updateOffscreenComponent(current, workInProgress, renderLanes) {
    var nextProps = workInProgress.pendingProps;
    var nextChildren = nextProps.children;
    var prevState = current !== null ? current.memoizedState : null;

    if (nextProps.mode === 'hidden' || enableLegacyHidden ) {
      // Rendering a hidden tree.
      if ((workInProgress.mode & ConcurrentMode) === NoMode) {
        // In legacy sync mode, don't defer the subtree. Render it now.
        // TODO: Consider how Offscreen should work with transitions in the future
        var nextState = {
          baseLanes: NoLanes,
          cachePool: null,
          transitions: null
        };
        workInProgress.memoizedState = nextState;

        pushRenderLanes(workInProgress, renderLanes);
      } else if (!includesSomeLane(renderLanes, OffscreenLane)) {
        var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out
        // and resume this tree later.

        var nextBaseLanes;

        if (prevState !== null) {
          var prevBaseLanes = prevState.baseLanes;
          nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
        } else {
          nextBaseLanes = renderLanes;
        } // Schedule this fiber to re-render at offscreen priority. Then bailout.


        workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
        var _nextState = {
          baseLanes: nextBaseLanes,
          cachePool: spawnedCachePool,
          transitions: null
        };
        workInProgress.memoizedState = _nextState;
        workInProgress.updateQueue = null;
        // to avoid a push/pop misalignment.


        pushRenderLanes(workInProgress, nextBaseLanes);

        return null;
      } else {
        // This is the second render. The surrounding visible content has already
        // committed. Now we resume rendering the hidden tree.
        // Rendering at offscreen, so we can clear the base lanes.
        var _nextState2 = {
          baseLanes: NoLanes,
          cachePool: null,
          transitions: null
        };
        workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.

        var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;

        pushRenderLanes(workInProgress, subtreeRenderLanes);
      }
    } else {
      // Rendering a visible tree.
      var _subtreeRenderLanes;

      if (prevState !== null) {
        // We're going from hidden -> visible.
        _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes);

        workInProgress.memoizedState = null;
      } else {
        // We weren't previously hidden, and we still aren't, so there's nothing
        // special to do. Need to push to the stack regardless, though, to avoid
        // a push/pop misalignment.
        _subtreeRenderLanes = renderLanes;
      }

      pushRenderLanes(workInProgress, _subtreeRenderLanes);
    }

    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  } // Note: These happen to have identical begin phases, for now. We shouldn't hold

  function updateFragment(current, workInProgress, renderLanes) {
    var nextChildren = workInProgress.pendingProps;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateMode(current, workInProgress, renderLanes) {
    var nextChildren = workInProgress.pendingProps.children;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateProfiler(current, workInProgress, renderLanes) {
    {
      workInProgress.flags |= Update;

      {
        // Reset effect durations for the next eventual effect phase.
        // These are reset during render to allow the DevTools commit hook a chance to read them,
        var stateNode = workInProgress.stateNode;
        stateNode.effectDuration = 0;
        stateNode.passiveEffectDuration = 0;
      }
    }

    var nextProps = workInProgress.pendingProps;
    var nextChildren = nextProps.children;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function markRef(current, workInProgress) {
    var ref = workInProgress.ref;

    if (current === null && ref !== null || current !== null && current.ref !== ref) {
      // Schedule a Ref effect
      workInProgress.flags |= Ref;

      {
        workInProgress.flags |= RefStatic;
      }
    }
  }

  function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
    {
      if (workInProgress.type !== workInProgress.elementType) {
        // Lazy component props can't be validated in createElement
        // because they're only guaranteed to be resolved here.
        var innerPropTypes = Component.propTypes;

        if (innerPropTypes) {
          checkPropTypes(innerPropTypes, nextProps, // Resolved props
          'prop', getComponentNameFromType(Component));
        }
      }
    }

    var context;

    {
      var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
      context = getMaskedContext(workInProgress, unmaskedContext);
    }

    var nextChildren;
    var hasId;
    prepareToReadContext(workInProgress, renderLanes);

    {
      markComponentRenderStarted(workInProgress);
    }

    {
      ReactCurrentOwner$1.current = workInProgress;
      setIsRendering(true);
      nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
      hasId = checkDidRenderIdHook();

      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
          hasId = checkDidRenderIdHook();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }

      setIsRendering(false);
    }

    {
      markComponentRenderStopped();
    }

    if (current !== null && !didReceiveUpdate) {
      bailoutHooks(current, workInProgress, renderLanes);
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }

    if (getIsHydrating() && hasId) {
      pushMaterializedTreeId(workInProgress);
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
    {
      // This is used by DevTools to force a boundary to error.
      switch (shouldError(workInProgress)) {
        case false:
          {
            var _instance = workInProgress.stateNode;
            var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack.
            // Is there a better way to do this?

            var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context);
            var state = tempInstance.state;

            _instance.updater.enqueueSetState(_instance, state, null);

            break;
          }

        case true:
          {
            workInProgress.flags |= DidCapture;
            workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes

            var error$1 = new Error('Simulated error coming from DevTools');
            var lane = pickArbitraryLane(renderLanes);
            workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state

            var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane);
            enqueueCapturedUpdate(workInProgress, update);
            break;
          }
      }

      if (workInProgress.type !== workInProgress.elementType) {
        // Lazy component props can't be validated in createElement
        // because they're only guaranteed to be resolved here.
        var innerPropTypes = Component.propTypes;

        if (innerPropTypes) {
          checkPropTypes(innerPropTypes, nextProps, // Resolved props
          'prop', getComponentNameFromType(Component));
        }
      }
    } // Push context providers early to prevent context stack mismatches.
    // During mounting we don't know the child context yet as the instance doesn't exist.
    // We will invalidate the child context in finishClassComponent() right after rendering.


    var hasContext;

    if (isContextProvider(Component)) {
      hasContext = true;
      pushContextProvider(workInProgress);
    } else {
      hasContext = false;
    }

    prepareToReadContext(workInProgress, renderLanes);
    var instance = workInProgress.stateNode;
    var shouldUpdate;

    if (instance === null) {
      resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance.

      constructClassInstance(workInProgress, Component, nextProps);
      mountClassInstance(workInProgress, Component, nextProps, renderLanes);
      shouldUpdate = true;
    } else if (current === null) {
      // In a resume, we'll already have an instance we can reuse.
      shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
    } else {
      shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
    }

    var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);

    {
      var inst = workInProgress.stateNode;

      if (shouldUpdate && inst.props !== nextProps) {
        if (!didWarnAboutReassigningProps) {
          error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component');
        }

        didWarnAboutReassigningProps = true;
      }
    }

    return nextUnitOfWork;
  }

  function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
    // Refs should update even if shouldComponentUpdate returns false
    markRef(current, workInProgress);
    var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;

    if (!shouldUpdate && !didCaptureError) {
      // Context providers should defer to sCU for rendering
      if (hasContext) {
        invalidateContextProvider(workInProgress, Component, false);
      }

      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }

    var instance = workInProgress.stateNode; // Rerender

    ReactCurrentOwner$1.current = workInProgress;
    var nextChildren;

    if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
      // If we captured an error, but getDerivedStateFromError is not defined,
      // unmount all the children. componentDidCatch will schedule an update to
      // re-render a fallback. This is temporary until we migrate everyone to
      // the new API.
      // TODO: Warn in a future release.
      nextChildren = null;

      {
        stopProfilerTimerIfRunning();
      }
    } else {
      {
        markComponentRenderStarted(workInProgress);
      }

      {
        setIsRendering(true);
        nextChildren = instance.render();

        if ( workInProgress.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);

          try {
            instance.render();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }

        setIsRendering(false);
      }

      {
        markComponentRenderStopped();
      }
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;

    if (current !== null && didCaptureError) {
      // If we're recovering from an error, reconcile without reusing any of
      // the existing children. Conceptually, the normal children and the children
      // that are shown on error are two different sets, so we shouldn't reuse
      // normal children even if their identities match.
      forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
    } else {
      reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    } // Memoize state using the values we just used to render.
    // TODO: Restructure so we never read values from the instance.


    workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.

    if (hasContext) {
      invalidateContextProvider(workInProgress, Component, true);
    }

    return workInProgress.child;
  }

  function pushHostRootContext(workInProgress) {
    var root = workInProgress.stateNode;

    if (root.pendingContext) {
      pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
    } else if (root.context) {
      // Should always be set
      pushTopLevelContextObject(workInProgress, root.context, false);
    }

    pushHostContainer(workInProgress, root.containerInfo);
  }

  function updateHostRoot(current, workInProgress, renderLanes) {
    pushHostRootContext(workInProgress);

    if (current === null) {
      throw new Error('Should have a current fiber. This is a bug in React.');
    }

    var nextProps = workInProgress.pendingProps;
    var prevState = workInProgress.memoizedState;
    var prevChildren = prevState.element;
    cloneUpdateQueue(current, workInProgress);
    processUpdateQueue(workInProgress, nextProps, null, renderLanes);
    var nextState = workInProgress.memoizedState;
    var root = workInProgress.stateNode;
    // being called "element".


    var nextChildren = nextState.element;

    if ( prevState.isDehydrated) {
      // This is a hydration root whose shell has not yet hydrated. We should
      // attempt to hydrate.
      // Flip isDehydrated to false to indicate that when this render
      // finishes, the root will no longer be dehydrated.
      var overrideState = {
        element: nextChildren,
        isDehydrated: false,
        cache: nextState.cache,
        pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
        transitions: nextState.transitions
      };
      var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't
      // have reducer functions so it doesn't need rebasing.

      updateQueue.baseState = overrideState;
      workInProgress.memoizedState = overrideState;

      if (workInProgress.flags & ForceClientRender) {
        // Something errored during a previous attempt to hydrate the shell, so we
        // forced a client render.
        var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress);
        return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError);
      } else if (nextChildren !== prevChildren) {
        var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress);

        return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError);
      } else {
        // The outermost shell has not hydrated yet. Start hydrating.
        enterHydrationState(workInProgress);

        var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
        workInProgress.child = child;
        var node = child;

        while (node) {
          // Mark each child as hydrating. This is a fast path to know whether this
          // tree is part of a hydrating tree. This is used to determine if a child
          // node has fully mounted yet, and for scheduling event replaying.
          // Conceptually this is similar to Placement in that a new subtree is
          // inserted into the React tree here. It just happens to not need DOM
          // mutations because it already exists.
          node.flags = node.flags & ~Placement | Hydrating;
          node = node.sibling;
        }
      }
    } else {
      // Root is not dehydrated. Either this is a client-only root, or it
      // already hydrated.
      resetHydrationState();

      if (nextChildren === prevChildren) {
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
      }

      reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    }

    return workInProgress.child;
  }

  function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) {
    // Revert to client rendering.
    resetHydrationState();
    queueHydrationError(recoverableError);
    workInProgress.flags |= ForceClientRender;
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateHostComponent(current, workInProgress, renderLanes) {
    pushHostContext(workInProgress);

    if (current === null) {
      tryToClaimNextHydratableInstance(workInProgress);
    }

    var type = workInProgress.type;
    var nextProps = workInProgress.pendingProps;
    var prevProps = current !== null ? current.memoizedProps : null;
    var nextChildren = nextProps.children;
    var isDirectTextChild = shouldSetTextContent(type, nextProps);

    if (isDirectTextChild) {
      // We special case a direct text child of a host node. This is a common
      // case. We won't handle it as a reified child. We will instead handle
      // this in the host environment that also has access to this prop. That
      // avoids allocating another HostText fiber and traversing it.
      nextChildren = null;
    } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
      // If we're switching from a direct text child to a normal child, or to
      // empty, we need to schedule the text content to be reset.
      workInProgress.flags |= ContentReset;
    }

    markRef(current, workInProgress);
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    return workInProgress.child;
  }

  function updateHostText(current, workInProgress) {
    if (current === null) {
      tryToClaimNextHydratableInstance(workInProgress);
    } // Nothing to do here. This is terminal. We'll do the completion step
    // immediately after.


    return null;
  }

  function mountLazyComponent(_current, workInProgress, elementType, renderLanes) {
    resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
    var props = workInProgress.pendingProps;
    var lazyComponent = elementType;
    var payload = lazyComponent._payload;
    var init = lazyComponent._init;
    var Component = init(payload); // Store the unwrapped component in the type.

    workInProgress.type = Component;
    var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
    var resolvedProps = resolveDefaultProps(Component, props);
    var child;

    switch (resolvedTag) {
      case FunctionComponent:
        {
          {
            validateFunctionComponentInDev(workInProgress, Component);
            workInProgress.type = Component = resolveFunctionForHotReloading(Component);
          }

          child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
          return child;
        }

      case ClassComponent:
        {
          {
            workInProgress.type = Component = resolveClassForHotReloading(Component);
          }

          child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
          return child;
        }

      case ForwardRef:
        {
          {
            workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
          }

          child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
          return child;
        }

      case MemoComponent:
        {
          {
            if (workInProgress.type !== workInProgress.elementType) {
              var outerPropTypes = Component.propTypes;

              if (outerPropTypes) {
                checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
                'prop', getComponentNameFromType(Component));
              }
            }
          }

          child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
          renderLanes);
          return child;
        }
    }

    var hint = '';

    {
      if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
        hint = ' Did you wrap a component in React.lazy() more than once?';
      }
    } // This message intentionally doesn't mention ForwardRef or MemoComponent
    // because the fact that it's a separate type of work is an
    // implementation detail.


    throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint));
  }

  function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
    resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again.

    workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
    // Push context providers early to prevent context stack mismatches.
    // During mounting we don't know the child context yet as the instance doesn't exist.
    // We will invalidate the child context in finishClassComponent() right after rendering.

    var hasContext;

    if (isContextProvider(Component)) {
      hasContext = true;
      pushContextProvider(workInProgress);
    } else {
      hasContext = false;
    }

    prepareToReadContext(workInProgress, renderLanes);
    constructClassInstance(workInProgress, Component, nextProps);
    mountClassInstance(workInProgress, Component, nextProps, renderLanes);
    return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
  }

  function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
    resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
    var props = workInProgress.pendingProps;
    var context;

    {
      var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
      context = getMaskedContext(workInProgress, unmaskedContext);
    }

    prepareToReadContext(workInProgress, renderLanes);
    var value;
    var hasId;

    {
      markComponentRenderStarted(workInProgress);
    }

    {
      if (Component.prototype && typeof Component.prototype.render === 'function') {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutBadClass[componentName]) {
          error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

          didWarnAboutBadClass[componentName] = true;
        }
      }

      if (workInProgress.mode & StrictLegacyMode) {
        ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
      }

      setIsRendering(true);
      ReactCurrentOwner$1.current = workInProgress;
      value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
      hasId = checkDidRenderIdHook();
      setIsRendering(false);
    }

    {
      markComponentRenderStopped();
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;

    {
      // Support for module components is deprecated and is removed behind a flag.
      // Whether or not it would crash later, we want to show a good message in DEV first.
      if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
        var _componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

          didWarnAboutModulePatternComponent[_componentName] = true;
        }
      }
    }

    if ( // Run these checks in production only if the flag is off.
    // Eventually we'll delete this branch altogether.
     typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      {
        var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutModulePatternComponent[_componentName2]) {
          error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

          didWarnAboutModulePatternComponent[_componentName2] = true;
        }
      } // Proceed under the assumption that this is a class instance


      workInProgress.tag = ClassComponent; // Throw out any hooks that were used.

      workInProgress.memoizedState = null;
      workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
      // During mounting we don't know the child context yet as the instance doesn't exist.
      // We will invalidate the child context in finishClassComponent() right after rendering.

      var hasContext = false;

      if (isContextProvider(Component)) {
        hasContext = true;
        pushContextProvider(workInProgress);
      } else {
        hasContext = false;
      }

      workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
      initializeUpdateQueue(workInProgress);
      adoptClassInstance(workInProgress, value);
      mountClassInstance(workInProgress, Component, props, renderLanes);
      return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
    } else {
      // Proceed under the assumption that this is a function component
      workInProgress.tag = FunctionComponent;

      {

        if ( workInProgress.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);

          try {
            value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
            hasId = checkDidRenderIdHook();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      }

      if (getIsHydrating() && hasId) {
        pushMaterializedTreeId(workInProgress);
      }

      reconcileChildren(null, workInProgress, value, renderLanes);

      {
        validateFunctionComponentInDev(workInProgress, Component);
      }

      return workInProgress.child;
    }
  }

  function validateFunctionComponentInDev(workInProgress, Component) {
    {
      if (Component) {
        if (Component.childContextTypes) {
          error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
        }
      }

      if (workInProgress.ref !== null) {
        var info = '';
        var ownerName = getCurrentFiberOwnerNameInDevOrNull();

        if (ownerName) {
          info += '\n\nCheck the render method of `' + ownerName + '`.';
        }

        var warningKey = ownerName || '';
        var debugSource = workInProgress._debugSource;

        if (debugSource) {
          warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
        }

        if (!didWarnAboutFunctionRefs[warningKey]) {
          didWarnAboutFunctionRefs[warningKey] = true;

          error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
        }
      }

      if ( Component.defaultProps !== undefined) {
        var componentName = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
          error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

          didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
        }
      }

      if (typeof Component.getDerivedStateFromProps === 'function') {
        var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
          error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

          didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
        }
      }

      if (typeof Component.contextType === 'object' && Component.contextType !== null) {
        var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

        if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
          error('%s: Function components do not support contextType.', _componentName4);

          didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
        }
      }
    }
  }

  var SUSPENDED_MARKER = {
    dehydrated: null,
    treeContext: null,
    retryLane: NoLane
  };

  function mountSuspenseOffscreenState(renderLanes) {
    return {
      baseLanes: renderLanes,
      cachePool: getSuspendedCache(),
      transitions: null
    };
  }

  function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
    var cachePool = null;

    return {
      baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes),
      cachePool: cachePool,
      transitions: prevOffscreenState.transitions
    };
  } // TODO: Probably should inline this back


  function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
    // If we're already showing a fallback, there are cases where we need to
    // remain on that fallback regardless of whether the content has resolved.
    // For example, SuspenseList coordinates when nested content appears.
    if (current !== null) {
      var suspenseState = current.memoizedState;

      if (suspenseState === null) {
        // Currently showing content. Don't hide it, even if ForceSuspenseFallback
        // is true. More precise name might be "ForceRemainSuspenseFallback".
        // Note: This is a factoring smell. Can't remain on a fallback if there's
        // no fallback to remain on.
        return false;
      }
    } // Not currently showing content. Consult the Suspense context.


    return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
  }

  function getRemainingWorkInPrimaryTree(current, renderLanes) {
    // TODO: Should not remove render lanes that were pinged during this render
    return removeLanes(current.childLanes, renderLanes);
  }

  function updateSuspenseComponent(current, workInProgress, renderLanes) {
    var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.

    {
      if (shouldSuspend(workInProgress)) {
        workInProgress.flags |= DidCapture;
      }
    }

    var suspenseContext = suspenseStackCursor.current;
    var showFallback = false;
    var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;

    if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
      // Something in this boundary's subtree already suspended. Switch to
      // rendering the fallback children.
      showFallback = true;
      workInProgress.flags &= ~DidCapture;
    } else {
      // Attempting the main content
      if (current === null || current.memoizedState !== null) {
        // This is a new mount or this boundary is already showing a fallback state.
        // Mark this subtree context as having at least one invisible parent that could
        // handle the fallback state.
        // Avoided boundaries are not considered since they cannot handle preferred fallback states.
        {
          suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
        }
      }
    }

    suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
    pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
    // boundary's children. This involves some custom reconciliation logic. Two
    // main reasons this is so complicated.
    //
    // First, Legacy Mode has different semantics for backwards compatibility. The
    // primary tree will commit in an inconsistent state, so when we do the
    // second pass to render the fallback, we do some exceedingly, uh, clever
    // hacks to make that not totally break. Like transferring effects and
    // deletions from hidden tree. In Concurrent Mode, it's much simpler,
    // because we bailout on the primary tree completely and leave it in its old
    // state, no effects. Same as what we do for Offscreen (except that
    // Offscreen doesn't have the first render pass).
    //
    // Second is hydration. During hydration, the Suspense fiber has a slightly
    // different layout, where the child points to a dehydrated fragment, which
    // contains the DOM rendered by the server.
    //
    // Third, even if you set all that aside, Suspense is like error boundaries in
    // that we first we try to render one tree, and if that fails, we render again
    // and switch to a different tree. Like a try/catch block. So we have to track
    // which branch we're currently rendering. Ideally we would model this using
    // a stack.

    if (current === null) {
      // Initial mount
      // Special path for hydration
      // If we're currently hydrating, try to hydrate this boundary.
      tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.

      var suspenseState = workInProgress.memoizedState;

      if (suspenseState !== null) {
        var dehydrated = suspenseState.dehydrated;

        if (dehydrated !== null) {
          return mountDehydratedSuspenseComponent(workInProgress, dehydrated);
        }
      }

      var nextPrimaryChildren = nextProps.children;
      var nextFallbackChildren = nextProps.fallback;

      if (showFallback) {
        var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
        var primaryChildFragment = workInProgress.child;
        primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
        workInProgress.memoizedState = SUSPENDED_MARKER;

        return fallbackFragment;
      } else {
        return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren);
      }
    } else {
      // This is an update.
      // Special path for hydration
      var prevState = current.memoizedState;

      if (prevState !== null) {
        var _dehydrated = prevState.dehydrated;

        if (_dehydrated !== null) {
          return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes);
        }
      }

      if (showFallback) {
        var _nextFallbackChildren = nextProps.fallback;
        var _nextPrimaryChildren = nextProps.children;
        var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes);
        var _primaryChildFragment2 = workInProgress.child;
        var prevOffscreenState = current.child.memoizedState;
        _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);

        _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
        workInProgress.memoizedState = SUSPENDED_MARKER;
        return fallbackChildFragment;
      } else {
        var _nextPrimaryChildren2 = nextProps.children;

        var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes);

        workInProgress.memoizedState = null;
        return _primaryChildFragment3;
      }
    }
  }

  function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
    var mode = workInProgress.mode;
    var primaryChildProps = {
      mode: 'visible',
      children: primaryChildren
    };
    var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
    primaryChildFragment.return = workInProgress;
    workInProgress.child = primaryChildFragment;
    return primaryChildFragment;
  }

  function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
    var mode = workInProgress.mode;
    var progressedPrimaryFragment = workInProgress.child;
    var primaryChildProps = {
      mode: 'hidden',
      children: primaryChildren
    };
    var primaryChildFragment;
    var fallbackChildFragment;

    if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
      // In legacy mode, we commit the primary tree as if it successfully
      // completed, even though it's in an inconsistent state.
      primaryChildFragment = progressedPrimaryFragment;
      primaryChildFragment.childLanes = NoLanes;
      primaryChildFragment.pendingProps = primaryChildProps;

      if ( workInProgress.mode & ProfileMode) {
        // Reset the durations from the first pass so they aren't included in the
        // final amounts. This seems counterintuitive, since we're intentionally
        // not measuring part of the render phase, but this makes it match what we
        // do in Concurrent Mode.
        primaryChildFragment.actualDuration = 0;
        primaryChildFragment.actualStartTime = -1;
        primaryChildFragment.selfBaseDuration = 0;
        primaryChildFragment.treeBaseDuration = 0;
      }

      fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
    } else {
      primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
      fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
    }

    primaryChildFragment.return = workInProgress;
    fallbackChildFragment.return = workInProgress;
    primaryChildFragment.sibling = fallbackChildFragment;
    workInProgress.child = primaryChildFragment;
    return fallbackChildFragment;
  }

  function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) {
    // The props argument to `createFiberFromOffscreen` is `any` typed, so we use
    // this wrapper function to constrain it.
    return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
  }

  function updateWorkInProgressOffscreenFiber(current, offscreenProps) {
    // The props argument to `createWorkInProgress` is `any` typed, so we use this
    // wrapper function to constrain it.
    return createWorkInProgress(current, offscreenProps);
  }

  function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
    var currentPrimaryChildFragment = current.child;
    var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
    var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
      mode: 'visible',
      children: primaryChildren
    });

    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      primaryChildFragment.lanes = renderLanes;
    }

    primaryChildFragment.return = workInProgress;
    primaryChildFragment.sibling = null;

    if (currentFallbackChildFragment !== null) {
      // Delete the fallback child fragment
      var deletions = workInProgress.deletions;

      if (deletions === null) {
        workInProgress.deletions = [currentFallbackChildFragment];
        workInProgress.flags |= ChildDeletion;
      } else {
        deletions.push(currentFallbackChildFragment);
      }
    }

    workInProgress.child = primaryChildFragment;
    return primaryChildFragment;
  }

  function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
    var mode = workInProgress.mode;
    var currentPrimaryChildFragment = current.child;
    var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
    var primaryChildProps = {
      mode: 'hidden',
      children: primaryChildren
    };
    var primaryChildFragment;

    if ( // In legacy mode, we commit the primary tree as if it successfully
    // completed, even though it's in an inconsistent state.
    (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
    // already cloned. In legacy mode, the only case where this isn't true is
    // when DevTools forces us to display a fallback; we skip the first render
    // pass entirely and go straight to rendering the fallback. (In Concurrent
    // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
    // only codepath.)
    workInProgress.child !== currentPrimaryChildFragment) {
      var progressedPrimaryFragment = workInProgress.child;
      primaryChildFragment = progressedPrimaryFragment;
      primaryChildFragment.childLanes = NoLanes;
      primaryChildFragment.pendingProps = primaryChildProps;

      if ( workInProgress.mode & ProfileMode) {
        // Reset the durations from the first pass so they aren't included in the
        // final amounts. This seems counterintuitive, since we're intentionally
        // not measuring part of the render phase, but this makes it match what we
        // do in Concurrent Mode.
        primaryChildFragment.actualDuration = 0;
        primaryChildFragment.actualStartTime = -1;
        primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
        primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
      } // The fallback fiber was added as a deletion during the first pass.
      // However, since we're going to remain on the fallback, we no longer want
      // to delete it.


      workInProgress.deletions = null;
    } else {
      primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too.
      // (We don't do this in legacy mode, because in legacy mode we don't re-use
      // the current tree; see previous branch.)

      primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
    }

    var fallbackChildFragment;

    if (currentFallbackChildFragment !== null) {
      fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
    } else {
      fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
      // mounted but this is a new fiber.

      fallbackChildFragment.flags |= Placement;
    }

    fallbackChildFragment.return = workInProgress;
    primaryChildFragment.return = workInProgress;
    primaryChildFragment.sibling = fallbackChildFragment;
    workInProgress.child = primaryChildFragment;
    return fallbackChildFragment;
  }

  function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) {
    // Falling back to client rendering. Because this has performance
    // implications, it's considered a recoverable error, even though the user
    // likely won't observe anything wrong with the UI.
    //
    // The error is passed in as an argument to enforce that every caller provide
    // a custom message, or explicitly opt out (currently the only path that opts
    // out is legacy mode; every concurrent path provides an error).
    if (recoverableError !== null) {
      queueHydrationError(recoverableError);
    } // This will add the old fiber to the deletion list


    reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated.

    var nextProps = workInProgress.pendingProps;
    var primaryChildren = nextProps.children;
    var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already
    // mounted but this is a new fiber.

    primaryChildFragment.flags |= Placement;
    workInProgress.memoizedState = null;
    return primaryChildFragment;
  }

  function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
    var fiberMode = workInProgress.mode;
    var primaryChildProps = {
      mode: 'visible',
      children: primaryChildren
    };
    var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
    var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense
    // boundary) already mounted but this is a new fiber.

    fallbackChildFragment.flags |= Placement;
    primaryChildFragment.return = workInProgress;
    fallbackChildFragment.return = workInProgress;
    primaryChildFragment.sibling = fallbackChildFragment;
    workInProgress.child = primaryChildFragment;

    if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
      // We will have dropped the effect list which contains the
      // deletion. We need to reconcile to delete the current child.
      reconcileChildFibers(workInProgress, current.child, null, renderLanes);
    }

    return fallbackChildFragment;
  }

  function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) {
    // During the first pass, we'll bail out and not drill into the children.
    // Instead, we'll leave the content in place and try to hydrate it later.
    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      {
        error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
      }

      workInProgress.lanes = laneToLanes(SyncLane);
    } else if (isSuspenseInstanceFallback(suspenseInstance)) {
      // This is a client-only boundary. Since we won't get any content from the server
      // for this, we need to schedule that at a higher priority based on when it would
      // have timed out. In theory we could render it in this pass but it would have the
      // wrong priority associated with it and will prevent hydration of parent path.
      // Instead, we'll leave work left on it to render it in a separate commit.
      // TODO This time should be the time at which the server rendered response that is
      // a parent to this boundary was displayed. However, since we currently don't have
      // a protocol to transfer that time, we'll just estimate it by using the current
      // time. This will mean that Suspense timeouts are slightly shifted to later than
      // they should be.
      // Schedule a normal pri update to render this content.
      workInProgress.lanes = laneToLanes(DefaultHydrationLane);
    } else {
      // We'll continue hydrating the rest at offscreen priority since we'll already
      // be showing the right content coming from the server, it is no rush.
      workInProgress.lanes = laneToLanes(OffscreenLane);
    }

    return null;
  }

  function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) {
    if (!didSuspend) {
      // This is the first render pass. Attempt to hydrate.
      // We should never be hydrating at this point because it is the first pass,
      // but after we've already committed once.
      warnIfHydrating();

      if ((workInProgress.mode & ConcurrentMode) === NoMode) {
        return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument
        // required â€” every concurrent mode path that causes hydration to
        // de-opt to client rendering should have an error message.
        null);
      }

      if (isSuspenseInstanceFallback(suspenseInstance)) {
        // This boundary is in a permanent fallback state. In this case, we'll never
        // get an update and we'll never be able to hydrate the final content. Let's just try the
        // client side render instead.
        var digest, message, stack;

        {
          var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);

          digest = _getSuspenseInstanceF.digest;
          message = _getSuspenseInstanceF.message;
          stack = _getSuspenseInstanceF.stack;
        }

        var error;

        if (message) {
          // eslint-disable-next-line react-internal/prod-error-codes
          error = new Error(message);
        } else {
          error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.');
        }

        var capturedValue = createCapturedValue(error, digest, stack);
        return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue);
      }
      // any context has changed, we need to treat is as if the input might have changed.


      var hasContextChanged = includesSomeLane(renderLanes, current.childLanes);

      if (didReceiveUpdate || hasContextChanged) {
        // This boundary has changed since the first render. This means that we are now unable to
        // hydrate it. We might still be able to hydrate it using a higher priority lane.
        var root = getWorkInProgressRoot();

        if (root !== null) {
          var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes);

          if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
            // Intentionally mutating since this render will get interrupted. This
            // is one of the very rare times where we mutate the current tree
            // during the render phase.
            suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render

            var eventTime = NoTimestamp;
            enqueueConcurrentRenderForLane(current, attemptHydrationAtLane);
            scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime);
          }
        } // If we have scheduled higher pri work above, this will probably just abort the render
        // since we now have higher priority work, but in case it doesn't, we need to prepare to
        // render something, if we time out. Even if that requires us to delete everything and
        // skip hydration.
        // Delay having to do this as long as the suspense timeout allows us.


        renderDidSuspendDelayIfPossible();

        var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.'));

        return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue);
      } else if (isSuspenseInstancePending(suspenseInstance)) {
        // This component is still pending more data from the server, so we can't hydrate its
        // content. We treat it as if this component suspended itself. It might seem as if
        // we could just try to render it client-side instead. However, this will perform a
        // lot of unnecessary work and is unlikely to complete since it often will suspend
        // on missing data anyway. Additionally, the server might be able to render more
        // than we can on the client yet. In that case we'd end up with more fallback states
        // on the client than if we just leave it alone. If the server times out or errors
        // these should update this boundary to the permanent Fallback state instead.
        // Mark it as having captured (i.e. suspended).
        workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.

        workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result.

        var retry = retryDehydratedSuspenseBoundary.bind(null, current);
        registerSuspenseInstanceRetry(suspenseInstance, retry);
        return null;
      } else {
        // This is the first attempt.
        reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext);
        var primaryChildren = nextProps.children;
        var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this
        // tree is part of a hydrating tree. This is used to determine if a child
        // node has fully mounted yet, and for scheduling event replaying.
        // Conceptually this is similar to Placement in that a new subtree is
        // inserted into the React tree here. It just happens to not need DOM
        // mutations because it already exists.

        primaryChildFragment.flags |= Hydrating;
        return primaryChildFragment;
      }
    } else {
      // This is the second render pass. We already attempted to hydrated, but
      // something either suspended or errored.
      if (workInProgress.flags & ForceClientRender) {
        // Something errored during hydration. Try again without hydrating.
        workInProgress.flags &= ~ForceClientRender;

        var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.'));

        return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2);
      } else if (workInProgress.memoizedState !== null) {
        // Something suspended and we should still be in dehydrated mode.
        // Leave the existing child in place.
        workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there
        // but the normal suspense pass doesn't.

        workInProgress.flags |= DidCapture;
        return null;
      } else {
        // Suspended but we should no longer be in dehydrated mode.
        // Therefore we now have to render the fallback.
        var nextPrimaryChildren = nextProps.children;
        var nextFallbackChildren = nextProps.fallback;
        var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
        var _primaryChildFragment4 = workInProgress.child;
        _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes);
        workInProgress.memoizedState = SUSPENDED_MARKER;
        return fallbackChildFragment;
      }
    }
  }

  function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {
    fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
    var alternate = fiber.alternate;

    if (alternate !== null) {
      alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
    }

    scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
  }

  function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
    // Mark any Suspense boundaries with fallbacks as having work to do.
    // If they were previously forced into fallbacks, they may now be able
    // to unblock.
    var node = firstChild;

    while (node !== null) {
      if (node.tag === SuspenseComponent) {
        var state = node.memoizedState;

        if (state !== null) {
          scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
        }
      } else if (node.tag === SuspenseListComponent) {
        // If the tail is hidden there might not be an Suspense boundaries
        // to schedule work on. In this case we have to schedule it on the
        // list itself.
        // We don't have to traverse to the children of the list since
        // the list will propagate the change when it rerenders.
        scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
      } else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === workInProgress) {
        return;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === workInProgress) {
          return;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }
  }

  function findLastContentRow(firstChild) {
    // This is going to find the last row among these children that is already
    // showing content on the screen, as opposed to being in fallback state or
    // new. If a row has multiple Suspense boundaries, any of them being in the
    // fallback state, counts as the whole row being in a fallback state.
    // Note that the "rows" will be workInProgress, but any nested children
    // will still be current since we haven't rendered them yet. The mounted
    // order may not be the same as the new order. We use the new order.
    var row = firstChild;
    var lastContentRow = null;

    while (row !== null) {
      var currentRow = row.alternate; // New rows can't be content rows.

      if (currentRow !== null && findFirstSuspended(currentRow) === null) {
        lastContentRow = row;
      }

      row = row.sibling;
    }

    return lastContentRow;
  }

  function validateRevealOrder(revealOrder) {
    {
      if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
        didWarnAboutRevealOrder[revealOrder] = true;

        if (typeof revealOrder === 'string') {
          switch (revealOrder.toLowerCase()) {
            case 'together':
            case 'forwards':
            case 'backwards':
              {
                error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());

                break;
              }

            case 'forward':
            case 'backward':
              {
                error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());

                break;
              }

            default:
              error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);

              break;
          }
        } else {
          error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
        }
      }
    }
  }

  function validateTailOptions(tailMode, revealOrder) {
    {
      if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
        if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
          didWarnAboutTailOptions[tailMode] = true;

          error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
        } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
          didWarnAboutTailOptions[tailMode] = true;

          error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
        }
      }
    }
  }

  function validateSuspenseListNestedChild(childSlot, index) {
    {
      var isAnArray = isArray(childSlot);
      var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function';

      if (isAnArray || isIterable) {
        var type = isAnArray ? 'array' : 'iterable';

        error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);

        return false;
      }
    }

    return true;
  }

  function validateSuspenseListChildren(children, revealOrder) {
    {
      if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
        if (isArray(children)) {
          for (var i = 0; i < children.length; i++) {
            if (!validateSuspenseListNestedChild(children[i], i)) {
              return;
            }
          }
        } else {
          var iteratorFn = getIteratorFn(children);

          if (typeof iteratorFn === 'function') {
            var childrenIterator = iteratorFn.call(children);

            if (childrenIterator) {
              var step = childrenIterator.next();
              var _i = 0;

              for (; !step.done; step = childrenIterator.next()) {
                if (!validateSuspenseListNestedChild(step.value, _i)) {
                  return;
                }

                _i++;
              }
            }
          } else {
            error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
          }
        }
      }
    }
  }

  function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
    var renderState = workInProgress.memoizedState;

    if (renderState === null) {
      workInProgress.memoizedState = {
        isBackwards: isBackwards,
        rendering: null,
        renderingStartTime: 0,
        last: lastContentRow,
        tail: tail,
        tailMode: tailMode
      };
    } else {
      // We can reuse the existing object from previous renders.
      renderState.isBackwards = isBackwards;
      renderState.rendering = null;
      renderState.renderingStartTime = 0;
      renderState.last = lastContentRow;
      renderState.tail = tail;
      renderState.tailMode = tailMode;
    }
  } // This can end up rendering this component multiple passes.
  // The first pass splits the children fibers into two sets. A head and tail.
  // We first render the head. If anything is in fallback state, we do another
  // pass through beginWork to rerender all children (including the tail) with
  // the force suspend context. If the first render didn't have anything in
  // in fallback state. Then we render each row in the tail one-by-one.
  // That happens in the completeWork phase without going back to beginWork.


  function updateSuspenseListComponent(current, workInProgress, renderLanes) {
    var nextProps = workInProgress.pendingProps;
    var revealOrder = nextProps.revealOrder;
    var tailMode = nextProps.tail;
    var newChildren = nextProps.children;
    validateRevealOrder(revealOrder);
    validateTailOptions(tailMode, revealOrder);
    validateSuspenseListChildren(newChildren, revealOrder);
    reconcileChildren(current, workInProgress, newChildren, renderLanes);
    var suspenseContext = suspenseStackCursor.current;
    var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);

    if (shouldForceFallback) {
      suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
      workInProgress.flags |= DidCapture;
    } else {
      var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;

      if (didSuspendBefore) {
        // If we previously forced a fallback, we need to schedule work
        // on any nested boundaries to let them know to try to render
        // again. This is the same as context updating.
        propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
      }

      suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
    }

    pushSuspenseContext(workInProgress, suspenseContext);

    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      // In legacy mode, SuspenseList doesn't work so we just
      // use make it a noop by treating it as the default revealOrder.
      workInProgress.memoizedState = null;
    } else {
      switch (revealOrder) {
        case 'forwards':
          {
            var lastContentRow = findLastContentRow(workInProgress.child);
            var tail;

            if (lastContentRow === null) {
              // The whole list is part of the tail.
              // TODO: We could fast path by just rendering the tail now.
              tail = workInProgress.child;
              workInProgress.child = null;
            } else {
              // Disconnect the tail rows after the content row.
              // We're going to render them separately later.
              tail = lastContentRow.sibling;
              lastContentRow.sibling = null;
            }

            initSuspenseListRenderState(workInProgress, false, // isBackwards
            tail, lastContentRow, tailMode);
            break;
          }

        case 'backwards':
          {
            // We're going to find the first row that has existing content.
            // At the same time we're going to reverse the list of everything
            // we pass in the meantime. That's going to be our tail in reverse
            // order.
            var _tail = null;
            var row = workInProgress.child;
            workInProgress.child = null;

            while (row !== null) {
              var currentRow = row.alternate; // New rows can't be content rows.

              if (currentRow !== null && findFirstSuspended(currentRow) === null) {
                // This is the beginning of the main content.
                workInProgress.child = row;
                break;
              }

              var nextRow = row.sibling;
              row.sibling = _tail;
              _tail = row;
              row = nextRow;
            } // TODO: If workInProgress.child is null, we can continue on the tail immediately.


            initSuspenseListRenderState(workInProgress, true, // isBackwards
            _tail, null, // last
            tailMode);
            break;
          }

        case 'together':
          {
            initSuspenseListRenderState(workInProgress, false, // isBackwards
            null, // tail
            null, // last
            undefined);
            break;
          }

        default:
          {
            // The default reveal order is the same as not having
            // a boundary.
            workInProgress.memoizedState = null;
          }
      }
    }

    return workInProgress.child;
  }

  function updatePortalComponent(current, workInProgress, renderLanes) {
    pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
    var nextChildren = workInProgress.pendingProps;

    if (current === null) {
      // Portals are special because we don't append the children during mount
      // but at commit. Therefore we need to track insertions which the normal
      // flow doesn't do during mount. This doesn't happen at the root because
      // the root always starts with a "current" with a null child.
      // TODO: Consider unifying this with how the root works.
      workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
    } else {
      reconcileChildren(current, workInProgress, nextChildren, renderLanes);
    }

    return workInProgress.child;
  }

  var hasWarnedAboutUsingNoValuePropOnContextProvider = false;

  function updateContextProvider(current, workInProgress, renderLanes) {
    var providerType = workInProgress.type;
    var context = providerType._context;
    var newProps = workInProgress.pendingProps;
    var oldProps = workInProgress.memoizedProps;
    var newValue = newProps.value;

    {
      if (!('value' in newProps)) {
        if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
          hasWarnedAboutUsingNoValuePropOnContextProvider = true;

          error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
        }
      }

      var providerPropTypes = workInProgress.type.propTypes;

      if (providerPropTypes) {
        checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
      }
    }

    pushProvider(workInProgress, context, newValue);

    {
      if (oldProps !== null) {
        var oldValue = oldProps.value;

        if (objectIs(oldValue, newValue)) {
          // No change. Bailout early if children are the same.
          if (oldProps.children === newProps.children && !hasContextChanged()) {
            return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
          }
        } else {
          // The context value changed. Search for matching consumers and schedule
          // them to update.
          propagateContextChange(workInProgress, context, renderLanes);
        }
      }
    }

    var newChildren = newProps.children;
    reconcileChildren(current, workInProgress, newChildren, renderLanes);
    return workInProgress.child;
  }

  var hasWarnedAboutUsingContextAsConsumer = false;

  function updateContextConsumer(current, workInProgress, renderLanes) {
    var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
    // DEV mode, we create a separate object for Context.Consumer that acts
    // like a proxy to Context. This proxy object adds unnecessary code in PROD
    // so we use the old behaviour (Context.Consumer references Context) to
    // reduce size and overhead. The separate object references context via
    // a property called "_context", which also gives us the ability to check
    // in DEV mode if this property exists or not and warn if it does not.

    {
      if (context._context === undefined) {
        // This may be because it's a Context (rather than a Consumer).
        // Or it may be because it's older React where they're the same thing.
        // We only want to warn if we're sure it's a new React.
        if (context !== context.Consumer) {
          if (!hasWarnedAboutUsingContextAsConsumer) {
            hasWarnedAboutUsingContextAsConsumer = true;

            error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
          }
        }
      } else {
        context = context._context;
      }
    }

    var newProps = workInProgress.pendingProps;
    var render = newProps.children;

    {
      if (typeof render !== 'function') {
        error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
      }
    }

    prepareToReadContext(workInProgress, renderLanes);
    var newValue = readContext(context);

    {
      markComponentRenderStarted(workInProgress);
    }

    var newChildren;

    {
      ReactCurrentOwner$1.current = workInProgress;
      setIsRendering(true);
      newChildren = render(newValue);
      setIsRendering(false);
    }

    {
      markComponentRenderStopped();
    } // React DevTools reads this flag.


    workInProgress.flags |= PerformedWork;
    reconcileChildren(current, workInProgress, newChildren, renderLanes);
    return workInProgress.child;
  }

  function markWorkInProgressReceivedUpdate() {
    didReceiveUpdate = true;
  }

  function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) {
    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      if (current !== null) {
        // A lazy component only mounts if it suspended inside a non-
        // concurrent tree, in an inconsistent state. We want to treat it like
        // a new mount, even though an empty version of it already committed.
        // Disconnect the alternate pointers.
        current.alternate = null;
        workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

        workInProgress.flags |= Placement;
      }
    }
  }

  function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
    if (current !== null) {
      // Reuse previous dependencies
      workInProgress.dependencies = current.dependencies;
    }

    {
      // Don't update "base" render times for bailouts.
      stopProfilerTimerIfRunning();
    }

    markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.

    if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
      // The children don't have any work either. We can skip them.
      // TODO: Once we add back resuming, we should check if the children are
      // a work-in-progress set. If so, we need to transfer their effects.
      {
        return null;
      }
    } // This fiber doesn't have work, but its subtree does. Clone the child
    // fibers and continue.


    cloneChildFibers(current, workInProgress);
    return workInProgress.child;
  }

  function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
    {
      var returnFiber = oldWorkInProgress.return;

      if (returnFiber === null) {
        // eslint-disable-next-line react-internal/prod-error-codes
        throw new Error('Cannot swap the root fiber.');
      } // Disconnect from the old current.
      // It will get deleted.


      current.alternate = null;
      oldWorkInProgress.alternate = null; // Connect to the new tree.

      newWorkInProgress.index = oldWorkInProgress.index;
      newWorkInProgress.sibling = oldWorkInProgress.sibling;
      newWorkInProgress.return = oldWorkInProgress.return;
      newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.

      if (oldWorkInProgress === returnFiber.child) {
        returnFiber.child = newWorkInProgress;
      } else {
        var prevSibling = returnFiber.child;

        if (prevSibling === null) {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('Expected parent to have a child.');
        }

        while (prevSibling.sibling !== oldWorkInProgress) {
          prevSibling = prevSibling.sibling;

          if (prevSibling === null) {
            // eslint-disable-next-line react-internal/prod-error-codes
            throw new Error('Expected to find the previous sibling.');
          }
        }

        prevSibling.sibling = newWorkInProgress;
      } // Delete the old fiber and place the new one.
      // Since the old fiber is disconnected, we have to schedule it manually.


      var deletions = returnFiber.deletions;

      if (deletions === null) {
        returnFiber.deletions = [current];
        returnFiber.flags |= ChildDeletion;
      } else {
        deletions.push(current);
      }

      newWorkInProgress.flags |= Placement; // Restart work from the new fiber.

      return newWorkInProgress;
    }
  }

  function checkScheduledUpdateOrContext(current, renderLanes) {
    // Before performing an early bailout, we must check if there are pending
    // updates or context.
    var updateLanes = current.lanes;

    if (includesSomeLane(updateLanes, renderLanes)) {
      return true;
    } // No pending update, but because context is propagated lazily, we need

    return false;
  }

  function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) {
    // This fiber does not have any pending work. Bailout without entering
    // the begin phase. There's still some bookkeeping we that needs to be done
    // in this optimized path, mostly pushing stuff onto the stack.
    switch (workInProgress.tag) {
      case HostRoot:
        pushHostRootContext(workInProgress);
        var root = workInProgress.stateNode;

        resetHydrationState();
        break;

      case HostComponent:
        pushHostContext(workInProgress);
        break;

      case ClassComponent:
        {
          var Component = workInProgress.type;

          if (isContextProvider(Component)) {
            pushContextProvider(workInProgress);
          }

          break;
        }

      case HostPortal:
        pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
        break;

      case ContextProvider:
        {
          var newValue = workInProgress.memoizedProps.value;
          var context = workInProgress.type._context;
          pushProvider(workInProgress, context, newValue);
          break;
        }

      case Profiler:
        {
          // Profiler should only call onRender when one of its descendants actually rendered.
          var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);

          if (hasChildWork) {
            workInProgress.flags |= Update;
          }

          {
            // Reset effect durations for the next eventual effect phase.
            // These are reset during render to allow the DevTools commit hook a chance to read them,
            var stateNode = workInProgress.stateNode;
            stateNode.effectDuration = 0;
            stateNode.passiveEffectDuration = 0;
          }
        }

        break;

      case SuspenseComponent:
        {
          var state = workInProgress.memoizedState;

          if (state !== null) {
            if (state.dehydrated !== null) {
              pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
              // been unsuspended it has committed as a resolved Suspense component.
              // If it needs to be retried, it should have work scheduled on it.

              workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we
              // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.

              return null;
            } // If this boundary is currently timed out, we need to decide
            // whether to retry the primary children, or to skip over it and
            // go straight to the fallback. Check the priority of the primary
            // child fragment.


            var primaryChildFragment = workInProgress.child;
            var primaryChildLanes = primaryChildFragment.childLanes;

            if (includesSomeLane(renderLanes, primaryChildLanes)) {
              // The primary children have pending work. Use the normal path
              // to attempt to render the primary children again.
              return updateSuspenseComponent(current, workInProgress, renderLanes);
            } else {
              // The primary child fragment does not have pending work marked
              // on it
              pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
              // priority. Bailout.

              var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);

              if (child !== null) {
                // The fallback children have pending work. Skip over the
                // primary children and work on the fallback.
                return child.sibling;
              } else {
                // Note: We can return `null` here because we already checked
                // whether there were nested context consumers, via the call to
                // `bailoutOnAlreadyFinishedWork` above.
                return null;
              }
            }
          } else {
            pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
          }

          break;
        }

      case SuspenseListComponent:
        {
          var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;

          var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);

          if (didSuspendBefore) {
            if (_hasChildWork) {
              // If something was in fallback state last time, and we have all the
              // same children then we're still in progressive loading state.
              // Something might get unblocked by state updates or retries in the
              // tree which will affect the tail. So we need to use the normal
              // path to compute the correct tail.
              return updateSuspenseListComponent(current, workInProgress, renderLanes);
            } // If none of the children had any work, that means that none of
            // them got retried so they'll still be blocked in the same way
            // as before. We can fast bail out.


            workInProgress.flags |= DidCapture;
          } // If nothing suspended before and we're rendering the same children,
          // then the tail doesn't matter. Anything new that suspends will work
          // in the "together" mode, so we can continue from the state we had.


          var renderState = workInProgress.memoizedState;

          if (renderState !== null) {
            // Reset to the "together" mode in case we've started a different
            // update in the past but didn't complete it.
            renderState.rendering = null;
            renderState.tail = null;
            renderState.lastEffect = null;
          }

          pushSuspenseContext(workInProgress, suspenseStackCursor.current);

          if (_hasChildWork) {
            break;
          } else {
            // If none of the children had any work, that means that none of
            // them got retried so they'll still be blocked in the same way
            // as before. We can fast bail out.
            return null;
          }
        }

      case OffscreenComponent:
      case LegacyHiddenComponent:
        {
          // Need to check if the tree still needs to be deferred. This is
          // almost identical to the logic used in the normal update path,
          // so we'll just enter that. The only difference is we'll bail out
          // at the next level instead of this one, because the child props
          // have not changed. Which is fine.
          // TODO: Probably should refactor `beginWork` to split the bailout
          // path from the normal path. I'm tempted to do a labeled break here
          // but I won't :)
          workInProgress.lanes = NoLanes;
          return updateOffscreenComponent(current, workInProgress, renderLanes);
        }
    }

    return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
  }

  function beginWork(current, workInProgress, renderLanes) {
    {
      if (workInProgress._debugNeedsRemount && current !== null) {
        // This will restart the begin phase with a new fiber.
        return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
      }
    }

    if (current !== null) {
      var oldProps = current.memoizedProps;
      var newProps = workInProgress.pendingProps;

      if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
       workInProgress.type !== current.type )) {
        // If props or context changed, mark the fiber as having performed work.
        // This may be unset if the props are determined to be equal later (memo).
        didReceiveUpdate = true;
      } else {
        // Neither props nor legacy context changes. Check if there's a pending
        // update or context change.
        var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);

        if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
        // may not be work scheduled on `current`, so we check for this flag.
        (workInProgress.flags & DidCapture) === NoFlags) {
          // No pending updates or context. Bail out now.
          didReceiveUpdate = false;
          return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes);
        }

        if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
          // This is a special case that only exists for legacy mode.
          // See https://github.com/facebook/react/pull/19216.
          didReceiveUpdate = true;
        } else {
          // An update was scheduled on this fiber, but there are no new props
          // nor legacy context. Set this to false. If an update queue or context
          // consumer produces a changed value, it will set this to true. Otherwise,
          // the component will assume the children have not changed and bail out.
          didReceiveUpdate = false;
        }
      }
    } else {
      didReceiveUpdate = false;

      if (getIsHydrating() && isForkedChild(workInProgress)) {
        // Check if this child belongs to a list of muliple children in
        // its parent.
        //
        // In a true multi-threaded implementation, we would render children on
        // parallel threads. This would represent the beginning of a new render
        // thread for this subtree.
        //
        // We only use this for id generation during hydration, which is why the
        // logic is located in this special branch.
        var slotIndex = workInProgress.index;
        var numberOfForks = getForksAtLevel();
        pushTreeId(workInProgress, numberOfForks, slotIndex);
      }
    } // Before entering the begin phase, clear pending update priority.
    // TODO: This assumes that we're about to evaluate the component and process
    // the update queue. However, there's an exception: SimpleMemoComponent
    // sometimes bails out later in the begin phase. This indicates that we should
    // move this assignment out of the common path and into each branch.


    workInProgress.lanes = NoLanes;

    switch (workInProgress.tag) {
      case IndeterminateComponent:
        {
          return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
        }

      case LazyComponent:
        {
          var elementType = workInProgress.elementType;
          return mountLazyComponent(current, workInProgress, elementType, renderLanes);
        }

      case FunctionComponent:
        {
          var Component = workInProgress.type;
          var unresolvedProps = workInProgress.pendingProps;
          var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps);
          return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes);
        }

      case ClassComponent:
        {
          var _Component = workInProgress.type;
          var _unresolvedProps = workInProgress.pendingProps;

          var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);

          return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes);
        }

      case HostRoot:
        return updateHostRoot(current, workInProgress, renderLanes);

      case HostComponent:
        return updateHostComponent(current, workInProgress, renderLanes);

      case HostText:
        return updateHostText(current, workInProgress);

      case SuspenseComponent:
        return updateSuspenseComponent(current, workInProgress, renderLanes);

      case HostPortal:
        return updatePortalComponent(current, workInProgress, renderLanes);

      case ForwardRef:
        {
          var type = workInProgress.type;
          var _unresolvedProps2 = workInProgress.pendingProps;

          var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);

          return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
        }

      case Fragment:
        return updateFragment(current, workInProgress, renderLanes);

      case Mode:
        return updateMode(current, workInProgress, renderLanes);

      case Profiler:
        return updateProfiler(current, workInProgress, renderLanes);

      case ContextProvider:
        return updateContextProvider(current, workInProgress, renderLanes);

      case ContextConsumer:
        return updateContextConsumer(current, workInProgress, renderLanes);

      case MemoComponent:
        {
          var _type2 = workInProgress.type;
          var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.

          var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);

          {
            if (workInProgress.type !== workInProgress.elementType) {
              var outerPropTypes = _type2.propTypes;

              if (outerPropTypes) {
                checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
                'prop', getComponentNameFromType(_type2));
              }
            }
          }

          _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
          return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes);
        }

      case SimpleMemoComponent:
        {
          return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes);
        }

      case IncompleteClassComponent:
        {
          var _Component2 = workInProgress.type;
          var _unresolvedProps4 = workInProgress.pendingProps;

          var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);

          return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes);
        }

      case SuspenseListComponent:
        {
          return updateSuspenseListComponent(current, workInProgress, renderLanes);
        }

      case ScopeComponent:
        {

          break;
        }

      case OffscreenComponent:
        {
          return updateOffscreenComponent(current, workInProgress, renderLanes);
        }
    }

    throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
  }

  function markUpdate(workInProgress) {
    // Tag the fiber with an update effect. This turns a Placement into
    // a PlacementAndUpdate.
    workInProgress.flags |= Update;
  }

  function markRef$1(workInProgress) {
    workInProgress.flags |= Ref;

    {
      workInProgress.flags |= RefStatic;
    }
  }

  var appendAllChildren;
  var updateHostContainer;
  var updateHostComponent$1;
  var updateHostText$1;

  {
    // Mutation mode
    appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
      // We only have the top Fiber that was created but we need recurse down its
      // children to find all the terminal nodes.
      var node = workInProgress.child;

      while (node !== null) {
        if (node.tag === HostComponent || node.tag === HostText) {
          appendInitialChild(parent, node.stateNode);
        } else if (node.tag === HostPortal) ; else if (node.child !== null) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === workInProgress) {
          return;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === workInProgress) {
            return;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    };

    updateHostContainer = function (current, workInProgress) {// Noop
    };

    updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
      // If we have an alternate, that means this is an update and we need to
      // schedule a side-effect to do the updates.
      var oldProps = current.memoizedProps;

      if (oldProps === newProps) {
        // In mutation mode, this is sufficient for a bailout because
        // we won't touch this node even if children changed.
        return;
      } // If we get updated because one of our children updated, we don't
      // have newProps so we'll have to reuse them.
      // TODO: Split the update API as separate for the props vs. children.
      // Even better would be if children weren't special cased at all tho.


      var instance = workInProgress.stateNode;
      var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
      // component is hitting the resume path. Figure out why. Possibly
      // related to `hidden`.

      var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.

      workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
      // is a new ref we mark this as an update. All the work is done in commitWork.

      if (updatePayload) {
        markUpdate(workInProgress);
      }
    };

    updateHostText$1 = function (current, workInProgress, oldText, newText) {
      // If the text differs, mark it as an update. All the work in done in commitWork.
      if (oldText !== newText) {
        markUpdate(workInProgress);
      }
    };
  }

  function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
    if (getIsHydrating()) {
      // If we're hydrating, we should consume as many items as we can
      // so we don't leave any behind.
      return;
    }

    switch (renderState.tailMode) {
      case 'hidden':
        {
          // Any insertions at the end of the tail list after this point
          // should be invisible. If there are already mounted boundaries
          // anything before them are not considered for collapsing.
          // Therefore we need to go through the whole tail to find if
          // there are any.
          var tailNode = renderState.tail;
          var lastTailNode = null;

          while (tailNode !== null) {
            if (tailNode.alternate !== null) {
              lastTailNode = tailNode;
            }

            tailNode = tailNode.sibling;
          } // Next we're simply going to delete all insertions after the
          // last rendered item.


          if (lastTailNode === null) {
            // All remaining items in the tail are insertions.
            renderState.tail = null;
          } else {
            // Detach the insertion after the last node that was already
            // inserted.
            lastTailNode.sibling = null;
          }

          break;
        }

      case 'collapsed':
        {
          // Any insertions at the end of the tail list after this point
          // should be invisible. If there are already mounted boundaries
          // anything before them are not considered for collapsing.
          // Therefore we need to go through the whole tail to find if
          // there are any.
          var _tailNode = renderState.tail;
          var _lastTailNode = null;

          while (_tailNode !== null) {
            if (_tailNode.alternate !== null) {
              _lastTailNode = _tailNode;
            }

            _tailNode = _tailNode.sibling;
          } // Next we're simply going to delete all insertions after the
          // last rendered item.


          if (_lastTailNode === null) {
            // All remaining items in the tail are insertions.
            if (!hasRenderedATailFallback && renderState.tail !== null) {
              // We suspended during the head. We want to show at least one
              // row at the tail. So we'll keep on and cut off the rest.
              renderState.tail.sibling = null;
            } else {
              renderState.tail = null;
            }
          } else {
            // Detach the insertion after the last node that was already
            // inserted.
            _lastTailNode.sibling = null;
          }

          break;
        }
    }
  }

  function bubbleProperties(completedWork) {
    var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
    var newChildLanes = NoLanes;
    var subtreeFlags = NoFlags;

    if (!didBailout) {
      // Bubble up the earliest expiration time.
      if ( (completedWork.mode & ProfileMode) !== NoMode) {
        // In profiling mode, resetChildExpirationTime is also used to reset
        // profiler durations.
        var actualDuration = completedWork.actualDuration;
        var treeBaseDuration = completedWork.selfBaseDuration;
        var child = completedWork.child;

        while (child !== null) {
          newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
          subtreeFlags |= child.subtreeFlags;
          subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will
          // only be updated if work is done on the fiber (i.e. it doesn't bailout).
          // When work is done, it should bubble to the parent's actualDuration. If
          // the fiber has not been cloned though, (meaning no work was done), then
          // this value will reflect the amount of time spent working on a previous
          // render. In that case it should not bubble. We determine whether it was
          // cloned by comparing the child pointer.

          actualDuration += child.actualDuration;
          treeBaseDuration += child.treeBaseDuration;
          child = child.sibling;
        }

        completedWork.actualDuration = actualDuration;
        completedWork.treeBaseDuration = treeBaseDuration;
      } else {
        var _child = completedWork.child;

        while (_child !== null) {
          newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
          subtreeFlags |= _child.subtreeFlags;
          subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code
          // smell because it assumes the commit phase is never concurrent with
          // the render phase. Will address during refactor to alternate model.

          _child.return = completedWork;
          _child = _child.sibling;
        }
      }

      completedWork.subtreeFlags |= subtreeFlags;
    } else {
      // Bubble up the earliest expiration time.
      if ( (completedWork.mode & ProfileMode) !== NoMode) {
        // In profiling mode, resetChildExpirationTime is also used to reset
        // profiler durations.
        var _treeBaseDuration = completedWork.selfBaseDuration;
        var _child2 = completedWork.child;

        while (_child2 !== null) {
          newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
          // so we should bubble those up even during a bailout. All the other
          // flags have a lifetime only of a single render + commit, so we should
          // ignore them.

          subtreeFlags |= _child2.subtreeFlags & StaticMask;
          subtreeFlags |= _child2.flags & StaticMask;
          _treeBaseDuration += _child2.treeBaseDuration;
          _child2 = _child2.sibling;
        }

        completedWork.treeBaseDuration = _treeBaseDuration;
      } else {
        var _child3 = completedWork.child;

        while (_child3 !== null) {
          newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
          // so we should bubble those up even during a bailout. All the other
          // flags have a lifetime only of a single render + commit, so we should
          // ignore them.

          subtreeFlags |= _child3.subtreeFlags & StaticMask;
          subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code
          // smell because it assumes the commit phase is never concurrent with
          // the render phase. Will address during refactor to alternate model.

          _child3.return = completedWork;
          _child3 = _child3.sibling;
        }
      }

      completedWork.subtreeFlags |= subtreeFlags;
    }

    completedWork.childLanes = newChildLanes;
    return didBailout;
  }

  function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) {
    if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) {
      warnIfUnhydratedTailNodes(workInProgress);
      resetHydrationState();
      workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture;
      return false;
    }

    var wasHydrated = popHydrationState(workInProgress);

    if (nextState !== null && nextState.dehydrated !== null) {
      // We might be inside a hydration state the first time we're picking up this
      // Suspense boundary, and also after we've reentered it for further hydration.
      if (current === null) {
        if (!wasHydrated) {
          throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.');
        }

        prepareToHydrateHostSuspenseInstance(workInProgress);
        bubbleProperties(workInProgress);

        {
          if ((workInProgress.mode & ProfileMode) !== NoMode) {
            var isTimedOutSuspense = nextState !== null;

            if (isTimedOutSuspense) {
              // Don't count time spent in a timed out Suspense subtree as part of the base duration.
              var primaryChildFragment = workInProgress.child;

              if (primaryChildFragment !== null) {
                // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
                workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
              }
            }
          }
        }

        return false;
      } else {
        // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
        // state since we're now exiting out of it. popHydrationState doesn't do that for us.
        resetHydrationState();

        if ((workInProgress.flags & DidCapture) === NoFlags) {
          // This boundary did not suspend so it's now hydrated and unsuspended.
          workInProgress.memoizedState = null;
        } // If nothing suspended, we need to schedule an effect to mark this boundary
        // as having hydrated so events know that they're free to be invoked.
        // It's also a signal to replay events and the suspense callback.
        // If something suspended, schedule an effect to attach retry listeners.
        // So we might as well always mark this.


        workInProgress.flags |= Update;
        bubbleProperties(workInProgress);

        {
          if ((workInProgress.mode & ProfileMode) !== NoMode) {
            var _isTimedOutSuspense = nextState !== null;

            if (_isTimedOutSuspense) {
              // Don't count time spent in a timed out Suspense subtree as part of the base duration.
              var _primaryChildFragment = workInProgress.child;

              if (_primaryChildFragment !== null) {
                // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
                workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
              }
            }
          }
        }

        return false;
      }
    } else {
      // Successfully completed this tree. If this was a forced client render,
      // there may have been recoverable errors during first hydration
      // attempt. If so, add them to a queue so we can log them in the
      // commit phase.
      upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path

      return true;
    }
  }

  function completeWork(current, workInProgress, renderLanes) {
    var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing
    // to the current tree provider fiber is just as fast and less error-prone.
    // Ideally we would have a special version of the work loop only
    // for hydration.

    popTreeContext(workInProgress);

    switch (workInProgress.tag) {
      case IndeterminateComponent:
      case LazyComponent:
      case SimpleMemoComponent:
      case FunctionComponent:
      case ForwardRef:
      case Fragment:
      case Mode:
      case Profiler:
      case ContextConsumer:
      case MemoComponent:
        bubbleProperties(workInProgress);
        return null;

      case ClassComponent:
        {
          var Component = workInProgress.type;

          if (isContextProvider(Component)) {
            popContext(workInProgress);
          }

          bubbleProperties(workInProgress);
          return null;
        }

      case HostRoot:
        {
          var fiberRoot = workInProgress.stateNode;
          popHostContainer(workInProgress);
          popTopLevelContextObject(workInProgress);
          resetWorkInProgressVersions();

          if (fiberRoot.pendingContext) {
            fiberRoot.context = fiberRoot.pendingContext;
            fiberRoot.pendingContext = null;
          }

          if (current === null || current.child === null) {
            // If we hydrated, pop so that we can delete any remaining children
            // that weren't hydrated.
            var wasHydrated = popHydrationState(workInProgress);

            if (wasHydrated) {
              // If we hydrated, then we'll need to schedule an update for
              // the commit side-effects on the root.
              markUpdate(workInProgress);
            } else {
              if (current !== null) {
                var prevState = current.memoizedState;

                if ( // Check if this is a client root
                !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
                (workInProgress.flags & ForceClientRender) !== NoFlags) {
                  // Schedule an effect to clear this container at the start of the
                  // next commit. This handles the case of React rendering into a
                  // container with previous children. It's also safe to do for
                  // updates too, because current.child would only be null if the
                  // previous render was null (so the container would already
                  // be empty).
                  workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been
                  // recoverable errors during first hydration attempt. If so, add
                  // them to a queue so we can log them in the commit phase.

                  upgradeHydrationErrorsToRecoverable();
                }
              }
            }
          }

          updateHostContainer(current, workInProgress);
          bubbleProperties(workInProgress);

          return null;
        }

      case HostComponent:
        {
          popHostContext(workInProgress);
          var rootContainerInstance = getRootHostContainer();
          var type = workInProgress.type;

          if (current !== null && workInProgress.stateNode != null) {
            updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);

            if (current.ref !== workInProgress.ref) {
              markRef$1(workInProgress);
            }
          } else {
            if (!newProps) {
              if (workInProgress.stateNode === null) {
                throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
              } // This can happen when we abort work.


              bubbleProperties(workInProgress);
              return null;
            }

            var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
            // "stack" as the parent. Then append children as we go in beginWork
            // or completeWork depending on whether we want to add them top->down or
            // bottom->up. Top->down is faster in IE11.

            var _wasHydrated = popHydrationState(workInProgress);

            if (_wasHydrated) {
              // TODO: Move this and createInstance step into the beginPhase
              // to consolidate.
              if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
                // If changes to the hydrated node need to be applied at the
                // commit-phase we mark this as such.
                markUpdate(workInProgress);
              }
            } else {
              var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
              appendAllChildren(instance, workInProgress, false, false);
              workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
              // (eg DOM renderer supports auto-focus for certain elements).
              // Make sure such renderers get scheduled for later work.

              if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
                markUpdate(workInProgress);
              }
            }

            if (workInProgress.ref !== null) {
              // If there is a ref on a host node we need to schedule a callback
              markRef$1(workInProgress);
            }
          }

          bubbleProperties(workInProgress);
          return null;
        }

      case HostText:
        {
          var newText = newProps;

          if (current && workInProgress.stateNode != null) {
            var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
            // to schedule a side-effect to do the updates.

            updateHostText$1(current, workInProgress, oldText, newText);
          } else {
            if (typeof newText !== 'string') {
              if (workInProgress.stateNode === null) {
                throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
              } // This can happen when we abort work.

            }

            var _rootContainerInstance = getRootHostContainer();

            var _currentHostContext = getHostContext();

            var _wasHydrated2 = popHydrationState(workInProgress);

            if (_wasHydrated2) {
              if (prepareToHydrateHostTextInstance(workInProgress)) {
                markUpdate(workInProgress);
              }
            } else {
              workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
            }
          }

          bubbleProperties(workInProgress);
          return null;
        }

      case SuspenseComponent:
        {
          popSuspenseContext(workInProgress);
          var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this
          // to its own fiber type so that we can add other kinds of hydration
          // boundaries that aren't associated with a Suspense tree. In anticipation
          // of such a refactor, all the hydration logic is contained in
          // this branch.

          if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) {
            var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState);

            if (!fallthroughToNormalSuspensePath) {
              if (workInProgress.flags & ShouldCapture) {
                // Special case. There were remaining unhydrated nodes. We treat
                // this as a mismatch. Revert to client rendering.
                return workInProgress;
              } else {
                // Did not finish hydrating, either because this is the initial
                // render or because something suspended.
                return null;
              }
            } // Continue with the normal Suspense path.

          }

          if ((workInProgress.flags & DidCapture) !== NoFlags) {
            // Something suspended. Re-render with the fallback children.
            workInProgress.lanes = renderLanes; // Do not reset the effect list.

            if ( (workInProgress.mode & ProfileMode) !== NoMode) {
              transferActualDuration(workInProgress);
            } // Don't bubble properties in this case.


            return workInProgress;
          }

          var nextDidTimeout = nextState !== null;
          var prevDidTimeout = current !== null && current.memoizedState !== null;
          // a passive effect, which is when we process the transitions


          if (nextDidTimeout !== prevDidTimeout) {
            // an effect to toggle the subtree's visibility. When we switch from
            // fallback -> primary, the inner Offscreen fiber schedules this effect
            // as part of its normal complete phase. But when we switch from
            // primary -> fallback, the inner Offscreen fiber does not have a complete
            // phase. So we need to schedule its effect here.
            //
            // We also use this flag to connect/disconnect the effects, but the same
            // logic applies: when re-connecting, the Offscreen fiber's complete
            // phase will handle scheduling the effect. It's only when the fallback
            // is active that we have to do anything special.


            if (nextDidTimeout) {
              var _offscreenFiber2 = workInProgress.child;
              _offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything
              // in the concurrent tree already suspended during this render.
              // This is a known bug.

              if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
                // TODO: Move this back to throwException because this is too late
                // if this is a large tree which is common for initial loads. We
                // don't know if we should restart a render or not until we get
                // this marker, and this is too late.
                // If this render already had a ping or lower pri updates,
                // and this is the first time we know we're going to suspend we
                // should be able to immediately restart from within throwException.
                var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback);

                if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
                  // If this was in an invisible tree or a new render, then showing
                  // this boundary is ok.
                  renderDidSuspend();
                } else {
                  // Otherwise, we're going to have to hide content so we should
                  // suspend for longer if possible.
                  renderDidSuspendDelayIfPossible();
                }
              }
            }
          }

          var wakeables = workInProgress.updateQueue;

          if (wakeables !== null) {
            // Schedule an effect to attach a retry listener to the promise.
            // TODO: Move to passive phase
            workInProgress.flags |= Update;
          }

          bubbleProperties(workInProgress);

          {
            if ((workInProgress.mode & ProfileMode) !== NoMode) {
              if (nextDidTimeout) {
                // Don't count time spent in a timed out Suspense subtree as part of the base duration.
                var primaryChildFragment = workInProgress.child;

                if (primaryChildFragment !== null) {
                  // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
                  workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
                }
              }
            }
          }

          return null;
        }

      case HostPortal:
        popHostContainer(workInProgress);
        updateHostContainer(current, workInProgress);

        if (current === null) {
          preparePortalMount(workInProgress.stateNode.containerInfo);
        }

        bubbleProperties(workInProgress);
        return null;

      case ContextProvider:
        // Pop provider fiber
        var context = workInProgress.type._context;
        popProvider(context, workInProgress);
        bubbleProperties(workInProgress);
        return null;

      case IncompleteClassComponent:
        {
          // Same as class component case. I put it down here so that the tags are
          // sequential to ensure this switch is compiled to a jump table.
          var _Component = workInProgress.type;

          if (isContextProvider(_Component)) {
            popContext(workInProgress);
          }

          bubbleProperties(workInProgress);
          return null;
        }

      case SuspenseListComponent:
        {
          popSuspenseContext(workInProgress);
          var renderState = workInProgress.memoizedState;

          if (renderState === null) {
            // We're running in the default, "independent" mode.
            // We don't do anything in this mode.
            bubbleProperties(workInProgress);
            return null;
          }

          var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
          var renderedTail = renderState.rendering;

          if (renderedTail === null) {
            // We just rendered the head.
            if (!didSuspendAlready) {
              // This is the first pass. We need to figure out if anything is still
              // suspended in the rendered set.
              // If new content unsuspended, but there's still some content that
              // didn't. Then we need to do a second pass that forces everything
              // to keep showing their fallbacks.
              // We might be suspended if something in this render pass suspended, or
              // something in the previous committed pass suspended. Otherwise,
              // there's no chance so we can skip the expensive call to
              // findFirstSuspended.
              var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);

              if (!cannotBeSuspended) {
                var row = workInProgress.child;

                while (row !== null) {
                  var suspended = findFirstSuspended(row);

                  if (suspended !== null) {
                    didSuspendAlready = true;
                    workInProgress.flags |= DidCapture;
                    cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
                    // part of the second pass. In that case nothing will subscribe to
                    // its thenables. Instead, we'll transfer its thenables to the
                    // SuspenseList so that it can retry if they resolve.
                    // There might be multiple of these in the list but since we're
                    // going to wait for all of them anyway, it doesn't really matter
                    // which ones gets to ping. In theory we could get clever and keep
                    // track of how many dependencies remain but it gets tricky because
                    // in the meantime, we can add/remove/change items and dependencies.
                    // We might bail out of the loop before finding any but that
                    // doesn't matter since that means that the other boundaries that
                    // we did find already has their listeners attached.

                    var newThenables = suspended.updateQueue;

                    if (newThenables !== null) {
                      workInProgress.updateQueue = newThenables;
                      workInProgress.flags |= Update;
                    } // Rerender the whole list, but this time, we'll force fallbacks
                    // to stay in place.
                    // Reset the effect flags before doing the second pass since that's now invalid.
                    // Reset the child fibers to their original state.


                    workInProgress.subtreeFlags = NoFlags;
                    resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
                    // rerender the children.

                    pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case.

                    return workInProgress.child;
                  }

                  row = row.sibling;
                }
              }

              if (renderState.tail !== null && now() > getRenderTargetTime()) {
                // We have already passed our CPU deadline but we still have rows
                // left in the tail. We'll just give up further attempts to render
                // the main content and only render fallbacks.
                workInProgress.flags |= DidCapture;
                didSuspendAlready = true;
                cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
                // to get it started back up to attempt the next item. While in terms
                // of priority this work has the same priority as this current render,
                // it's not part of the same transition once the transition has
                // committed. If it's sync, we still want to yield so that it can be
                // painted. Conceptually, this is really the same as pinging.
                // We can use any RetryLane even if it's the one currently rendering
                // since we're leaving it behind on this node.

                workInProgress.lanes = SomeRetryLane;
              }
            } else {
              cutOffTailIfNeeded(renderState, false);
            } // Next we're going to render the tail.

          } else {
            // Append the rendered row to the child list.
            if (!didSuspendAlready) {
              var _suspended = findFirstSuspended(renderedTail);

              if (_suspended !== null) {
                workInProgress.flags |= DidCapture;
                didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
                // get lost if this row ends up dropped during a second pass.

                var _newThenables = _suspended.updateQueue;

                if (_newThenables !== null) {
                  workInProgress.updateQueue = _newThenables;
                  workInProgress.flags |= Update;
                }

                cutOffTailIfNeeded(renderState, true); // This might have been modified.

                if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
                ) {
                    // We're done.
                    bubbleProperties(workInProgress);
                    return null;
                  }
              } else if ( // The time it took to render last row is greater than the remaining
              // time we have to render. So rendering one more row would likely
              // exceed it.
              now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
                // We have now passed our CPU deadline and we'll just give up further
                // attempts to render the main content and only render fallbacks.
                // The assumption is that this is usually faster.
                workInProgress.flags |= DidCapture;
                didSuspendAlready = true;
                cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
                // to get it started back up to attempt the next item. While in terms
                // of priority this work has the same priority as this current render,
                // it's not part of the same transition once the transition has
                // committed. If it's sync, we still want to yield so that it can be
                // painted. Conceptually, this is really the same as pinging.
                // We can use any RetryLane even if it's the one currently rendering
                // since we're leaving it behind on this node.

                workInProgress.lanes = SomeRetryLane;
              }
            }

            if (renderState.isBackwards) {
              // The effect list of the backwards tail will have been added
              // to the end. This breaks the guarantee that life-cycles fire in
              // sibling order but that isn't a strong guarantee promised by React.
              // Especially since these might also just pop in during future commits.
              // Append to the beginning of the list.
              renderedTail.sibling = workInProgress.child;
              workInProgress.child = renderedTail;
            } else {
              var previousSibling = renderState.last;

              if (previousSibling !== null) {
                previousSibling.sibling = renderedTail;
              } else {
                workInProgress.child = renderedTail;
              }

              renderState.last = renderedTail;
            }
          }

          if (renderState.tail !== null) {
            // We still have tail rows to render.
            // Pop a row.
            var next = renderState.tail;
            renderState.rendering = next;
            renderState.tail = next.sibling;
            renderState.renderingStartTime = now();
            next.sibling = null; // Restore the context.
            // TODO: We can probably just avoid popping it instead and only
            // setting it the first time we go from not suspended to suspended.

            var suspenseContext = suspenseStackCursor.current;

            if (didSuspendAlready) {
              suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
            } else {
              suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
            }

            pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
            // Don't bubble properties in this case.

            return next;
          }

          bubbleProperties(workInProgress);
          return null;
        }

      case ScopeComponent:
        {

          break;
        }

      case OffscreenComponent:
      case LegacyHiddenComponent:
        {
          popRenderLanes(workInProgress);
          var _nextState = workInProgress.memoizedState;
          var nextIsHidden = _nextState !== null;

          if (current !== null) {
            var _prevState = current.memoizedState;
            var prevIsHidden = _prevState !== null;

            if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding â€” it only pre-renders.
            !enableLegacyHidden )) {
              workInProgress.flags |= Visibility;
            }
          }

          if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) {
            bubbleProperties(workInProgress);
          } else {
            // Don't bubble properties for hidden children unless we're rendering
            // at offscreen priority.
            if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
              bubbleProperties(workInProgress);

              {
                // Check if there was an insertion or update in the hidden subtree.
                // If so, we need to hide those nodes in the commit phase, so
                // schedule a visibility effect.
                if ( workInProgress.subtreeFlags & (Placement | Update)) {
                  workInProgress.flags |= Visibility;
                }
              }
            }
          }
          return null;
        }

      case CacheComponent:
        {

          return null;
        }

      case TracingMarkerComponent:
        {

          return null;
        }
    }

    throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
  }

  function unwindWork(current, workInProgress, renderLanes) {
    // Note: This intentionally doesn't check if we're hydrating because comparing
    // to the current tree provider fiber is just as fast and less error-prone.
    // Ideally we would have a special version of the work loop only
    // for hydration.
    popTreeContext(workInProgress);

    switch (workInProgress.tag) {
      case ClassComponent:
        {
          var Component = workInProgress.type;

          if (isContextProvider(Component)) {
            popContext(workInProgress);
          }

          var flags = workInProgress.flags;

          if (flags & ShouldCapture) {
            workInProgress.flags = flags & ~ShouldCapture | DidCapture;

            if ( (workInProgress.mode & ProfileMode) !== NoMode) {
              transferActualDuration(workInProgress);
            }

            return workInProgress;
          }

          return null;
        }

      case HostRoot:
        {
          var root = workInProgress.stateNode;
          popHostContainer(workInProgress);
          popTopLevelContextObject(workInProgress);
          resetWorkInProgressVersions();
          var _flags = workInProgress.flags;

          if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
            // There was an error during render that wasn't captured by a suspense
            // boundary. Do a second pass on the root to unmount the children.
            workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
            return workInProgress;
          } // We unwound to the root without completing it. Exit.


          return null;
        }

      case HostComponent:
        {
          // TODO: popHydrationState
          popHostContext(workInProgress);
          return null;
        }

      case SuspenseComponent:
        {
          popSuspenseContext(workInProgress);
          var suspenseState = workInProgress.memoizedState;

          if (suspenseState !== null && suspenseState.dehydrated !== null) {
            if (workInProgress.alternate === null) {
              throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.');
            }

            resetHydrationState();
          }

          var _flags2 = workInProgress.flags;

          if (_flags2 & ShouldCapture) {
            workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.

            if ( (workInProgress.mode & ProfileMode) !== NoMode) {
              transferActualDuration(workInProgress);
            }

            return workInProgress;
          }

          return null;
        }

      case SuspenseListComponent:
        {
          popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
          // caught by a nested boundary. If not, it should bubble through.

          return null;
        }

      case HostPortal:
        popHostContainer(workInProgress);
        return null;

      case ContextProvider:
        var context = workInProgress.type._context;
        popProvider(context, workInProgress);
        return null;

      case OffscreenComponent:
      case LegacyHiddenComponent:
        popRenderLanes(workInProgress);
        return null;

      case CacheComponent:

        return null;

      default:
        return null;
    }
  }

  function unwindInterruptedWork(current, interruptedWork, renderLanes) {
    // Note: This intentionally doesn't check if we're hydrating because comparing
    // to the current tree provider fiber is just as fast and less error-prone.
    // Ideally we would have a special version of the work loop only
    // for hydration.
    popTreeContext(interruptedWork);

    switch (interruptedWork.tag) {
      case ClassComponent:
        {
          var childContextTypes = interruptedWork.type.childContextTypes;

          if (childContextTypes !== null && childContextTypes !== undefined) {
            popContext(interruptedWork);
          }

          break;
        }

      case HostRoot:
        {
          var root = interruptedWork.stateNode;
          popHostContainer(interruptedWork);
          popTopLevelContextObject(interruptedWork);
          resetWorkInProgressVersions();
          break;
        }

      case HostComponent:
        {
          popHostContext(interruptedWork);
          break;
        }

      case HostPortal:
        popHostContainer(interruptedWork);
        break;

      case SuspenseComponent:
        popSuspenseContext(interruptedWork);
        break;

      case SuspenseListComponent:
        popSuspenseContext(interruptedWork);
        break;

      case ContextProvider:
        var context = interruptedWork.type._context;
        popProvider(context, interruptedWork);
        break;

      case OffscreenComponent:
      case LegacyHiddenComponent:
        popRenderLanes(interruptedWork);
        break;
    }
  }

  var didWarnAboutUndefinedSnapshotBeforeUpdate = null;

  {
    didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
  } // Used during the commit phase to track the state of the Offscreen component stack.
  // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
  // Only used when enableSuspenseLayoutEffectSemantics is enabled.


  var offscreenSubtreeIsHidden = false;
  var offscreenSubtreeWasHidden = false;
  var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
  var nextEffect = null; // Used for Profiling builds to track updaters.

  var inProgressLanes = null;
  var inProgressRoot = null;
  function reportUncaughtErrorInDEV(error) {
    // Wrapping each small part of the commit phase into a guarded
    // callback is a bit too slow (https://github.com/facebook/react/pull/21666).
    // But we rely on it to surface errors to DEV tools like overlays
    // (https://github.com/facebook/react/issues/21712).
    // As a compromise, rethrow only caught errors in a guard.
    {
      invokeGuardedCallback(null, function () {
        throw error;
      });
      clearCaughtError();
    }
  }

  var callComponentWillUnmountWithTimer = function (current, instance) {
    instance.props = current.memoizedProps;
    instance.state = current.memoizedState;

    if ( current.mode & ProfileMode) {
      try {
        startLayoutEffectTimer();
        instance.componentWillUnmount();
      } finally {
        recordLayoutEffectDuration(current);
      }
    } else {
      instance.componentWillUnmount();
    }
  }; // Capture errors so they don't interrupt mounting.


  function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) {
    try {
      commitHookEffectListMount(Layout, current);
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  } // Capture errors so they don't interrupt unmounting.


  function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
    try {
      callComponentWillUnmountWithTimer(current, instance);
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  } // Capture errors so they don't interrupt mounting.


  function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) {
    try {
      instance.componentDidMount();
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  } // Capture errors so they don't interrupt mounting.


  function safelyAttachRef(current, nearestMountedAncestor) {
    try {
      commitAttachRef(current);
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  }

  function safelyDetachRef(current, nearestMountedAncestor) {
    var ref = current.ref;

    if (ref !== null) {
      if (typeof ref === 'function') {
        var retVal;

        try {
          if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) {
            try {
              startLayoutEffectTimer();
              retVal = ref(null);
            } finally {
              recordLayoutEffectDuration(current);
            }
          } else {
            retVal = ref(null);
          }
        } catch (error) {
          captureCommitPhaseError(current, nearestMountedAncestor, error);
        }

        {
          if (typeof retVal === 'function') {
            error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current));
          }
        }
      } else {
        ref.current = null;
      }
    }
  }

  function safelyCallDestroy(current, nearestMountedAncestor, destroy) {
    try {
      destroy();
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  }

  var focusedInstanceHandle = null;
  var shouldFireAfterActiveInstanceBlur = false;
  function commitBeforeMutationEffects(root, firstChild) {
    focusedInstanceHandle = prepareForCommit(root.containerInfo);
    nextEffect = firstChild;
    commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber

    var shouldFire = shouldFireAfterActiveInstanceBlur;
    shouldFireAfterActiveInstanceBlur = false;
    focusedInstanceHandle = null;
    return shouldFire;
  }

  function commitBeforeMutationEffects_begin() {
    while (nextEffect !== null) {
      var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur.

      var child = fiber.child;

      if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
        child.return = fiber;
        nextEffect = child;
      } else {
        commitBeforeMutationEffects_complete();
      }
    }
  }

  function commitBeforeMutationEffects_complete() {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      setCurrentFiber(fiber);

      try {
        commitBeforeMutationEffectsOnFiber(fiber);
      } catch (error) {
        captureCommitPhaseError(fiber, fiber.return, error);
      }

      resetCurrentFiber();
      var sibling = fiber.sibling;

      if (sibling !== null) {
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function commitBeforeMutationEffectsOnFiber(finishedWork) {
    var current = finishedWork.alternate;
    var flags = finishedWork.flags;

    if ((flags & Snapshot) !== NoFlags) {
      setCurrentFiber(finishedWork);

      switch (finishedWork.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            break;
          }

        case ClassComponent:
          {
            if (current !== null) {
              var prevProps = current.memoizedProps;
              var prevState = current.memoizedState;
              var instance = finishedWork.stateNode; // We could update instance props and state here,
              // but instead we rely on them being set during last render.
              // TODO: revisit this when we implement resuming.

              {
                if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                  if (instance.props !== finishedWork.memoizedProps) {
                    error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                  }

                  if (instance.state !== finishedWork.memoizedState) {
                    error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                  }
                }
              }

              var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);

              {
                var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;

                if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
                  didWarnSet.add(finishedWork.type);

                  error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork));
                }
              }

              instance.__reactInternalSnapshotBeforeUpdate = snapshot;
            }

            break;
          }

        case HostRoot:
          {
            {
              var root = finishedWork.stateNode;
              clearContainer(root.containerInfo);
            }

            break;
          }

        case HostComponent:
        case HostText:
        case HostPortal:
        case IncompleteClassComponent:
          // Nothing to do for these component types
          break;

        default:
          {
            throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
          }
      }

      resetCurrentFiber();
    }
  }

  function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
    var updateQueue = finishedWork.updateQueue;
    var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

    if (lastEffect !== null) {
      var firstEffect = lastEffect.next;
      var effect = firstEffect;

      do {
        if ((effect.tag & flags) === flags) {
          // Unmount
          var destroy = effect.destroy;
          effect.destroy = undefined;

          if (destroy !== undefined) {
            {
              if ((flags & Passive$1) !== NoFlags$1) {
                markComponentPassiveEffectUnmountStarted(finishedWork);
              } else if ((flags & Layout) !== NoFlags$1) {
                markComponentLayoutEffectUnmountStarted(finishedWork);
              }
            }

            {
              if ((flags & Insertion) !== NoFlags$1) {
                setIsRunningInsertionEffect(true);
              }
            }

            safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);

            {
              if ((flags & Insertion) !== NoFlags$1) {
                setIsRunningInsertionEffect(false);
              }
            }

            {
              if ((flags & Passive$1) !== NoFlags$1) {
                markComponentPassiveEffectUnmountStopped();
              } else if ((flags & Layout) !== NoFlags$1) {
                markComponentLayoutEffectUnmountStopped();
              }
            }
          }
        }

        effect = effect.next;
      } while (effect !== firstEffect);
    }
  }

  function commitHookEffectListMount(flags, finishedWork) {
    var updateQueue = finishedWork.updateQueue;
    var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

    if (lastEffect !== null) {
      var firstEffect = lastEffect.next;
      var effect = firstEffect;

      do {
        if ((effect.tag & flags) === flags) {
          {
            if ((flags & Passive$1) !== NoFlags$1) {
              markComponentPassiveEffectMountStarted(finishedWork);
            } else if ((flags & Layout) !== NoFlags$1) {
              markComponentLayoutEffectMountStarted(finishedWork);
            }
          } // Mount


          var create = effect.create;

          {
            if ((flags & Insertion) !== NoFlags$1) {
              setIsRunningInsertionEffect(true);
            }
          }

          effect.destroy = create();

          {
            if ((flags & Insertion) !== NoFlags$1) {
              setIsRunningInsertionEffect(false);
            }
          }

          {
            if ((flags & Passive$1) !== NoFlags$1) {
              markComponentPassiveEffectMountStopped();
            } else if ((flags & Layout) !== NoFlags$1) {
              markComponentLayoutEffectMountStopped();
            }
          }

          {
            var destroy = effect.destroy;

            if (destroy !== undefined && typeof destroy !== 'function') {
              var hookName = void 0;

              if ((effect.tag & Layout) !== NoFlags) {
                hookName = 'useLayoutEffect';
              } else if ((effect.tag & Insertion) !== NoFlags) {
                hookName = 'useInsertionEffect';
              } else {
                hookName = 'useEffect';
              }

              var addendum = void 0;

              if (destroy === null) {
                addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
              } else if (typeof destroy.then === 'function') {
                addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + '  async function fetchData() {\n' + '    // You can await here\n' + '    const response = await MyAPI.getData(someId);\n' + '    // ...\n' + '  }\n' + '  fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
              } else {
                addendum = ' You returned: ' + destroy;
              }

              error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum);
            }
          }
        }

        effect = effect.next;
      } while (effect !== firstEffect);
    }
  }

  function commitPassiveEffectDurations(finishedRoot, finishedWork) {
    {
      // Only Profilers with work in their subtree will have an Update effect scheduled.
      if ((finishedWork.flags & Update) !== NoFlags) {
        switch (finishedWork.tag) {
          case Profiler:
            {
              var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
              var _finishedWork$memoize = finishedWork.memoizedProps,
                  id = _finishedWork$memoize.id,
                  onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase.
              // It does not get reset until the start of the next commit phase.

              var commitTime = getCommitTime();
              var phase = finishedWork.alternate === null ? 'mount' : 'update';

              {
                if (isCurrentUpdateNested()) {
                  phase = 'nested-update';
                }
              }

              if (typeof onPostCommit === 'function') {
                onPostCommit(id, phase, passiveEffectDuration, commitTime);
              } // Bubble times to the next nearest ancestor Profiler.
              // After we process that Profiler, we'll bubble further up.


              var parentFiber = finishedWork.return;

              outer: while (parentFiber !== null) {
                switch (parentFiber.tag) {
                  case HostRoot:
                    var root = parentFiber.stateNode;
                    root.passiveEffectDuration += passiveEffectDuration;
                    break outer;

                  case Profiler:
                    var parentStateNode = parentFiber.stateNode;
                    parentStateNode.passiveEffectDuration += passiveEffectDuration;
                    break outer;
                }

                parentFiber = parentFiber.return;
              }

              break;
            }
        }
      }
    }
  }

  function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) {
    if ((finishedWork.flags & LayoutMask) !== NoFlags) {
      switch (finishedWork.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            if ( !offscreenSubtreeWasHidden) {
              // At this point layout effects have already been destroyed (during mutation phase).
              // This is done to prevent sibling component effects from interfering with each other,
              // e.g. a destroy function in one component should never override a ref set
              // by a create function in another component during the same commit.
              if ( finishedWork.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  commitHookEffectListMount(Layout | HasEffect, finishedWork);
                } finally {
                  recordLayoutEffectDuration(finishedWork);
                }
              } else {
                commitHookEffectListMount(Layout | HasEffect, finishedWork);
              }
            }

            break;
          }

        case ClassComponent:
          {
            var instance = finishedWork.stateNode;

            if (finishedWork.flags & Update) {
              if (!offscreenSubtreeWasHidden) {
                if (current === null) {
                  // We could update instance props and state here,
                  // but instead we rely on them being set during last render.
                  // TODO: revisit this when we implement resuming.
                  {
                    if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                      if (instance.props !== finishedWork.memoizedProps) {
                        error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                      }

                      if (instance.state !== finishedWork.memoizedState) {
                        error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                      }
                    }
                  }

                  if ( finishedWork.mode & ProfileMode) {
                    try {
                      startLayoutEffectTimer();
                      instance.componentDidMount();
                    } finally {
                      recordLayoutEffectDuration(finishedWork);
                    }
                  } else {
                    instance.componentDidMount();
                  }
                } else {
                  var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
                  var prevState = current.memoizedState; // We could update instance props and state here,
                  // but instead we rely on them being set during last render.
                  // TODO: revisit this when we implement resuming.

                  {
                    if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                      if (instance.props !== finishedWork.memoizedProps) {
                        error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                      }

                      if (instance.state !== finishedWork.memoizedState) {
                        error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                      }
                    }
                  }

                  if ( finishedWork.mode & ProfileMode) {
                    try {
                      startLayoutEffectTimer();
                      instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                    } finally {
                      recordLayoutEffectDuration(finishedWork);
                    }
                  } else {
                    instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                  }
                }
              }
            } // TODO: I think this is now always non-null by the time it reaches the
            // commit phase. Consider removing the type check.


            var updateQueue = finishedWork.updateQueue;

            if (updateQueue !== null) {
              {
                if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                  if (instance.props !== finishedWork.memoizedProps) {
                    error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                  }

                  if (instance.state !== finishedWork.memoizedState) {
                    error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                  }
                }
              } // We could update instance props and state here,
              // but instead we rely on them being set during last render.
              // TODO: revisit this when we implement resuming.


              commitUpdateQueue(finishedWork, updateQueue, instance);
            }

            break;
          }

        case HostRoot:
          {
            // TODO: I think this is now always non-null by the time it reaches the
            // commit phase. Consider removing the type check.
            var _updateQueue = finishedWork.updateQueue;

            if (_updateQueue !== null) {
              var _instance = null;

              if (finishedWork.child !== null) {
                switch (finishedWork.child.tag) {
                  case HostComponent:
                    _instance = getPublicInstance(finishedWork.child.stateNode);
                    break;

                  case ClassComponent:
                    _instance = finishedWork.child.stateNode;
                    break;
                }
              }

              commitUpdateQueue(finishedWork, _updateQueue, _instance);
            }

            break;
          }

        case HostComponent:
          {
            var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
            // (eg DOM renderer may schedule auto-focus for inputs and form controls).
            // These effects should only be committed when components are first mounted,
            // aka when there is no current/alternate.

            if (current === null && finishedWork.flags & Update) {
              var type = finishedWork.type;
              var props = finishedWork.memoizedProps;
              commitMount(_instance2, type, props);
            }

            break;
          }

        case HostText:
          {
            // We have no life-cycles associated with text.
            break;
          }

        case HostPortal:
          {
            // We have no life-cycles associated with portals.
            break;
          }

        case Profiler:
          {
            {
              var _finishedWork$memoize2 = finishedWork.memoizedProps,
                  onCommit = _finishedWork$memoize2.onCommit,
                  onRender = _finishedWork$memoize2.onRender;
              var effectDuration = finishedWork.stateNode.effectDuration;
              var commitTime = getCommitTime();
              var phase = current === null ? 'mount' : 'update';

              {
                if (isCurrentUpdateNested()) {
                  phase = 'nested-update';
                }
              }

              if (typeof onRender === 'function') {
                onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime);
              }

              {
                if (typeof onCommit === 'function') {
                  onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime);
                } // Schedule a passive effect for this Profiler to call onPostCommit hooks.
                // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
                // because the effect is also where times bubble to parent Profilers.


                enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor.
                // Do not reset these values until the next render so DevTools has a chance to read them first.

                var parentFiber = finishedWork.return;

                outer: while (parentFiber !== null) {
                  switch (parentFiber.tag) {
                    case HostRoot:
                      var root = parentFiber.stateNode;
                      root.effectDuration += effectDuration;
                      break outer;

                    case Profiler:
                      var parentStateNode = parentFiber.stateNode;
                      parentStateNode.effectDuration += effectDuration;
                      break outer;
                  }

                  parentFiber = parentFiber.return;
                }
              }
            }

            break;
          }

        case SuspenseComponent:
          {
            commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            break;
          }

        case SuspenseListComponent:
        case IncompleteClassComponent:
        case ScopeComponent:
        case OffscreenComponent:
        case LegacyHiddenComponent:
        case TracingMarkerComponent:
          {
            break;
          }

        default:
          throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
      }
    }

    if ( !offscreenSubtreeWasHidden) {
      {
        if (finishedWork.flags & Ref) {
          commitAttachRef(finishedWork);
        }
      }
    }
  }

  function reappearLayoutEffectsOnFiber(node) {
    // Turn on layout effects in a tree that previously disappeared.
    // TODO (Offscreen) Check: flags & LayoutStatic
    switch (node.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          if ( node.mode & ProfileMode) {
            try {
              startLayoutEffectTimer();
              safelyCallCommitHookLayoutEffectListMount(node, node.return);
            } finally {
              recordLayoutEffectDuration(node);
            }
          } else {
            safelyCallCommitHookLayoutEffectListMount(node, node.return);
          }

          break;
        }

      case ClassComponent:
        {
          var instance = node.stateNode;

          if (typeof instance.componentDidMount === 'function') {
            safelyCallComponentDidMount(node, node.return, instance);
          }

          safelyAttachRef(node, node.return);
          break;
        }

      case HostComponent:
        {
          safelyAttachRef(node, node.return);
          break;
        }
    }
  }

  function hideOrUnhideAllChildren(finishedWork, isHidden) {
    // Only hide or unhide the top-most host nodes.
    var hostSubtreeRoot = null;

    {
      // We only have the top Fiber that was inserted but we need to recurse down its
      // children to find all the terminal nodes.
      var node = finishedWork;

      while (true) {
        if (node.tag === HostComponent) {
          if (hostSubtreeRoot === null) {
            hostSubtreeRoot = node;

            try {
              var instance = node.stateNode;

              if (isHidden) {
                hideInstance(instance);
              } else {
                unhideInstance(node.stateNode, node.memoizedProps);
              }
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
        } else if (node.tag === HostText) {
          if (hostSubtreeRoot === null) {
            try {
              var _instance3 = node.stateNode;

              if (isHidden) {
                hideTextInstance(_instance3);
              } else {
                unhideTextInstance(_instance3, node.memoizedProps);
              }
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
        } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === finishedWork) {
          return;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === finishedWork) {
            return;
          }

          if (hostSubtreeRoot === node) {
            hostSubtreeRoot = null;
          }

          node = node.return;
        }

        if (hostSubtreeRoot === node) {
          hostSubtreeRoot = null;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    }
  }

  function commitAttachRef(finishedWork) {
    var ref = finishedWork.ref;

    if (ref !== null) {
      var instance = finishedWork.stateNode;
      var instanceToUse;

      switch (finishedWork.tag) {
        case HostComponent:
          instanceToUse = getPublicInstance(instance);
          break;

        default:
          instanceToUse = instance;
      } // Moved outside to ensure DCE works with this flag

      if (typeof ref === 'function') {
        var retVal;

        if ( finishedWork.mode & ProfileMode) {
          try {
            startLayoutEffectTimer();
            retVal = ref(instanceToUse);
          } finally {
            recordLayoutEffectDuration(finishedWork);
          }
        } else {
          retVal = ref(instanceToUse);
        }

        {
          if (typeof retVal === 'function') {
            error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork));
          }
        }
      } else {
        {
          if (!ref.hasOwnProperty('current')) {
            error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork));
          }
        }

        ref.current = instanceToUse;
      }
    }
  }

  function detachFiberMutation(fiber) {
    // Cut off the return pointer to disconnect it from the tree.
    // This enables us to detect and warn against state updates on an unmounted component.
    // It also prevents events from bubbling from within disconnected components.
    //
    // Ideally, we should also clear the child pointer of the parent alternate to let this
    // get GC:ed but we don't know which for sure which parent is the current
    // one so we'll settle for GC:ing the subtree of this child.
    // This child itself will be GC:ed when the parent updates the next time.
    //
    // Note that we can't clear child or sibling pointers yet.
    // They're needed for passive effects and for findDOMNode.
    // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
    //
    // Don't reset the alternate yet, either. We need that so we can detach the
    // alternate's fields in the passive phase. Clearing the return pointer is
    // sufficient for findDOMNode semantics.
    var alternate = fiber.alternate;

    if (alternate !== null) {
      alternate.return = null;
    }

    fiber.return = null;
  }

  function detachFiberAfterEffects(fiber) {
    var alternate = fiber.alternate;

    if (alternate !== null) {
      fiber.alternate = null;
      detachFiberAfterEffects(alternate);
    } // Note: Defensively using negation instead of < in case
    // `deletedTreeCleanUpLevel` is undefined.


    {
      // Clear cyclical Fiber fields. This level alone is designed to roughly
      // approximate the planned Fiber refactor. In that world, `setState` will be
      // bound to a special "instance" object instead of a Fiber. The Instance
      // object will not have any of these fields. It will only be connected to
      // the fiber tree via a single link at the root. So if this level alone is
      // sufficient to fix memory issues, that bodes well for our plans.
      fiber.child = null;
      fiber.deletions = null;
      fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host
      // tree, which has its own pointers to children, parents, and siblings.
      // The other host nodes also point back to fibers, so we should detach that
      // one, too.

      if (fiber.tag === HostComponent) {
        var hostInstance = fiber.stateNode;

        if (hostInstance !== null) {
          detachDeletedInstance(hostInstance);
        }
      }

      fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We
      // already disconnect the `return` pointer at the root of the deleted
      // subtree (in `detachFiberMutation`). Besides, `return` by itself is not
      // cyclical â€” it's only cyclical when combined with `child`, `sibling`, and
      // `alternate`. But we'll clear it in the next level anyway, just in case.

      {
        fiber._debugOwner = null;
      }

      {
        // Theoretically, nothing in here should be necessary, because we already
        // disconnected the fiber from the tree. So even if something leaks this
        // particular fiber, it won't leak anything else
        //
        // The purpose of this branch is to be super aggressive so we can measure
        // if there's any difference in memory impact. If there is, that could
        // indicate a React leak we don't know about.
        fiber.return = null;
        fiber.dependencies = null;
        fiber.memoizedProps = null;
        fiber.memoizedState = null;
        fiber.pendingProps = null;
        fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.

        fiber.updateQueue = null;
      }
    }
  }

  function getHostParentFiber(fiber) {
    var parent = fiber.return;

    while (parent !== null) {
      if (isHostParent(parent)) {
        return parent;
      }

      parent = parent.return;
    }

    throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.');
  }

  function isHostParent(fiber) {
    return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
  }

  function getHostSibling(fiber) {
    // We're going to search forward into the tree until we find a sibling host
    // node. Unfortunately, if multiple insertions are done in a row we have to
    // search past them. This leads to exponential search for the next sibling.
    // TODO: Find a more efficient way to do this.
    var node = fiber;

    siblings: while (true) {
      // If we didn't find anything, let's try the next sibling.
      while (node.sibling === null) {
        if (node.return === null || isHostParent(node.return)) {
          // If we pop out of the root or hit the parent the fiber we are the
          // last sibling.
          return null;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;

      while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
        // If it is not host node and, we might have a host node inside it.
        // Try to search down until we find one.
        if (node.flags & Placement) {
          // If we don't have a child, try the siblings instead.
          continue siblings;
        } // If we don't have a child, try the siblings instead.
        // We also skip portals because they are not part of this host tree.


        if (node.child === null || node.tag === HostPortal) {
          continue siblings;
        } else {
          node.child.return = node;
          node = node.child;
        }
      } // Check if this host node is stable or about to be placed.


      if (!(node.flags & Placement)) {
        // Found it!
        return node.stateNode;
      }
    }
  }

  function commitPlacement(finishedWork) {


    var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.

    switch (parentFiber.tag) {
      case HostComponent:
        {
          var parent = parentFiber.stateNode;

          if (parentFiber.flags & ContentReset) {
            // Reset the text content of the parent before doing any insertions
            resetTextContent(parent); // Clear ContentReset from the effect tag

            parentFiber.flags &= ~ContentReset;
          }

          var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
          // children to find all the terminal nodes.

          insertOrAppendPlacementNode(finishedWork, before, parent);
          break;
        }

      case HostRoot:
      case HostPortal:
        {
          var _parent = parentFiber.stateNode.containerInfo;

          var _before = getHostSibling(finishedWork);

          insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
          break;
        }
      // eslint-disable-next-line-no-fallthrough

      default:
        throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.');
    }
  }

  function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
    var tag = node.tag;
    var isHost = tag === HostComponent || tag === HostText;

    if (isHost) {
      var stateNode = node.stateNode;

      if (before) {
        insertInContainerBefore(parent, stateNode, before);
      } else {
        appendChildToContainer(parent, stateNode);
      }
    } else if (tag === HostPortal) ; else {
      var child = node.child;

      if (child !== null) {
        insertOrAppendPlacementNodeIntoContainer(child, before, parent);
        var sibling = child.sibling;

        while (sibling !== null) {
          insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
          sibling = sibling.sibling;
        }
      }
    }
  }

  function insertOrAppendPlacementNode(node, before, parent) {
    var tag = node.tag;
    var isHost = tag === HostComponent || tag === HostText;

    if (isHost) {
      var stateNode = node.stateNode;

      if (before) {
        insertBefore(parent, stateNode, before);
      } else {
        appendChild(parent, stateNode);
      }
    } else if (tag === HostPortal) ; else {
      var child = node.child;

      if (child !== null) {
        insertOrAppendPlacementNode(child, before, parent);
        var sibling = child.sibling;

        while (sibling !== null) {
          insertOrAppendPlacementNode(sibling, before, parent);
          sibling = sibling.sibling;
        }
      }
    }
  } // These are tracked on the stack as we recursively traverse a
  // deleted subtree.
  // TODO: Update these during the whole mutation phase, not just during
  // a deletion.


  var hostParent = null;
  var hostParentIsContainer = false;

  function commitDeletionEffects(root, returnFiber, deletedFiber) {
    {
      // We only have the top Fiber that was deleted but we need to recurse down its
      // children to find all the terminal nodes.
      // Recursively delete all host nodes from the parent, detach refs, clean
      // up mounted layout effects, and call componentWillUnmount.
      // We only need to remove the topmost host child in each branch. But then we
      // still need to keep traversing to unmount effects, refs, and cWU. TODO: We
      // could split this into two separate traversals functions, where the second
      // one doesn't include any removeChild logic. This is maybe the same
      // function as "disappearLayoutEffects" (or whatever that turns into after
      // the layout phase is refactored to use recursion).
      // Before starting, find the nearest host parent on the stack so we know
      // which instance/container to remove the children from.
      // TODO: Instead of searching up the fiber return path on every deletion, we
      // can track the nearest host component on the JS stack as we traverse the
      // tree during the commit phase. This would make insertions faster, too.
      var parent = returnFiber;

      findParent: while (parent !== null) {
        switch (parent.tag) {
          case HostComponent:
            {
              hostParent = parent.stateNode;
              hostParentIsContainer = false;
              break findParent;
            }

          case HostRoot:
            {
              hostParent = parent.stateNode.containerInfo;
              hostParentIsContainer = true;
              break findParent;
            }

          case HostPortal:
            {
              hostParent = parent.stateNode.containerInfo;
              hostParentIsContainer = true;
              break findParent;
            }
        }

        parent = parent.return;
      }

      if (hostParent === null) {
        throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.');
      }

      commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
      hostParent = null;
      hostParentIsContainer = false;
    }

    detachFiberMutation(deletedFiber);
  }

  function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
    // TODO: Use a static flag to skip trees that don't have unmount effects
    var child = parent.child;

    while (child !== null) {
      commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
      child = child.sibling;
    }
  }

  function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
    onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse
    // into their subtree. There are simpler cases in the inner switch
    // that don't modify the stack.

    switch (deletedFiber.tag) {
      case HostComponent:
        {
          if (!offscreenSubtreeWasHidden) {
            safelyDetachRef(deletedFiber, nearestMountedAncestor);
          } // Intentional fallthrough to next branch

        }
      // eslint-disable-next-line-no-fallthrough

      case HostText:
        {
          // We only need to remove the nearest host child. Set the host parent
          // to `null` on the stack to indicate that nested children don't
          // need to be removed.
          {
            var prevHostParent = hostParent;
            var prevHostParentIsContainer = hostParentIsContainer;
            hostParent = null;
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            hostParent = prevHostParent;
            hostParentIsContainer = prevHostParentIsContainer;

            if (hostParent !== null) {
              // Now that all the child effects have unmounted, we can remove the
              // node from the tree.
              if (hostParentIsContainer) {
                removeChildFromContainer(hostParent, deletedFiber.stateNode);
              } else {
                removeChild(hostParent, deletedFiber.stateNode);
              }
            }
          }

          return;
        }

      case DehydratedFragment:
        {
          // Delete the dehydrated suspense boundary and all of its content.


          {
            if (hostParent !== null) {
              if (hostParentIsContainer) {
                clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
              } else {
                clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
              }
            }
          }

          return;
        }

      case HostPortal:
        {
          {
            // When we go into a portal, it becomes the parent to remove from.
            var _prevHostParent = hostParent;
            var _prevHostParentIsContainer = hostParentIsContainer;
            hostParent = deletedFiber.stateNode.containerInfo;
            hostParentIsContainer = true;
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            hostParent = _prevHostParent;
            hostParentIsContainer = _prevHostParentIsContainer;
          }

          return;
        }

      case FunctionComponent:
      case ForwardRef:
      case MemoComponent:
      case SimpleMemoComponent:
        {
          if (!offscreenSubtreeWasHidden) {
            var updateQueue = deletedFiber.updateQueue;

            if (updateQueue !== null) {
              var lastEffect = updateQueue.lastEffect;

              if (lastEffect !== null) {
                var firstEffect = lastEffect.next;
                var effect = firstEffect;

                do {
                  var _effect = effect,
                      destroy = _effect.destroy,
                      tag = _effect.tag;

                  if (destroy !== undefined) {
                    if ((tag & Insertion) !== NoFlags$1) {
                      safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                    } else if ((tag & Layout) !== NoFlags$1) {
                      {
                        markComponentLayoutEffectUnmountStarted(deletedFiber);
                      }

                      if ( deletedFiber.mode & ProfileMode) {
                        startLayoutEffectTimer();
                        safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                        recordLayoutEffectDuration(deletedFiber);
                      } else {
                        safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                      }

                      {
                        markComponentLayoutEffectUnmountStopped();
                      }
                    }
                  }

                  effect = effect.next;
                } while (effect !== firstEffect);
              }
            }
          }

          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          return;
        }

      case ClassComponent:
        {
          if (!offscreenSubtreeWasHidden) {
            safelyDetachRef(deletedFiber, nearestMountedAncestor);
            var instance = deletedFiber.stateNode;

            if (typeof instance.componentWillUnmount === 'function') {
              safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance);
            }
          }

          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          return;
        }

      case ScopeComponent:
        {

          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          return;
        }

      case OffscreenComponent:
        {
          if ( // TODO: Remove this dead flag
           deletedFiber.mode & ConcurrentMode) {
            // If this offscreen component is hidden, we already unmounted it. Before
            // deleting the children, track that it's already unmounted so that we
            // don't attempt to unmount the effects again.
            // TODO: If the tree is hidden, in most cases we should be able to skip
            // over the nested children entirely. An exception is we haven't yet found
            // the topmost host node to delete, which we already track on the stack.
            // But the other case is portals, which need to be detached no matter how
            // deeply they are nested. We should use a subtree flag to track whether a
            // subtree includes a nested portal.
            var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          } else {
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          }

          break;
        }

      default:
        {
          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          return;
        }
    }
  }

  function commitSuspenseCallback(finishedWork) {
    // TODO: Move this to passive phase
    var newState = finishedWork.memoizedState;
  }

  function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {

    var newState = finishedWork.memoizedState;

    if (newState === null) {
      var current = finishedWork.alternate;

      if (current !== null) {
        var prevState = current.memoizedState;

        if (prevState !== null) {
          var suspenseInstance = prevState.dehydrated;

          if (suspenseInstance !== null) {
            commitHydratedSuspenseInstance(suspenseInstance);
          }
        }
      }
    }
  }

  function attachSuspenseRetryListeners(finishedWork) {
    // If this boundary just timed out, then it will have a set of wakeables.
    // For each wakeable, attach a listener so that when it resolves, React
    // attempts to re-render the boundary in the primary (pre-timeout) state.
    var wakeables = finishedWork.updateQueue;

    if (wakeables !== null) {
      finishedWork.updateQueue = null;
      var retryCache = finishedWork.stateNode;

      if (retryCache === null) {
        retryCache = finishedWork.stateNode = new PossiblyWeakSet();
      }

      wakeables.forEach(function (wakeable) {
        // Memoize using the boundary fiber to prevent redundant listeners.
        var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);

        if (!retryCache.has(wakeable)) {
          retryCache.add(wakeable);

          {
            if (isDevToolsPresent) {
              if (inProgressLanes !== null && inProgressRoot !== null) {
                // If we have pending work still, associate the original updaters with it.
                restorePendingUpdaters(inProgressRoot, inProgressLanes);
              } else {
                throw Error('Expected finished root and lanes to be set. This is a bug in React.');
              }
            }
          }

          wakeable.then(retry, retry);
        }
      });
    }
  } // This function detects when a Suspense boundary goes from visible to hidden.
  function commitMutationEffects(root, finishedWork, committedLanes) {
    inProgressLanes = committedLanes;
    inProgressRoot = root;
    setCurrentFiber(finishedWork);
    commitMutationEffectsOnFiber(finishedWork, root);
    setCurrentFiber(finishedWork);
    inProgressLanes = null;
    inProgressRoot = null;
  }

  function recursivelyTraverseMutationEffects(root, parentFiber, lanes) {
    // Deletions effects can be scheduled on any fiber type. They need to happen
    // before the children effects hae fired.
    var deletions = parentFiber.deletions;

    if (deletions !== null) {
      for (var i = 0; i < deletions.length; i++) {
        var childToDelete = deletions[i];

        try {
          commitDeletionEffects(root, parentFiber, childToDelete);
        } catch (error) {
          captureCommitPhaseError(childToDelete, parentFiber, error);
        }
      }
    }

    var prevDebugFiber = getCurrentFiber();

    if (parentFiber.subtreeFlags & MutationMask) {
      var child = parentFiber.child;

      while (child !== null) {
        setCurrentFiber(child);
        commitMutationEffectsOnFiber(child, root);
        child = child.sibling;
      }
    }

    setCurrentFiber(prevDebugFiber);
  }

  function commitMutationEffectsOnFiber(finishedWork, root, lanes) {
    var current = finishedWork.alternate;
    var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber,
    // because the fiber tag is more specific. An exception is any flag related
    // to reconcilation, because those can be set on all fiber types.

    switch (finishedWork.tag) {
      case FunctionComponent:
      case ForwardRef:
      case MemoComponent:
      case SimpleMemoComponent:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Update) {
            try {
              commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
              commitHookEffectListMount(Insertion | HasEffect, finishedWork);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            } // Layout effects are destroyed during the mutation phase so that all
            // destroy functions for all fibers are called before any create functions.
            // This prevents sibling component effects from interfering with each other,
            // e.g. a destroy function in one component should never override a ref set
            // by a create function in another component during the same commit.


            if ( finishedWork.mode & ProfileMode) {
              try {
                startLayoutEffectTimer();
                commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }

              recordLayoutEffectDuration(finishedWork);
            } else {
              try {
                commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
          }

          return;
        }

      case ClassComponent:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Ref) {
            if (current !== null) {
              safelyDetachRef(current, current.return);
            }
          }

          return;
        }

      case HostComponent:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Ref) {
            if (current !== null) {
              safelyDetachRef(current, current.return);
            }
          }

          {
            // TODO: ContentReset gets cleared by the children during the commit
            // phase. This is a refactor hazard because it means we must read
            // flags the flags after `commitReconciliationEffects` has already run;
            // the order matters. We should refactor so that ContentReset does not
            // rely on mutating the flag during commit. Like by setting a flag
            // during the render phase instead.
            if (finishedWork.flags & ContentReset) {
              var instance = finishedWork.stateNode;

              try {
                resetTextContent(instance);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }

            if (flags & Update) {
              var _instance4 = finishedWork.stateNode;

              if (_instance4 != null) {
                // Commit the work prepared earlier.
                var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
                // as the newProps. The updatePayload will contain the real change in
                // this case.

                var oldProps = current !== null ? current.memoizedProps : newProps;
                var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.

                var updatePayload = finishedWork.updateQueue;
                finishedWork.updateQueue = null;

                if (updatePayload !== null) {
                  try {
                    commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork);
                  } catch (error) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error);
                  }
                }
              }
            }
          }

          return;
        }

      case HostText:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Update) {
            {
              if (finishedWork.stateNode === null) {
                throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.');
              }

              var textInstance = finishedWork.stateNode;
              var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
              // as the newProps. The updatePayload will contain the real change in
              // this case.

              var oldText = current !== null ? current.memoizedProps : newText;

              try {
                commitTextUpdate(textInstance, oldText, newText);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
          }

          return;
        }

      case HostRoot:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Update) {
            {
              if (current !== null) {
                var prevRootState = current.memoizedState;

                if (prevRootState.isDehydrated) {
                  try {
                    commitHydratedContainer(root.containerInfo);
                  } catch (error) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error);
                  }
                }
              }
            }
          }

          return;
        }

      case HostPortal:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          return;
        }

      case SuspenseComponent:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);
          var offscreenFiber = finishedWork.child;

          if (offscreenFiber.flags & Visibility) {
            var offscreenInstance = offscreenFiber.stateNode;
            var newState = offscreenFiber.memoizedState;
            var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can
            // read it during an event

            offscreenInstance.isHidden = isHidden;

            if (isHidden) {
              var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;

              if (!wasHidden) {
                // TODO: Move to passive phase
                markCommitTimeOfFallback();
              }
            }
          }

          if (flags & Update) {
            try {
              commitSuspenseCallback(finishedWork);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }

            attachSuspenseRetryListeners(finishedWork);
          }

          return;
        }

      case OffscreenComponent:
        {
          var _wasHidden = current !== null && current.memoizedState !== null;

          if ( // TODO: Remove this dead flag
           finishedWork.mode & ConcurrentMode) {
            // Before committing the children, track on the stack whether this
            // offscreen subtree was already hidden, so that we don't unmount the
            // effects again.
            var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
            recursivelyTraverseMutationEffects(root, finishedWork);
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          } else {
            recursivelyTraverseMutationEffects(root, finishedWork);
          }

          commitReconciliationEffects(finishedWork);

          if (flags & Visibility) {
            var _offscreenInstance = finishedWork.stateNode;
            var _newState = finishedWork.memoizedState;

            var _isHidden = _newState !== null;

            var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can
            // read it during an event

            _offscreenInstance.isHidden = _isHidden;

            {
              if (_isHidden) {
                if (!_wasHidden) {
                  if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
                    nextEffect = offscreenBoundary;
                    var offscreenChild = offscreenBoundary.child;

                    while (offscreenChild !== null) {
                      nextEffect = offscreenChild;
                      disappearLayoutEffects_begin(offscreenChild);
                      offscreenChild = offscreenChild.sibling;
                    }
                  }
                }
              }
            }

            {
              // TODO: This needs to run whenever there's an insertion or update
              // inside a hidden Offscreen tree.
              hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
            }
          }

          return;
        }

      case SuspenseListComponent:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);

          if (flags & Update) {
            attachSuspenseRetryListeners(finishedWork);
          }

          return;
        }

      case ScopeComponent:
        {

          return;
        }

      default:
        {
          recursivelyTraverseMutationEffects(root, finishedWork);
          commitReconciliationEffects(finishedWork);
          return;
        }
    }
  }

  function commitReconciliationEffects(finishedWork) {
    // Placement effects (insertions, reorders) can be scheduled on any fiber
    // type. They needs to happen after the children effects have fired, but
    // before the effects on this fiber have fired.
    var flags = finishedWork.flags;

    if (flags & Placement) {
      try {
        commitPlacement(finishedWork);
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      } // Clear the "placement" from effect tag so that we know that this is
      // inserted, before any life-cycles like componentDidMount gets called.
      // TODO: findDOMNode doesn't rely on this any more but isMounted does
      // and isMounted is deprecated anyway so we should be able to kill this.


      finishedWork.flags &= ~Placement;
    }

    if (flags & Hydrating) {
      finishedWork.flags &= ~Hydrating;
    }
  }

  function commitLayoutEffects(finishedWork, root, committedLanes) {
    inProgressLanes = committedLanes;
    inProgressRoot = root;
    nextEffect = finishedWork;
    commitLayoutEffects_begin(finishedWork, root, committedLanes);
    inProgressLanes = null;
    inProgressRoot = null;
  }

  function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) {
    // Suspense layout effects semantics don't change for legacy roots.
    var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;

    while (nextEffect !== null) {
      var fiber = nextEffect;
      var firstChild = fiber.child;

      if ( fiber.tag === OffscreenComponent && isModernRoot) {
        // Keep track of the current Offscreen stack's state.
        var isHidden = fiber.memoizedState !== null;
        var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden;

        if (newOffscreenSubtreeIsHidden) {
          // The Offscreen tree is hidden. Skip over its layout effects.
          commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
          continue;
        } else {
          // TODO (Offscreen) Also check: subtreeFlags & LayoutMask
          var current = fiber.alternate;
          var wasHidden = current !== null && current.memoizedState !== null;
          var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
          var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
          var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root.

          offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
          offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;

          if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
            // This is the root of a reappearing boundary. Turn its layout effects
            // back on.
            nextEffect = fiber;
            reappearLayoutEffects_begin(fiber);
          }

          var child = firstChild;

          while (child !== null) {
            nextEffect = child;
            commitLayoutEffects_begin(child, // New root; bubble back up to here and stop.
            root, committedLanes);
            child = child.sibling;
          } // Restore Offscreen state and resume in our-progress traversal.


          nextEffect = fiber;
          offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
          continue;
        }
      }

      if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
        firstChild.return = fiber;
        nextEffect = firstChild;
      } else {
        commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
      }
    }
  }

  function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) {
    while (nextEffect !== null) {
      var fiber = nextEffect;

      if ((fiber.flags & LayoutMask) !== NoFlags) {
        var current = fiber.alternate;
        setCurrentFiber(fiber);

        try {
          commitLayoutEffectOnFiber(root, current, fiber, committedLanes);
        } catch (error) {
          captureCommitPhaseError(fiber, fiber.return, error);
        }

        resetCurrentFiber();
      }

      if (fiber === subtreeRoot) {
        nextEffect = null;
        return;
      }

      var sibling = fiber.sibling;

      if (sibling !== null) {
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function disappearLayoutEffects_begin(subtreeRoot) {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)

      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case MemoComponent:
        case SimpleMemoComponent:
          {
            if ( fiber.mode & ProfileMode) {
              try {
                startLayoutEffectTimer();
                commitHookEffectListUnmount(Layout, fiber, fiber.return);
              } finally {
                recordLayoutEffectDuration(fiber);
              }
            } else {
              commitHookEffectListUnmount(Layout, fiber, fiber.return);
            }

            break;
          }

        case ClassComponent:
          {
            // TODO (Offscreen) Check: flags & RefStatic
            safelyDetachRef(fiber, fiber.return);
            var instance = fiber.stateNode;

            if (typeof instance.componentWillUnmount === 'function') {
              safelyCallComponentWillUnmount(fiber, fiber.return, instance);
            }

            break;
          }

        case HostComponent:
          {
            safelyDetachRef(fiber, fiber.return);
            break;
          }

        case OffscreenComponent:
          {
            // Check if this is a
            var isHidden = fiber.memoizedState !== null;

            if (isHidden) {
              // Nested Offscreen tree is already hidden. Don't disappear
              // its effects.
              disappearLayoutEffects_complete(subtreeRoot);
              continue;
            }

            break;
          }
      } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic


      if (firstChild !== null) {
        firstChild.return = fiber;
        nextEffect = firstChild;
      } else {
        disappearLayoutEffects_complete(subtreeRoot);
      }
    }
  }

  function disappearLayoutEffects_complete(subtreeRoot) {
    while (nextEffect !== null) {
      var fiber = nextEffect;

      if (fiber === subtreeRoot) {
        nextEffect = null;
        return;
      }

      var sibling = fiber.sibling;

      if (sibling !== null) {
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function reappearLayoutEffects_begin(subtreeRoot) {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      var firstChild = fiber.child;

      if (fiber.tag === OffscreenComponent) {
        var isHidden = fiber.memoizedState !== null;

        if (isHidden) {
          // Nested Offscreen tree is still hidden. Don't re-appear its effects.
          reappearLayoutEffects_complete(subtreeRoot);
          continue;
        }
      } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic


      if (firstChild !== null) {
        // This node may have been reused from a previous render, so we can't
        // assume its return pointer is correct.
        firstChild.return = fiber;
        nextEffect = firstChild;
      } else {
        reappearLayoutEffects_complete(subtreeRoot);
      }
    }
  }

  function reappearLayoutEffects_complete(subtreeRoot) {
    while (nextEffect !== null) {
      var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic

      setCurrentFiber(fiber);

      try {
        reappearLayoutEffectsOnFiber(fiber);
      } catch (error) {
        captureCommitPhaseError(fiber, fiber.return, error);
      }

      resetCurrentFiber();

      if (fiber === subtreeRoot) {
        nextEffect = null;
        return;
      }

      var sibling = fiber.sibling;

      if (sibling !== null) {
        // This node may have been reused from a previous render, so we can't
        // assume its return pointer is correct.
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) {
    nextEffect = finishedWork;
    commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions);
  }

  function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      var firstChild = fiber.child;

      if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
        firstChild.return = fiber;
        nextEffect = firstChild;
      } else {
        commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions);
      }
    }
  }

  function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) {
    while (nextEffect !== null) {
      var fiber = nextEffect;

      if ((fiber.flags & Passive) !== NoFlags) {
        setCurrentFiber(fiber);

        try {
          commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions);
        } catch (error) {
          captureCommitPhaseError(fiber, fiber.return, error);
        }

        resetCurrentFiber();
      }

      if (fiber === subtreeRoot) {
        nextEffect = null;
        return;
      }

      var sibling = fiber.sibling;

      if (sibling !== null) {
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
    switch (finishedWork.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          if ( finishedWork.mode & ProfileMode) {
            startPassiveEffectTimer();

            try {
              commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
            } finally {
              recordPassiveEffectDuration(finishedWork);
            }
          } else {
            commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
          }

          break;
        }
    }
  }

  function commitPassiveUnmountEffects(firstChild) {
    nextEffect = firstChild;
    commitPassiveUnmountEffects_begin();
  }

  function commitPassiveUnmountEffects_begin() {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      var child = fiber.child;

      if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
        var deletions = fiber.deletions;

        if (deletions !== null) {
          for (var i = 0; i < deletions.length; i++) {
            var fiberToDelete = deletions[i];
            nextEffect = fiberToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
          }

          {
            // A fiber was deleted from this parent fiber, but it's still part of
            // the previous (alternate) parent fiber's list of children. Because
            // children are a linked list, an earlier sibling that's still alive
            // will be connected to the deleted fiber via its `alternate`:
            //
            //   live fiber
            //   --alternate--> previous live fiber
            //   --sibling--> deleted fiber
            //
            // We can't disconnect `alternate` on nodes that haven't been deleted
            // yet, but we can disconnect the `sibling` and `child` pointers.
            var previousFiber = fiber.alternate;

            if (previousFiber !== null) {
              var detachedChild = previousFiber.child;

              if (detachedChild !== null) {
                previousFiber.child = null;

                do {
                  var detachedSibling = detachedChild.sibling;
                  detachedChild.sibling = null;
                  detachedChild = detachedSibling;
                } while (detachedChild !== null);
              }
            }
          }

          nextEffect = fiber;
        }
      }

      if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
        child.return = fiber;
        nextEffect = child;
      } else {
        commitPassiveUnmountEffects_complete();
      }
    }
  }

  function commitPassiveUnmountEffects_complete() {
    while (nextEffect !== null) {
      var fiber = nextEffect;

      if ((fiber.flags & Passive) !== NoFlags) {
        setCurrentFiber(fiber);
        commitPassiveUnmountOnFiber(fiber);
        resetCurrentFiber();
      }

      var sibling = fiber.sibling;

      if (sibling !== null) {
        sibling.return = fiber.return;
        nextEffect = sibling;
        return;
      }

      nextEffect = fiber.return;
    }
  }

  function commitPassiveUnmountOnFiber(finishedWork) {
    switch (finishedWork.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          if ( finishedWork.mode & ProfileMode) {
            startPassiveEffectTimer();
            commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
            recordPassiveEffectDuration(finishedWork);
          } else {
            commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
          }

          break;
        }
    }
  }

  function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
    while (nextEffect !== null) {
      var fiber = nextEffect; // Deletion effects fire in parent -> child order
      // TODO: Check if fiber has a PassiveStatic flag

      setCurrentFiber(fiber);
      commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
      resetCurrentFiber();
      var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
      // do this, still need to handle `deletedTreeCleanUpLevel` correctly.)

      if (child !== null) {
        child.return = fiber;
        nextEffect = child;
      } else {
        commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
      }
    }
  }

  function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
    while (nextEffect !== null) {
      var fiber = nextEffect;
      var sibling = fiber.sibling;
      var returnFiber = fiber.return;

      {
        // Recursively traverse the entire deleted tree and clean up fiber fields.
        // This is more aggressive than ideal, and the long term goal is to only
        // have to detach the deleted tree at the root.
        detachFiberAfterEffects(fiber);

        if (fiber === deletedSubtreeRoot) {
          nextEffect = null;
          return;
        }
      }

      if (sibling !== null) {
        sibling.return = returnFiber;
        nextEffect = sibling;
        return;
      }

      nextEffect = returnFiber;
    }
  }

  function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) {
    switch (current.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          if ( current.mode & ProfileMode) {
            startPassiveEffectTimer();
            commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
            recordPassiveEffectDuration(current);
          } else {
            commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
          }

          break;
        }
    }
  } // TODO: Reuse reappearLayoutEffects traversal here?


  function invokeLayoutEffectMountInDEV(fiber) {
    {
      // We don't need to re-check StrictEffectsMode here.
      // This function is only called if that check has already passed.
      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            try {
              commitHookEffectListMount(Layout | HasEffect, fiber);
            } catch (error) {
              captureCommitPhaseError(fiber, fiber.return, error);
            }

            break;
          }

        case ClassComponent:
          {
            var instance = fiber.stateNode;

            try {
              instance.componentDidMount();
            } catch (error) {
              captureCommitPhaseError(fiber, fiber.return, error);
            }

            break;
          }
      }
    }
  }

  function invokePassiveEffectMountInDEV(fiber) {
    {
      // We don't need to re-check StrictEffectsMode here.
      // This function is only called if that check has already passed.
      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            try {
              commitHookEffectListMount(Passive$1 | HasEffect, fiber);
            } catch (error) {
              captureCommitPhaseError(fiber, fiber.return, error);
            }

            break;
          }
      }
    }
  }

  function invokeLayoutEffectUnmountInDEV(fiber) {
    {
      // We don't need to re-check StrictEffectsMode here.
      // This function is only called if that check has already passed.
      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            try {
              commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
            } catch (error) {
              captureCommitPhaseError(fiber, fiber.return, error);
            }

            break;
          }

        case ClassComponent:
          {
            var instance = fiber.stateNode;

            if (typeof instance.componentWillUnmount === 'function') {
              safelyCallComponentWillUnmount(fiber, fiber.return, instance);
            }

            break;
          }
      }
    }
  }

  function invokePassiveEffectUnmountInDEV(fiber) {
    {
      // We don't need to re-check StrictEffectsMode here.
      // This function is only called if that check has already passed.
      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            try {
              commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
            } catch (error) {
              captureCommitPhaseError(fiber, fiber.return, error);
            }
          }
      }
    }
  }

  var COMPONENT_TYPE = 0;
  var HAS_PSEUDO_CLASS_TYPE = 1;
  var ROLE_TYPE = 2;
  var TEST_NAME_TYPE = 3;
  var TEXT_TYPE = 4;

  if (typeof Symbol === 'function' && Symbol.for) {
    var symbolFor = Symbol.for;
    COMPONENT_TYPE = symbolFor('selector.component');
    HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class');
    ROLE_TYPE = symbolFor('selector.role');
    TEST_NAME_TYPE = symbolFor('selector.test_id');
    TEXT_TYPE = symbolFor('selector.text');
  }
  var commitHooks = [];
  function onCommitRoot$1() {
    {
      commitHooks.forEach(function (commitHook) {
        return commitHook();
      });
    }
  }

  var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
  function isLegacyActEnvironment(fiber) {
    {
      // Legacy mode. We preserve the behavior of React 17's act. It assumes an
      // act environment whenever `jest` is defined, but you can still turn off
      // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
      // to false.
      var isReactActEnvironmentGlobal = // $FlowExpectedError â€“ Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
      typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest

      var jestIsDefined = typeof jest !== 'undefined';
      return  jestIsDefined && isReactActEnvironmentGlobal !== false;
    }
  }
  function isConcurrentActEnvironment() {
    {
      var isReactActEnvironmentGlobal = // $FlowExpectedError â€“ Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
      typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined;

      if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
        // TODO: Include link to relevant documentation page.
        error('The current testing environment is not configured to support ' + 'act(...)');
      }

      return isReactActEnvironmentGlobal;
    }
  }

  var ceil = Math.ceil;
  var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
      ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
      ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig,
      ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
  var NoContext =
  /*             */
  0;
  var BatchedContext =
  /*               */
  1;
  var RenderContext =
  /*                */
  2;
  var CommitContext =
  /*                */
  4;
  var RootInProgress = 0;
  var RootFatalErrored = 1;
  var RootErrored = 2;
  var RootSuspended = 3;
  var RootSuspendedWithDelay = 4;
  var RootCompleted = 5;
  var RootDidNotComplete = 6; // Describes where we are in the React execution stack

  var executionContext = NoContext; // The root we're working on

  var workInProgressRoot = null; // The fiber we're working on

  var workInProgress = null; // The lanes we're rendering

  var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
  // This is a superset of the lanes we started working on at the root. The only
  // case where it's different from `workInProgressRootRenderLanes` is when we
  // enter a subtree that is hidden and needs to be unhidden: Suspense and
  // Offscreen component.
  //
  // Most things in the work loop should deal with workInProgressRootRenderLanes.
  // Most things in begin/complete phases should deal with subtreeRenderLanes.

  var subtreeRenderLanes = NoLanes;
  var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.

  var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown

  var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
  // slightly different than `renderLanes` because `renderLanes` can change as you
  // enter and exit an Offscreen tree. This value is the combination of all render
  // lanes for the entire render phase.

  var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
  // includes unprocessed updates, not work in bailed out children.

  var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.

  var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event).

  var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase.

  var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI.
  // We will log them once the tree commits.

  var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train
  // model where we don't commit new loading states in too quick succession.

  var globalMostRecentFallbackTime = 0;
  var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
  // more and prefer CPU suspense heuristics instead.

  var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
  // suspense heuristics and opt out of rendering more content.

  var RENDER_TIMEOUT_MS = 500;
  var workInProgressTransitions = null;

  function resetRenderTimer() {
    workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
  }

  function getRenderTargetTime() {
    return workInProgressRootRenderTargetTime;
  }
  var hasUncaughtError = false;
  var firstUncaughtError = null;
  var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true;
  var rootDoesHavePassiveEffects = false;
  var rootWithPendingPassiveEffects = null;
  var pendingPassiveEffectsLanes = NoLanes;
  var pendingPassiveProfilerEffects = [];
  var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates

  var NESTED_UPDATE_LIMIT = 50;
  var nestedUpdateCount = 0;
  var rootWithNestedUpdates = null;
  var isFlushingPassiveEffects = false;
  var didScheduleUpdateDuringPassiveEffects = false;
  var NESTED_PASSIVE_UPDATE_LIMIT = 50;
  var nestedPassiveUpdateCount = 0;
  var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their
  // event times as simultaneous, even if the actual clock time has advanced
  // between the first and second call.

  var currentEventTime = NoTimestamp;
  var currentEventTransitionLane = NoLanes;
  var isRunningInsertionEffect = false;
  function getWorkInProgressRoot() {
    return workInProgressRoot;
  }
  function requestEventTime() {
    if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
      // We're inside React, so it's fine to read the actual time.
      return now();
    } // We're not inside React, so we may be in the middle of a browser event.


    if (currentEventTime !== NoTimestamp) {
      // Use the same start time for all updates until we enter React again.
      return currentEventTime;
    } // This is the first update since React yielded. Compute a new start time.


    currentEventTime = now();
    return currentEventTime;
  }
  function requestUpdateLane(fiber) {
    // Special cases
    var mode = fiber.mode;

    if ((mode & ConcurrentMode) === NoMode) {
      return SyncLane;
    } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
      // This is a render phase update. These are not officially supported. The
      // old behavior is to give this the same "thread" (lanes) as
      // whatever is currently rendering. So if you call `setState` on a component
      // that happens later in the same render, it will flush. Ideally, we want to
      // remove the special case and treat them as if they came from an
      // interleaved event. Regardless, this pattern is not officially supported.
      // This behavior is only a fallback. The flag only exists until we can roll
      // out the setState warning, since existing code might accidentally rely on
      // the current behavior.
      return pickArbitraryLane(workInProgressRootRenderLanes);
    }

    var isTransition = requestCurrentTransition() !== NoTransition;

    if (isTransition) {
      if ( ReactCurrentBatchConfig$3.transition !== null) {
        var transition = ReactCurrentBatchConfig$3.transition;

        if (!transition._updatedFibers) {
          transition._updatedFibers = new Set();
        }

        transition._updatedFibers.add(fiber);
      } // The algorithm for assigning an update to a lane should be stable for all
      // updates at the same priority within the same event. To do this, the
      // inputs to the algorithm must be the same.
      //
      // The trick we use is to cache the first of each of these inputs within an
      // event. Then reset the cached values once we can be sure the event is
      // over. Our heuristic for that is whenever we enter a concurrent work loop.


      if (currentEventTransitionLane === NoLane) {
        // All transitions within the same event are assigned the same lane.
        currentEventTransitionLane = claimNextTransitionLane();
      }

      return currentEventTransitionLane;
    } // Updates originating inside certain React methods, like flushSync, have
    // their priority set by tracking it with a context variable.
    //
    // The opaque type returned by the host config is internally a lane, so we can
    // use that directly.
    // TODO: Move this type conversion to the event priority module.


    var updateLane = getCurrentUpdatePriority();

    if (updateLane !== NoLane) {
      return updateLane;
    } // This update originated outside React. Ask the host environment for an
    // appropriate priority, based on the type of event.
    //
    // The opaque type returned by the host config is internally a lane, so we can
    // use that directly.
    // TODO: Move this type conversion to the event priority module.


    var eventLane = getCurrentEventPriority();
    return eventLane;
  }

  function requestRetryLane(fiber) {
    // This is a fork of `requestUpdateLane` designed specifically for Suspense
    // "retries" â€” a special update that attempts to flip a Suspense boundary
    // from its placeholder state to its primary/resolved state.
    // Special cases
    var mode = fiber.mode;

    if ((mode & ConcurrentMode) === NoMode) {
      return SyncLane;
    }

    return claimNextRetryLane();
  }

  function scheduleUpdateOnFiber(root, fiber, lane, eventTime) {
    checkForNestedUpdates();

    {
      if (isRunningInsertionEffect) {
        error('useInsertionEffect must not schedule updates.');
      }
    }

    {
      if (isFlushingPassiveEffects) {
        didScheduleUpdateDuringPassiveEffects = true;
      }
    } // Mark that the root has a pending update.


    markRootUpdated(root, lane, eventTime);

    if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) {
      // This update was dispatched during the render phase. This is a mistake
      // if the update originates from user space (with the exception of local
      // hook updates, which are handled differently and don't reach this
      // function), but there are some internal React features that use this as
      // an implementation detail, like selective hydration.
      warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase
    } else {
      // This is a normal update, scheduled from outside the render phase. For
      // example, during an input event.
      {
        if (isDevToolsPresent) {
          addFiberToLanesMap(root, fiber, lane);
        }
      }

      warnIfUpdatesNotWrappedWithActDEV(fiber);

      if (root === workInProgressRoot) {
        // Received an update to a tree that's in the middle of rendering. Mark
        // that there was an interleaved update work on this root. Unless the
        // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
        // phase update. In that case, we don't treat render phase updates as if
        // they were interleaved, for backwards compat reasons.
        if ( (executionContext & RenderContext) === NoContext) {
          workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
        }

        if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
          // The root already suspended with a delay, which means this render
          // definitely won't finish. Since we have a new update, let's mark it as
          // suspended now, right before marking the incoming update. This has the
          // effect of interrupting the current render and switching to the update.
          // TODO: Make sure this doesn't override pings that happen while we've
          // already started rendering.
          markRootSuspended$1(root, workInProgressRootRenderLanes);
        }
      }

      ensureRootIsScheduled(root, eventTime);

      if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
      !( ReactCurrentActQueue$1.isBatchingLegacy)) {
        // Flush the synchronous work now, unless we're already working or inside
        // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
        // scheduleCallbackForFiber to preserve the ability to schedule a callback
        // without immediately flushing it. We only do this for user-initiated
        // updates, to preserve historical behavior of legacy mode.
        resetRenderTimer();
        flushSyncCallbacksOnlyInLegacyMode();
      }
    }
  }
  function scheduleInitialHydrationOnRoot(root, lane, eventTime) {
    // This is a special fork of scheduleUpdateOnFiber that is only used to
    // schedule the initial hydration of a root that has just been created. Most
    // of the stuff in scheduleUpdateOnFiber can be skipped.
    //
    // The main reason for this separate path, though, is to distinguish the
    // initial children from subsequent updates. In fully client-rendered roots
    // (createRoot instead of hydrateRoot), all top-level renders are modeled as
    // updates, but hydration roots are special because the initial render must
    // match what was rendered on the server.
    var current = root.current;
    current.lanes = lane;
    markRootUpdated(root, lane, eventTime);
    ensureRootIsScheduled(root, eventTime);
  }
  function isUnsafeClassRenderPhaseUpdate(fiber) {
    // Check if this is a render phase update. Only called by class components,
    // which special (deprecated) behavior for UNSAFE_componentWillReceive props.
    return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
      // decided not to enable it.
       (executionContext & RenderContext) !== NoContext
    );
  } // Use this function to schedule a task for a root. There's only one task per
  // root; if a task was already scheduled, we'll check to make sure the priority
  // of the existing task is the same as the priority of the next level that the
  // root has work on. This function is called on every update, and right before
  // exiting a task.

  function ensureRootIsScheduled(root, currentTime) {
    var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
    // expired so we know to work on those next.

    markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.

    var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);

    if (nextLanes === NoLanes) {
      // Special case: There's nothing to work on.
      if (existingCallbackNode !== null) {
        cancelCallback$1(existingCallbackNode);
      }

      root.callbackNode = null;
      root.callbackPriority = NoLane;
      return;
    } // We use the highest priority lane to represent the priority of the callback.


    var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it.

    var existingCallbackPriority = root.callbackPriority;

    if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
    // Scheduler task, rather than an `act` task, cancel it and re-scheduled
    // on the `act` queue.
    !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
      {
        // If we're going to re-use an existing task, it needs to exist.
        // Assume that discrete update microtasks are non-cancellable and null.
        // TODO: Temporary until we confirm this warning is not fired.
        if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
          error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.');
        }
      } // The priority hasn't changed. We can reuse the existing task. Exit.


      return;
    }

    if (existingCallbackNode != null) {
      // Cancel the existing callback. We'll schedule a new one below.
      cancelCallback$1(existingCallbackNode);
    } // Schedule a new callback.


    var newCallbackNode;

    if (newCallbackPriority === SyncLane) {
      // Special case: Sync React callbacks are scheduled on a special
      // internal queue
      if (root.tag === LegacyRoot) {
        if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) {
          ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
        }

        scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root));
      } else {
        scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
      }

      {
        // Flush the queue in a microtask.
        if ( ReactCurrentActQueue$1.current !== null) {
          // Inside `act`, use our internal `act` queue so that these get flushed
          // at the end of the current scope even when using the sync version
          // of `act`.
          ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
        } else {
          scheduleMicrotask(function () {
            // In Safari, appending an iframe forces microtasks to run.
            // https://github.com/facebook/react/issues/22459
            // We don't support running callbacks in the middle of render
            // or commit so we need to check against that.
            if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
              // Note that this would still prematurely flush the callbacks
              // if this happens outside render or commit phase (e.g. in an event).
              flushSyncCallbacks();
            }
          });
        }
      }

      newCallbackNode = null;
    } else {
      var schedulerPriorityLevel;

      switch (lanesToEventPriority(nextLanes)) {
        case DiscreteEventPriority:
          schedulerPriorityLevel = ImmediatePriority;
          break;

        case ContinuousEventPriority:
          schedulerPriorityLevel = UserBlockingPriority;
          break;

        case DefaultEventPriority:
          schedulerPriorityLevel = NormalPriority;
          break;

        case IdleEventPriority:
          schedulerPriorityLevel = IdlePriority;
          break;

        default:
          schedulerPriorityLevel = NormalPriority;
          break;
      }

      newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
    }

    root.callbackPriority = newCallbackPriority;
    root.callbackNode = newCallbackNode;
  } // This is the entry point for every concurrent task, i.e. anything that
  // goes through Scheduler.


  function performConcurrentWorkOnRoot(root, didTimeout) {
    {
      resetNestedUpdateFlag();
    } // Since we know we're in a React event, we can clear the current
    // event time. The next update will compute a new event time.


    currentEventTime = NoTimestamp;
    currentEventTransitionLane = NoLanes;

    if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
      throw new Error('Should not already be working.');
    } // Flush any pending passive effects before deciding which lanes to work on,
    // in case they schedule additional work.


    var originalCallbackNode = root.callbackNode;
    var didFlushPassiveEffects = flushPassiveEffects();

    if (didFlushPassiveEffects) {
      // Something in the passive effect phase may have canceled the current task.
      // Check if the task node for this root was changed.
      if (root.callbackNode !== originalCallbackNode) {
        // The current task was canceled. Exit. We don't need to call
        // `ensureRootIsScheduled` because the check above implies either that
        // there's a new task, or that there's no remaining work on this root.
        return null;
      }
    } // Determine the next lanes to work on, using the fields stored
    // on the root.


    var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);

    if (lanes === NoLanes) {
      // Defensive coding. This is never expected to happen.
      return null;
    } // We disable time-slicing in some cases: if the work has been CPU-bound
    // for too long ("expired" work, to prevent starvation), or we're in
    // sync-updates-by-default mode.
    // TODO: We only check `didTimeout` defensively, to account for a Scheduler
    // bug we're still investigating. Once the bug in Scheduler is fixed,
    // we can remove this, since we track expiration ourselves.


    var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout);
    var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes);

    if (exitStatus !== RootInProgress) {
      if (exitStatus === RootErrored) {
        // If something threw an error, try rendering one more time. We'll
        // render synchronously to block concurrent data mutations, and we'll
        // includes all pending updates are included. If it still fails after
        // the second attempt, we'll give up and commit the resulting tree.
        var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

        if (errorRetryLanes !== NoLanes) {
          lanes = errorRetryLanes;
          exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
        }
      }

      if (exitStatus === RootFatalErrored) {
        var fatalError = workInProgressRootFatalError;
        prepareFreshStack(root, NoLanes);
        markRootSuspended$1(root, lanes);
        ensureRootIsScheduled(root, now());
        throw fatalError;
      }

      if (exitStatus === RootDidNotComplete) {
        // The render unwound without completing the tree. This happens in special
        // cases where need to exit the current render without producing a
        // consistent tree or committing.
        //
        // This should only happen during a concurrent render, not a discrete or
        // synchronous update. We should have already checked for this when we
        // unwound the stack.
        markRootSuspended$1(root, lanes);
      } else {
        // The render completed.
        // Check if this render may have yielded to a concurrent event, and if so,
        // confirm that any newly rendered stores are consistent.
        // TODO: It's possible that even a concurrent render may never have yielded
        // to the main thread, if it was fast enough, or if it expired. We could
        // skip the consistency check in that case, too.
        var renderWasConcurrent = !includesBlockingLane(root, lanes);
        var finishedWork = root.current.alternate;

        if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
          // A store was mutated in an interleaved event. Render again,
          // synchronously, to block further mutations.
          exitStatus = renderRootSync(root, lanes); // We need to check again if something threw

          if (exitStatus === RootErrored) {
            var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

            if (_errorRetryLanes !== NoLanes) {
              lanes = _errorRetryLanes;
              exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any
              // concurrent events.
            }
          }

          if (exitStatus === RootFatalErrored) {
            var _fatalError = workInProgressRootFatalError;
            prepareFreshStack(root, NoLanes);
            markRootSuspended$1(root, lanes);
            ensureRootIsScheduled(root, now());
            throw _fatalError;
          }
        } // We now have a consistent tree. The next step is either to commit it,
        // or, if something suspended, wait to commit it after a timeout.


        root.finishedWork = finishedWork;
        root.finishedLanes = lanes;
        finishConcurrentRender(root, exitStatus, lanes);
      }
    }

    ensureRootIsScheduled(root, now());

    if (root.callbackNode === originalCallbackNode) {
      // The task node scheduled for this root is the same one that's
      // currently executed. Need to return a continuation.
      return performConcurrentWorkOnRoot.bind(null, root);
    }

    return null;
  }

  function recoverFromConcurrentError(root, errorRetryLanes) {
    // If an error occurred during hydration, discard server response and fall
    // back to client side render.
    // Before rendering again, save the errors from the previous attempt.
    var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;

    if (isRootDehydrated(root)) {
      // The shell failed to hydrate. Set a flag to force a client rendering
      // during the next attempt. To do this, we call prepareFreshStack now
      // to create the root work-in-progress fiber. This is a bit weird in terms
      // of factoring, because it relies on renderRootSync not calling
      // prepareFreshStack again in the call below, which happens because the
      // root and lanes haven't changed.
      //
      // TODO: I think what we should do is set ForceClientRender inside
      // throwException, like we do for nested Suspense boundaries. The reason
      // it's here instead is so we can switch to the synchronous work loop, too.
      // Something to consider for a future refactor.
      var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
      rootWorkInProgress.flags |= ForceClientRender;

      {
        errorHydratingContainer(root.containerInfo);
      }
    }

    var exitStatus = renderRootSync(root, errorRetryLanes);

    if (exitStatus !== RootErrored) {
      // Successfully finished rendering on retry
      // The errors from the failed first attempt have been recovered. Add
      // them to the collection of recoverable errors. We'll log them in the
      // commit phase.
      var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
      workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors
      // from the first attempt, to preserve the causal sequence.

      if (errorsFromSecondAttempt !== null) {
        queueRecoverableErrors(errorsFromSecondAttempt);
      }
    }

    return exitStatus;
  }

  function queueRecoverableErrors(errors) {
    if (workInProgressRootRecoverableErrors === null) {
      workInProgressRootRecoverableErrors = errors;
    } else {
      workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors);
    }
  }

  function finishConcurrentRender(root, exitStatus, lanes) {
    switch (exitStatus) {
      case RootInProgress:
      case RootFatalErrored:
        {
          throw new Error('Root did not complete. This is a bug in React.');
        }
      // Flow knows about invariant, so it complains if I add a break
      // statement, but eslint doesn't know about invariant, so it complains
      // if I do. eslint-disable-next-line no-fallthrough

      case RootErrored:
        {
          // We should have already attempted to retry this tree. If we reached
          // this point, it errored again. Commit it.
          commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
          break;
        }

      case RootSuspended:
        {
          markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
          // should immediately commit it or wait a bit.

          if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
          !shouldForceFlushFallbacksInDEV()) {
            // This render only included retries, no updates. Throttle committing
            // retries so that we don't show too many loading states too quickly.
            var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.

            if (msUntilTimeout > 10) {
              var nextLanes = getNextLanes(root, NoLanes);

              if (nextLanes !== NoLanes) {
                // There's additional work on this root.
                break;
              }

              var suspendedLanes = root.suspendedLanes;

              if (!isSubsetOfLanes(suspendedLanes, lanes)) {
                // We should prefer to render the fallback of at the last
                // suspended level. Ping the last suspended level to try
                // rendering it again.
                // FIXME: What if the suspended lanes are Idle? Should not restart.
                var eventTime = requestEventTime();
                markRootPinged(root, suspendedLanes);
                break;
              } // The render is suspended, it hasn't timed out, and there's no
              // lower priority work to do. Instead of committing the fallback
              // immediately, wait for more data to arrive.


              root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
              break;
            }
          } // The work expired. Commit immediately.


          commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
          break;
        }

      case RootSuspendedWithDelay:
        {
          markRootSuspended$1(root, lanes);

          if (includesOnlyTransitions(lanes)) {
            // This is a transition, so we should exit without committing a
            // placeholder and without scheduling a timeout. Delay indefinitely
            // until we receive more data.
            break;
          }

          if (!shouldForceFlushFallbacksInDEV()) {
            // This is not a transition, but we did trigger an avoided state.
            // Schedule a placeholder to display after a short delay, using the Just
            // Noticeable Difference.
            // TODO: Is the JND optimization worth the added complexity? If this is
            // the only reason we track the event time, then probably not.
            // Consider removing.
            var mostRecentEventTime = getMostRecentEventTime(root, lanes);
            var eventTimeMs = mostRecentEventTime;
            var timeElapsedMs = now() - eventTimeMs;

            var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.


            if (_msUntilTimeout > 10) {
              // Instead of committing the fallback immediately, wait for more data
              // to arrive.
              root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
              break;
            }
          } // Commit the placeholder.


          commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
          break;
        }

      case RootCompleted:
        {
          // The work completed. Ready to commit.
          commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
          break;
        }

      default:
        {
          throw new Error('Unknown root exit status.');
        }
    }
  }

  function isRenderConsistentWithExternalStores(finishedWork) {
    // Search the rendered tree for external store reads, and check whether the
    // stores were mutated in a concurrent event. Intentionally using an iterative
    // loop instead of recursion so we can exit early.
    var node = finishedWork;

    while (true) {
      if (node.flags & StoreConsistency) {
        var updateQueue = node.updateQueue;

        if (updateQueue !== null) {
          var checks = updateQueue.stores;

          if (checks !== null) {
            for (var i = 0; i < checks.length; i++) {
              var check = checks[i];
              var getSnapshot = check.getSnapshot;
              var renderedValue = check.value;

              try {
                if (!objectIs(getSnapshot(), renderedValue)) {
                  // Found an inconsistent store.
                  return false;
                }
              } catch (error) {
                // If `getSnapshot` throws, return `false`. This will schedule
                // a re-render, and the error will be rethrown during render.
                return false;
              }
            }
          }
        }
      }

      var child = node.child;

      if (node.subtreeFlags & StoreConsistency && child !== null) {
        child.return = node;
        node = child;
        continue;
      }

      if (node === finishedWork) {
        return true;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === finishedWork) {
          return true;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    } // Flow doesn't know this is unreachable, but eslint does
    // eslint-disable-next-line no-unreachable


    return true;
  }

  function markRootSuspended$1(root, suspendedLanes) {
    // When suspending, we should always exclude lanes that were pinged or (more
    // rarely, since we try to avoid it) updated during the render phase.
    // TODO: Lol maybe there's a better way to factor this besides this
    // obnoxiously named function :)
    suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
    suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
    markRootSuspended(root, suspendedLanes);
  } // This is the entry point for synchronous tasks that don't go
  // through Scheduler


  function performSyncWorkOnRoot(root) {
    {
      syncNestedUpdateFlag();
    }

    if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
      throw new Error('Should not already be working.');
    }

    flushPassiveEffects();
    var lanes = getNextLanes(root, NoLanes);

    if (!includesSomeLane(lanes, SyncLane)) {
      // There's no remaining sync work left.
      ensureRootIsScheduled(root, now());
      return null;
    }

    var exitStatus = renderRootSync(root, lanes);

    if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
      // If something threw an error, try rendering one more time. We'll render
      // synchronously to block concurrent data mutations, and we'll includes
      // all pending updates are included. If it still fails after the second
      // attempt, we'll give up and commit the resulting tree.
      var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

      if (errorRetryLanes !== NoLanes) {
        lanes = errorRetryLanes;
        exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
      }
    }

    if (exitStatus === RootFatalErrored) {
      var fatalError = workInProgressRootFatalError;
      prepareFreshStack(root, NoLanes);
      markRootSuspended$1(root, lanes);
      ensureRootIsScheduled(root, now());
      throw fatalError;
    }

    if (exitStatus === RootDidNotComplete) {
      throw new Error('Root did not complete. This is a bug in React.');
    } // We now have a consistent tree. Because this is a sync render, we
    // will commit it even if something suspended.


    var finishedWork = root.current.alternate;
    root.finishedWork = finishedWork;
    root.finishedLanes = lanes;
    commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next
    // pending level.

    ensureRootIsScheduled(root, now());
    return null;
  }

  function flushRoot(root, lanes) {
    if (lanes !== NoLanes) {
      markRootEntangled(root, mergeLanes(lanes, SyncLane));
      ensureRootIsScheduled(root, now());

      if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
        resetRenderTimer();
        flushSyncCallbacks();
      }
    }
  }
  function batchedUpdates$1(fn, a) {
    var prevExecutionContext = executionContext;
    executionContext |= BatchedContext;

    try {
      return fn(a);
    } finally {
      executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer
      // most batchedUpdates-like method.

      if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
      !( ReactCurrentActQueue$1.isBatchingLegacy)) {
        resetRenderTimer();
        flushSyncCallbacksOnlyInLegacyMode();
      }
    }
  }
  function discreteUpdates(fn, a, b, c, d) {
    var previousPriority = getCurrentUpdatePriority();
    var prevTransition = ReactCurrentBatchConfig$3.transition;

    try {
      ReactCurrentBatchConfig$3.transition = null;
      setCurrentUpdatePriority(DiscreteEventPriority);
      return fn(a, b, c, d);
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig$3.transition = prevTransition;

      if (executionContext === NoContext) {
        resetRenderTimer();
      }
    }
  } // Overload the definition to the two valid signatures.
  // Warning, this opts-out of checking the function body.

  // eslint-disable-next-line no-redeclare
  function flushSync(fn) {
    // In legacy mode, we flush pending passive effects at the beginning of the
    // next event, not at the end of the previous one.
    if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
      flushPassiveEffects();
    }

    var prevExecutionContext = executionContext;
    executionContext |= BatchedContext;
    var prevTransition = ReactCurrentBatchConfig$3.transition;
    var previousPriority = getCurrentUpdatePriority();

    try {
      ReactCurrentBatchConfig$3.transition = null;
      setCurrentUpdatePriority(DiscreteEventPriority);

      if (fn) {
        return fn();
      } else {
        return undefined;
      }
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig$3.transition = prevTransition;
      executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
      // Note that this will happen even if batchedUpdates is higher up
      // the stack.

      if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
        flushSyncCallbacks();
      }
    }
  }
  function isAlreadyRendering() {
    // Used by the renderer to print a warning if certain APIs are called from
    // the wrong context.
    return  (executionContext & (RenderContext | CommitContext)) !== NoContext;
  }
  function pushRenderLanes(fiber, lanes) {
    push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
    subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
    workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
  }
  function popRenderLanes(fiber) {
    subtreeRenderLanes = subtreeRenderLanesCursor.current;
    pop(subtreeRenderLanesCursor, fiber);
  }

  function prepareFreshStack(root, lanes) {
    root.finishedWork = null;
    root.finishedLanes = NoLanes;
    var timeoutHandle = root.timeoutHandle;

    if (timeoutHandle !== noTimeout) {
      // The root previous suspended and scheduled a timeout to commit a fallback
      // state. Now that we have additional work, cancel the timeout.
      root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above

      cancelTimeout(timeoutHandle);
    }

    if (workInProgress !== null) {
      var interruptedWork = workInProgress.return;

      while (interruptedWork !== null) {
        var current = interruptedWork.alternate;
        unwindInterruptedWork(current, interruptedWork);
        interruptedWork = interruptedWork.return;
      }
    }

    workInProgressRoot = root;
    var rootWorkInProgress = createWorkInProgress(root.current, null);
    workInProgress = rootWorkInProgress;
    workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
    workInProgressRootExitStatus = RootInProgress;
    workInProgressRootFatalError = null;
    workInProgressRootSkippedLanes = NoLanes;
    workInProgressRootInterleavedUpdatedLanes = NoLanes;
    workInProgressRootPingedLanes = NoLanes;
    workInProgressRootConcurrentErrors = null;
    workInProgressRootRecoverableErrors = null;
    finishQueueingConcurrentUpdates();

    {
      ReactStrictModeWarnings.discardPendingWarnings();
    }

    return rootWorkInProgress;
  }

  function handleError(root, thrownValue) {
    do {
      var erroredWork = workInProgress;

      try {
        // Reset module-level state that was set during the render phase.
        resetContextDependencies();
        resetHooksAfterThrow();
        resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
        // separate issue. Write a regression test using string refs.

        ReactCurrentOwner$2.current = null;

        if (erroredWork === null || erroredWork.return === null) {
          // Expected to be working on a non-root fiber. This is a fatal error
          // because there's no ancestor that can handle it; the root is
          // supposed to capture all errors that weren't caught by an error
          // boundary.
          workInProgressRootExitStatus = RootFatalErrored;
          workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
          // sibling, or the parent if there are no siblings. But since the root
          // has no siblings nor a parent, we set it to null. Usually this is
          // handled by `completeUnitOfWork` or `unwindWork`, but since we're
          // intentionally not calling those, we need set it here.
          // TODO: Consider calling `unwindWork` to pop the contexts.

          workInProgress = null;
          return;
        }

        if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
          // Record the time spent rendering before an error was thrown. This
          // avoids inaccurate Profiler durations in the case of a
          // suspended render.
          stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
        }

        if (enableSchedulingProfiler) {
          markComponentRenderStopped();

          if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
            var wakeable = thrownValue;
            markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
          } else {
            markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
          }
        }

        throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
        completeUnitOfWork(erroredWork);
      } catch (yetAnotherThrownValue) {
        // Something in the return path also threw.
        thrownValue = yetAnotherThrownValue;

        if (workInProgress === erroredWork && erroredWork !== null) {
          // If this boundary has already errored, then we had trouble processing
          // the error. Bubble it to the next boundary.
          erroredWork = erroredWork.return;
          workInProgress = erroredWork;
        } else {
          erroredWork = workInProgress;
        }

        continue;
      } // Return to the normal work loop.


      return;
    } while (true);
  }

  function pushDispatcher() {
    var prevDispatcher = ReactCurrentDispatcher$2.current;
    ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;

    if (prevDispatcher === null) {
      // The React isomorphic package does not include a default dispatcher.
      // Instead the first renderer will lazily attach one, in order to give
      // nicer error messages.
      return ContextOnlyDispatcher;
    } else {
      return prevDispatcher;
    }
  }

  function popDispatcher(prevDispatcher) {
    ReactCurrentDispatcher$2.current = prevDispatcher;
  }

  function markCommitTimeOfFallback() {
    globalMostRecentFallbackTime = now();
  }
  function markSkippedUpdateLanes(lane) {
    workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
  }
  function renderDidSuspend() {
    if (workInProgressRootExitStatus === RootInProgress) {
      workInProgressRootExitStatus = RootSuspended;
    }
  }
  function renderDidSuspendDelayIfPossible() {
    if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
      workInProgressRootExitStatus = RootSuspendedWithDelay;
    } // Check if there are updates that we skipped tree that might have unblocked
    // this render.


    if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
      // Mark the current render as suspended so that we switch to working on
      // the updates that were skipped. Usually we only suspend at the end of
      // the render phase.
      // TODO: We should probably always mark the root as suspended immediately
      // (inside this function), since by suspending at the end of the render
      // phase introduces a potential mistake where we suspend lanes that were
      // pinged or updated while we were rendering.
      markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
    }
  }
  function renderDidError(error) {
    if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
      workInProgressRootExitStatus = RootErrored;
    }

    if (workInProgressRootConcurrentErrors === null) {
      workInProgressRootConcurrentErrors = [error];
    } else {
      workInProgressRootConcurrentErrors.push(error);
    }
  } // Called during render to determine if anything has suspended.
  // Returns false if we're not sure.

  function renderHasNotSuspendedYet() {
    // If something errored or completed, we can't really be sure,
    // so those are false.
    return workInProgressRootExitStatus === RootInProgress;
  }

  function renderRootSync(root, lanes) {
    var prevExecutionContext = executionContext;
    executionContext |= RenderContext;
    var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
    // and prepare a fresh one. Otherwise we'll continue where we left off.

    if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
      {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root.memoizedUpdaters;

          if (memoizedUpdaters.size > 0) {
            restorePendingUpdaters(root, workInProgressRootRenderLanes);
            memoizedUpdaters.clear();
          } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
          // If we bailout on this work, we'll move them back (like above).
          // It's important to move them now in case the work spawns more work at the same priority with different updaters.
          // That way we can keep the current update and future updates separate.


          movePendingFibersToMemoized(root, lanes);
        }
      }

      workInProgressTransitions = getTransitionsForLanes();
      prepareFreshStack(root, lanes);
    }

    {
      markRenderStarted(lanes);
    }

    do {
      try {
        workLoopSync();
        break;
      } catch (thrownValue) {
        handleError(root, thrownValue);
      }
    } while (true);

    resetContextDependencies();
    executionContext = prevExecutionContext;
    popDispatcher(prevDispatcher);

    if (workInProgress !== null) {
      // This is a sync render, so we should have finished the whole tree.
      throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.');
    }

    {
      markRenderStopped();
    } // Set this to null to indicate there's no in-progress render.


    workInProgressRoot = null;
    workInProgressRootRenderLanes = NoLanes;
    return workInProgressRootExitStatus;
  } // The work loop is an extremely hot path. Tell Closure not to inline it.

  /** @noinline */


  function workLoopSync() {
    // Already timed out, so perform work without checking if we need to yield.
    while (workInProgress !== null) {
      performUnitOfWork(workInProgress);
    }
  }

  function renderRootConcurrent(root, lanes) {
    var prevExecutionContext = executionContext;
    executionContext |= RenderContext;
    var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
    // and prepare a fresh one. Otherwise we'll continue where we left off.

    if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
      {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root.memoizedUpdaters;

          if (memoizedUpdaters.size > 0) {
            restorePendingUpdaters(root, workInProgressRootRenderLanes);
            memoizedUpdaters.clear();
          } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
          // If we bailout on this work, we'll move them back (like above).
          // It's important to move them now in case the work spawns more work at the same priority with different updaters.
          // That way we can keep the current update and future updates separate.


          movePendingFibersToMemoized(root, lanes);
        }
      }

      workInProgressTransitions = getTransitionsForLanes();
      resetRenderTimer();
      prepareFreshStack(root, lanes);
    }

    {
      markRenderStarted(lanes);
    }

    do {
      try {
        workLoopConcurrent();
        break;
      } catch (thrownValue) {
        handleError(root, thrownValue);
      }
    } while (true);

    resetContextDependencies();
    popDispatcher(prevDispatcher);
    executionContext = prevExecutionContext;


    if (workInProgress !== null) {
      // Still work remaining.
      {
        markRenderYielded();
      }

      return RootInProgress;
    } else {
      // Completed the tree.
      {
        markRenderStopped();
      } // Set this to null to indicate there's no in-progress render.


      workInProgressRoot = null;
      workInProgressRootRenderLanes = NoLanes; // Return the final exit status.

      return workInProgressRootExitStatus;
    }
  }
  /** @noinline */


  function workLoopConcurrent() {
    // Perform work until Scheduler asks us to yield
    while (workInProgress !== null && !shouldYield()) {
      performUnitOfWork(workInProgress);
    }
  }

  function performUnitOfWork(unitOfWork) {
    // The current, flushed, state of this fiber is the alternate. Ideally
    // nothing should rely on this, but relying on it here means that we don't
    // need an additional field on the work in progress.
    var current = unitOfWork.alternate;
    setCurrentFiber(unitOfWork);
    var next;

    if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
      startProfilerTimer(unitOfWork);
      next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
      stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
    } else {
      next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
    }

    resetCurrentFiber();
    unitOfWork.memoizedProps = unitOfWork.pendingProps;

    if (next === null) {
      // If this doesn't spawn new work, complete the current work.
      completeUnitOfWork(unitOfWork);
    } else {
      workInProgress = next;
    }

    ReactCurrentOwner$2.current = null;
  }

  function completeUnitOfWork(unitOfWork) {
    // Attempt to complete the current unit of work, then move to the next
    // sibling. If there are no more siblings, return to the parent fiber.
    var completedWork = unitOfWork;

    do {
      // The current, flushed, state of this fiber is the alternate. Ideally
      // nothing should rely on this, but relying on it here means that we don't
      // need an additional field on the work in progress.
      var current = completedWork.alternate;
      var returnFiber = completedWork.return; // Check if the work completed or if something threw.

      if ((completedWork.flags & Incomplete) === NoFlags) {
        setCurrentFiber(completedWork);
        var next = void 0;

        if ( (completedWork.mode & ProfileMode) === NoMode) {
          next = completeWork(current, completedWork, subtreeRenderLanes);
        } else {
          startProfilerTimer(completedWork);
          next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.

          stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
        }

        resetCurrentFiber();

        if (next !== null) {
          // Completing this fiber spawned new work. Work on that next.
          workInProgress = next;
          return;
        }
      } else {
        // This fiber did not complete because something threw. Pop values off
        // the stack without entering the complete phase. If this is a boundary,
        // capture values if possible.
        var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes.


        if (_next !== null) {
          // If completing this work spawned new work, do that next. We'll come
          // back here again.
          // Since we're restarting, remove anything that is not a host effect
          // from the effect tag.
          _next.flags &= HostEffectMask;
          workInProgress = _next;
          return;
        }

        if ( (completedWork.mode & ProfileMode) !== NoMode) {
          // Record the render duration for the fiber that errored.
          stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.

          var actualDuration = completedWork.actualDuration;
          var child = completedWork.child;

          while (child !== null) {
            actualDuration += child.actualDuration;
            child = child.sibling;
          }

          completedWork.actualDuration = actualDuration;
        }

        if (returnFiber !== null) {
          // Mark the parent fiber as incomplete and clear its subtree flags.
          returnFiber.flags |= Incomplete;
          returnFiber.subtreeFlags = NoFlags;
          returnFiber.deletions = null;
        } else {
          // We've unwound all the way to the root.
          workInProgressRootExitStatus = RootDidNotComplete;
          workInProgress = null;
          return;
        }
      }

      var siblingFiber = completedWork.sibling;

      if (siblingFiber !== null) {
        // If there is more work to do in this returnFiber, do that next.
        workInProgress = siblingFiber;
        return;
      } // Otherwise, return to the parent


      completedWork = returnFiber; // Update the next thing we're working on in case something throws.

      workInProgress = completedWork;
    } while (completedWork !== null); // We've reached the root.


    if (workInProgressRootExitStatus === RootInProgress) {
      workInProgressRootExitStatus = RootCompleted;
    }
  }

  function commitRoot(root, recoverableErrors, transitions) {
    // TODO: This no longer makes any sense. We already wrap the mutation and
    // layout phases. Should be able to remove.
    var previousUpdateLanePriority = getCurrentUpdatePriority();
    var prevTransition = ReactCurrentBatchConfig$3.transition;

    try {
      ReactCurrentBatchConfig$3.transition = null;
      setCurrentUpdatePriority(DiscreteEventPriority);
      commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority);
    } finally {
      ReactCurrentBatchConfig$3.transition = prevTransition;
      setCurrentUpdatePriority(previousUpdateLanePriority);
    }

    return null;
  }

  function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) {
    do {
      // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
      // means `flushPassiveEffects` will sometimes result in additional
      // passive effects. So we need to keep flushing in a loop until there are
      // no more pending effects.
      // TODO: Might be better if `flushPassiveEffects` did not automatically
      // flush synchronous work at the end, to avoid factoring hazards like this.
      flushPassiveEffects();
    } while (rootWithPendingPassiveEffects !== null);

    flushRenderPhaseStrictModeWarningsInDEV();

    if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
      throw new Error('Should not already be working.');
    }

    var finishedWork = root.finishedWork;
    var lanes = root.finishedLanes;

    {
      markCommitStarted(lanes);
    }

    if (finishedWork === null) {

      {
        markCommitStopped();
      }

      return null;
    } else {
      {
        if (lanes === NoLanes) {
          error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.');
        }
      }
    }

    root.finishedWork = null;
    root.finishedLanes = NoLanes;

    if (finishedWork === root.current) {
      throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.');
    } // commitRoot never returns a continuation; it always finishes synchronously.
    // So we can clear these now to allow a new callback to be scheduled.


    root.callbackNode = null;
    root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first
    // pending time is whatever is left on the root fiber.

    var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
    markRootFinished(root, remainingLanes);

    if (root === workInProgressRoot) {
      // We can reset these now that they are finished.
      workInProgressRoot = null;
      workInProgress = null;
      workInProgressRootRenderLanes = NoLanes;
    } // If there are pending passive effects, schedule a callback to process them.
    // Do this as early as possible, so it is queued before anything else that
    // might get scheduled in the commit phase. (See #16714.)
    // TODO: Delete all other places that schedule the passive effect callback
    // They're redundant.


    if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
      if (!rootDoesHavePassiveEffects) {
        rootDoesHavePassiveEffects = true;
        // to store it in pendingPassiveTransitions until they get processed
        // We need to pass this through as an argument to commitRoot
        // because workInProgressTransitions might have changed between
        // the previous render and commit if we throttle the commit
        // with setTimeout

        pendingPassiveTransitions = transitions;
        scheduleCallback$1(NormalPriority, function () {
          flushPassiveEffects(); // This render triggered passive effects: release the root cache pool
          // *after* passive effects fire to avoid freeing a cache pool that may
          // be referenced by a node in the tree (HostRoot, Cache boundary etc)

          return null;
        });
      }
    } // Check if there are any effects in the whole tree.
    // TODO: This is left over from the effect list implementation, where we had
    // to check for the existence of `firstEffect` to satisfy Flow. I think the
    // only other reason this optimization exists is because it affects profiling.
    // Reconsider whether this is necessary.


    var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
    var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;

    if (subtreeHasEffects || rootHasEffect) {
      var prevTransition = ReactCurrentBatchConfig$3.transition;
      ReactCurrentBatchConfig$3.transition = null;
      var previousPriority = getCurrentUpdatePriority();
      setCurrentUpdatePriority(DiscreteEventPriority);
      var prevExecutionContext = executionContext;
      executionContext |= CommitContext; // Reset this to null before calling lifecycles

      ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
      // of the effect list for each phase: all mutation effects come before all
      // layout effects, and so on.
      // The first phase a "before mutation" phase. We use this phase to read the
      // state of the host tree right before we mutate it. This is where
      // getSnapshotBeforeUpdate is called.

      var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork);

      {
        // Mark the current commit time to be shared by all Profilers in this
        // batch. This enables them to be grouped later.
        recordCommitTime();
      }


      commitMutationEffects(root, finishedWork, lanes);

      resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
      // the mutation phase, so that the previous tree is still current during
      // componentWillUnmount, but before the layout phase, so that the finished
      // work is current during componentDidMount/Update.

      root.current = finishedWork; // The next phase is the layout phase, where we call effects that read

      {
        markLayoutEffectsStarted(lanes);
      }

      commitLayoutEffects(finishedWork, root, lanes);

      {
        markLayoutEffectsStopped();
      }
      // opportunity to paint.


      requestPaint();
      executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value.

      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig$3.transition = prevTransition;
    } else {
      // No effects.
      root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
      // no effects.
      // TODO: Maybe there's a better way to report this.

      {
        recordCommitTime();
      }
    }

    var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;

    if (rootDoesHavePassiveEffects) {
      // This commit has passive effects. Stash a reference to them. But don't
      // schedule a callback until after flushing layout work.
      rootDoesHavePassiveEffects = false;
      rootWithPendingPassiveEffects = root;
      pendingPassiveEffectsLanes = lanes;
    } else {

      {
        nestedPassiveUpdateCount = 0;
        rootWithPassiveNestedUpdates = null;
      }
    } // Read this again, since an effect might have updated it


    remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
    // TODO: This is part of the `componentDidCatch` implementation. Its purpose
    // is to detect whether something might have called setState inside
    // `componentDidCatch`. The mechanism is known to be flawed because `setState`
    // inside `componentDidCatch` is itself flawed â€” that's why we recommend
    // `getDerivedStateFromError` instead. However, it could be improved by
    // checking if remainingLanes includes Sync work, instead of whether there's
    // any work remaining at all (which would also include stuff like Suspense
    // retries or transitions). It's been like this for a while, though, so fixing
    // it probably isn't that urgent.

    if (remainingLanes === NoLanes) {
      // If there's no remaining work, we can clear the set of already failed
      // error boundaries.
      legacyErrorBoundariesThatAlreadyFailed = null;
    }

    {
      if (!rootDidHavePassiveEffects) {
        commitDoubleInvokeEffectsInDEV(root.current, false);
      }
    }

    onCommitRoot(finishedWork.stateNode, renderPriorityLevel);

    {
      if (isDevToolsPresent) {
        root.memoizedUpdaters.clear();
      }
    }

    {
      onCommitRoot$1();
    } // Always call this before exiting `commitRoot`, to ensure that any
    // additional work on this root is scheduled.


    ensureRootIsScheduled(root, now());

    if (recoverableErrors !== null) {
      // There were errors during this render, but recovered from them without
      // needing to surface it to the UI. We log them here.
      var onRecoverableError = root.onRecoverableError;

      for (var i = 0; i < recoverableErrors.length; i++) {
        var recoverableError = recoverableErrors[i];
        var componentStack = recoverableError.stack;
        var digest = recoverableError.digest;
        onRecoverableError(recoverableError.value, {
          componentStack: componentStack,
          digest: digest
        });
      }
    }

    if (hasUncaughtError) {
      hasUncaughtError = false;
      var error$1 = firstUncaughtError;
      firstUncaughtError = null;
      throw error$1;
    } // If the passive effects are the result of a discrete render, flush them
    // synchronously at the end of the current task so that the result is
    // immediately observable. Otherwise, we assume that they are not
    // order-dependent and do not need to be observed by external systems, so we
    // can wait until after paint.
    // TODO: We can optimize this by not scheduling the callback earlier. Since we
    // currently schedule the callback in multiple places, will wait until those
    // are consolidated.


    if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) {
      flushPassiveEffects();
    } // Read this again, since a passive effect might have updated it


    remainingLanes = root.pendingLanes;

    if (includesSomeLane(remainingLanes, SyncLane)) {
      {
        markNestedUpdateScheduled();
      } // Count the number of times the root synchronously re-renders without
      // finishing. If there are too many, it indicates an infinite update loop.


      if (root === rootWithNestedUpdates) {
        nestedUpdateCount++;
      } else {
        nestedUpdateCount = 0;
        rootWithNestedUpdates = root;
      }
    } else {
      nestedUpdateCount = 0;
    } // If layout work was scheduled, flush it now.


    flushSyncCallbacks();

    {
      markCommitStopped();
    }

    return null;
  }

  function flushPassiveEffects() {
    // Returns whether passive effects were flushed.
    // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
    // probably just combine the two functions. I believe they were only separate
    // in the first place because we used to wrap it with
    // `Scheduler.runWithPriority`, which accepts a function. But now we track the
    // priority within React itself, so we can mutate the variable directly.
    if (rootWithPendingPassiveEffects !== null) {
      var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
      var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
      var prevTransition = ReactCurrentBatchConfig$3.transition;
      var previousPriority = getCurrentUpdatePriority();

      try {
        ReactCurrentBatchConfig$3.transition = null;
        setCurrentUpdatePriority(priority);
        return flushPassiveEffectsImpl();
      } finally {
        setCurrentUpdatePriority(previousPriority);
        ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a
      }
    }

    return false;
  }
  function enqueuePendingPassiveProfilerEffect(fiber) {
    {
      pendingPassiveProfilerEffects.push(fiber);

      if (!rootDoesHavePassiveEffects) {
        rootDoesHavePassiveEffects = true;
        scheduleCallback$1(NormalPriority, function () {
          flushPassiveEffects();
          return null;
        });
      }
    }
  }

  function flushPassiveEffectsImpl() {
    if (rootWithPendingPassiveEffects === null) {
      return false;
    } // Cache and clear the transitions flag


    var transitions = pendingPassiveTransitions;
    pendingPassiveTransitions = null;
    var root = rootWithPendingPassiveEffects;
    var lanes = pendingPassiveEffectsLanes;
    rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
    // Figure out why and fix it. It's not causing any known issues (probably
    // because it's only used for profiling), but it's a refactor hazard.

    pendingPassiveEffectsLanes = NoLanes;

    if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
      throw new Error('Cannot flush passive effects while already rendering.');
    }

    {
      isFlushingPassiveEffects = true;
      didScheduleUpdateDuringPassiveEffects = false;
    }

    {
      markPassiveEffectsStarted(lanes);
    }

    var prevExecutionContext = executionContext;
    executionContext |= CommitContext;
    commitPassiveUnmountEffects(root.current);
    commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects

    {
      var profilerEffects = pendingPassiveProfilerEffects;
      pendingPassiveProfilerEffects = [];

      for (var i = 0; i < profilerEffects.length; i++) {
        var _fiber = profilerEffects[i];
        commitPassiveEffectDurations(root, _fiber);
      }
    }

    {
      markPassiveEffectsStopped();
    }

    {
      commitDoubleInvokeEffectsInDEV(root.current, true);
    }

    executionContext = prevExecutionContext;
    flushSyncCallbacks();

    {
      // If additional passive effects were scheduled, increment a counter. If this
      // exceeds the limit, we'll fire a warning.
      if (didScheduleUpdateDuringPassiveEffects) {
        if (root === rootWithPassiveNestedUpdates) {
          nestedPassiveUpdateCount++;
        } else {
          nestedPassiveUpdateCount = 0;
          rootWithPassiveNestedUpdates = root;
        }
      } else {
        nestedPassiveUpdateCount = 0;
      }

      isFlushingPassiveEffects = false;
      didScheduleUpdateDuringPassiveEffects = false;
    } // TODO: Move to commitPassiveMountEffects


    onPostCommitRoot(root);

    {
      var stateNode = root.current.stateNode;
      stateNode.effectDuration = 0;
      stateNode.passiveEffectDuration = 0;
    }

    return true;
  }

  function isAlreadyFailedLegacyErrorBoundary(instance) {
    return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
  }
  function markLegacyErrorBoundaryAsFailed(instance) {
    if (legacyErrorBoundariesThatAlreadyFailed === null) {
      legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
    } else {
      legacyErrorBoundariesThatAlreadyFailed.add(instance);
    }
  }

  function prepareToThrowUncaughtError(error) {
    if (!hasUncaughtError) {
      hasUncaughtError = true;
      firstUncaughtError = error;
    }
  }

  var onUncaughtError = prepareToThrowUncaughtError;

  function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
    var errorInfo = createCapturedValueAtFiber(error, sourceFiber);
    var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
    var root = enqueueUpdate(rootFiber, update, SyncLane);
    var eventTime = requestEventTime();

    if (root !== null) {
      markRootUpdated(root, SyncLane, eventTime);
      ensureRootIsScheduled(root, eventTime);
    }
  }

  function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
    {
      reportUncaughtErrorInDEV(error$1);
      setIsRunningInsertionEffect(false);
    }

    if (sourceFiber.tag === HostRoot) {
      // Error was thrown at the root. There is no parent, so the root
      // itself should capture it.
      captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
      return;
    }

    var fiber = null;

    {
      fiber = nearestMountedAncestor;
    }

    while (fiber !== null) {
      if (fiber.tag === HostRoot) {
        captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
        return;
      } else if (fiber.tag === ClassComponent) {
        var ctor = fiber.type;
        var instance = fiber.stateNode;

        if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
          var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
          var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
          var root = enqueueUpdate(fiber, update, SyncLane);
          var eventTime = requestEventTime();

          if (root !== null) {
            markRootUpdated(root, SyncLane, eventTime);
            ensureRootIsScheduled(root, eventTime);
          }

          return;
        }
      }

      fiber = fiber.return;
    }

    {
      // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
      // will fire for errors that are thrown by destroy functions inside deleted
      // trees. What it should instead do is propagate the error to the parent of
      // the deleted tree. In the meantime, do not add this warning to the
      // allowlist; this is only for our internal use.
      error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1);
    }
  }
  function pingSuspendedRoot(root, wakeable, pingedLanes) {
    var pingCache = root.pingCache;

    if (pingCache !== null) {
      // The wakeable resolved, so we no longer need to memoize, because it will
      // never be thrown again.
      pingCache.delete(wakeable);
    }

    var eventTime = requestEventTime();
    markRootPinged(root, pingedLanes);
    warnIfSuspenseResolutionNotWrappedWithActDEV(root);

    if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
      // Received a ping at the same priority level at which we're currently
      // rendering. We might want to restart this render. This should mirror
      // the logic of whether or not a root suspends once it completes.
      // TODO: If we're rendering sync either due to Sync, Batched or expired,
      // we should probably never restart.
      // If we're suspended with delay, or if it's a retry, we'll always suspend
      // so we can always restart.
      if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
        // Restart from the root.
        prepareFreshStack(root, NoLanes);
      } else {
        // Even though we can't restart right now, we might get an
        // opportunity later. So we mark this render as having a ping.
        workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
      }
    }

    ensureRootIsScheduled(root, eventTime);
  }

  function retryTimedOutBoundary(boundaryFiber, retryLane) {
    // The boundary fiber (a Suspense component or SuspenseList component)
    // previously was rendered in its fallback state. One of the promises that
    // suspended it has resolved, which means at least part of the tree was
    // likely unblocked. Try rendering again, at a new lanes.
    if (retryLane === NoLane) {
      // TODO: Assign this to `suspenseState.retryLane`? to avoid
      // unnecessary entanglement?
      retryLane = requestRetryLane(boundaryFiber);
    } // TODO: Special case idle priority?


    var eventTime = requestEventTime();
    var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);

    if (root !== null) {
      markRootUpdated(root, retryLane, eventTime);
      ensureRootIsScheduled(root, eventTime);
    }
  }

  function retryDehydratedSuspenseBoundary(boundaryFiber) {
    var suspenseState = boundaryFiber.memoizedState;
    var retryLane = NoLane;

    if (suspenseState !== null) {
      retryLane = suspenseState.retryLane;
    }

    retryTimedOutBoundary(boundaryFiber, retryLane);
  }
  function resolveRetryWakeable(boundaryFiber, wakeable) {
    var retryLane = NoLane; // Default

    var retryCache;

    switch (boundaryFiber.tag) {
      case SuspenseComponent:
        retryCache = boundaryFiber.stateNode;
        var suspenseState = boundaryFiber.memoizedState;

        if (suspenseState !== null) {
          retryLane = suspenseState.retryLane;
        }

        break;

      case SuspenseListComponent:
        retryCache = boundaryFiber.stateNode;
        break;

      default:
        throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.');
    }

    if (retryCache !== null) {
      // The wakeable resolved, so we no longer need to memoize, because it will
      // never be thrown again.
      retryCache.delete(wakeable);
    }

    retryTimedOutBoundary(boundaryFiber, retryLane);
  } // Computes the next Just Noticeable Difference (JND) boundary.
  // The theory is that a person can't tell the difference between small differences in time.
  // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
  // difference in the experience. However, waiting for longer might mean that we can avoid
  // showing an intermediate loading state. The longer we have already waited, the harder it
  // is to tell small differences in time. Therefore, the longer we've already waited,
  // the longer we can wait additionally. At some point we have to give up though.
  // We pick a train model where the next boundary commits at a consistent schedule.
  // These particular numbers are vague estimates. We expect to adjust them based on research.

  function jnd(timeElapsed) {
    return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
  }

  function checkForNestedUpdates() {
    if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
      nestedUpdateCount = 0;
      rootWithNestedUpdates = null;
      throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.');
    }

    {
      if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
        nestedPassiveUpdateCount = 0;
        rootWithPassiveNestedUpdates = null;

        error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
      }
    }
  }

  function flushRenderPhaseStrictModeWarningsInDEV() {
    {
      ReactStrictModeWarnings.flushLegacyContextWarning();

      {
        ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
      }
    }
  }

  function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
    {
      // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
      // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
      // Maybe not a big deal since this is DEV only behavior.
      setCurrentFiber(fiber);
      invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);

      if (hasPassiveEffects) {
        invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
      }

      invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);

      if (hasPassiveEffects) {
        invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
      }

      resetCurrentFiber();
    }
  }

  function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
    {
      // We don't need to re-check StrictEffectsMode here.
      // This function is only called if that check has already passed.
      var current = firstChild;
      var subtreeRoot = null;

      while (current !== null) {
        var primarySubtreeFlag = current.subtreeFlags & fiberFlags;

        if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) {
          current = current.child;
        } else {
          if ((current.flags & fiberFlags) !== NoFlags) {
            invokeEffectFn(current);
          }

          if (current.sibling !== null) {
            current = current.sibling;
          } else {
            current = subtreeRoot = current.return;
          }
        }
      }
    }
  }

  var didWarnStateUpdateForNotYetMountedComponent = null;
  function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
    {
      if ((executionContext & RenderContext) !== NoContext) {
        // We let the other warning about render phase updates deal with this one.
        return;
      }

      if (!(fiber.mode & ConcurrentMode)) {
        return;
      }

      var tag = fiber.tag;

      if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
        // Only warn for user-defined components, not internal ones like Suspense.
        return;
      } // We show the whole stack but dedupe on the top component's name because
      // the problematic code almost always lies inside that component.


      var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';

      if (didWarnStateUpdateForNotYetMountedComponent !== null) {
        if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
          return;
        }

        didWarnStateUpdateForNotYetMountedComponent.add(componentName);
      } else {
        didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
      }

      var previousFiber = current;

      try {
        setCurrentFiber(fiber);

        error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.');
      } finally {
        if (previousFiber) {
          setCurrentFiber(fiber);
        } else {
          resetCurrentFiber();
        }
      }
    }
  }
  var beginWork$1;

  {
    var dummyFiber = null;

    beginWork$1 = function (current, unitOfWork, lanes) {
      // If a component throws an error, we replay it again in a synchronously
      // dispatched event, so that the debugger will treat it as an uncaught
      // error See ReactErrorUtils for more information.
      // Before entering the begin phase, copy the work-in-progress onto a dummy
      // fiber. If beginWork throws, we'll use this to reset the state.
      var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);

      try {
        return beginWork(current, unitOfWork, lanes);
      } catch (originalError) {
        if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
          // Don't replay promises.
          // Don't replay errors if we are hydrating and have already suspended or handled an error
          throw originalError;
        } // Keep this code in sync with handleError; any changes here must have
        // corresponding changes there.


        resetContextDependencies();
        resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
        // same fiber again.
        // Unwind the failed stack frame

        unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber.

        assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);

        if ( unitOfWork.mode & ProfileMode) {
          // Reset the profiler timer.
          startProfilerTimer(unitOfWork);
        } // Run beginWork again.


        invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);

        if (hasCaughtError()) {
          var replayError = clearCaughtError();

          if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) {
            // If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
            originalError._suppressLogging = true;
          }
        } // We always throw the original error in case the second render pass is not idempotent.
        // This can happen if a memoized function or CommonJS module doesn't throw after first invocation.


        throw originalError;
      }
    };
  }

  var didWarnAboutUpdateInRender = false;
  var didWarnAboutUpdateInRenderForAnotherComponent;

  {
    didWarnAboutUpdateInRenderForAnotherComponent = new Set();
  }

  function warnAboutRenderPhaseUpdatesInDEV(fiber) {
    {
      if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
        switch (fiber.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent:
            {
              var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.

              var dedupeKey = renderingComponentName;

              if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
                didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
                var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown';

                error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
              }

              break;
            }

          case ClassComponent:
            {
              if (!didWarnAboutUpdateInRender) {
                error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');

                didWarnAboutUpdateInRender = true;
              }

              break;
            }
        }
      }
    }
  }

  function restorePendingUpdaters(root, lanes) {
    {
      if (isDevToolsPresent) {
        var memoizedUpdaters = root.memoizedUpdaters;
        memoizedUpdaters.forEach(function (schedulingFiber) {
          addFiberToLanesMap(root, schedulingFiber, lanes);
        }); // This function intentionally does not clear memoized updaters.
        // Those may still be relevant to the current commit
        // and a future one (e.g. Suspense).
      }
    }
  }
  var fakeActCallbackNode = {};

  function scheduleCallback$1(priorityLevel, callback) {
    {
      // If we're currently inside an `act` scope, bypass Scheduler and push to
      // the `act` queue instead.
      var actQueue = ReactCurrentActQueue$1.current;

      if (actQueue !== null) {
        actQueue.push(callback);
        return fakeActCallbackNode;
      } else {
        return scheduleCallback(priorityLevel, callback);
      }
    }
  }

  function cancelCallback$1(callbackNode) {
    if ( callbackNode === fakeActCallbackNode) {
      return;
    } // In production, always call Scheduler. This function will be stripped out.


    return cancelCallback(callbackNode);
  }

  function shouldForceFlushFallbacksInDEV() {
    // Never force flush in production. This function should get stripped out.
    return  ReactCurrentActQueue$1.current !== null;
  }

  function warnIfUpdatesNotWrappedWithActDEV(fiber) {
    {
      if (fiber.mode & ConcurrentMode) {
        if (!isConcurrentActEnvironment()) {
          // Not in an act environment. No need to warn.
          return;
        }
      } else {
        // Legacy mode has additional cases where we suppress a warning.
        if (!isLegacyActEnvironment()) {
          // Not in an act environment. No need to warn.
          return;
        }

        if (executionContext !== NoContext) {
          // Legacy mode doesn't warn if the update is batched, i.e.
          // batchedUpdates or flushSync.
          return;
        }

        if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
          // For backwards compatibility with pre-hooks code, legacy mode only
          // warns for updates that originate from a hook.
          return;
        }
      }

      if (ReactCurrentActQueue$1.current === null) {
        var previousFiber = current;

        try {
          setCurrentFiber(fiber);

          error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber));
        } finally {
          if (previousFiber) {
            setCurrentFiber(fiber);
          } else {
            resetCurrentFiber();
          }
        }
      }
    }
  }

  function warnIfSuspenseResolutionNotWrappedWithActDEV(root) {
    {
      if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
        error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + '  /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act');
      }
    }
  }

  function setIsRunningInsertionEffect(isRunning) {
    {
      isRunningInsertionEffect = isRunning;
    }
  }

  /* eslint-disable react-internal/prod-error-codes */
  var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.

  var failedBoundaries = null;
  var setRefreshHandler = function (handler) {
    {
      resolveFamily = handler;
    }
  };
  function resolveFunctionForHotReloading(type) {
    {
      if (resolveFamily === null) {
        // Hot reloading is disabled.
        return type;
      }

      var family = resolveFamily(type);

      if (family === undefined) {
        return type;
      } // Use the latest known implementation.


      return family.current;
    }
  }
  function resolveClassForHotReloading(type) {
    // No implementation differences.
    return resolveFunctionForHotReloading(type);
  }
  function resolveForwardRefForHotReloading(type) {
    {
      if (resolveFamily === null) {
        // Hot reloading is disabled.
        return type;
      }

      var family = resolveFamily(type);

      if (family === undefined) {
        // Check if we're dealing with a real forwardRef. Don't want to crash early.
        if (type !== null && type !== undefined && typeof type.render === 'function') {
          // ForwardRef is special because its resolved .type is an object,
          // but it's possible that we only have its inner render function in the map.
          // If that inner render function is different, we'll build a new forwardRef type.
          var currentRender = resolveFunctionForHotReloading(type.render);

          if (type.render !== currentRender) {
            var syntheticType = {
              $$typeof: REACT_FORWARD_REF_TYPE,
              render: currentRender
            };

            if (type.displayName !== undefined) {
              syntheticType.displayName = type.displayName;
            }

            return syntheticType;
          }
        }

        return type;
      } // Use the latest known implementation.


      return family.current;
    }
  }
  function isCompatibleFamilyForHotReloading(fiber, element) {
    {
      if (resolveFamily === null) {
        // Hot reloading is disabled.
        return false;
      }

      var prevType = fiber.elementType;
      var nextType = element.type; // If we got here, we know types aren't === equal.

      var needsCompareFamilies = false;
      var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;

      switch (fiber.tag) {
        case ClassComponent:
          {
            if (typeof nextType === 'function') {
              needsCompareFamilies = true;
            }

            break;
          }

        case FunctionComponent:
          {
            if (typeof nextType === 'function') {
              needsCompareFamilies = true;
            } else if ($$typeofNextType === REACT_LAZY_TYPE) {
              // We don't know the inner type yet.
              // We're going to assume that the lazy inner type is stable,
              // and so it is sufficient to avoid reconciling it away.
              // We're not going to unwrap or actually use the new lazy type.
              needsCompareFamilies = true;
            }

            break;
          }

        case ForwardRef:
          {
            if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
              needsCompareFamilies = true;
            } else if ($$typeofNextType === REACT_LAZY_TYPE) {
              needsCompareFamilies = true;
            }

            break;
          }

        case MemoComponent:
        case SimpleMemoComponent:
          {
            if ($$typeofNextType === REACT_MEMO_TYPE) {
              // TODO: if it was but can no longer be simple,
              // we shouldn't set this.
              needsCompareFamilies = true;
            } else if ($$typeofNextType === REACT_LAZY_TYPE) {
              needsCompareFamilies = true;
            }

            break;
          }

        default:
          return false;
      } // Check if both types have a family and it's the same one.


      if (needsCompareFamilies) {
        // Note: memo() and forwardRef() we'll compare outer rather than inner type.
        // This means both of them need to be registered to preserve state.
        // If we unwrapped and compared the inner types for wrappers instead,
        // then we would risk falsely saying two separate memo(Foo)
        // calls are equivalent because they wrap the same Foo function.
        var prevFamily = resolveFamily(prevType);

        if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
          return true;
        }
      }

      return false;
    }
  }
  function markFailedErrorBoundaryForHotReloading(fiber) {
    {
      if (resolveFamily === null) {
        // Hot reloading is disabled.
        return;
      }

      if (typeof WeakSet !== 'function') {
        return;
      }

      if (failedBoundaries === null) {
        failedBoundaries = new WeakSet();
      }

      failedBoundaries.add(fiber);
    }
  }
  var scheduleRefresh = function (root, update) {
    {
      if (resolveFamily === null) {
        // Hot reloading is disabled.
        return;
      }

      var staleFamilies = update.staleFamilies,
          updatedFamilies = update.updatedFamilies;
      flushPassiveEffects();
      flushSync(function () {
        scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
      });
    }
  };
  var scheduleRoot = function (root, element) {
    {
      if (root.context !== emptyContextObject) {
        // Super edge case: root has a legacy _renderSubtree context
        // but we don't know the parentComponent so we can't pass it.
        // Just ignore. We'll delete this with _renderSubtree code path later.
        return;
      }

      flushPassiveEffects();
      flushSync(function () {
        updateContainer(element, root, null, null);
      });
    }
  };

  function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
    {
      var alternate = fiber.alternate,
          child = fiber.child,
          sibling = fiber.sibling,
          tag = fiber.tag,
          type = fiber.type;
      var candidateType = null;

      switch (tag) {
        case FunctionComponent:
        case SimpleMemoComponent:
        case ClassComponent:
          candidateType = type;
          break;

        case ForwardRef:
          candidateType = type.render;
          break;
      }

      if (resolveFamily === null) {
        throw new Error('Expected resolveFamily to be set during hot reload.');
      }

      var needsRender = false;
      var needsRemount = false;

      if (candidateType !== null) {
        var family = resolveFamily(candidateType);

        if (family !== undefined) {
          if (staleFamilies.has(family)) {
            needsRemount = true;
          } else if (updatedFamilies.has(family)) {
            if (tag === ClassComponent) {
              needsRemount = true;
            } else {
              needsRender = true;
            }
          }
        }
      }

      if (failedBoundaries !== null) {
        if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
          needsRemount = true;
        }
      }

      if (needsRemount) {
        fiber._debugNeedsRemount = true;
      }

      if (needsRemount || needsRender) {
        var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);

        if (_root !== null) {
          scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
        }
      }

      if (child !== null && !needsRemount) {
        scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
      }

      if (sibling !== null) {
        scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
      }
    }
  }

  var findHostInstancesForRefresh = function (root, families) {
    {
      var hostInstances = new Set();
      var types = new Set(families.map(function (family) {
        return family.current;
      }));
      findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
      return hostInstances;
    }
  };

  function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
    {
      var child = fiber.child,
          sibling = fiber.sibling,
          tag = fiber.tag,
          type = fiber.type;
      var candidateType = null;

      switch (tag) {
        case FunctionComponent:
        case SimpleMemoComponent:
        case ClassComponent:
          candidateType = type;
          break;

        case ForwardRef:
          candidateType = type.render;
          break;
      }

      var didMatch = false;

      if (candidateType !== null) {
        if (types.has(candidateType)) {
          didMatch = true;
        }
      }

      if (didMatch) {
        // We have a match. This only drills down to the closest host components.
        // There's no need to search deeper because for the purpose of giving
        // visual feedback, "flashing" outermost parent rectangles is sufficient.
        findHostInstancesForFiberShallowly(fiber, hostInstances);
      } else {
        // If there's no match, maybe there will be one further down in the child tree.
        if (child !== null) {
          findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
        }
      }

      if (sibling !== null) {
        findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
      }
    }
  }

  function findHostInstancesForFiberShallowly(fiber, hostInstances) {
    {
      var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);

      if (foundHostInstances) {
        return;
      } // If we didn't find any host children, fallback to closest host parent.


      var node = fiber;

      while (true) {
        switch (node.tag) {
          case HostComponent:
            hostInstances.add(node.stateNode);
            return;

          case HostPortal:
            hostInstances.add(node.stateNode.containerInfo);
            return;

          case HostRoot:
            hostInstances.add(node.stateNode.containerInfo);
            return;
        }

        if (node.return === null) {
          throw new Error('Expected to reach root first.');
        }

        node = node.return;
      }
    }
  }

  function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
    {
      var node = fiber;
      var foundHostInstances = false;

      while (true) {
        if (node.tag === HostComponent) {
          // We got a match.
          foundHostInstances = true;
          hostInstances.add(node.stateNode); // There may still be more, so keep searching.
        } else if (node.child !== null) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === fiber) {
          return foundHostInstances;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === fiber) {
            return foundHostInstances;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    }

    return false;
  }

  var hasBadMapPolyfill;

  {
    hasBadMapPolyfill = false;

    try {
      var nonExtensibleObject = Object.preventExtensions({});
      /* eslint-disable no-new */

      new Map([[nonExtensibleObject, null]]);
      new Set([nonExtensibleObject]);
      /* eslint-enable no-new */
    } catch (e) {
      // TODO: Consider warning about bad polyfills
      hasBadMapPolyfill = true;
    }
  }

  function FiberNode(tag, pendingProps, key, mode) {
    // Instance
    this.tag = tag;
    this.key = key;
    this.elementType = null;
    this.type = null;
    this.stateNode = null; // Fiber

    this.return = null;
    this.child = null;
    this.sibling = null;
    this.index = 0;
    this.ref = null;
    this.pendingProps = pendingProps;
    this.memoizedProps = null;
    this.updateQueue = null;
    this.memoizedState = null;
    this.dependencies = null;
    this.mode = mode; // Effects

    this.flags = NoFlags;
    this.subtreeFlags = NoFlags;
    this.deletions = null;
    this.lanes = NoLanes;
    this.childLanes = NoLanes;
    this.alternate = null;

    {
      // Note: The following is done to avoid a v8 performance cliff.
      //
      // Initializing the fields below to smis and later updating them with
      // double values will cause Fibers to end up having separate shapes.
      // This behavior/bug has something to do with Object.preventExtension().
      // Fortunately this only impacts DEV builds.
      // Unfortunately it makes React unusably slow for some applications.
      // To work around this, initialize the fields below with doubles.
      //
      // Learn more about this here:
      // https://github.com/facebook/react/issues/14365
      // https://bugs.chromium.org/p/v8/issues/detail?id=8538
      this.actualDuration = Number.NaN;
      this.actualStartTime = Number.NaN;
      this.selfBaseDuration = Number.NaN;
      this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
      // This won't trigger the performance cliff mentioned above,
      // and it simplifies other profiler code (including DevTools).

      this.actualDuration = 0;
      this.actualStartTime = -1;
      this.selfBaseDuration = 0;
      this.treeBaseDuration = 0;
    }

    {
      // This isn't directly used but is handy for debugging internals:
      this._debugSource = null;
      this._debugOwner = null;
      this._debugNeedsRemount = false;
      this._debugHookTypes = null;

      if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
        Object.preventExtensions(this);
      }
    }
  } // This is a constructor function, rather than a POJO constructor, still
  // please ensure we do the following:
  // 1) Nobody should add any instance methods on this. Instance methods can be
  //    more difficult to predict when they get optimized and they are almost
  //    never inlined properly in static compilers.
  // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
  //    always know when it is a fiber.
  // 3) We might want to experiment with using numeric keys since they are easier
  //    to optimize in a non-JIT environment.
  // 4) We can easily go from a constructor to a createFiber object literal if that
  //    is faster.
  // 5) It should be easy to port this to a C struct and keep a C implementation
  //    compatible.


  var createFiber = function (tag, pendingProps, key, mode) {
    // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
    return new FiberNode(tag, pendingProps, key, mode);
  };

  function shouldConstruct$1(Component) {
    var prototype = Component.prototype;
    return !!(prototype && prototype.isReactComponent);
  }

  function isSimpleFunctionComponent(type) {
    return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
  }
  function resolveLazyComponentTag(Component) {
    if (typeof Component === 'function') {
      return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
    } else if (Component !== undefined && Component !== null) {
      var $$typeof = Component.$$typeof;

      if ($$typeof === REACT_FORWARD_REF_TYPE) {
        return ForwardRef;
      }

      if ($$typeof === REACT_MEMO_TYPE) {
        return MemoComponent;
      }
    }

    return IndeterminateComponent;
  } // This is used to create an alternate fiber to do work on.

  function createWorkInProgress(current, pendingProps) {
    var workInProgress = current.alternate;

    if (workInProgress === null) {
      // We use a double buffering pooling technique because we know that we'll
      // only ever need at most two versions of a tree. We pool the "other" unused
      // node that we're free to reuse. This is lazily created to avoid allocating
      // extra objects for things that are never updated. It also allow us to
      // reclaim the extra memory if needed.
      workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
      workInProgress.elementType = current.elementType;
      workInProgress.type = current.type;
      workInProgress.stateNode = current.stateNode;

      {
        // DEV-only fields
        workInProgress._debugSource = current._debugSource;
        workInProgress._debugOwner = current._debugOwner;
        workInProgress._debugHookTypes = current._debugHookTypes;
      }

      workInProgress.alternate = current;
      current.alternate = workInProgress;
    } else {
      workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.

      workInProgress.type = current.type; // We already have an alternate.
      // Reset the effect tag.

      workInProgress.flags = NoFlags; // The effects are no longer valid.

      workInProgress.subtreeFlags = NoFlags;
      workInProgress.deletions = null;

      {
        // We intentionally reset, rather than copy, actualDuration & actualStartTime.
        // This prevents time from endlessly accumulating in new commits.
        // This has the downside of resetting values for different priority renders,
        // But works for yielding (the common case) and should support resuming.
        workInProgress.actualDuration = 0;
        workInProgress.actualStartTime = -1;
      }
    } // Reset all effects except static ones.
    // Static effects are not specific to a render.


    workInProgress.flags = current.flags & StaticMask;
    workInProgress.childLanes = current.childLanes;
    workInProgress.lanes = current.lanes;
    workInProgress.child = current.child;
    workInProgress.memoizedProps = current.memoizedProps;
    workInProgress.memoizedState = current.memoizedState;
    workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
    // it cannot be shared with the current fiber.

    var currentDependencies = current.dependencies;
    workInProgress.dependencies = currentDependencies === null ? null : {
      lanes: currentDependencies.lanes,
      firstContext: currentDependencies.firstContext
    }; // These will be overridden during the parent's reconciliation

    workInProgress.sibling = current.sibling;
    workInProgress.index = current.index;
    workInProgress.ref = current.ref;

    {
      workInProgress.selfBaseDuration = current.selfBaseDuration;
      workInProgress.treeBaseDuration = current.treeBaseDuration;
    }

    {
      workInProgress._debugNeedsRemount = current._debugNeedsRemount;

      switch (workInProgress.tag) {
        case IndeterminateComponent:
        case FunctionComponent:
        case SimpleMemoComponent:
          workInProgress.type = resolveFunctionForHotReloading(current.type);
          break;

        case ClassComponent:
          workInProgress.type = resolveClassForHotReloading(current.type);
          break;

        case ForwardRef:
          workInProgress.type = resolveForwardRefForHotReloading(current.type);
          break;
      }
    }

    return workInProgress;
  } // Used to reuse a Fiber for a second pass.

  function resetWorkInProgress(workInProgress, renderLanes) {
    // This resets the Fiber to what createFiber or createWorkInProgress would
    // have set the values to before during the first pass. Ideally this wouldn't
    // be necessary but unfortunately many code paths reads from the workInProgress
    // when they should be reading from current and writing to workInProgress.
    // We assume pendingProps, index, key, ref, return are still untouched to
    // avoid doing another reconciliation.
    // Reset the effect flags but keep any Placement tags, since that's something
    // that child fiber is setting, not the reconciliation.
    workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid.

    var current = workInProgress.alternate;

    if (current === null) {
      // Reset to createFiber's initial values.
      workInProgress.childLanes = NoLanes;
      workInProgress.lanes = renderLanes;
      workInProgress.child = null;
      workInProgress.subtreeFlags = NoFlags;
      workInProgress.memoizedProps = null;
      workInProgress.memoizedState = null;
      workInProgress.updateQueue = null;
      workInProgress.dependencies = null;
      workInProgress.stateNode = null;

      {
        // Note: We don't reset the actualTime counts. It's useful to accumulate
        // actual time across multiple render passes.
        workInProgress.selfBaseDuration = 0;
        workInProgress.treeBaseDuration = 0;
      }
    } else {
      // Reset to the cloned values that createWorkInProgress would've.
      workInProgress.childLanes = current.childLanes;
      workInProgress.lanes = current.lanes;
      workInProgress.child = current.child;
      workInProgress.subtreeFlags = NoFlags;
      workInProgress.deletions = null;
      workInProgress.memoizedProps = current.memoizedProps;
      workInProgress.memoizedState = current.memoizedState;
      workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.

      workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
      // it cannot be shared with the current fiber.

      var currentDependencies = current.dependencies;
      workInProgress.dependencies = currentDependencies === null ? null : {
        lanes: currentDependencies.lanes,
        firstContext: currentDependencies.firstContext
      };

      {
        // Note: We don't reset the actualTime counts. It's useful to accumulate
        // actual time across multiple render passes.
        workInProgress.selfBaseDuration = current.selfBaseDuration;
        workInProgress.treeBaseDuration = current.treeBaseDuration;
      }
    }

    return workInProgress;
  }
  function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
    var mode;

    if (tag === ConcurrentRoot) {
      mode = ConcurrentMode;

      if (isStrictMode === true) {
        mode |= StrictLegacyMode;

        {
          mode |= StrictEffectsMode;
        }
      }
    } else {
      mode = NoMode;
    }

    if ( isDevToolsPresent) {
      // Always collect profile timings when DevTools are present.
      // This enables DevTools to start capturing timing at any pointâ€“
      // Without some nodes in the tree having empty base times.
      mode |= ProfileMode;
    }

    return createFiber(HostRoot, null, null, mode);
  }
  function createFiberFromTypeAndProps(type, // React$ElementType
  key, pendingProps, owner, mode, lanes) {
    var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.

    var resolvedType = type;

    if (typeof type === 'function') {
      if (shouldConstruct$1(type)) {
        fiberTag = ClassComponent;

        {
          resolvedType = resolveClassForHotReloading(resolvedType);
        }
      } else {
        {
          resolvedType = resolveFunctionForHotReloading(resolvedType);
        }
      }
    } else if (typeof type === 'string') {
      fiberTag = HostComponent;
    } else {
      getTag: switch (type) {
        case REACT_FRAGMENT_TYPE:
          return createFiberFromFragment(pendingProps.children, mode, lanes, key);

        case REACT_STRICT_MODE_TYPE:
          fiberTag = Mode;
          mode |= StrictLegacyMode;

          if ( (mode & ConcurrentMode) !== NoMode) {
            // Strict effects should never run on legacy roots
            mode |= StrictEffectsMode;
          }

          break;

        case REACT_PROFILER_TYPE:
          return createFiberFromProfiler(pendingProps, mode, lanes, key);

        case REACT_SUSPENSE_TYPE:
          return createFiberFromSuspense(pendingProps, mode, lanes, key);

        case REACT_SUSPENSE_LIST_TYPE:
          return createFiberFromSuspenseList(pendingProps, mode, lanes, key);

        case REACT_OFFSCREEN_TYPE:
          return createFiberFromOffscreen(pendingProps, mode, lanes, key);

        case REACT_LEGACY_HIDDEN_TYPE:

        // eslint-disable-next-line no-fallthrough

        case REACT_SCOPE_TYPE:

        // eslint-disable-next-line no-fallthrough

        case REACT_CACHE_TYPE:

        // eslint-disable-next-line no-fallthrough

        case REACT_TRACING_MARKER_TYPE:

        // eslint-disable-next-line no-fallthrough

        case REACT_DEBUG_TRACING_MODE_TYPE:

        // eslint-disable-next-line no-fallthrough

        default:
          {
            if (typeof type === 'object' && type !== null) {
              switch (type.$$typeof) {
                case REACT_PROVIDER_TYPE:
                  fiberTag = ContextProvider;
                  break getTag;

                case REACT_CONTEXT_TYPE:
                  // This is a consumer
                  fiberTag = ContextConsumer;
                  break getTag;

                case REACT_FORWARD_REF_TYPE:
                  fiberTag = ForwardRef;

                  {
                    resolvedType = resolveForwardRefForHotReloading(resolvedType);
                  }

                  break getTag;

                case REACT_MEMO_TYPE:
                  fiberTag = MemoComponent;
                  break getTag;

                case REACT_LAZY_TYPE:
                  fiberTag = LazyComponent;
                  resolvedType = null;
                  break getTag;
              }
            }

            var info = '';

            {
              if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
                info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
              }

              var ownerName = owner ? getComponentNameFromFiber(owner) : null;

              if (ownerName) {
                info += '\n\nCheck the render method of `' + ownerName + '`.';
              }
            }

            throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
          }
      }
    }

    var fiber = createFiber(fiberTag, pendingProps, key, mode);
    fiber.elementType = type;
    fiber.type = resolvedType;
    fiber.lanes = lanes;

    {
      fiber._debugOwner = owner;
    }

    return fiber;
  }
  function createFiberFromElement(element, mode, lanes) {
    var owner = null;

    {
      owner = element._owner;
    }

    var type = element.type;
    var key = element.key;
    var pendingProps = element.props;
    var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);

    {
      fiber._debugSource = element._source;
      fiber._debugOwner = element._owner;
    }

    return fiber;
  }
  function createFiberFromFragment(elements, mode, lanes, key) {
    var fiber = createFiber(Fragment, elements, key, mode);
    fiber.lanes = lanes;
    return fiber;
  }

  function createFiberFromProfiler(pendingProps, mode, lanes, key) {
    {
      if (typeof pendingProps.id !== 'string') {
        error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
      }
    }

    var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
    fiber.elementType = REACT_PROFILER_TYPE;
    fiber.lanes = lanes;

    {
      fiber.stateNode = {
        effectDuration: 0,
        passiveEffectDuration: 0
      };
    }

    return fiber;
  }

  function createFiberFromSuspense(pendingProps, mode, lanes, key) {
    var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
    fiber.elementType = REACT_SUSPENSE_TYPE;
    fiber.lanes = lanes;
    return fiber;
  }
  function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
    var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
    fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
    fiber.lanes = lanes;
    return fiber;
  }
  function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
    var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
    fiber.elementType = REACT_OFFSCREEN_TYPE;
    fiber.lanes = lanes;
    var primaryChildInstance = {
      isHidden: false
    };
    fiber.stateNode = primaryChildInstance;
    return fiber;
  }
  function createFiberFromText(content, mode, lanes) {
    var fiber = createFiber(HostText, content, null, mode);
    fiber.lanes = lanes;
    return fiber;
  }
  function createFiberFromHostInstanceForDeletion() {
    var fiber = createFiber(HostComponent, null, null, NoMode);
    fiber.elementType = 'DELETED';
    return fiber;
  }
  function createFiberFromDehydratedFragment(dehydratedNode) {
    var fiber = createFiber(DehydratedFragment, null, null, NoMode);
    fiber.stateNode = dehydratedNode;
    return fiber;
  }
  function createFiberFromPortal(portal, mode, lanes) {
    var pendingProps = portal.children !== null ? portal.children : [];
    var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
    fiber.lanes = lanes;
    fiber.stateNode = {
      containerInfo: portal.containerInfo,
      pendingChildren: null,
      // Used by persistent updates
      implementation: portal.implementation
    };
    return fiber;
  } // Used for stashing WIP properties to replay failed work in DEV.

  function assignFiberPropertiesInDEV(target, source) {
    if (target === null) {
      // This Fiber's initial properties will always be overwritten.
      // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
      target = createFiber(IndeterminateComponent, null, null, NoMode);
    } // This is intentionally written as a list of all properties.
    // We tried to use Object.assign() instead but this is called in
    // the hottest path, and Object.assign() was too slow:
    // https://github.com/facebook/react/issues/12502
    // This code is DEV-only so size is not a concern.


    target.tag = source.tag;
    target.key = source.key;
    target.elementType = source.elementType;
    target.type = source.type;
    target.stateNode = source.stateNode;
    target.return = source.return;
    target.child = source.child;
    target.sibling = source.sibling;
    target.index = source.index;
    target.ref = source.ref;
    target.pendingProps = source.pendingProps;
    target.memoizedProps = source.memoizedProps;
    target.updateQueue = source.updateQueue;
    target.memoizedState = source.memoizedState;
    target.dependencies = source.dependencies;
    target.mode = source.mode;
    target.flags = source.flags;
    target.subtreeFlags = source.subtreeFlags;
    target.deletions = source.deletions;
    target.lanes = source.lanes;
    target.childLanes = source.childLanes;
    target.alternate = source.alternate;

    {
      target.actualDuration = source.actualDuration;
      target.actualStartTime = source.actualStartTime;
      target.selfBaseDuration = source.selfBaseDuration;
      target.treeBaseDuration = source.treeBaseDuration;
    }

    target._debugSource = source._debugSource;
    target._debugOwner = source._debugOwner;
    target._debugNeedsRemount = source._debugNeedsRemount;
    target._debugHookTypes = source._debugHookTypes;
    return target;
  }

  function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) {
    this.tag = tag;
    this.containerInfo = containerInfo;
    this.pendingChildren = null;
    this.current = null;
    this.pingCache = null;
    this.finishedWork = null;
    this.timeoutHandle = noTimeout;
    this.context = null;
    this.pendingContext = null;
    this.callbackNode = null;
    this.callbackPriority = NoLane;
    this.eventTimes = createLaneMap(NoLanes);
    this.expirationTimes = createLaneMap(NoTimestamp);
    this.pendingLanes = NoLanes;
    this.suspendedLanes = NoLanes;
    this.pingedLanes = NoLanes;
    this.expiredLanes = NoLanes;
    this.mutableReadLanes = NoLanes;
    this.finishedLanes = NoLanes;
    this.entangledLanes = NoLanes;
    this.entanglements = createLaneMap(NoLanes);
    this.identifierPrefix = identifierPrefix;
    this.onRecoverableError = onRecoverableError;

    {
      this.mutableSourceEagerHydrationData = null;
    }

    {
      this.effectDuration = 0;
      this.passiveEffectDuration = 0;
    }

    {
      this.memoizedUpdaters = new Set();
      var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];

      for (var _i = 0; _i < TotalLanes; _i++) {
        pendingUpdatersLaneMap.push(new Set());
      }
    }

    {
      switch (tag) {
        case ConcurrentRoot:
          this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
          break;

        case LegacyRoot:
          this._debugRootType = hydrate ? 'hydrate()' : 'render()';
          break;
      }
    }
  }

  function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the
  // host config, but because they are passed in at runtime, we have to thread
  // them through the root constructor. Perhaps we should put them all into a
  // single type, like a DynamicHostConfig that is defined by the renderer.
  identifierPrefix, onRecoverableError, transitionCallbacks) {
    var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError);
    // stateNode is any.


    var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
    root.current = uninitializedFiber;
    uninitializedFiber.stateNode = root;

    {
      var _initialState = {
        element: initialChildren,
        isDehydrated: hydrate,
        cache: null,
        // not enabled yet
        transitions: null,
        pendingSuspenseBoundaries: null
      };
      uninitializedFiber.memoizedState = _initialState;
    }

    initializeUpdateQueue(uninitializedFiber);
    return root;
  }

  var ReactVersion = '18.3.1';

  function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
  implementation) {
    var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

    {
      checkKeyStringCoercion(key);
    }

    return {
      // This tag allow us to uniquely identify this as a React Portal
      $$typeof: REACT_PORTAL_TYPE,
      key: key == null ? null : '' + key,
      children: children,
      containerInfo: containerInfo,
      implementation: implementation
    };
  }

  var didWarnAboutNestedUpdates;
  var didWarnAboutFindNodeInStrictMode;

  {
    didWarnAboutNestedUpdates = false;
    didWarnAboutFindNodeInStrictMode = {};
  }

  function getContextForSubtree(parentComponent) {
    if (!parentComponent) {
      return emptyContextObject;
    }

    var fiber = get(parentComponent);
    var parentContext = findCurrentUnmaskedContext(fiber);

    if (fiber.tag === ClassComponent) {
      var Component = fiber.type;

      if (isContextProvider(Component)) {
        return processChildContext(fiber, Component, parentContext);
      }
    }

    return parentContext;
  }

  function findHostInstanceWithWarning(component, methodName) {
    {
      var fiber = get(component);

      if (fiber === undefined) {
        if (typeof component.render === 'function') {
          throw new Error('Unable to find node on an unmounted component.');
        } else {
          var keys = Object.keys(component).join(',');
          throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
        }
      }

      var hostFiber = findCurrentHostFiber(fiber);

      if (hostFiber === null) {
        return null;
      }

      if (hostFiber.mode & StrictLegacyMode) {
        var componentName = getComponentNameFromFiber(fiber) || 'Component';

        if (!didWarnAboutFindNodeInStrictMode[componentName]) {
          didWarnAboutFindNodeInStrictMode[componentName] = true;
          var previousFiber = current;

          try {
            setCurrentFiber(hostFiber);

            if (fiber.mode & StrictLegacyMode) {
              error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
            } else {
              error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
            }
          } finally {
            // Ideally this should reset to previous but this shouldn't be called in
            // render and there's another warning for that anyway.
            if (previousFiber) {
              setCurrentFiber(previousFiber);
            } else {
              resetCurrentFiber();
            }
          }
        }
      }

      return hostFiber.stateNode;
    }
  }

  function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
    var hydrate = false;
    var initialChildren = null;
    return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
  }
  function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode.
  callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
    var hydrate = true;
    var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor

    root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from
    // a regular update because the initial render must match was was rendered
    // on the server.
    // NOTE: This update intentionally doesn't have a payload. We're only using
    // the update to schedule work on the root fiber (and, for legacy roots, to
    // enqueue the callback if one is provided).

    var current = root.current;
    var eventTime = requestEventTime();
    var lane = requestUpdateLane(current);
    var update = createUpdate(eventTime, lane);
    update.callback = callback !== undefined && callback !== null ? callback : null;
    enqueueUpdate(current, update, lane);
    scheduleInitialHydrationOnRoot(root, lane, eventTime);
    return root;
  }
  function updateContainer(element, container, parentComponent, callback) {
    {
      onScheduleRoot(container, element);
    }

    var current$1 = container.current;
    var eventTime = requestEventTime();
    var lane = requestUpdateLane(current$1);

    {
      markRenderScheduled(lane);
    }

    var context = getContextForSubtree(parentComponent);

    if (container.context === null) {
      container.context = context;
    } else {
      container.pendingContext = context;
    }

    {
      if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
        didWarnAboutNestedUpdates = true;

        error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown');
      }
    }

    var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
    // being called "element".

    update.payload = {
      element: element
    };
    callback = callback === undefined ? null : callback;

    if (callback !== null) {
      {
        if (typeof callback !== 'function') {
          error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
        }
      }

      update.callback = callback;
    }

    var root = enqueueUpdate(current$1, update, lane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, current$1, lane, eventTime);
      entangleTransitions(root, current$1, lane);
    }

    return lane;
  }
  function getPublicRootInstance(container) {
    var containerFiber = container.current;

    if (!containerFiber.child) {
      return null;
    }

    switch (containerFiber.child.tag) {
      case HostComponent:
        return getPublicInstance(containerFiber.child.stateNode);

      default:
        return containerFiber.child.stateNode;
    }
  }
  function attemptSynchronousHydration$1(fiber) {
    switch (fiber.tag) {
      case HostRoot:
        {
          var root = fiber.stateNode;

          if (isRootDehydrated(root)) {
            // Flush the first scheduled "update".
            var lanes = getHighestPriorityPendingLanes(root);
            flushRoot(root, lanes);
          }

          break;
        }

      case SuspenseComponent:
        {
          flushSync(function () {
            var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

            if (root !== null) {
              var eventTime = requestEventTime();
              scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime);
            }
          }); // If we're still blocked after this, we need to increase
          // the priority of any promises resolving within this
          // boundary so that they next attempt also has higher pri.

          var retryLane = SyncLane;
          markRetryLaneIfNotHydrated(fiber, retryLane);
          break;
        }
    }
  }

  function markRetryLaneImpl(fiber, retryLane) {
    var suspenseState = fiber.memoizedState;

    if (suspenseState !== null && suspenseState.dehydrated !== null) {
      suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
    }
  } // Increases the priority of thenables when they resolve within this boundary.


  function markRetryLaneIfNotHydrated(fiber, retryLane) {
    markRetryLaneImpl(fiber, retryLane);
    var alternate = fiber.alternate;

    if (alternate) {
      markRetryLaneImpl(alternate, retryLane);
    }
  }
  function attemptContinuousHydration$1(fiber) {
    if (fiber.tag !== SuspenseComponent) {
      // We ignore HostRoots here because we can't increase
      // their priority and they should not suspend on I/O,
      // since you have to wrap anything that might suspend in
      // Suspense.
      return;
    }

    var lane = SelectiveHydrationLane;
    var root = enqueueConcurrentRenderForLane(fiber, lane);

    if (root !== null) {
      var eventTime = requestEventTime();
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
    }

    markRetryLaneIfNotHydrated(fiber, lane);
  }
  function attemptHydrationAtCurrentPriority$1(fiber) {
    if (fiber.tag !== SuspenseComponent) {
      // We ignore HostRoots here because we can't increase
      // their priority other than synchronously flush it.
      return;
    }

    var lane = requestUpdateLane(fiber);
    var root = enqueueConcurrentRenderForLane(fiber, lane);

    if (root !== null) {
      var eventTime = requestEventTime();
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
    }

    markRetryLaneIfNotHydrated(fiber, lane);
  }
  function findHostInstanceWithNoPortals(fiber) {
    var hostFiber = findCurrentHostFiberWithNoPortals(fiber);

    if (hostFiber === null) {
      return null;
    }

    return hostFiber.stateNode;
  }

  var shouldErrorImpl = function (fiber) {
    return null;
  };

  function shouldError(fiber) {
    return shouldErrorImpl(fiber);
  }

  var shouldSuspendImpl = function (fiber) {
    return false;
  };

  function shouldSuspend(fiber) {
    return shouldSuspendImpl(fiber);
  }
  var overrideHookState = null;
  var overrideHookStateDeletePath = null;
  var overrideHookStateRenamePath = null;
  var overrideProps = null;
  var overridePropsDeletePath = null;
  var overridePropsRenamePath = null;
  var scheduleUpdate = null;
  var setErrorHandler = null;
  var setSuspenseHandler = null;

  {
    var copyWithDeleteImpl = function (obj, path, index) {
      var key = path[index];
      var updated = isArray(obj) ? obj.slice() : assign({}, obj);

      if (index + 1 === path.length) {
        if (isArray(updated)) {
          updated.splice(key, 1);
        } else {
          delete updated[key];
        }

        return updated;
      } // $FlowFixMe number or string is fine here


      updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
      return updated;
    };

    var copyWithDelete = function (obj, path) {
      return copyWithDeleteImpl(obj, path, 0);
    };

    var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
      var oldKey = oldPath[index];
      var updated = isArray(obj) ? obj.slice() : assign({}, obj);

      if (index + 1 === oldPath.length) {
        var newKey = newPath[index]; // $FlowFixMe number or string is fine here

        updated[newKey] = updated[oldKey];

        if (isArray(updated)) {
          updated.splice(oldKey, 1);
        } else {
          delete updated[oldKey];
        }
      } else {
        // $FlowFixMe number or string is fine here
        updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
        obj[oldKey], oldPath, newPath, index + 1);
      }

      return updated;
    };

    var copyWithRename = function (obj, oldPath, newPath) {
      if (oldPath.length !== newPath.length) {
        warn('copyWithRename() expects paths of the same length');

        return;
      } else {
        for (var i = 0; i < newPath.length - 1; i++) {
          if (oldPath[i] !== newPath[i]) {
            warn('copyWithRename() expects paths to be the same except for the deepest key');

            return;
          }
        }
      }

      return copyWithRenameImpl(obj, oldPath, newPath, 0);
    };

    var copyWithSetImpl = function (obj, path, index, value) {
      if (index >= path.length) {
        return value;
      }

      var key = path[index];
      var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here

      updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
      return updated;
    };

    var copyWithSet = function (obj, path, value) {
      return copyWithSetImpl(obj, path, 0, value);
    };

    var findHook = function (fiber, id) {
      // For now, the "id" of stateful hooks is just the stateful hook index.
      // This may change in the future with e.g. nested hooks.
      var currentHook = fiber.memoizedState;

      while (currentHook !== null && id > 0) {
        currentHook = currentHook.next;
        id--;
      }

      return currentHook;
    }; // Support DevTools editable values for useState and useReducer.


    overrideHookState = function (fiber, id, path, value) {
      var hook = findHook(fiber, id);

      if (hook !== null) {
        var newState = copyWithSet(hook.memoizedState, path, value);
        hook.memoizedState = newState;
        hook.baseState = newState; // We aren't actually adding an update to the queue,
        // because there is no update we can add for useReducer hooks that won't trigger an error.
        // (There's no appropriate action type for DevTools overrides.)
        // As a result though, React will see the scheduled update as a noop and bailout.
        // Shallow cloning props works as a workaround for now to bypass the bailout check.

        fiber.memoizedProps = assign({}, fiber.memoizedProps);
        var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

        if (root !== null) {
          scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
        }
      }
    };

    overrideHookStateDeletePath = function (fiber, id, path) {
      var hook = findHook(fiber, id);

      if (hook !== null) {
        var newState = copyWithDelete(hook.memoizedState, path);
        hook.memoizedState = newState;
        hook.baseState = newState; // We aren't actually adding an update to the queue,
        // because there is no update we can add for useReducer hooks that won't trigger an error.
        // (There's no appropriate action type for DevTools overrides.)
        // As a result though, React will see the scheduled update as a noop and bailout.
        // Shallow cloning props works as a workaround for now to bypass the bailout check.

        fiber.memoizedProps = assign({}, fiber.memoizedProps);
        var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

        if (root !== null) {
          scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
        }
      }
    };

    overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
      var hook = findHook(fiber, id);

      if (hook !== null) {
        var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
        hook.memoizedState = newState;
        hook.baseState = newState; // We aren't actually adding an update to the queue,
        // because there is no update we can add for useReducer hooks that won't trigger an error.
        // (There's no appropriate action type for DevTools overrides.)
        // As a result though, React will see the scheduled update as a noop and bailout.
        // Shallow cloning props works as a workaround for now to bypass the bailout check.

        fiber.memoizedProps = assign({}, fiber.memoizedProps);
        var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

        if (root !== null) {
          scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
        }
      }
    }; // Support DevTools props for function components, forwardRef, memo, host components, etc.


    overrideProps = function (fiber, path, value) {
      fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);

      if (fiber.alternate) {
        fiber.alternate.pendingProps = fiber.pendingProps;
      }

      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    };

    overridePropsDeletePath = function (fiber, path) {
      fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);

      if (fiber.alternate) {
        fiber.alternate.pendingProps = fiber.pendingProps;
      }

      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    };

    overridePropsRenamePath = function (fiber, oldPath, newPath) {
      fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);

      if (fiber.alternate) {
        fiber.alternate.pendingProps = fiber.pendingProps;
      }

      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    };

    scheduleUpdate = function (fiber) {
      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    };

    setErrorHandler = function (newShouldErrorImpl) {
      shouldErrorImpl = newShouldErrorImpl;
    };

    setSuspenseHandler = function (newShouldSuspendImpl) {
      shouldSuspendImpl = newShouldSuspendImpl;
    };
  }

  function findHostInstanceByFiber(fiber) {
    var hostFiber = findCurrentHostFiber(fiber);

    if (hostFiber === null) {
      return null;
    }

    return hostFiber.stateNode;
  }

  function emptyFindFiberByHostInstance(instance) {
    return null;
  }

  function getCurrentFiberForDevTools() {
    return current;
  }

  function injectIntoDevTools(devToolsConfig) {
    var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
    var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
    return injectInternals({
      bundleType: devToolsConfig.bundleType,
      version: devToolsConfig.version,
      rendererPackageName: devToolsConfig.rendererPackageName,
      rendererConfig: devToolsConfig.rendererConfig,
      overrideHookState: overrideHookState,
      overrideHookStateDeletePath: overrideHookStateDeletePath,
      overrideHookStateRenamePath: overrideHookStateRenamePath,
      overrideProps: overrideProps,
      overridePropsDeletePath: overridePropsDeletePath,
      overridePropsRenamePath: overridePropsRenamePath,
      setErrorHandler: setErrorHandler,
      setSuspenseHandler: setSuspenseHandler,
      scheduleUpdate: scheduleUpdate,
      currentDispatcherRef: ReactCurrentDispatcher,
      findHostInstanceByFiber: findHostInstanceByFiber,
      findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
      // React Refresh
      findHostInstancesForRefresh:  findHostInstancesForRefresh ,
      scheduleRefresh:  scheduleRefresh ,
      scheduleRoot:  scheduleRoot ,
      setRefreshHandler:  setRefreshHandler ,
      // Enables DevTools to append owner stacks to error messages in DEV mode.
      getCurrentFiber:  getCurrentFiberForDevTools ,
      // Enables DevTools to detect reconciler version rather than renderer version
      // which may not match for third party renderers.
      reconcilerVersion: ReactVersion
    });
  }

  /* global reportError */

  var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event,
  // emulating an uncaught JavaScript error.
  reportError : function (error) {
    // In older browsers and test environments, fallback to console.error.
    // eslint-disable-next-line react-internal/no-production-logging
    console['error'](error);
  };

  function ReactDOMRoot(internalRoot) {
    this._internalRoot = internalRoot;
  }

  ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) {
    var root = this._internalRoot;

    if (root === null) {
      throw new Error('Cannot update an unmounted root.');
    }

    {
      if (typeof arguments[1] === 'function') {
        error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
      } else if (isValidContainer(arguments[1])) {
        error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root.");
      } else if (typeof arguments[1] !== 'undefined') {
        error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.');
      }

      var container = root.containerInfo;

      if (container.nodeType !== COMMENT_NODE) {
        var hostInstance = findHostInstanceWithNoPortals(root.current);

        if (hostInstance) {
          if (hostInstance.parentNode !== container) {
            error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
          }
        }
      }
    }

    updateContainer(children, root, null, null);
  };

  ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () {
    {
      if (typeof arguments[0] === 'function') {
        error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
      }
    }

    var root = this._internalRoot;

    if (root !== null) {
      this._internalRoot = null;
      var container = root.containerInfo;

      {
        if (isAlreadyRendering()) {
          error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.');
        }
      }

      flushSync(function () {
        updateContainer(null, root, null, null);
      });
      unmarkContainerAsRoot(container);
    }
  };

  function createRoot(container, options) {
    if (!isValidContainer(container)) {
      throw new Error('createRoot(...): Target container is not a DOM element.');
    }

    warnIfReactDOMContainerInDEV(container);
    var isStrictMode = false;
    var concurrentUpdatesByDefaultOverride = false;
    var identifierPrefix = '';
    var onRecoverableError = defaultOnRecoverableError;
    var transitionCallbacks = null;

    if (options !== null && options !== undefined) {
      {
        if (options.hydrate) {
          warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.');
        } else {
          if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) {
            error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + '  let root = createRoot(domContainer);\n' + '  root.render(<App />);');
          }
        }
      }

      if (options.unstable_strictMode === true) {
        isStrictMode = true;
      }

      if (options.identifierPrefix !== undefined) {
        identifierPrefix = options.identifierPrefix;
      }

      if (options.onRecoverableError !== undefined) {
        onRecoverableError = options.onRecoverableError;
      }

      if (options.transitionCallbacks !== undefined) {
        transitionCallbacks = options.transitionCallbacks;
      }
    }

    var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
    markContainerAsRoot(root.current, container);
    var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
    listenToAllSupportedEvents(rootContainerElement);
    return new ReactDOMRoot(root);
  }

  function ReactDOMHydrationRoot(internalRoot) {
    this._internalRoot = internalRoot;
  }

  function scheduleHydration(target) {
    if (target) {
      queueExplicitHydrationTarget(target);
    }
  }

  ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
  function hydrateRoot(container, initialChildren, options) {
    if (!isValidContainer(container)) {
      throw new Error('hydrateRoot(...): Target container is not a DOM element.');
    }

    warnIfReactDOMContainerInDEV(container);

    {
      if (initialChildren === undefined) {
        error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)');
      }
    } // For now we reuse the whole bag of options since they contain
    // the hydration callbacks.


    var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option

    var mutableSources = options != null && options.hydratedSources || null;
    var isStrictMode = false;
    var concurrentUpdatesByDefaultOverride = false;
    var identifierPrefix = '';
    var onRecoverableError = defaultOnRecoverableError;

    if (options !== null && options !== undefined) {
      if (options.unstable_strictMode === true) {
        isStrictMode = true;
      }

      if (options.identifierPrefix !== undefined) {
        identifierPrefix = options.identifierPrefix;
      }

      if (options.onRecoverableError !== undefined) {
        onRecoverableError = options.onRecoverableError;
      }
    }

    var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
    markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway.

    listenToAllSupportedEvents(container);

    if (mutableSources) {
      for (var i = 0; i < mutableSources.length; i++) {
        var mutableSource = mutableSources[i];
        registerMutableSourceForHydration(root, mutableSource);
      }
    }

    return new ReactDOMHydrationRoot(root);
  }
  function isValidContainer(node) {
    return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers  ));
  } // TODO: Remove this function which also includes comment nodes.
  // We only use it in places that are currently more relaxed.

  function isValidContainerLegacy(node) {
    return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
  }

  function warnIfReactDOMContainerInDEV(container) {
    {
      if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
        error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.');
      }

      if (isContainerMarkedAsRoot(container)) {
        if (container._reactRootContainer) {
          error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.');
        } else {
          error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.');
        }
      }
    }
  }

  var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
  var topLevelUpdateWarnings;

  {
    topLevelUpdateWarnings = function (container) {
      if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
        var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);

        if (hostInstance) {
          if (hostInstance.parentNode !== container) {
            error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
          }
        }
      }

      var isRootRenderedBySomeReact = !!container._reactRootContainer;
      var rootEl = getReactRootElementInContainer(container);
      var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));

      if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
        error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
      }

      if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
        error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
      }
    };
  }

  function getReactRootElementInContainer(container) {
    if (!container) {
      return null;
    }

    if (container.nodeType === DOCUMENT_NODE) {
      return container.documentElement;
    } else {
      return container.firstChild;
    }
  }

  function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the
    // legacy API.
  }

  function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
    if (isHydrationContainer) {
      if (typeof callback === 'function') {
        var originalCallback = callback;

        callback = function () {
          var instance = getPublicRootInstance(root);
          originalCallback.call(instance);
        };
      }

      var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks
      false, // isStrictMode
      false, // concurrentUpdatesByDefaultOverride,
      '', // identifierPrefix
      noopOnRecoverableError);
      container._reactRootContainer = root;
      markContainerAsRoot(root.current, container);
      var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
      listenToAllSupportedEvents(rootContainerElement);
      flushSync();
      return root;
    } else {
      // First clear any existing content.
      var rootSibling;

      while (rootSibling = container.lastChild) {
        container.removeChild(rootSibling);
      }

      if (typeof callback === 'function') {
        var _originalCallback = callback;

        callback = function () {
          var instance = getPublicRootInstance(_root);

          _originalCallback.call(instance);
        };
      }

      var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks
      false, // isStrictMode
      false, // concurrentUpdatesByDefaultOverride,
      '', // identifierPrefix
      noopOnRecoverableError);

      container._reactRootContainer = _root;
      markContainerAsRoot(_root.current, container);

      var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;

      listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched.

      flushSync(function () {
        updateContainer(initialChildren, _root, parentComponent, callback);
      });
      return _root;
    }
  }

  function warnOnInvalidCallback$1(callback, callerName) {
    {
      if (callback !== null && typeof callback !== 'function') {
        error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
      }
    }
  }

  function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
    {
      topLevelUpdateWarnings(container);
      warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
    }

    var maybeRoot = container._reactRootContainer;
    var root;

    if (!maybeRoot) {
      // Initial mount
      root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
    } else {
      root = maybeRoot;

      if (typeof callback === 'function') {
        var originalCallback = callback;

        callback = function () {
          var instance = getPublicRootInstance(root);
          originalCallback.call(instance);
        };
      } // Update


      updateContainer(children, root, parentComponent, callback);
    }

    return getPublicRootInstance(root);
  }

  var didWarnAboutFindDOMNode = false;
  function findDOMNode(componentOrElement) {
    {
      if (!didWarnAboutFindDOMNode) {
        didWarnAboutFindDOMNode = true;

        error('findDOMNode is deprecated and will be removed in the next major ' + 'release. Instead, add a ref directly to the element you want ' + 'to reference. Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node');
      }

      var owner = ReactCurrentOwner$3.current;

      if (owner !== null && owner.stateNode !== null) {
        var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;

        if (!warnedAboutRefsInRender) {
          error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component');
        }

        owner.stateNode._warnedAboutRefsInRender = true;
      }
    }

    if (componentOrElement == null) {
      return null;
    }

    if (componentOrElement.nodeType === ELEMENT_NODE) {
      return componentOrElement;
    }

    {
      return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
    }
  }
  function hydrate(element, container, callback) {
    {
      error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
    }

    if (!isValidContainerLegacy(container)) {
      throw new Error('Target container is not a DOM element.');
    }

    {
      var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

      if (isModernRoot) {
        error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?');
      }
    } // TODO: throw or warn if we couldn't hydrate?


    return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
  }
  function render(element, container, callback) {
    {
      error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
    }

    if (!isValidContainerLegacy(container)) {
      throw new Error('Target container is not a DOM element.');
    }

    {
      var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

      if (isModernRoot) {
        error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
      }
    }

    return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
  }
  function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
    {
      error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot');
    }

    if (!isValidContainerLegacy(containerNode)) {
      throw new Error('Target container is not a DOM element.');
    }

    if (parentComponent == null || !has(parentComponent)) {
      throw new Error('parentComponent must be a valid React Component');
    }

    return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
  }
  var didWarnAboutUnmountComponentAtNode = false;
  function unmountComponentAtNode(container) {
    {
      if (!didWarnAboutUnmountComponentAtNode) {
        didWarnAboutUnmountComponentAtNode = true;

        error('unmountComponentAtNode is deprecated and will be removed in the ' + 'next major release. Switch to the createRoot API. Learn ' + 'more: https://reactjs.org/link/switch-to-createroot');
      }
    }

    if (!isValidContainerLegacy(container)) {
      throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.');
    }

    {
      var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

      if (isModernRoot) {
        error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?');
      }
    }

    if (container._reactRootContainer) {
      {
        var rootEl = getReactRootElementInContainer(container);
        var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);

        if (renderedByDifferentReact) {
          error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
        }
      } // Unmount should not be batched.


      flushSync(function () {
        legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
          // $FlowFixMe This should probably use `delete container._reactRootContainer`
          container._reactRootContainer = null;
          unmarkContainerAsRoot(container);
        });
      }); // If you call unmountComponentAtNode twice in quick succession, you'll
      // get `true` twice. That's probably fine?

      return true;
    } else {
      {
        var _rootEl = getReactRootElementInContainer(container);

        var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node.

        var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;

        if (hasNonRootReactChild) {
          error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
        }
      }

      return false;
    }
  }

  setAttemptSynchronousHydration(attemptSynchronousHydration$1);
  setAttemptContinuousHydration(attemptContinuousHydration$1);
  setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
  setGetCurrentUpdatePriority(getCurrentUpdatePriority);
  setAttemptHydrationAtPriority(runWithPriority);

  {
    if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
    Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
    Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
      error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
    }
  }

  setRestoreImplementation(restoreControlledState$3);
  setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync);

  function createPortal$1(children, container) {
    var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

    if (!isValidContainer(container)) {
      throw new Error('Target container is not a DOM element.');
    } // TODO: pass ReactDOM portal implementation as third argument
    // $FlowFixMe The Flow type is opaque but there's no way to actually create it.


    return createPortal(children, container, null, key);
  }

  function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
    return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
  }

  var Internals = {
    usingClientEntryPoint: false,
    // Keep in sync with ReactTestUtils.js.
    // This is an array for better minification.
    Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
  };

  function createRoot$1(container, options) {
    {
      if (!Internals.usingClientEntryPoint && !true) {
        error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
      }
    }

    return createRoot(container, options);
  }

  function hydrateRoot$1(container, initialChildren, options) {
    {
      if (!Internals.usingClientEntryPoint && !true) {
        error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
      }
    }

    return hydrateRoot(container, initialChildren, options);
  } // Overload the definition to the two valid signatures.
  // Warning, this opts-out of checking the function body.


  // eslint-disable-next-line no-redeclare
  function flushSync$1(fn) {
    {
      if (isAlreadyRendering()) {
        error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.');
      }
    }

    return flushSync(fn);
  }
  var foundDevTools = injectIntoDevTools({
    findFiberByHostInstance: getClosestInstanceFromNode,
    bundleType:  1 ,
    version: ReactVersion,
    rendererPackageName: 'react-dom'
  });

  {
    if (!foundDevTools && canUseDOM && window.top === window.self) {
      // If we're in Chrome or Firefox, provide a download link if not installed.
      if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
        var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.

        if (/^(https?|file):$/.test(protocol)) {
          // eslint-disable-next-line react-internal/no-production-logging
          console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold');
        }
      }
    }
  }

  exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
  exports.createPortal = createPortal$1;
  exports.createRoot = createRoot$1;
  exports.findDOMNode = findDOMNode;
  exports.flushSync = flushSync$1;
  exports.hydrate = hydrate;
  exports.hydrateRoot = hydrateRoot$1;
  exports.render = render;
  exports.unmountComponentAtNode = unmountComponentAtNode;
  exports.unstable_batchedUpdates = batchedUpdates$1;
  exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
  exports.version = ReactVersion;

})));
/**
 * @license React
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
'use strict';(function(Q,zb){"object"===typeof exports&&"undefined"!==typeof module?zb(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],zb):(Q=Q||self,zb(Q.ReactDOM={},Q.React))})(this,function(Q,zb){function m(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
function mb(a,b){Ab(a,b);Ab(a+"Capture",b)}function Ab(a,b){$b[a]=b;for(a=0;a<b.length;a++)cg.add(b[a])}function bj(a){if(Zd.call(dg,a))return!0;if(Zd.call(eg,a))return!1;if(cj.test(a))return dg[a]=!0;eg[a]=!0;return!1}function dj(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}function ej(a,b,c,d){if(null===
b||"undefined"===typeof b||dj(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function Y(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}function $d(a,b,c,d){var e=R.hasOwnProperty(b)?R[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==
b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])ej(b,c,e,d)&&(c=null),d||null===e?bj(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}function ac(a){if(null===a||"object"!==typeof a)return null;a=fg&&a[fg]||a["@@iterator"];return"function"===typeof a?a:null}function bc(a,b,
c){if(void 0===ae)try{throw Error();}catch(d){ae=(b=d.stack.trim().match(/\n( *(at )?)/))&&b[1]||""}return"\n"+ae+a}function be(a,b){if(!a||ce)return"";ce=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(n){var d=n}Reflect.construct(a,[],b)}else{try{b.call()}catch(n){d=n}a.call(b.prototype)}else{try{throw Error();
}catch(n){d=n}a()}}catch(n){if(n&&d&&"string"===typeof n.stack){for(var e=n.stack.split("\n"),f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{ce=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?bc(a):
""}function fj(a){switch(a.tag){case 5:return bc(a.type);case 16:return bc("Lazy");case 13:return bc("Suspense");case 19:return bc("SuspenseList");case 0:case 2:case 15:return a=be(a.type,!1),a;case 11:return a=be(a.type.render,!1),a;case 1:return a=be(a.type,!0),a;default:return""}}function de(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Bb:return"Fragment";case Cb:return"Portal";case ee:return"Profiler";case fe:return"StrictMode";
case ge:return"Suspense";case he:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case gg:return(a.displayName||"Context")+".Consumer";case hg:return(a._context.displayName||"Context")+".Provider";case ie:var b=a.render;a=a.displayName;a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case je:return b=a.displayName||null,null!==b?b:de(a.type)||"Memo";case Ta:b=a._payload;a=a._init;try{return de(a(b))}catch(c){}}return null}function gj(a){var b=a.type;
switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return de(b);case 8:return b===fe?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";
case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Ua(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}}function ig(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===
b)}function hj(a){var b=ig(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function Pc(a){a._valueTracker||(a._valueTracker=hj(a))}function jg(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=ig(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Qc(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function ke(a,b){var c=b.checked;return E({},b,{defaultChecked:void 0,defaultValue:void 0,
value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function kg(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Ua(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function lg(a,b){b=b.checked;null!=b&&$d(a,"checked",b,!1)}function le(a,b){lg(a,b);var c=Ua(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=
c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?me(a,b.type,c):b.hasOwnProperty("defaultValue")&&me(a,b.type,Ua(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}function mg(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;
c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}function me(a,b,c){if("number"!==b||Qc(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}function Db(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=
!0)}else{c=""+Ua(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}function ne(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(m(91));return E({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function ng(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(m(92));if(cc(c)){if(1<c.length)throw Error(m(93));
c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:Ua(c)}}function og(a,b){var c=Ua(b.value),d=Ua(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function pg(a,b){b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}function qg(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}
function oe(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?qg(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}function rg(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||dc.hasOwnProperty(a)&&dc[a]?(""+b).trim():b+"px"}function sg(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rg(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}function pe(a,b){if(b){if(ij[a]&&
(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(m(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(m(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(m(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(m(62));}}function qe(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;
default:return!0}}function re(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function tg(a){if(a=ec(a)){if("function"!==typeof se)throw Error(m(280));var b=a.stateNode;b&&(b=Rc(b),se(a.stateNode,a.type,b))}}function ug(a){Eb?Fb?Fb.push(a):Fb=[a]:Eb=a}function vg(){if(Eb){var a=Eb,b=Fb;Fb=Eb=null;tg(a);if(b)for(a=0;a<b.length;a++)tg(b[a])}}function wg(a,b,c){if(te)return a(b,c);te=!0;try{return xg(a,b,c)}finally{if(te=
!1,null!==Eb||null!==Fb)yg(),vg()}}function fc(a,b){var c=a.stateNode;if(null===c)return null;var d=Rc(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;
if(c&&"function"!==typeof c)throw Error(m(231,b,typeof c));return c}function jj(a,b,c,d,e,f,g,h,k){gc=!1;Sc=null;kj.apply(lj,arguments)}function mj(a,b,c,d,e,f,g,h,k){jj.apply(this,arguments);if(gc){if(gc){var n=Sc;gc=!1;Sc=null}else throw Error(m(198));Tc||(Tc=!0,ue=n)}}function nb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function zg(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,
null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Ag(a){if(nb(a)!==a)throw Error(m(188));}function nj(a){var b=a.alternate;if(!b){b=nb(a);if(null===b)throw Error(m(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Ag(e),a;if(f===d)return Ag(e),b;f=f.sibling}throw Error(m(188));}if(c.return!==d.return)c=e,d=f;
else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(m(189));}}if(c.alternate!==d)throw Error(m(190));}if(3!==c.tag)throw Error(m(188));return c.stateNode.current===c?a:b}function Bg(a){a=nj(a);return null!==a?Cg(a):null}function Cg(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=Cg(a);if(null!==b)return b;a=a.sibling}return null}
function oj(a,b){if(Ca&&"function"===typeof Ca.onCommitFiberRoot)try{Ca.onCommitFiberRoot(Uc,a,void 0,128===(a.current.flags&128))}catch(c){}}function pj(a){a>>>=0;return 0===a?32:31-(qj(a)/rj|0)|0}function hc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&
4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function Vc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=hc(h):(f&=g,0!==f&&(d=hc(f)))}else g=c&~e,0!==g?d=hc(g):0!==f&&(d=hc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&
(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-ta(b),e=1<<c,d|=a[c],b&=~e;return d}function sj(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;
case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function tj(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-ta(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=sj(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function ve(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function Dg(){var a=Wc;Wc<<=1;0===(Wc&4194240)&&(Wc=64);return a}function we(a){for(var b=[],c=0;31>c;c++)b.push(a);
return b}function ic(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-ta(b);a[b]=c}function uj(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-ta(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}function xe(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-ta(c),e=1<<d;e&b|a[d]&
b&&(a[d]|=b);c&=~e}}function Eg(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}function Fg(a,b){switch(a){case "focusin":case "focusout":Va=null;break;case "dragenter":case "dragleave":Wa=null;break;case "mouseover":case "mouseout":Xa=null;break;case "pointerover":case "pointerout":jc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":kc.delete(b.pointerId)}}function lc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,
nativeEvent:f,targetContainers:[e]},null!==b&&(b=ec(b),null!==b&&Gg(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}function vj(a,b,c,d,e){switch(b){case "focusin":return Va=lc(Va,a,b,c,d,e),!0;case "dragenter":return Wa=lc(Wa,a,b,c,d,e),!0;case "mouseover":return Xa=lc(Xa,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;jc.set(f,lc(jc.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,kc.set(f,lc(kc.get(f)||null,a,b,
c,d,e)),!0}return!1}function Hg(a){var b=ob(a.target);if(null!==b){var c=nb(b);if(null!==c)if(b=c.tag,13===b){if(b=zg(c),null!==b){a.blockedOn=b;wj(a.priority,function(){xj(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function Xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=ye(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;
var d=new c.constructor(c.type,c);ze=d;c.target.dispatchEvent(d);ze=null}else return b=ec(c),null!==b&&Gg(b),a.blockedOn=c,!1;b.shift()}return!0}function Ig(a,b,c){Xc(a)&&c.delete(b)}function yj(){Ae=!1;null!==Va&&Xc(Va)&&(Va=null);null!==Wa&&Xc(Wa)&&(Wa=null);null!==Xa&&Xc(Xa)&&(Xa=null);jc.forEach(Ig);kc.forEach(Ig)}function mc(a,b){a.blockedOn===b&&(a.blockedOn=null,Ae||(Ae=!0,Jg(Kg,yj)))}function nc(a){if(0<Yc.length){mc(Yc[0],a);for(var b=1;b<Yc.length;b++){var c=Yc[b];c.blockedOn===a&&(c.blockedOn=
null)}}null!==Va&&mc(Va,a);null!==Wa&&mc(Wa,a);null!==Xa&&mc(Xa,a);b=function(b){return mc(b,a)};jc.forEach(b);kc.forEach(b);for(b=0;b<Ya.length;b++)c=Ya[b],c.blockedOn===a&&(c.blockedOn=null);for(;0<Ya.length&&(b=Ya[0],null===b.blockedOn);)Hg(b),null===b.blockedOn&&Ya.shift()}function zj(a,b,c,d){var e=z,f=Gb.transition;Gb.transition=null;try{z=1,Be(a,b,c,d)}finally{z=e,Gb.transition=f}}function Aj(a,b,c,d){var e=z,f=Gb.transition;Gb.transition=null;try{z=4,Be(a,b,c,d)}finally{z=e,Gb.transition=
f}}function Be(a,b,c,d){if(Zc){var e=ye(a,b,c,d);if(null===e)Ce(a,b,d,$c,c),Fg(a,d);else if(vj(e,a,b,c,d))d.stopPropagation();else if(Fg(a,d),b&4&&-1<Bj.indexOf(a)){for(;null!==e;){var f=ec(e);null!==f&&Cj(f);f=ye(a,b,c,d);null===f&&Ce(a,b,d,$c,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else Ce(a,b,d,null,c)}}function ye(a,b,c,d){$c=null;a=re(d);a=ob(a);if(null!==a)if(b=nb(a),null===b)a=null;else if(c=b.tag,13===c){a=zg(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===
b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);$c=a;return null}function Lg(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;
case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;case "message":switch(Dj()){case De:return 1;case Mg:return 4;case ad:case Ej:return 16;case Ng:return 536870912;default:return 16}default:return 16}}function Og(){if(bd)return bd;
var a,b=Ee,c=b.length,d,e="value"in Za?Za.value:Za.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return bd=e.slice(a,1<d?1-d:void 0)}function cd(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function dd(){return!0}function Pg(){return!1}function ka(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;
for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?dd:Pg;this.isPropagationStopped=Pg;return this}E(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=dd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():
"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=dd)},persist:function(){},isPersistent:dd});return b}function Fj(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Gj[a])?!!b[a]:!1}function Fe(a){return Fj}function Qg(a,b){switch(a){case "keyup":return-1!==Hj.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function Rg(a){a=a.detail;return"object"===typeof a&&
"data"in a?a.data:null}function Ij(a,b){switch(a){case "compositionend":return Rg(b);case "keypress":if(32!==b.which)return null;Sg=!0;return Tg;case "textInput":return a=b.data,a===Tg&&Sg?null:a;default:return null}}function Jj(a,b){if(Hb)return"compositionend"===a||!Ge&&Qg(a,b)?(a=Og(),bd=Ee=Za=null,Hb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;
case "compositionend":return Ug&&"ko"!==b.locale?null:b.data;default:return null}}function Vg(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!Kj[a.type]:"textarea"===b?!0:!1}function Lj(a){if(!Ia)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function Wg(a,b,c,d){ug(d);b=ed(b,"onChange");0<b.length&&(c=new He("onChange","change",null,c,d),a.push({event:c,listeners:b}))}function Mj(a){Xg(a,
0)}function fd(a){var b=Ib(a);if(jg(b))return a}function Nj(a,b){if("change"===a)return b}function Yg(){oc&&(oc.detachEvent("onpropertychange",Zg),pc=oc=null)}function Zg(a){if("value"===a.propertyName&&fd(pc)){var b=[];Wg(b,pc,a,re(a));wg(Mj,b)}}function Oj(a,b,c){"focusin"===a?(Yg(),oc=b,pc=c,oc.attachEvent("onpropertychange",Zg)):"focusout"===a&&Yg()}function Pj(a,b){if("selectionchange"===a||"keyup"===a||"keydown"===a)return fd(pc)}function Qj(a,b){if("click"===a)return fd(b)}function Rj(a,b){if("input"===
a||"change"===a)return fd(b)}function Sj(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function qc(a,b){if(ua(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!Zd.call(b,e)||!ua(a[e],b[e]))return!1}return!0}function $g(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function ah(a,b){var c=$g(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;
if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=$g(c)}}function bh(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?bh(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function ch(){for(var a=window,b=Qc();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;
b=Qc(a.document)}return b}function Ie(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}function Tj(a){var b=ch(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&bh(c.ownerDocument.documentElement,c)){if(null!==d&&Ie(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);
else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=ah(c,f);var g=ah(c,d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),
a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}function dh(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Je||null==Jb||Jb!==Qc(d)||(d=Jb,"selectionStart"in d&&Ie(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d=
{anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),rc&&qc(rc,d)||(rc=d,d=ed(Ke,"onSelect"),0<d.length&&(b=new He("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=Jb)))}function gd(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}function hd(a){if(Le[a])return Le[a];if(!Kb[a])return a;var b=Kb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in eh)return Le[a]=b[c];return a}function $a(a,
b){fh.set(a,b);mb(b,[a])}function gh(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;mj(d,b,void 0,a);a.currentTarget=null}function Xg(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,n=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;gh(e,h,n);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;n=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;
gh(e,h,n);f=k}}}if(Tc)throw a=ue,Tc=!1,ue=null,a;}function B(a,b){var c=b[Me];void 0===c&&(c=b[Me]=new Set);var d=a+"__bubble";c.has(d)||(hh(b,a,2,!1),c.add(d))}function Ne(a,b,c){var d=0;b&&(d|=4);hh(c,a,d,b)}function sc(a){if(!a[id]){a[id]=!0;cg.forEach(function(b){"selectionchange"!==b&&(Uj.has(b)||Ne(b,!1,a),Ne(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[id]||(b[id]=!0,Ne("selectionchange",!1,b))}}function hh(a,b,c,d,e){switch(Lg(b)){case 1:e=zj;break;case 4:e=Aj;break;default:e=
Be}c=e.bind(null,b,c,a);e=void 0;!Oe||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}function Ce(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;
if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=ob(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}wg(function(){var d=f,e=re(c),g=[];a:{var h=fh.get(a);if(void 0!==h){var k=He,m=a;switch(a){case "keypress":if(0===cd(c))break a;case "keydown":case "keyup":k=Vj;break;case "focusin":m="focus";k=Pe;break;case "focusout":m="blur";k=Pe;break;case "beforeblur":case "afterblur":k=Pe;break;
case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=ih;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=Wj;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=Xj;break;case jh:case kh:case lh:k=Yj;break;case mh:k=Zj;break;case "scroll":k=ak;break;case "wheel":k=bk;break;case "copy":case "cut":case "paste":k=
ck;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=nh}var l=0!==(b&4),p=!l&&"scroll"===a,w=l?null!==h?h+"Capture":null:h;l=[];for(var A=d,t;null!==A;){t=A;var M=t.stateNode;5===t.tag&&null!==M&&(t=M,null!==w&&(M=fc(A,w),null!=M&&l.push(tc(A,M,t))));if(p)break;A=A.return}0<l.length&&(h=new k(h,m,null,c,e),g.push({event:h,listeners:l}))}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===
a;k="mouseout"===a||"pointerout"===a;if(h&&c!==ze&&(m=c.relatedTarget||c.fromElement)&&(ob(m)||m[Ja]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(m=c.relatedTarget||c.toElement,k=d,m=m?ob(m):null,null!==m&&(p=nb(m),m!==p||5!==m.tag&&6!==m.tag))m=null}else k=null,m=d;if(k!==m){l=ih;M="onMouseLeave";w="onMouseEnter";A="mouse";if("pointerout"===a||"pointerover"===a)l=nh,M="onPointerLeave",w="onPointerEnter",A="pointer";p=null==k?h:Ib(k);t=null==
m?h:Ib(m);h=new l(M,A+"leave",k,c,e);h.target=p;h.relatedTarget=t;M=null;ob(e)===d&&(l=new l(w,A+"enter",m,c,e),l.target=t,l.relatedTarget=p,M=l);p=M;if(k&&m)b:{l=k;w=m;A=0;for(t=l;t;t=Lb(t))A++;t=0;for(M=w;M;M=Lb(M))t++;for(;0<A-t;)l=Lb(l),A--;for(;0<t-A;)w=Lb(w),t--;for(;A--;){if(l===w||null!==w&&l===w.alternate)break b;l=Lb(l);w=Lb(w)}l=null}else l=null;null!==k&&oh(g,h,k,l,!1);null!==m&&null!==p&&oh(g,p,m,l,!0)}}}a:{h=d?Ib(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===
k&&"file"===h.type)var ma=Nj;else if(Vg(h))if(ph)ma=Rj;else{ma=Pj;var va=Oj}else(k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(ma=Qj);if(ma&&(ma=ma(a,d))){Wg(g,ma,c,e);break a}va&&va(a,h,d);"focusout"===a&&(va=h._wrapperState)&&va.controlled&&"number"===h.type&&me(h,"number",h.value)}va=d?Ib(d):window;switch(a){case "focusin":if(Vg(va)||"true"===va.contentEditable)Jb=va,Ke=d,rc=null;break;case "focusout":rc=Ke=Jb=null;break;case "mousedown":Je=!0;break;case "contextmenu":case "mouseup":case "dragend":Je=
!1;dh(g,c,e);break;case "selectionchange":if(dk)break;case "keydown":case "keyup":dh(g,c,e)}var ab;if(Ge)b:{switch(a){case "compositionstart":var da="onCompositionStart";break b;case "compositionend":da="onCompositionEnd";break b;case "compositionupdate":da="onCompositionUpdate";break b}da=void 0}else Hb?Qg(a,c)&&(da="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(da="onCompositionStart");da&&(Ug&&"ko"!==c.locale&&(Hb||"onCompositionStart"!==da?"onCompositionEnd"===da&&Hb&&(ab=Og()):(Za=e,Ee=
"value"in Za?Za.value:Za.textContent,Hb=!0)),va=ed(d,da),0<va.length&&(da=new qh(da,a,null,c,e),g.push({event:da,listeners:va}),ab?da.data=ab:(ab=Rg(c),null!==ab&&(da.data=ab))));if(ab=ek?Ij(a,c):Jj(a,c))d=ed(d,"onBeforeInput"),0<d.length&&(e=new fk("onBeforeInput","beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=ab)}Xg(g,b)})}function tc(a,b,c){return{instance:a,listener:b,currentTarget:c}}function ed(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==
f&&(e=f,f=fc(a,c),null!=f&&d.unshift(tc(a,f,e)),f=fc(a,b),null!=f&&d.push(tc(a,f,e)));a=a.return}return d}function Lb(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}function oh(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,n=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==n&&(h=n,e?(k=fc(c,f),null!=k&&g.unshift(tc(c,k,h))):e||(k=fc(c,f),null!=k&&g.push(tc(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}function rh(a){return("string"===
typeof a?a:""+a).replace(gk,"\n").replace(hk,"")}function jd(a,b,c,d){b=rh(b);if(rh(a)!==b&&c)throw Error(m(425));}function kd(){}function Qe(a,b){return"textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}function ik(a){setTimeout(function(){throw a;})}function Re(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=
e.data,"/$"===c){if(0===d){a.removeChild(e);nc(b);return}d--}else"$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e}while(c);nc(b)}function Ka(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}function sh(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--}else"/$"===c&&b++}a=a.previousSibling}return null}function ob(a){var b=a[Da];
if(b)return b;for(var c=a.parentNode;c;){if(b=c[Ja]||c[Da]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=sh(a);null!==a;){if(c=a[Da])return c;a=sh(a)}return b}a=c;c=a.parentNode}return null}function ec(a){a=a[Da]||a[Ja];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Ib(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(m(33));}function Rc(a){return a[uc]||null}function bb(a){return{current:a}}function v(a,b){0>Mb||(a.current=Se[Mb],Se[Mb]=null,Mb--)}
function y(a,b,c){Mb++;Se[Mb]=a.current;a.current=b}function Nb(a,b){var c=a.type.contextTypes;if(!c)return cb;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function ea(a){a=a.childContextTypes;return null!==a&&void 0!==a}function th(a,b,c){if(J.current!==cb)throw Error(m(168));
y(J,b);y(S,c)}function uh(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(m(108,gj(a)||"Unknown",e));return E({},c,d)}function ld(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||cb;pb=J.current;y(J,a);y(S,S.current);return!0}function vh(a,b,c){var d=a.stateNode;if(!d)throw Error(m(169));c?(a=uh(a,b,pb),d.__reactInternalMemoizedMergedChildContext=a,v(S),v(J),y(J,a)):v(S);
y(S,c)}function wh(a){null===La?La=[a]:La.push(a)}function jk(a){md=!0;wh(a)}function db(){if(!Te&&null!==La){Te=!0;var a=0,b=z;try{var c=La;for(z=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}La=null;md=!1}catch(e){throw null!==La&&(La=La.slice(a+1)),xh(De,db),e;}finally{z=b,Te=!1}}return null}function qb(a,b){Ob[Pb++]=nd;Ob[Pb++]=od;od=a;nd=b}function yh(a,b,c){na[oa++]=Ma;na[oa++]=Na;na[oa++]=rb;rb=a;var d=Ma;a=Na;var e=32-ta(d)-1;d&=~(1<<e);c+=1;var f=32-ta(b)+e;if(30<f){var g=e-e%5;
f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;Ma=1<<32-ta(b)+e|c<<e|d;Na=f+a}else Ma=1<<f|c<<e|d,Na=a}function Ue(a){null!==a.return&&(qb(a,1),yh(a,1,0))}function Ve(a){for(;a===od;)od=Ob[--Pb],Ob[Pb]=null,nd=Ob[--Pb],Ob[Pb]=null;for(;a===rb;)rb=na[--oa],na[oa]=null,Na=na[--oa],na[oa]=null,Ma=na[--oa],na[oa]=null}function zh(a,b){var c=pa(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}function Ah(a,b){switch(a.tag){case 5:var c=
a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,la=a,fa=Ka(b.firstChild),!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,la=a,fa=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==rb?{id:Ma,overflow:Na}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=pa(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,la=a,fa=null,!0):!1;default:return!1}}function We(a){return 0!==
(a.mode&1)&&0===(a.flags&128)}function Xe(a){if(D){var b=fa;if(b){var c=b;if(!Ah(a,b)){if(We(a))throw Error(m(418));b=Ka(c.nextSibling);var d=la;b&&Ah(a,b)?zh(d,c):(a.flags=a.flags&-4097|2,D=!1,la=a)}}else{if(We(a))throw Error(m(418));a.flags=a.flags&-4097|2;D=!1;la=a}}}function Bh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;la=a}function pd(a){if(a!==la)return!1;if(!D)return Bh(a),D=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!Qe(a.type,
a.memoizedProps));if(b&&(b=fa)){if(We(a)){for(a=fa;a;)a=Ka(a.nextSibling);throw Error(m(418));}for(;b;)zh(a,b),b=Ka(b.nextSibling)}Bh(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(m(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){fa=Ka(a.nextSibling);break a}b--}else"$"!==c&&"$!"!==c&&"$?"!==c||b++}a=a.nextSibling}fa=null}}else fa=la?Ka(a.stateNode.nextSibling):null;return!0}function Qb(){fa=la=null;D=!1}function Ye(a){null===
wa?wa=[a]:wa.push(a)}function vc(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(m(309));var d=c.stateNode}if(!d)throw Error(m(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if("string"!==typeof a)throw Error(m(284));if(!c._owner)throw Error(m(290,a));}return a}function qd(a,b){a=
Object.prototype.toString.call(b);throw Error(m(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function Ch(a){var b=a._init;return b(a._payload)}function Dh(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=eb(a,b);a.index=
0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=Ze(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===Bb)return l(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ta&&
Ch(f)===b.type))return d=e(b,c.props),d.ref=vc(a,b,c),d.return=a,d;d=rd(c.type,c.key,c.props,null,a.mode,d);d.ref=vc(a,b,c);d.return=a;return d}function n(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=$e(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function l(a,b,c,d,f){if(null===b||7!==b.tag)return b=sb(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function u(a,b,c){if("string"===
typeof b&&""!==b||"number"===typeof b)return b=Ze(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case sd:return c=rd(b.type,b.key,b.props,null,a.mode,c),c.ref=vc(a,null,b),c.return=a,c;case Cb:return b=$e(b,a.mode,c),b.return=a,b;case Ta:var d=b._init;return u(a,d(b._payload),c)}if(cc(b)||ac(b))return b=sb(b,a.mode,c,null),b.return=a,b;qd(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==
e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case sd:return c.key===e?k(a,b,c,d):null;case Cb:return c.key===e?n(a,b,c,d):null;case Ta:return e=c._init,r(a,b,e(c._payload),d)}if(cc(c)||ac(c))return null!==e?null:l(a,b,c,d,null);qd(a,c)}return null}function p(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case sd:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,
e);case Cb:return a=a.get(null===d.key?c:d.key)||null,n(b,a,d,e);case Ta:var f=d._init;return p(a,b,c,f(d._payload),e)}if(cc(d)||ac(d))return a=a.get(c)||null,l(b,a,d,e,null);qd(b,d)}return null}function x(e,g,h,k){for(var n=null,m=null,l=g,t=g=0,q=null;null!==l&&t<h.length;t++){l.index>t?(q=l,l=null):q=l.sibling;var A=r(e,l,h[t],k);if(null===A){null===l&&(l=q);break}a&&l&&null===A.alternate&&b(e,l);g=f(A,g,t);null===m?n=A:m.sibling=A;m=A;l=q}if(t===h.length)return c(e,l),D&&qb(e,t),n;if(null===l){for(;t<
h.length;t++)l=u(e,h[t],k),null!==l&&(g=f(l,g,t),null===m?n=l:m.sibling=l,m=l);D&&qb(e,t);return n}for(l=d(e,l);t<h.length;t++)q=p(l,e,t,h[t],k),null!==q&&(a&&null!==q.alternate&&l.delete(null===q.key?t:q.key),g=f(q,g,t),null===m?n=q:m.sibling=q,m=q);a&&l.forEach(function(a){return b(e,a)});D&&qb(e,t);return n}function I(e,g,h,k){var n=ac(h);if("function"!==typeof n)throw Error(m(150));h=n.call(h);if(null==h)throw Error(m(151));for(var l=n=null,q=g,t=g=0,A=null,w=h.next();null!==q&&!w.done;t++,w=
h.next()){q.index>t?(A=q,q=null):A=q.sibling;var x=r(e,q,w.value,k);if(null===x){null===q&&(q=A);break}a&&q&&null===x.alternate&&b(e,q);g=f(x,g,t);null===l?n=x:l.sibling=x;l=x;q=A}if(w.done)return c(e,q),D&&qb(e,t),n;if(null===q){for(;!w.done;t++,w=h.next())w=u(e,w.value,k),null!==w&&(g=f(w,g,t),null===l?n=w:l.sibling=w,l=w);D&&qb(e,t);return n}for(q=d(e,q);!w.done;t++,w=h.next())w=p(q,e,t,w.value,k),null!==w&&(a&&null!==w.alternate&&q.delete(null===w.key?t:w.key),g=f(w,g,t),null===l?n=w:l.sibling=
w,l=w);a&&q.forEach(function(a){return b(e,a)});D&&qb(e,t);return n}function v(a,d,f,h){"object"===typeof f&&null!==f&&f.type===Bb&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case sd:a:{for(var k=f.key,n=d;null!==n;){if(n.key===k){k=f.type;if(k===Bb){if(7===n.tag){c(a,n.sibling);d=e(n,f.props.children);d.return=a;a=d;break a}}else if(n.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ta&&Ch(k)===n.type){c(a,n.sibling);d=e(n,f.props);d.ref=vc(a,
n,f);d.return=a;a=d;break a}c(a,n);break}else b(a,n);n=n.sibling}f.type===Bb?(d=sb(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=rd(f.type,f.key,f.props,null,a.mode,h),h.ref=vc(a,d,f),h.return=a,a=h)}return g(a);case Cb:a:{for(n=f.key;null!==d;){if(d.key===n)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=$e(f,a.mode,h);d.return=a;
a=d}return g(a);case Ta:return n=f._init,v(a,d,n(f._payload),h)}if(cc(f))return x(a,d,f,h);if(ac(f))return I(a,d,f,h);qd(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Ze(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return v}function af(){bf=Rb=td=null}function cf(a,b){b=ud.current;v(ud);a._currentValue=b}function df(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=
b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}function Sb(a,b){td=a;bf=Rb=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(ha=!0),a.firstContext=null)}function qa(a){var b=a._currentValue;if(bf!==a)if(a={context:a,memoizedValue:b,next:null},null===Rb){if(null===td)throw Error(m(308));Rb=a;td.dependencies={lanes:0,firstContext:a}}else Rb=Rb.next=a;return b}function ef(a){null===tb?tb=[a]:tb.push(a)}function Eh(a,b,c,d){var e=b.interleaved;
null===e?(c.next=c,ef(b)):(c.next=e.next,e.next=c);b.interleaved=c;return Oa(a,d)}function Oa(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}function ff(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Fh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue=
{baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Pa(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}function fb(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(p&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return kk(a,c)}e=d.interleaved;null===e?(b.next=b,ef(d)):(b.next=e.next,e.next=b);d.interleaved=b;return Oa(a,c)}function vd(a,b,c){b=
b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;xe(a,c)}}function Gh(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,
shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=b;c.lastBaseUpdate=b}function wd(a,b,c,d){var e=a.updateQueue;gb=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,n=k.next;k.next=null;null===g?f=n:g.next=n;g=k;var l=a.alternate;null!==l&&(l=l.updateQueue,h=l.lastBaseUpdate,h!==g&&(null===h?l.firstBaseUpdate=n:h.next=n,l.lastBaseUpdate=k))}if(null!==f){var m=e.baseState;g=0;l=
n=k=null;h=f;do{var r=h.lane,p=h.eventTime;if((d&r)===r){null!==l&&(l=l.next={eventTime:p,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,next:null});a:{var x=a,v=h;r=b;p=c;switch(v.tag){case 1:x=v.payload;if("function"===typeof x){m=x.call(p,m,r);break a}m=x;break a;case 3:x.flags=x.flags&-65537|128;case 0:x=v.payload;r="function"===typeof x?x.call(p,m,r):x;if(null===r||void 0===r)break a;m=E({},m,r);break a;case 2:gb=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=
[h]:r.push(h))}else p={eventTime:p,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===l?(n=l=p,k=m):l=l.next=p,g|=r;h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===l&&(k=m);e.baseState=k;e.firstBaseUpdate=n;e.lastBaseUpdate=l;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);ra|=g;a.lanes=g;a.memoizedState=m}}function Hh(a,
b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(m(191,e));e.call(d)}}}function ub(a){if(a===wc)throw Error(m(174));return a}function gf(a,b){y(xc,b);y(yc,a);y(Ea,wc);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:oe(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=oe(b,a)}v(Ea);y(Ea,b)}function Tb(a){v(Ea);v(yc);v(xc)}function Ih(a){ub(xc.current);
var b=ub(Ea.current);var c=oe(b,a.type);b!==c&&(y(yc,a),y(Ea,c))}function hf(a){yc.current===a&&(v(Ea),v(yc))}function xd(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=
b.return;b=b.sibling}return null}function jf(){for(var a=0;a<kf.length;a++)kf[a]._workInProgressVersionPrimary=null;kf.length=0}function V(){throw Error(m(321));}function lf(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!ua(a[c],b[c]))return!1;return!0}function mf(a,b,c,d,e,f){vb=f;C=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;yd.current=null===a||null===a.memoizedState?lk:mk;a=c(d,e);if(zc){f=0;do{zc=!1;Ac=0;if(25<=f)throw Error(m(301));f+=1;N=K=null;b.updateQueue=null;
yd.current=nk;a=c(d,e)}while(zc)}yd.current=zd;b=null!==K&&null!==K.next;vb=0;N=K=C=null;Ad=!1;if(b)throw Error(m(300));return a}function nf(){var a=0!==Ac;Ac=0;return a}function Fa(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===N?C.memoizedState=N=a:N=N.next=a;return N}function sa(){if(null===K){var a=C.alternate;a=null!==a?a.memoizedState:null}else a=K.next;var b=null===N?C.memoizedState:N.next;if(null!==b)N=b,K=a;else{if(null===a)throw Error(m(310));K=a;
a={memoizedState:K.memoizedState,baseState:K.baseState,baseQueue:K.baseQueue,queue:K.queue,next:null};null===N?C.memoizedState=N=a:N=N.next=a}return N}function Bc(a,b){return"function"===typeof b?b(a):b}function of(a,b,c){b=sa();c=b.queue;if(null===c)throw Error(m(311));c.lastRenderedReducer=a;var d=K,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,n=f;do{var l=n.lane;if((vb&
l)===l)null!==k&&(k=k.next={lane:0,action:n.action,hasEagerState:n.hasEagerState,eagerState:n.eagerState,next:null}),d=n.hasEagerState?n.eagerState:a(d,n.action);else{var u={lane:l,action:n.action,hasEagerState:n.hasEagerState,eagerState:n.eagerState,next:null};null===k?(h=k=u,g=d):k=k.next=u;C.lanes|=l;ra|=l}n=n.next}while(null!==n&&n!==f);null===k?g=d:k.next=h;ua(d,b.memoizedState)||(ha=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=
e.lane,C.lanes|=f,ra|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}function pf(a,b,c){b=sa();c=b.queue;if(null===c)throw Error(m(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);ua(f,b.memoizedState)||(ha=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function Jh(a,b,c){}function Kh(a,b,c){c=C;var d=sa(),
e=b(),f=!ua(d.memoizedState,e);f&&(d.memoizedState=e,ha=!0);d=d.queue;qf(Lh.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==N&&N.memoizedState.tag&1){c.flags|=2048;Cc(9,Mh.bind(null,c,d,e,b),void 0,null);if(null===O)throw Error(m(349));0!==(vb&30)||Nh(c,b,e)}return e}function Nh(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=C.updateQueue;null===b?(b={lastEffect:null,stores:null},C.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}function Mh(a,b,c,d){b.value=c;b.getSnapshot=
d;Oh(b)&&Ph(a)}function Lh(a,b,c){return c(function(){Oh(b)&&Ph(a)})}function Oh(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!ua(a,c)}catch(d){return!0}}function Ph(a){var b=Oa(a,1);null!==b&&xa(b,a,1,-1)}function Qh(a){var b=Fa();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Bc,lastRenderedState:a};b.queue=a;a=a.dispatch=ok.bind(null,C,a);return[b.memoizedState,a]}function Cc(a,b,c,d){a={tag:a,create:b,
destroy:c,deps:d,next:null};b=C.updateQueue;null===b?(b={lastEffect:null,stores:null},C.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function Rh(a){return sa().memoizedState}function Bd(a,b,c,d){var e=Fa();C.flags|=a;e.memoizedState=Cc(1|b,c,void 0,void 0===d?null:d)}function Cd(a,b,c,d){var e=sa();d=void 0===d?null:d;var f=void 0;if(null!==K){var g=K.memoizedState;f=g.destroy;if(null!==d&&lf(d,g.deps)){e.memoizedState=
Cc(b,c,f,d);return}}C.flags|=a;e.memoizedState=Cc(1|b,c,f,d)}function Sh(a,b){return Bd(8390656,8,a,b)}function qf(a,b){return Cd(2048,8,a,b)}function Th(a,b){return Cd(4,2,a,b)}function Uh(a,b){return Cd(4,4,a,b)}function Vh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function Wh(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Cd(4,4,Vh.bind(null,b,a),c)}function rf(a,b){}function Xh(a,b){var c=
sa();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&lf(b,d[1]))return d[0];c.memoizedState=[a,b];return a}function Yh(a,b){var c=sa();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&lf(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Zh(a,b,c){if(0===(vb&21))return a.baseState&&(a.baseState=!1,ha=!0),a.memoizedState=c;ua(c,b)||(c=Dg(),C.lanes|=c,ra|=c,a.baseState=!0);return b}function pk(a,b,c){c=z;z=0!==c&&4>c?c:4;a(!0);var d=sf.transition;sf.transition=
{};try{a(!1),b()}finally{z=c,sf.transition=d}}function $h(){return sa().memoizedState}function qk(a,b,c){var d=hb(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(ai(a))bi(b,c);else if(c=Eh(a,b,c,d),null!==c){var e=Z();xa(c,a,d,e);ci(c,b,d)}}function ok(a,b,c){var d=hb(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(ai(a))bi(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,
h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(ua(h,g)){var k=b.interleaved;null===k?(e.next=e,ef(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(n){}finally{}c=Eh(a,b,e,d);null!==c&&(e=Z(),xa(c,a,d,e),ci(c,b,d))}}function ai(a){var b=a.alternate;return a===C||null!==b&&b===C}function bi(a,b){zc=Ad=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function ci(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;xe(a,c)}}function ya(a,b){if(a&&
a.defaultProps){b=E({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function tf(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:E({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}function di(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!qc(c,d)||!qc(e,f):!0}function ei(a,b,c){var d=!1,e=cb;var f=b.contextType;"object"===typeof f&&
null!==f?f=qa(f):(e=ea(b)?pb:J.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Nb(a,e):cb);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Dd;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}function fi(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&
b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Dd.enqueueReplaceState(b,b.state,null)}function uf(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs={};ff(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=qa(f):(f=ea(b)?pb:J.current,e.context=Nb(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(tf(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==
typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Dd.enqueueReplaceState(e,e.state,null),wd(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308)}function Ub(a,b){try{var c="",d=b;do c+=fj(d),d=d.return;while(d);var e=c}catch(f){e="\nError generating stack: "+f.message+
"\n"+f.stack}return{value:a,source:b,stack:e,digest:null}}function vf(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}function wf(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}function gi(a,b,c){c=Pa(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Ed||(Ed=!0,xf=d);wf(a,b)};return c}function hi(a,b,c){c=Pa(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};
c.callback=function(){wf(a,b)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){wf(a,b);"function"!==typeof d&&(null===ib?ib=new Set([this]):ib.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}function ii(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new rk;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=sk.bind(null,a,b,c),b.then(a,a))}function ji(a){do{var b;
if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}function ki(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=Pa(-1,1),b.tag=2,fb(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}function aa(a,b,c,d){b.child=null===a?li(b,null,c,d):Vb(b,a.child,c,d)}function mi(a,b,c,d,e){c=c.render;var f=b.ref;Sb(b,e);d=mf(a,b,c,d,f,
e);c=nf();if(null!==a&&!ha)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Qa(a,b,e);D&&c&&Ue(b);b.flags|=1;aa(a,b,d,e);return b.child}function ni(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!yf(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,oi(a,b,f,d,e);a=rd(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:qc;if(c(g,d)&&a.ref===
b.ref)return Qa(a,b,e)}b.flags|=1;a=eb(f,d);a.ref=b.ref;a.return=b;return b.child=a}function oi(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(qc(f,d)&&a.ref===b.ref)if(ha=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(ha=!0);else return b.lanes=a.lanes,Qa(a,b,e)}return zf(a,b,c,d,e)}function pi(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},y(Ga,ba),ba|=c;
else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,y(Ga,ba),ba|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;y(Ga,ba);ba|=d}else null!==f?(d=f.baseLanes|c,b.memoizedState=null):d=c,y(Ga,ba),ba|=d;aa(a,b,e,c);return b.child}function qi(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function zf(a,
b,c,d,e){var f=ea(c)?pb:J.current;f=Nb(b,f);Sb(b,e);c=mf(a,b,c,d,f,e);d=nf();if(null!==a&&!ha)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Qa(a,b,e);D&&d&&Ue(b);b.flags|=1;aa(a,b,c,e);return b.child}function ri(a,b,c,d,e){if(ea(c)){var f=!0;ld(b)}else f=!1;Sb(b,e);if(null===b.stateNode)Fd(a,b),ei(b,c,d),uf(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,n=c.contextType;"object"===typeof n&&null!==n?n=qa(n):(n=ea(c)?pb:J.current,n=Nb(b,
n));var l=c.getDerivedStateFromProps,m="function"===typeof l||"function"===typeof g.getSnapshotBeforeUpdate;m||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==n)&&fi(b,g,d,n);gb=!1;var r=b.memoizedState;g.state=r;wd(b,d,g,e);k=b.memoizedState;h!==d||r!==k||S.current||gb?("function"===typeof l&&(tf(b,c,l,d),k=b.memoizedState),(h=gb||di(b,c,h,d,r,k,n))?(m||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||
("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=n,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;Fh(a,b);h=b.memoizedProps;n=b.type===b.elementType?h:ya(b.type,h);g.props=
n;m=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=qa(k):(k=ea(c)?pb:J.current,k=Nb(b,k));var p=c.getDerivedStateFromProps;(l="function"===typeof p||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==m||r!==k)&&fi(b,g,d,k);gb=!1;r=b.memoizedState;g.state=r;wd(b,d,g,e);var x=b.memoizedState;h!==m||r!==x||S.current||gb?("function"===typeof p&&(tf(b,c,p,d),x=b.memoizedState),
(n=gb||di(b,c,n,d,r,x,k)||!1)?(l||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,x,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,x,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=
4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=x),g.props=d,g.state=x,g.context=k,d=n):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return Af(a,b,c,d,f,e)}function Af(a,b,c,d,e,f){qi(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&vh(b,c,!1),
Qa(a,b,f);d=b.stateNode;tk.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Vb(b,a.child,null,f),b.child=Vb(b,null,h,f)):aa(a,b,h,f);b.memoizedState=d.state;e&&vh(b,c,!0);return b.child}function si(a){var b=a.stateNode;b.pendingContext?th(a,b.pendingContext,b.pendingContext!==b.context):b.context&&th(a,b.context,!1);gf(a,b.containerInfo)}function ti(a,b,c,d,e){Qb();Ye(e);b.flags|=256;aa(a,b,c,d);return b.child}function Bf(a){return{baseLanes:a,
cachePool:null,transitions:null}}function ui(a,b,c){var d=b.pendingProps,e=F.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;y(F,e&1);if(null===a){Xe(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==
f?(f.childLanes=0,f.pendingProps=g):f=Gd(g,d,0,null),a=sb(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=Bf(c),b.memoizedState=Cf,a):Df(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return uk(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=eb(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=eb(h,f):(f=
sb(f,g,c,null),f.flags|=2);f.return=b;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?Bf(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=Cf;return d}f=a.child;a=f.sibling;d=eb(f,{mode:"visible",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}
function Df(a,b,c){b=Gd({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function Hd(a,b,c,d){null!==d&&Ye(d);Vb(b,a.child,null,c);a=Df(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}function uk(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=vf(Error(m(422))),Hd(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=Gd({mode:"visible",children:d.children},e,0,null);f=sb(f,e,g,null);f.flags|=2;d.return=
b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Vb(b,a.child,null,g);b.child.memoizedState=Bf(g);b.memoizedState=Cf;return f}if(0===(b.mode&1))return Hd(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;if(d)var h=d.dgst;d=h;f=Error(m(419));d=vf(f,d,void 0);return Hd(a,b,g,d)}h=0!==(g&a.childLanes);if(ha||h){d=O;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=
32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;0!==e&&e!==f.retryLane&&(f.retryLane=e,Oa(a,e),xa(d,a,e,-1))}Ef();d=vf(Error(m(421)));return Hd(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=vk.bind(null,a),e._reactRetry=b,null;a=f.treeContext;fa=Ka(e.nextSibling);la=b;D=!0;wa=null;null!==a&&(na[oa++]=Ma,na[oa++]=Na,na[oa++]=rb,Ma=a.id,Na=a.overflow,rb=b);b=Df(b,d.children);b.flags|=4096;return b}function vi(a,b,c){a.lanes|=b;var d=a.alternate;
null!==d&&(d.lanes|=b);df(a.return,b,c)}function Ff(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}function wi(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;aa(a,b,d.children,c);d=F.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&
vi(a,c,b);else if(19===a.tag)vi(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}y(F,d);if(0===(b.mode&1))b.memoizedState=null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===xd(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);Ff(b,!1,e,c,f);break;case "backwards":c=
null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===xd(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}Ff(b,!0,c,null,f);break;case "together":Ff(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}function Fd(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function Qa(a,b,c){null!==a&&(b.dependencies=a.dependencies);ra|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(m(153));if(null!==
b.child){a=b.child;c=eb(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=eb(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}function wk(a,b,c){switch(b.tag){case 3:si(b);Qb();break;case 5:Ih(b);break;case 1:ea(b.type)&&ld(b);break;case 4:gf(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;y(ud,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return y(F,F.current&
1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return ui(a,b,c);y(F,F.current&1);a=Qa(a,b,c);return null!==a?a.sibling:null}y(F,F.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return wi(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);y(F,F.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,pi(a,b,c)}return Qa(a,b,c)}function Dc(a,b){if(!D)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==
b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}function W(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,
d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}function xk(a,b,c){var d=b.pendingProps;Ve(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return W(b),null;case 1:return ea(b.type)&&(v(S),v(J)),W(b),null;case 3:d=b.stateNode;Tb();v(S);v(J);jf();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)pd(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&
256)||(b.flags|=1024,null!==wa&&(Gf(wa),wa=null));xi(a,b);W(b);return null;case 5:hf(b);var e=ub(xc.current);c=b.type;if(null!==a&&null!=b.stateNode)yk(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(m(166));W(b);return null}a=ub(Ea.current);if(pd(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Da]=b;d[uc]=f;a=0!==(b.mode&1);switch(c){case "dialog":B("cancel",d);B("close",d);break;case "iframe":case "object":case "embed":B("load",d);break;
case "video":case "audio":for(e=0;e<Ec.length;e++)B(Ec[e],d);break;case "source":B("error",d);break;case "img":case "image":case "link":B("error",d);B("load",d);break;case "details":B("toggle",d);break;case "input":kg(d,f);B("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!f.multiple};B("invalid",d);break;case "textarea":ng(d,f),B("invalid",d)}pe(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(!0!==f.suppressHydrationWarning&&
jd(d.textContent,h,a),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(!0!==f.suppressHydrationWarning&&jd(d.textContent,h,a),e=["children",""+h]):$b.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&B("scroll",d)}switch(c){case "input":Pc(d);mg(d,f,!0);break;case "textarea":Pc(d);pg(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&(d.onclick=kd)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===
a&&(a=qg(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Da]=b;a[uc]=d;zk(a,b,!1,!1);b.stateNode=a;a:{g=qe(c,d);switch(c){case "dialog":B("cancel",a);B("close",a);e=d;break;case "iframe":case "object":case "embed":B("load",a);e=d;break;
case "video":case "audio":for(e=0;e<Ec.length;e++)B(Ec[e],a);e=d;break;case "source":B("error",a);e=d;break;case "img":case "image":case "link":B("error",a);B("load",a);e=d;break;case "details":B("toggle",a);e=d;break;case "input":kg(a,d);e=ke(a,d);B("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=E({},d,{value:void 0});B("invalid",a);break;case "textarea":ng(a,d);e=ne(a,d);B("invalid",a);break;default:e=d}pe(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=
h[f];"style"===f?sg(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&yi(a,k)):"children"===f?"string"===typeof k?("textarea"!==c||""!==k)&&Fc(a,k):"number"===typeof k&&Fc(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&($b.hasOwnProperty(f)?null!=k&&"onScroll"===f&&B("scroll",a):null!=k&&$d(a,f,k,g))}switch(c){case "input":Pc(a);mg(a,d,!1);break;case "textarea":Pc(a);pg(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Ua(d.value));
break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?Db(a,!!d.multiple,f,!1):null!=d.defaultValue&&Db(a,!!d.multiple,d.defaultValue,!0);break;default:"function"===typeof e.onClick&&(a.onclick=kd)}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}W(b);return null;case 6:if(a&&null!=b.stateNode)Ak(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===
b.stateNode)throw Error(m(166));c=ub(xc.current);ub(Ea.current);if(pd(b)){d=b.stateNode;c=b.memoizedProps;d[Da]=b;if(f=d.nodeValue!==c)if(a=la,null!==a)switch(a.tag){case 3:jd(d.nodeValue,c,0!==(a.mode&1));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&jd(d.nodeValue,c,0!==(a.mode&1))}f&&(b.flags|=4)}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Da]=b,b.stateNode=d}W(b);return null;case 13:v(F);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(D&&
null!==fa&&0!==(b.mode&1)&&0===(b.flags&128)){for(f=fa;f;)f=Ka(f.nextSibling);Qb();b.flags|=98560;f=!1}else if(f=pd(b),null!==d&&null!==d.dehydrated){if(null===a){if(!f)throw Error(m(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(m(317));f[Da]=b}else Qb(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;W(b);f=!1}else null!==wa&&(Gf(wa),wa=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&
d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(F.current&1)?0===L&&(L=3):Ef()));null!==b.updateQueue&&(b.flags|=4);W(b);return null;case 4:return Tb(),xi(a,b),null===a&&sc(b.stateNode.containerInfo),W(b),null;case 10:return cf(b.type._context),W(b),null;case 17:return ea(b.type)&&(v(S),v(J)),W(b),null;case 19:v(F);f=b.memoizedState;if(null===f)return W(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Dc(f,!1);else{if(0!==L||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=
xd(a);if(null!==g){b.flags|=128;Dc(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,g=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,
f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;y(F,F.current&1|2);return b.child}a=a.sibling}null!==f.tail&&P()>Hf&&(b.flags|=128,d=!0,Dc(f,!1),b.lanes=4194304)}else{if(!d)if(a=xd(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dc(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!D)return W(b),null}else 2*P()-f.renderingStartTime>Hf&&1073741824!==c&&(b.flags|=
128,d=!0,Dc(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=b,f.tail=b.sibling,f.renderingStartTime=P(),b.sibling=null,c=F.current,y(F,d?c&1|2:c&1),b;W(b);return null;case 22:case 23:return ba=Ga.current,v(Ga),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(ba&1073741824)&&(W(b),b.subtreeFlags&6&&(b.flags|=8192)):W(b),null;case 24:return null;
case 25:return null}throw Error(m(156,b.tag));}function Bk(a,b,c){Ve(b);switch(b.tag){case 1:return ea(b.type)&&(v(S),v(J)),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Tb(),v(S),v(J),jf(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return hf(b),null;case 13:v(F);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(m(340));Qb()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return v(F),null;case 4:return Tb(),
null;case 10:return cf(b.type._context),null;case 22:case 23:return ba=Ga.current,v(Ga),null;case 24:return null;default:return null}}function Wb(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null)}catch(d){G(a,b,d)}else c.current=null}function If(a,b,c){try{c()}catch(d){G(a,b,d)}}function Ck(a,b){Jf=Zc;a=ch();if(Ie(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();
if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(M){c=null;break a}var g=0,h=-1,k=-1,n=0,q=0,u=a,r=null;b:for(;;){for(var p;;){u!==c||0!==e&&3!==u.nodeType||(h=g+e);u!==f||0!==d&&3!==u.nodeType||(k=g+d);3===u.nodeType&&(g+=u.nodeValue.length);if(null===(p=u.firstChild))break;r=u;u=p}for(;;){if(u===a)break b;r===c&&++n===e&&(h=g);r===f&&++q===d&&(k=g);if(null!==(p=u.nextSibling))break;u=r;r=u.parentNode}u=p}c=-1===h||-1===k?null:
{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Kf={focusedElem:a,selectionRange:c};Zc=!1;for(l=b;null!==l;)if(b=l,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,l=a;else for(;null!==l;){b=l;try{var x=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;case 1:if(null!==x){var v=x.memoizedProps,z=x.memoizedState,w=b.stateNode,A=w.getSnapshotBeforeUpdate(b.elementType===b.type?v:ya(b.type,v),z);w.__reactInternalSnapshotBeforeUpdate=A}break;case 3:var t=
b.stateNode.containerInfo;1===t.nodeType?t.textContent="":9===t.nodeType&&t.documentElement&&t.removeChild(t.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(m(163));}}catch(M){G(b,b.return,M)}a=b.sibling;if(null!==a){a.return=b.return;l=a;break}l=b.return}x=zi;zi=!1;return x}function Gc(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&If(b,c,f)}e=e.next}while(e!==d)}}
function Id(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Lf(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}"function"===typeof b?b(a):b.current=a}}function Ai(a){var b=a.alternate;null!==b&&(a.alternate=null,Ai(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Da],delete b[uc],delete b[Me],delete b[Dk],
delete b[Ek]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Bi(a){return 5===a.tag||3===a.tag||4===a.tag}function Ci(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Bi(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&
2))return a.stateNode}}function Mf(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=kd));else if(4!==d&&(a=a.child,null!==a))for(Mf(a,b,c),a=a.sibling;null!==a;)Mf(a,b,c),a=a.sibling}function Nf(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);
else if(4!==d&&(a=a.child,null!==a))for(Nf(a,b,c),a=a.sibling;null!==a;)Nf(a,b,c),a=a.sibling}function jb(a,b,c){for(c=c.child;null!==c;)Di(a,b,c),c=c.sibling}function Di(a,b,c){if(Ca&&"function"===typeof Ca.onCommitFiberUnmount)try{Ca.onCommitFiberUnmount(Uc,c)}catch(h){}switch(c.tag){case 5:X||Wb(c,b);case 6:var d=T,e=za;T=null;jb(a,b,c);T=d;za=e;null!==T&&(za?(a=T,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):T.removeChild(c.stateNode));break;case 18:null!==T&&(za?
(a=T,c=c.stateNode,8===a.nodeType?Re(a.parentNode,c):1===a.nodeType&&Re(a,c),nc(a)):Re(T,c.stateNode));break;case 4:d=T;e=za;T=c.stateNode.containerInfo;za=!0;jb(a,b,c);T=d;za=e;break;case 0:case 11:case 14:case 15:if(!X&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?If(c,b,g):0!==(f&4)&&If(c,b,g));e=e.next}while(e!==d)}jb(a,b,c);break;case 1:if(!X&&(Wb(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=
c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){G(c,b,h)}jb(a,b,c);break;case 21:jb(a,b,c);break;case 22:c.mode&1?(X=(d=X)||null!==c.memoizedState,jb(a,b,c),X=d):jb(a,b,c);break;default:jb(a,b,c)}}function Ei(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Fk);b.forEach(function(b){var d=Gk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}function Aa(a,b,c){c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=
c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:T=h.stateNode;za=!1;break a;case 3:T=h.stateNode.containerInfo;za=!0;break a;case 4:T=h.stateNode.containerInfo;za=!0;break a}h=h.return}if(null===T)throw Error(m(160));Di(f,g,e);T=null;za=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(n){G(e,b,n)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)Fi(b,a),b=b.sibling}function Fi(a,b,c){var d=a.alternate;c=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:Aa(b,a);
Ha(a);if(c&4){try{Gc(3,a,a.return),Id(3,a)}catch(I){G(a,a.return,I)}try{Gc(5,a,a.return)}catch(I){G(a,a.return,I)}}break;case 1:Aa(b,a);Ha(a);c&512&&null!==d&&Wb(d,d.return);break;case 5:Aa(b,a);Ha(a);c&512&&null!==d&&Wb(d,d.return);if(a.flags&32){var e=a.stateNode;try{Fc(e,"")}catch(I){G(a,a.return,I)}}if(c&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==d?d.memoizedProps:f,h=a.type,k=a.updateQueue;a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&lg(e,f);
qe(h,g);var n=qe(h,f);for(g=0;g<k.length;g+=2){var q=k[g],u=k[g+1];"style"===q?sg(e,u):"dangerouslySetInnerHTML"===q?yi(e,u):"children"===q?Fc(e,u):$d(e,q,u,n)}switch(h){case "input":le(e,f);break;case "textarea":og(e,f);break;case "select":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var p=f.value;null!=p?Db(e,!!f.multiple,p,!1):r!==!!f.multiple&&(null!=f.defaultValue?Db(e,!!f.multiple,f.defaultValue,!0):Db(e,!!f.multiple,f.multiple?[]:"",!1))}e[uc]=f}catch(I){G(a,a.return,
I)}}break;case 6:Aa(b,a);Ha(a);if(c&4){if(null===a.stateNode)throw Error(m(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(I){G(a,a.return,I)}}break;case 3:Aa(b,a);Ha(a);if(c&4&&null!==d&&d.memoizedState.isDehydrated)try{nc(b.containerInfo)}catch(I){G(a,a.return,I)}break;case 4:Aa(b,a);Ha(a);break;case 13:Aa(b,a);Ha(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||null!==e.alternate&&null!==e.alternate.memoizedState||(Of=P()));c&4&&Ei(a);break;case 22:q=
null!==d&&null!==d.memoizedState;a.mode&1?(X=(n=X)||q,Aa(b,a),X=n):Aa(b,a);Ha(a);if(c&8192){n=null!==a.memoizedState;if((a.stateNode.isHidden=n)&&!q&&0!==(a.mode&1))for(l=a,q=a.child;null!==q;){for(u=l=q;null!==l;){r=l;p=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Gc(4,r,r.return);break;case 1:Wb(r,r.return);var x=r.stateNode;if("function"===typeof x.componentWillUnmount){c=r;b=r.return;try{d=c,x.props=d.memoizedProps,x.state=d.memoizedState,x.componentWillUnmount()}catch(I){G(c,b,I)}}break;
case 5:Wb(r,r.return);break;case 22:if(null!==r.memoizedState){Gi(u);continue}}null!==p?(p.return=r,l=p):Gi(u)}q=q.sibling}a:for(q=null,u=a;;){if(5===u.tag){if(null===q){q=u;try{e=u.stateNode,n?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=u.stateNode,k=u.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=rg("display",g))}catch(I){G(a,a.return,I)}}}else if(6===u.tag){if(null===q)try{u.stateNode.nodeValue=
n?"":u.memoizedProps}catch(I){G(a,a.return,I)}}else if((22!==u.tag&&23!==u.tag||null===u.memoizedState||u===a)&&null!==u.child){u.child.return=u;u=u.child;continue}if(u===a)break a;for(;null===u.sibling;){if(null===u.return||u.return===a)break a;q===u&&(q=null);u=u.return}q===u&&(q=null);u.sibling.return=u.return;u=u.sibling}}break;case 19:Aa(b,a);Ha(a);c&4&&Ei(a);break;case 21:break;default:Aa(b,a),Ha(a)}}function Ha(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Bi(c)){var d=c;
break a}c=c.return}throw Error(m(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(Fc(e,""),d.flags&=-33);var f=Ci(a);Nf(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Ci(a);Mf(a,h,g);break;default:throw Error(m(161));}}catch(k){G(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function Hk(a,b,c){l=a;Hi(a,b,c)}function Hi(a,b,c){for(var d=0!==(a.mode&1);null!==l;){var e=l,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Jd;if(!g){var h=e.alternate,k=null!==h&&null!==
h.memoizedState||X;h=Jd;var n=X;Jd=g;if((X=k)&&!n)for(l=e;null!==l;)g=l,k=g.child,22===g.tag&&null!==g.memoizedState?Ii(e):null!==k?(k.return=g,l=k):Ii(e);for(;null!==f;)l=f,Hi(f,b,c),f=f.sibling;l=e;Jd=h;X=n}Ji(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,l=f):Ji(a,b,c)}}function Ji(a,b,c){for(;null!==l;){b=l;if(0!==(b.flags&8772)){c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:X||Id(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!X)if(null===c)d.componentDidMount();
else{var e=b.elementType===b.type?c.memoizedProps:ya(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}var f=b.updateQueue;null!==f&&Hh(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=b.child.stateNode;break;case 1:c=b.child.stateNode}Hh(b,g,c)}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":k.autoFocus&&
c.focus();break;case "img":k.src&&(c.src=k.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var n=b.alternate;if(null!==n){var q=n.memoizedState;if(null!==q){var p=q.dehydrated;null!==p&&nc(p)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(m(163));}X||b.flags&512&&Lf(b)}catch(r){G(b,b.return,r)}}if(b===a){l=null;break}c=b.sibling;if(null!==c){c.return=b.return;l=c;break}l=b.return}}function Gi(a){for(;null!==l;){var b=l;if(b===
a){l=null;break}var c=b.sibling;if(null!==c){c.return=b.return;l=c;break}l=b.return}}function Ii(a){for(;null!==l;){var b=l;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Id(4,b)}catch(k){G(b,c,k)}break;case 1:var d=b.stateNode;if("function"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount()}catch(k){G(b,e,k)}}var f=b.return;try{Lf(b)}catch(k){G(b,f,k)}break;case 5:var g=b.return;try{Lf(b)}catch(k){G(b,g,k)}}}catch(k){G(b,b.return,k)}if(b===a){l=null;break}var h=b.sibling;
if(null!==h){h.return=b.return;l=h;break}l=b.return}}function Hc(){Hf=P()+500}function Z(){return 0!==(p&6)?P():-1!==Kd?Kd:Kd=P()}function hb(a){if(0===(a.mode&1))return 1;if(0!==(p&2)&&0!==U)return U&-U;if(null!==Ik.transition)return 0===Ld&&(Ld=Dg()),Ld;a=z;if(0!==a)return a;a=window.event;a=void 0===a?16:Lg(a.type);return a}function xa(a,b,c,d){if(50<Ic)throw Ic=0,Pf=null,Error(m(185));ic(a,c,d);if(0===(p&2)||a!==O)a===O&&(0===(p&2)&&(Md|=c),4===L&&kb(a,U)),ia(a,d),1===c&&0===p&&0===(b.mode&1)&&
(Hc(),md&&db())}function ia(a,b){var c=a.callbackNode;tj(a,b);var d=Vc(a,a===O?U:0);if(0===d)null!==c&&Ki(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&Ki(c);if(1===b)0===a.tag?jk(Li.bind(null,a)):wh(Li.bind(null,a)),Jk(function(){0===(p&6)&&db()}),c=null;else{switch(Eg(d)){case 1:c=De;break;case 4:c=Mg;break;case 16:c=ad;break;case 536870912:c=Ng;break;default:c=ad}c=Mi(c,Ni.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}function Ni(a,b){Kd=-1;
Ld=0;if(0!==(p&6))throw Error(m(327));var c=a.callbackNode;if(Xb()&&a.callbackNode!==c)return null;var d=Vc(a,a===O?U:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Nd(a,d);else{b=d;var e=p;p|=2;var f=Oi();if(O!==a||U!==b)Ra=null,Hc(),wb(a,b);do try{Kk();break}catch(h){Pi(a,h)}while(1);af();Od.current=f;p=e;null!==H?b=0:(O=null,U=0,b=L)}if(0!==b){2===b&&(e=ve(a),0!==e&&(d=e,b=Qf(a,e)));if(1===b)throw c=Jc,wb(a,0),kb(a,d),ia(a,P()),c;if(6===b)kb(a,d);else{e=a.current.alternate;
if(0===(d&30)&&!Lk(e)&&(b=Nd(a,d),2===b&&(f=ve(a),0!==f&&(d=f,b=Qf(a,f))),1===b))throw c=Jc,wb(a,0),kb(a,d),ia(a,P()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(m(345));case 2:xb(a,ja,Ra);break;case 3:kb(a,d);if((d&130023424)===d&&(b=Of+500-P(),10<b)){if(0!==Vc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){Z();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Rf(xb.bind(null,a,ja,Ra),b);break}xb(a,ja,Ra);break;case 4:kb(a,d);if((d&4194240)===d)break;b=a.eventTimes;
for(e=-1;0<d;){var g=31-ta(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f}d=e;d=P()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*Mk(d/1960))-d;if(10<d){a.timeoutHandle=Rf(xb.bind(null,a,ja,Ra),d);break}xb(a,ja,Ra);break;case 5:xb(a,ja,Ra);break;default:throw Error(m(329));}}}ia(a,P());return a.callbackNode===c?Ni.bind(null,a):null}function Qf(a,b){var c=Kc;a.current.memoizedState.isDehydrated&&(wb(a,b).flags|=256);a=Nd(a,b);2!==a&&(b=ja,ja=c,null!==b&&Gf(b));return a}function Gf(a){null===
ja?ja=a:ja.push.apply(ja,a)}function Lk(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!ua(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}function kb(a,b){b&=~Sf;b&=~Md;a.suspendedLanes|=b;a.pingedLanes&=
~b;for(a=a.expirationTimes;0<b;){var c=31-ta(b),d=1<<c;a[c]=-1;b&=~d}}function Li(a){if(0!==(p&6))throw Error(m(327));Xb();var b=Vc(a,0);if(0===(b&1))return ia(a,P()),null;var c=Nd(a,b);if(0!==a.tag&&2===c){var d=ve(a);0!==d&&(b=d,c=Qf(a,d))}if(1===c)throw c=Jc,wb(a,0),kb(a,b),ia(a,P()),c;if(6===c)throw Error(m(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;xb(a,ja,Ra);ia(a,P());return null}function Tf(a,b){var c=p;p|=1;try{return a(b)}finally{p=c,0===p&&(Hc(),md&&db())}}function yb(a){null!==
lb&&0===lb.tag&&0===(p&6)&&Xb();var b=p;p|=1;var c=ca.transition,d=z;try{if(ca.transition=null,z=1,a)return a()}finally{z=d,ca.transition=c,p=b,0===(p&6)&&db()}}function wb(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Nk(c));if(null!==H)for(c=H.return;null!==c;){var d=c;Ve(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&(v(S),v(J));break;case 3:Tb();v(S);v(J);jf();break;case 5:hf(d);break;case 4:Tb();break;case 13:v(F);break;
case 19:v(F);break;case 10:cf(d.type._context);break;case 22:case 23:ba=Ga.current,v(Ga)}c=c.return}O=a;H=a=eb(a.current,null);U=ba=b;L=0;Jc=null;Sf=Md=ra=0;ja=Kc=null;if(null!==tb){for(b=0;b<tb.length;b++)if(c=tb[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}tb=null}return a}function Pi(a,b){do{var c=H;try{af();yd.current=zd;if(Ad){for(var d=C.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Ad=
!1}vb=0;N=K=C=null;zc=!1;Ac=0;Uf.current=null;if(null===c||null===c.return){L=1;Jc=b;H=null;break}a:{var f=a,g=c.return,h=c,k=b;b=U;h.flags|=32768;if(null!==k&&"object"===typeof k&&"function"===typeof k.then){var n=k,l=h,p=l.tag;if(0===(l.mode&1)&&(0===p||11===p||15===p)){var r=l.alternate;r?(l.updateQueue=r.updateQueue,l.memoizedState=r.memoizedState,l.lanes=r.lanes):(l.updateQueue=null,l.memoizedState=null)}var v=ji(g);if(null!==v){v.flags&=-257;ki(v,g,h,f,b);v.mode&1&&ii(f,n,b);b=v;k=n;var x=b.updateQueue;
if(null===x){var z=new Set;z.add(k);b.updateQueue=z}else x.add(k);break a}else{if(0===(b&1)){ii(f,n,b);Ef();break a}k=Error(m(426))}}else if(D&&h.mode&1){var y=ji(g);if(null!==y){0===(y.flags&65536)&&(y.flags|=256);ki(y,g,h,f,b);Ye(Ub(k,h));break a}}f=k=Ub(k,h);4!==L&&(L=2);null===Kc?Kc=[f]:Kc.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;b&=-b;f.lanes|=b;var w=gi(f,k,b);Gh(f,w);break a;case 1:h=k;var A=f.type,t=f.stateNode;if(0===(f.flags&128)&&("function"===typeof A.getDerivedStateFromError||
null!==t&&"function"===typeof t.componentDidCatch&&(null===ib||!ib.has(t)))){f.flags|=65536;b&=-b;f.lanes|=b;var B=hi(f,h,b);Gh(f,B);break a}}f=f.return}while(null!==f)}Qi(c)}catch(ma){b=ma;H===c&&null!==c&&(H=c=c.return);continue}break}while(1)}function Oi(){var a=Od.current;Od.current=zd;return null===a?zd:a}function Ef(){if(0===L||3===L||2===L)L=4;null===O||0===(ra&268435455)&&0===(Md&268435455)||kb(O,U)}function Nd(a,b){var c=p;p|=2;var d=Oi();if(O!==a||U!==b)Ra=null,wb(a,b);do try{Ok();break}catch(e){Pi(a,
e)}while(1);af();p=c;Od.current=d;if(null!==H)throw Error(m(261));O=null;U=0;return L}function Ok(){for(;null!==H;)Ri(H)}function Kk(){for(;null!==H&&!Pk();)Ri(H)}function Ri(a){var b=Qk(a.alternate,a,ba);a.memoizedProps=a.pendingProps;null===b?Qi(a):H=b;Uf.current=null}function Qi(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=xk(c,b,ba),null!==c){H=c;return}}else{c=Bk(c,b);if(null!==c){c.flags&=32767;H=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;
else{L=6;H=null;return}}b=b.sibling;if(null!==b){H=b;return}H=b=a}while(null!==b);0===L&&(L=5)}function xb(a,b,c){var d=z,e=ca.transition;try{ca.transition=null,z=1,Rk(a,b,c,d)}finally{ca.transition=e,z=d}return null}function Rk(a,b,c,d){do Xb();while(null!==lb);if(0!==(p&6))throw Error(m(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(m(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;
uj(a,f);a===O&&(H=O=null,U=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||Pd||(Pd=!0,Mi(ad,function(){Xb();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=ca.transition;ca.transition=null;var g=z;z=1;var h=p;p|=4;Uf.current=null;Ck(a,c);Fi(c,a);Tj(Kf);Zc=!!Jf;Kf=Jf=null;a.current=c;Hk(c,a,e);Sk();p=h;z=g;ca.transition=f}else a.current=c;Pd&&(Pd=!1,lb=a,Qd=e);f=a.pendingLanes;0===f&&(ib=null);oj(c.stateNode,d);ia(a,P());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=
b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Ed)throw Ed=!1,a=xf,xf=null,a;0!==(Qd&1)&&0!==a.tag&&Xb();f=a.pendingLanes;0!==(f&1)?a===Pf?Ic++:(Ic=0,Pf=a):Ic=0;db();return null}function Xb(){if(null!==lb){var a=Eg(Qd),b=ca.transition,c=z;try{ca.transition=null;z=16>a?16:a;if(null===lb)var d=!1;else{a=lb;lb=null;Qd=0;if(0!==(p&6))throw Error(m(331));var e=p;p|=4;for(l=a.current;null!==l;){var f=l,g=f.child;if(0!==(l.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var n=
h[k];for(l=n;null!==l;){var q=l;switch(q.tag){case 0:case 11:case 15:Gc(8,q,f)}var u=q.child;if(null!==u)u.return=q,l=u;else for(;null!==l;){q=l;var r=q.sibling,v=q.return;Ai(q);if(q===n){l=null;break}if(null!==r){r.return=v;l=r;break}l=v}}}var x=f.alternate;if(null!==x){var y=x.child;if(null!==y){x.child=null;do{var C=y.sibling;y.sibling=null;y=C}while(null!==y)}}l=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,l=g;else b:for(;null!==l;){f=l;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Gc(9,
f,f.return)}var w=f.sibling;if(null!==w){w.return=f.return;l=w;break b}l=f.return}}var A=a.current;for(l=A;null!==l;){g=l;var t=g.child;if(0!==(g.subtreeFlags&2064)&&null!==t)t.return=g,l=t;else b:for(g=A;null!==l;){h=l;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Id(9,h)}}catch(ma){G(h,h.return,ma)}if(h===g){l=null;break b}var B=h.sibling;if(null!==B){B.return=h.return;l=B;break b}l=h.return}}p=e;db();if(Ca&&"function"===typeof Ca.onPostCommitFiberRoot)try{Ca.onPostCommitFiberRoot(Uc,
a)}catch(ma){}d=!0}return d}finally{z=c,ca.transition=b}}return!1}function Si(a,b,c){b=Ub(c,b);b=gi(a,b,1);a=fb(a,b,1);b=Z();null!==a&&(ic(a,1,b),ia(a,b))}function G(a,b,c){if(3===a.tag)Si(a,a,c);else for(;null!==b;){if(3===b.tag){Si(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===ib||!ib.has(d))){a=Ub(c,a);a=hi(b,a,1);b=fb(b,a,1);a=Z();null!==b&&(ic(b,1,a),ia(b,a));break}}b=b.return}}function sk(a,
b,c){var d=a.pingCache;null!==d&&d.delete(b);b=Z();a.pingedLanes|=a.suspendedLanes&c;O===a&&(U&c)===c&&(4===L||3===L&&(U&130023424)===U&&500>P()-Of?wb(a,0):Sf|=c);ia(a,b)}function Ti(a,b){0===b&&(0===(a.mode&1)?b=1:(b=Rd,Rd<<=1,0===(Rd&130023424)&&(Rd=4194304)));var c=Z();a=Oa(a,b);null!==a&&(ic(a,b,c),ia(a,c))}function vk(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Ti(a,c)}function Gk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);
break;case 19:d=a.stateNode;break;default:throw Error(m(314));}null!==d&&d.delete(b);Ti(a,c)}function Mi(a,b){return xh(a,b)}function Tk(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function yf(a){a=
a.prototype;return!(!a||!a.isReactComponent)}function Uk(a){if("function"===typeof a)return yf(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===ie)return 11;if(a===je)return 14}return 2}function eb(a,b){var c=a.alternate;null===c?(c=pa(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=
a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}function rd(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)yf(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case Bb:return sb(c.children,e,f,b);case fe:g=8;e|=8;break;case ee:return a=pa(12,c,b,e|2),a.elementType=ee,a.lanes=f,a;case ge:return a=
pa(13,c,b,e),a.elementType=ge,a.lanes=f,a;case he:return a=pa(19,c,b,e),a.elementType=he,a.lanes=f,a;case Ui:return Gd(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case hg:g=10;break a;case gg:g=9;break a;case ie:g=11;break a;case je:g=14;break a;case Ta:g=16;d=null;break a}throw Error(m(130,null==a?a:typeof a,""));}b=pa(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function sb(a,b,c,d){a=pa(7,a,d,b);a.lanes=c;return a}function Gd(a,b,c,d){a=pa(22,a,d,b);a.elementType=
Ui;a.lanes=c;a.stateNode={isHidden:!1};return a}function Ze(a,b,c){a=pa(6,a,null,b);a.lanes=c;return a}function $e(a,b,c){b=pa(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function Vk(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=
0;this.eventTimes=we(0);this.expirationTimes=we(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=we(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=null}function Vf(a,b,c,d,e,f,g,h,k,l){a=new Vk(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=pa(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,
pendingSuspenseBoundaries:null};ff(f);return a}function Wk(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Cb,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}function Vi(a){if(!a)return cb;a=a._reactInternals;a:{if(nb(a)!==a||1!==a.tag)throw Error(m(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(ea(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(m(171));
}if(1===a.tag){var c=a.type;if(ea(c))return uh(a,c,b)}return b}function Wi(a,b,c,d,e,f,g,h,k,l){a=Vf(c,d,!0,a,e,f,g,h,k);a.context=Vi(null);c=a.current;d=Z();e=hb(c);f=Pa(d,e);f.callback=void 0!==b&&null!==b?b:null;fb(c,f,e);a.current.lanes=e;ic(a,e,d);ia(a,d);return a}function Sd(a,b,c,d){var e=b.current,f=Z(),g=hb(e);c=Vi(c);null===b.context?b.context=c:b.pendingContext=c;b=Pa(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=fb(e,b,g);null!==a&&(xa(a,e,g,f),vd(a,e,g));return g}
function Td(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Xi(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function Wf(a,b){Xi(a,b);(a=a.alternate)&&Xi(a,b)}function Xk(a){a=Bg(a);return null===a?null:a.stateNode}function Yk(a){return null}function Xf(a){this._internalRoot=a}function Ud(a){this._internalRoot=a}function Yf(a){return!(!a||1!==a.nodeType&&9!==
a.nodeType&&11!==a.nodeType)}function Vd(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function Yi(){}function Zk(a,b,c,d,e){if(e){if("function"===typeof d){var f=d;d=function(){var a=Td(g);f.call(a)}}var g=Wi(b,d,a,0,null,!1,!1,"",Yi);a._reactRootContainer=g;a[Ja]=g.current;sc(8===a.nodeType?a.parentNode:a);yb();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=Td(k);
h.call(a)}}var k=Vf(a,0,!1,null,null,!1,!1,"",Yi);a._reactRootContainer=k;a[Ja]=k.current;sc(8===a.nodeType?a.parentNode:a);yb(function(){Sd(b,k,c,d)});return k}function Wd(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===typeof e){var h=e;e=function(){var a=Td(g);h.call(a)}}Sd(b,g,a,e)}else g=Zk(c,b,a,e,d);return Td(g)}var cg=new Set,$b={},Ia=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),Zd=Object.prototype.hasOwnProperty,
cj=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,eg={},dg={},R={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){R[a]=
new Y(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];R[b]=new Y(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){R[a]=new Y(a,2,!1,a.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){R[a]=new Y(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){R[a]=
new Y(a,3,!1,a.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(a){R[a]=new Y(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){R[a]=new Y(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){R[a]=new Y(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){R[a]=new Y(a,5,!1,a.toLowerCase(),null,!1,!1)});var Zf=/[\-:]([a-z])/g,$f=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
a.replace(Zf,$f);R[b]=new Y(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Zf,$f);R[b]=new Y(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Zf,$f);R[b]=new Y(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){R[a]=new Y(a,1,!1,a.toLowerCase(),null,!1,!1)});R.xlinkHref=new Y("xlinkHref",
1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){R[a]=new Y(a,1,!1,a.toLowerCase(),null,!0,!0)});var Sa=zb.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,sd=Symbol.for("react.element"),Cb=Symbol.for("react.portal"),Bb=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),ee=Symbol.for("react.profiler"),hg=Symbol.for("react.provider"),gg=Symbol.for("react.context"),ie=Symbol.for("react.forward_ref"),ge=Symbol.for("react.suspense"),
he=Symbol.for("react.suspense_list"),je=Symbol.for("react.memo"),Ta=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var Ui=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var fg=Symbol.iterator,E=Object.assign,ae,ce=!1,cc=Array.isArray,Xd,yi=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,
c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{Xd=Xd||document.createElement("div");Xd.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=Xd.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}),Fc=function(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b},dc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,
borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,
strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},$k=["Webkit","ms","Moz","O"];Object.keys(dc).forEach(function(a){$k.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);dc[b]=dc[a]})});var ij=E({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),ze=null,se=null,Eb=null,Fb=null,xg=function(a,b){return a(b)},yg=function(){},te=!1,Oe=!1;if(Ia)try{var Lc={};Object.defineProperty(Lc,
"passive",{get:function(){Oe=!0}});window.addEventListener("test",Lc,Lc);window.removeEventListener("test",Lc,Lc)}catch(a){Oe=!1}var kj=function(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(q){this.onError(q)}},gc=!1,Sc=null,Tc=!1,ue=null,lj={onError:function(a){gc=!0;Sc=a}},Ba=zb.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,Jg=Ba.unstable_scheduleCallback,Kg=Ba.unstable_NormalPriority,xh=Jg,Ki=Ba.unstable_cancelCallback,Pk=Ba.unstable_shouldYield,
Sk=Ba.unstable_requestPaint,P=Ba.unstable_now,Dj=Ba.unstable_getCurrentPriorityLevel,De=Ba.unstable_ImmediatePriority,Mg=Ba.unstable_UserBlockingPriority,ad=Kg,Ej=Ba.unstable_LowPriority,Ng=Ba.unstable_IdlePriority,Uc=null,Ca=null,ta=Math.clz32?Math.clz32:pj,qj=Math.log,rj=Math.LN2,Wc=64,Rd=4194304,z=0,Ae=!1,Yc=[],Va=null,Wa=null,Xa=null,jc=new Map,kc=new Map,Ya=[],Bj="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "),
Gb=Sa.ReactCurrentBatchConfig,Zc=!0,$c=null,Za=null,Ee=null,bd=null,Yb={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},He=ka(Yb),Mc=E({},Yb,{view:0,detail:0}),ak=ka(Mc),ag,bg,Nc,Yd=E({},Mc,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Fe,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:
a.relatedTarget},movementX:function(a){if("movementX"in a)return a.movementX;a!==Nc&&(Nc&&"mousemove"===a.type?(ag=a.screenX-Nc.screenX,bg=a.screenY-Nc.screenY):bg=ag=0,Nc=a);return ag},movementY:function(a){return"movementY"in a?a.movementY:bg}}),ih=ka(Yd),al=E({},Yd,{dataTransfer:0}),Wj=ka(al),bl=E({},Mc,{relatedTarget:0}),Pe=ka(bl),cl=E({},Yb,{animationName:0,elapsedTime:0,pseudoElement:0}),Yj=ka(cl),dl=E({},Yb,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),
ck=ka(dl),el=E({},Yb,{data:0}),qh=ka(el),fk=qh,fl={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},gl={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",
112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Gj={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},hl=E({},Mc,{key:function(a){if(a.key){var b=fl[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=cd(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?gl[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,
metaKey:0,repeat:0,locale:0,getModifierState:Fe,charCode:function(a){return"keypress"===a.type?cd(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?cd(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),Vj=ka(hl),il=E({},Yd,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),nh=ka(il),jl=E({},Mc,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,
ctrlKey:0,shiftKey:0,getModifierState:Fe}),Xj=ka(jl),kl=E({},Yb,{propertyName:0,elapsedTime:0,pseudoElement:0}),Zj=ka(kl),ll=E({},Yd,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),bk=ka(ll),Hj=[9,13,27,32],Ge=Ia&&"CompositionEvent"in window,Oc=null;Ia&&"documentMode"in document&&(Oc=document.documentMode);var ek=Ia&&"TextEvent"in
window&&!Oc,Ug=Ia&&(!Ge||Oc&&8<Oc&&11>=Oc),Tg=String.fromCharCode(32),Sg=!1,Hb=!1,Kj={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},oc=null,pc=null,ph=!1;Ia&&(ph=Lj("input")&&(!document.documentMode||9<document.documentMode));var ua="function"===typeof Object.is?Object.is:Sj,dk=Ia&&"documentMode"in document&&11>=document.documentMode,Jb=null,Ke=null,rc=null,Je=!1,Kb={animationend:gd("Animation","AnimationEnd"),
animationiteration:gd("Animation","AnimationIteration"),animationstart:gd("Animation","AnimationStart"),transitionend:gd("Transition","TransitionEnd")},Le={},eh={};Ia&&(eh=document.createElement("div").style,"AnimationEvent"in window||(delete Kb.animationend.animation,delete Kb.animationiteration.animation,delete Kb.animationstart.animation),"TransitionEvent"in window||delete Kb.transitionend.transition);var jh=hd("animationend"),kh=hd("animationiteration"),lh=hd("animationstart"),mh=hd("transitionend"),
fh=new Map,Zi="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
(function(){for(var a=0;a<Zi.length;a++){var b=Zi[a],c=b.toLowerCase();b=b[0].toUpperCase()+b.slice(1);$a(c,"on"+b)}$a(jh,"onAnimationEnd");$a(kh,"onAnimationIteration");$a(lh,"onAnimationStart");$a("dblclick","onDoubleClick");$a("focusin","onFocus");$a("focusout","onBlur");$a(mh,"onTransitionEnd")})();Ab("onMouseEnter",["mouseout","mouseover"]);Ab("onMouseLeave",["mouseout","mouseover"]);Ab("onPointerEnter",["pointerout","pointerover"]);Ab("onPointerLeave",["pointerout","pointerover"]);mb("onChange",
"change click focusin focusout input keydown keyup selectionchange".split(" "));mb("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));mb("onBeforeInput",["compositionend","keypress","textInput","paste"]);mb("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));mb("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));mb("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));
var Ec="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Uj=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ec)),id="_reactListening"+Math.random().toString(36).slice(2),gk=/\r\n?/g,hk=/\u0000|\uFFFD/g,Jf=null,Kf=null,Rf="function"===typeof setTimeout?setTimeout:void 0,Nk="function"===typeof clearTimeout?
clearTimeout:void 0,$i="function"===typeof Promise?Promise:void 0,Jk="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof $i?function(a){return $i.resolve(null).then(a).catch(ik)}:Rf,Zb=Math.random().toString(36).slice(2),Da="__reactFiber$"+Zb,uc="__reactProps$"+Zb,Ja="__reactContainer$"+Zb,Me="__reactEvents$"+Zb,Dk="__reactListeners$"+Zb,Ek="__reactHandles$"+Zb,Se=[],Mb=-1,cb={},J=bb(cb),S=bb(!1),pb=cb,La=null,md=!1,Te=!1,Ob=[],Pb=0,od=null,nd=0,na=[],oa=0,rb=null,Ma=1,Na="",la=
null,fa=null,D=!1,wa=null,Ik=Sa.ReactCurrentBatchConfig,Vb=Dh(!0),li=Dh(!1),ud=bb(null),td=null,Rb=null,bf=null,tb=null,kk=Oa,gb=!1,wc={},Ea=bb(wc),yc=bb(wc),xc=bb(wc),F=bb(0),kf=[],yd=Sa.ReactCurrentDispatcher,sf=Sa.ReactCurrentBatchConfig,vb=0,C=null,K=null,N=null,Ad=!1,zc=!1,Ac=0,ml=0,zd={readContext:qa,useCallback:V,useContext:V,useEffect:V,useImperativeHandle:V,useInsertionEffect:V,useLayoutEffect:V,useMemo:V,useReducer:V,useRef:V,useState:V,useDebugValue:V,useDeferredValue:V,useTransition:V,
useMutableSource:V,useSyncExternalStore:V,useId:V,unstable_isNewReconciler:!1},lk={readContext:qa,useCallback:function(a,b){Fa().memoizedState=[a,void 0===b?null:b];return a},useContext:qa,useEffect:Sh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Bd(4194308,4,Vh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Bd(4194308,4,a,b)},useInsertionEffect:function(a,b){return Bd(4,2,a,b)},useMemo:function(a,b){var c=Fa();b=void 0===b?null:b;a=a();c.memoizedState=
[a,b];return a},useReducer:function(a,b,c){var d=Fa();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=qk.bind(null,C,a);return[d.memoizedState,a]},useRef:function(a){var b=Fa();a={current:a};return b.memoizedState=a},useState:Qh,useDebugValue:rf,useDeferredValue:function(a){return Fa().memoizedState=a},useTransition:function(){var a=Qh(!1),b=a[0];a=pk.bind(null,a[1]);Fa().memoizedState=
a;return[b,a]},useMutableSource:function(a,b,c){},useSyncExternalStore:function(a,b,c){var d=C,e=Fa();if(D){if(void 0===c)throw Error(m(407));c=c()}else{c=b();if(null===O)throw Error(m(349));0!==(vb&30)||Nh(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;Sh(Lh.bind(null,d,f,a),[a]);d.flags|=2048;Cc(9,Mh.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Fa(),b=O.identifierPrefix;if(D){var c=Na;var d=Ma;c=(d&~(1<<32-ta(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Ac++;0<c&&
(b+="H"+c.toString(32));b+=":"}else c=ml++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:!1},mk={readContext:qa,useCallback:Xh,useContext:qa,useEffect:qf,useImperativeHandle:Wh,useInsertionEffect:Th,useLayoutEffect:Uh,useMemo:Yh,useReducer:of,useRef:Rh,useState:function(a){return of(Bc)},useDebugValue:rf,useDeferredValue:function(a){var b=sa();return Zh(b,K.memoizedState,a)},useTransition:function(){var a=of(Bc)[0],b=sa().memoizedState;return[a,b]},useMutableSource:Jh,
useSyncExternalStore:Kh,useId:$h,unstable_isNewReconciler:!1},nk={readContext:qa,useCallback:Xh,useContext:qa,useEffect:qf,useImperativeHandle:Wh,useInsertionEffect:Th,useLayoutEffect:Uh,useMemo:Yh,useReducer:pf,useRef:Rh,useState:function(a){return pf(Bc)},useDebugValue:rf,useDeferredValue:function(a){var b=sa();return null===K?b.memoizedState=a:Zh(b,K.memoizedState,a)},useTransition:function(){var a=pf(Bc)[0],b=sa().memoizedState;return[a,b]},useMutableSource:Jh,useSyncExternalStore:Kh,useId:$h,
unstable_isNewReconciler:!1},Dd={isMounted:function(a){return(a=a._reactInternals)?nb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=Z(),e=hb(a),f=Pa(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=fb(a,f,e);null!==b&&(xa(b,a,e,d),vd(b,a,e))},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=Z(),e=hb(a),f=Pa(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=fb(a,f,e);null!==b&&(xa(b,a,e,d),vd(b,a,e))},enqueueForceUpdate:function(a,b){a=a._reactInternals;
var c=Z(),d=hb(a),e=Pa(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=fb(a,e,d);null!==b&&(xa(b,a,d,c),vd(b,a,d))}},rk="function"===typeof WeakMap?WeakMap:Map,tk=Sa.ReactCurrentOwner,ha=!1,Cf={dehydrated:null,treeContext:null,retryLane:0};var zk=function(a,b,c,d){for(c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=
c.return;c=c.sibling}};var xi=function(a,b){};var yk=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){a=b.stateNode;ub(Ea.current);e=null;switch(c){case "input":f=ke(a,f);d=ke(a,d);e=[];break;case "select":f=E({},f,{value:void 0});d=E({},d,{value:void 0});e=[];break;case "textarea":f=ne(a,f);d=ne(a,d);e=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(a.onclick=kd)}pe(c,d);var g;c=null;for(l in f)if(!d.hasOwnProperty(l)&&f.hasOwnProperty(l)&&null!=f[l])if("style"===
l){var h=f[l];for(g in h)h.hasOwnProperty(g)&&(c||(c={}),c[g]="")}else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&($b.hasOwnProperty(l)?e||(e=[]):(e=e||[]).push(l,null));for(l in d){var k=d[l];h=null!=f?f[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||
(c={}),c[g]=k[g])}else c||(e||(e=[]),e.push(l,c)),c=k;else"dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(e=e||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(e=e||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&($b.hasOwnProperty(l)?(null!=k&&"onScroll"===l&&B("scroll",a),e||h===k||(e=[])):(e=e||[]).push(l,k))}c&&(e=e||[]).push("style",c);var l=e;if(b.updateQueue=l)b.flags|=4}};var Ak=function(a,
b,c,d){c!==d&&(b.flags|=4)};var Jd=!1,X=!1,Fk="function"===typeof WeakSet?WeakSet:Set,l=null,zi=!1,T=null,za=!1,Mk=Math.ceil,Od=Sa.ReactCurrentDispatcher,Uf=Sa.ReactCurrentOwner,ca=Sa.ReactCurrentBatchConfig,p=0,O=null,H=null,U=0,ba=0,Ga=bb(0),L=0,Jc=null,ra=0,Md=0,Sf=0,Kc=null,ja=null,Of=0,Hf=Infinity,Ra=null,Ed=!1,xf=null,ib=null,Pd=!1,lb=null,Qd=0,Ic=0,Pf=null,Kd=-1,Ld=0;var Qk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||S.current)ha=!0;else{if(0===(a.lanes&c)&&0===(b.flags&
128))return ha=!1,wk(a,b,c);ha=0!==(a.flags&131072)?!0:!1}else ha=!1,D&&0!==(b.flags&1048576)&&yh(b,nd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;Fd(a,b);a=b.pendingProps;var e=Nb(b,J.current);Sb(b,c);e=mf(null,b,d,a,e,c);var f=nf();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=null,ea(d)?(f=!0,ld(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ff(b),e.updater=Dd,b.stateNode=
e,e._reactInternals=b,uf(b,d,a,c),b=Af(null,b,d,!0,f,c)):(b.tag=0,D&&f&&Ue(b),aa(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{Fd(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Uk(d);a=ya(d,a);switch(e){case 0:b=zf(null,b,d,a,c);break a;case 1:b=ri(null,b,d,a,c);break a;case 11:b=mi(null,b,d,a,c);break a;case 14:b=ni(null,b,d,ya(d.type,a),c);break a}throw Error(m(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ya(d,e),zf(a,b,d,e,c);
case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ya(d,e),ri(a,b,d,e,c);case 3:a:{si(b);if(null===a)throw Error(m(387));d=b.pendingProps;f=b.memoizedState;e=f.element;Fh(a,b);wd(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Ub(Error(m(423)),b);b=ti(a,b,d,c,e);break a}else if(d!==e){e=
Ub(Error(m(424)),b);b=ti(a,b,d,c,e);break a}else for(fa=Ka(b.stateNode.containerInfo.firstChild),la=b,D=!0,wa=null,c=li(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Qb();if(d===e){b=Qa(a,b,c);break a}aa(a,b,d,c)}b=b.child}return b;case 5:return Ih(b),null===a&&Xe(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Qe(d,e)?g=null:null!==f&&Qe(d,f)&&(b.flags|=32),qi(a,b),aa(a,b,g,c),b.child;case 6:return null===a&&Xe(b),null;case 13:return ui(a,b,c);case 4:return gf(b,
b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Vb(b,null,d,c):aa(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ya(d,e),mi(a,b,d,e,c);case 7:return aa(a,b,b.pendingProps,c),b.child;case 8:return aa(a,b,b.pendingProps.children,c),b.child;case 12:return aa(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;y(ud,d._currentValue);d._currentValue=g;if(null!==f)if(ua(f.value,g)){if(f.children===
e.children&&!S.current){b=Qa(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=Pa(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var p=l.pending;null===p?k.next=k:(k.next=p.next,p.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);df(f.return,c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===
f.tag){g=f.return;if(null===g)throw Error(m(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);df(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}aa(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Sb(b,c),e=qa(e),d=d(e),b.flags|=1,aa(a,b,d,c),b.child;case 14:return d=b.type,e=ya(d,b.pendingProps),e=ya(d.type,e),ni(a,b,d,e,c);case 15:return oi(a,
b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ya(d,e),Fd(a,b),b.tag=1,ea(d)?(a=!0,ld(b)):a=!1,Sb(b,c),ei(b,d,e),uf(b,d,e,c),Af(null,b,d,!0,a,c);case 19:return wi(a,b,c);case 22:return pi(a,b,c)}throw Error(m(156,b.tag));};var pa=function(a,b,c,d){return new Tk(a,b,c,d)},aj="function"===typeof reportError?reportError:function(a){console.error(a)};Ud.prototype.render=Xf.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(m(409));
Sd(a,b,null,null)};Ud.prototype.unmount=Xf.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;yb(function(){Sd(null,a,null,null)});b[Ja]=null}};Ud.prototype.unstable_scheduleHydration=function(a){if(a){var b=nl();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Ya.length&&0!==b&&b<Ya[c].priority;c++);Ya.splice(c,0,a);0===c&&Hg(a)}};var Cj=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=
hc(b.pendingLanes);0!==c&&(xe(b,c|1),ia(b,P()),0===(p&6)&&(Hc(),db()))}break;case 13:yb(function(){var b=Oa(a,1);if(null!==b){var c=Z();xa(b,a,1,c)}}),Wf(a,1)}};var Gg=function(a){if(13===a.tag){var b=Oa(a,134217728);if(null!==b){var c=Z();xa(b,a,134217728,c)}Wf(a,134217728)}};var xj=function(a){if(13===a.tag){var b=hb(a),c=Oa(a,b);if(null!==c){var d=Z();xa(c,a,b,d)}Wf(a,b)}};var nl=function(){return z};var wj=function(a,b){var c=z;try{return z=a,b()}finally{z=c}};se=function(a,b,c){switch(b){case "input":le(a,
c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Rc(d);if(!e)throw Error(m(90));jg(d);le(d,e)}}}break;case "textarea":og(a,c);break;case "select":b=c.value,null!=b&&Db(a,!!c.multiple,b,!1)}};(function(a,b,c){xg=a;yg=c})(Tf,function(a,b,c,d,e){var f=z,g=ca.transition;try{return ca.transition=null,z=1,a(b,c,d,e)}finally{z=f,ca.transition=
g,0===p&&Hc()}},yb);var ol={usingClientEntryPoint:!1,Events:[ec,Ib,Rc,ug,vg,Tf]};(function(a){a={bundleType:a.bundleType,version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Sa.ReactCurrentDispatcher,findHostInstanceByFiber:Xk,
findFiberByHostInstance:a.findFiberByHostInstance||Yk,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"};if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)a=!1;else{var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)a=!0;else{try{Uc=b.inject(a),Ca=b}catch(c){}a=b.checkDCE?!0:!1}}return a})({findFiberByHostInstance:ob,bundleType:0,version:"18.3.1-next-f1338f8080-20240426",
rendererPackageName:"react-dom"});Q.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ol;Q.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Yf(b))throw Error(m(200));return Wk(a,b,null,c)};Q.createRoot=function(a,b){if(!Yf(a))throw Error(m(299));var c=!1,d="",e=aj;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=Vf(a,1,!1,null,null,
c,!1,d,e);a[Ja]=b.current;sc(8===a.nodeType?a.parentNode:a);return new Xf(b)};Q.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(m(188));a=Object.keys(a).join(",");throw Error(m(268,a));}a=Bg(b);a=null===a?null:a.stateNode;return a};Q.flushSync=function(a){return yb(a)};Q.hydrate=function(a,b,c){if(!Vd(b))throw Error(m(200));return Wd(null,a,b,!0,c)};Q.hydrateRoot=function(a,b,c){if(!Yf(a))throw Error(m(405));
var d=null!=c&&c.hydratedSources||null,e=!1,f="",g=aj;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=Wi(b,null,a,1,null!=c?c:null,e,!1,f,g);a[Ja]=b.current;sc(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,e);return new Ud(b)};Q.render=
function(a,b,c){if(!Vd(b))throw Error(m(200));return Wd(null,a,b,!1,c)};Q.unmountComponentAtNode=function(a){if(!Vd(a))throw Error(m(40));return a._reactRootContainer?(yb(function(){Wd(null,null,a,!1,function(){a._reactRootContainer=null;a[Ja]=null})}),!0):!1};Q.unstable_batchedUpdates=Tf;Q.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!Vd(c))throw Error(m(200));if(null==a||void 0===a._reactInternals)throw Error(m(38));return Wd(a,b,c,!1,d)};Q.version="18.3.1-next-f1338f8080-20240426"});
})();
/**
 * @license React
 * react-dom.profiling.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
'use strict';(function(R,Ib){"object"===typeof exports&&"undefined"!==typeof module?Ib(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],Ib):(R=R||self,Ib(R.ReactDOM={},R.React))})(this,function(R,Ib){function m(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
function rb(a,b){Jb(a,b);Jb(a+"Capture",b)}function Jb(a,b){mc[a]=b;for(a=0;a<b.length;a++)Ag.add(b[a])}function Ij(a){if(re.call(Bg,a))return!0;if(re.call(Cg,a))return!1;if(Jj.test(a))return Bg[a]=!0;Cg[a]=!0;return!1}function Kj(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}function Lj(a,b,c,d){if(null===
b||"undefined"===typeof b||Kj(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function Z(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}function se(a,b,c,d){var e=S.hasOwnProperty(b)?S[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==
b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])Lj(b,c,e,d)&&(c=null),d||null===e?Ij(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}function nc(a){if(null===a||"object"!==typeof a)return null;a=Dg&&a[Dg]||a["@@iterator"];return"function"===typeof a?a:null}function oc(a,b,
c){if(void 0===te)try{throw Error();}catch(d){te=(b=d.stack.trim().match(/\n( *(at )?)/))&&b[1]||""}return"\n"+te+a}function ue(a,b){if(!a||ve)return"";ve=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(n){var d=n}Reflect.construct(a,[],b)}else{try{b.call()}catch(n){d=n}a.call(b.prototype)}else{try{throw Error();
}catch(n){d=n}a()}}catch(n){if(n&&d&&"string"===typeof n.stack){for(var e=n.stack.split("\n"),f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{ve=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?oc(a):
""}function Mj(a){switch(a.tag){case 5:return oc(a.type);case 16:return oc("Lazy");case 13:return oc("Suspense");case 19:return oc("SuspenseList");case 0:case 2:case 15:return a=ue(a.type,!1),a;case 11:return a=ue(a.type.render,!1),a;case 1:return a=ue(a.type,!0),a;default:return""}}function we(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Kb:return"Fragment";case Lb:return"Portal";case xe:return"Profiler";case ye:return"StrictMode";
case ze:return"Suspense";case Ae:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Eg:return(a.displayName||"Context")+".Consumer";case Fg:return(a._context.displayName||"Context")+".Provider";case Be:var b=a.render;a=a.displayName;a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ce:return b=a.displayName||null,null!==b?b:we(a.type)||"Memo";case Ya:b=a._payload;a=a._init;try{return we(a(b))}catch(c){}}return null}function Nj(a){var b=a.type;
switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return we(b);case 8:return b===ye?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";
case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Za(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}}function Gg(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===
b)}function Oj(a){var b=Gg(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function dd(a){a._valueTracker||(a._valueTracker=Oj(a))}function Hg(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Gg(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function ed(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function De(a,b){var c=b.checked;return D({},b,{defaultChecked:void 0,defaultValue:void 0,
value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Ig(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Za(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function Jg(a,b){b=b.checked;null!=b&&se(a,"checked",b,!1)}function Ee(a,b){Jg(a,b);var c=Za(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=
c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?Fe(a,b.type,c):b.hasOwnProperty("defaultValue")&&Fe(a,b.type,Za(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}function Kg(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;
c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}function Fe(a,b,c){if("number"!==b||ed(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}function Mb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=
!0)}else{c=""+Za(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}function Ge(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(m(91));return D({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Lg(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(m(92));if(pc(c)){if(1<c.length)throw Error(m(93));
c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:Za(c)}}function Mg(a,b){var c=Za(b.value),d=Za(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Ng(a,b){b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}function Og(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}
function He(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Og(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}function Pg(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||qc.hasOwnProperty(a)&&qc[a]?(""+b).trim():b+"px"}function Qg(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=Pg(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}function Ie(a,b){if(b){if(Pj[a]&&
(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(m(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(m(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(m(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(m(62));}}function Je(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;
default:return!0}}function Ke(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function Rg(a){if(a=rc(a)){if("function"!==typeof Le)throw Error(m(280));var b=a.stateNode;b&&(b=fd(b),Le(a.stateNode,a.type,b))}}function Sg(a){Nb?Ob?Ob.push(a):Ob=[a]:Nb=a}function Tg(){if(Nb){var a=Nb,b=Ob;Ob=Nb=null;Rg(a);if(b)for(a=0;a<b.length;a++)Rg(b[a])}}function Ug(a,b,c){if(Me)return a(b,c);Me=!0;try{return Vg(a,b,c)}finally{if(Me=
!1,null!==Nb||null!==Ob)Wg(),Tg()}}function sc(a,b){var c=a.stateNode;if(null===c)return null;var d=fd(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;
if(c&&"function"!==typeof c)throw Error(m(231,b,typeof c));return c}function Qj(a,b,c,d,e,f,g,h,k){tc=!1;gd=null;Rj.apply(Sj,arguments)}function Tj(a,b,c,d,e,f,g,h,k){Qj.apply(this,arguments);if(tc){if(tc){var n=gd;tc=!1;gd=null}else throw Error(m(198));hd||(hd=!0,Ne=n)}}function sb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Xg(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,
null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Yg(a){if(sb(a)!==a)throw Error(m(188));}function Uj(a){var b=a.alternate;if(!b){b=sb(a);if(null===b)throw Error(m(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Yg(e),a;if(f===d)return Yg(e),b;f=f.sibling}throw Error(m(188));}if(c.return!==d.return)c=e,d=f;
else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(m(189));}}if(c.alternate!==d)throw Error(m(190));}if(3!==c.tag)throw Error(m(188));return c.stateNode.current===c?a:b}function Zg(a){a=Uj(a);return null!==a?$g(a):null}function $g(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$g(a);if(null!==b)return b;a=a.sibling}return null}
function Vj(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{a=D({},a,{getLaneLabelMap:Wj,injectProfilingHooks:Xj}),id=b.inject(a),Da=b}catch(c){}return b.checkDCE?!0:!1}function Yj(a,b){if(Da&&"function"===typeof Da.onCommitFiberRoot)try{var c=128===(a.current.flags&128);switch(b){case 1:var d=jd;break;case 4:d=Oe;break;case 16:d=tb;break;case 536870912:d=Pe;break;default:d=tb}Da.onCommitFiberRoot(id,
a,d,c)}catch(e){}}function Xj(a){l=a}function Wj(){for(var a=new Map,b=1,c=0;31>c;c++){var d=Zj(b);a.set(b,d);b*=2}return a}function ah(){null!==l&&"function"===typeof l.markCommitStopped&&l.markCommitStopped()}function uc(a){null!==l&&"function"===typeof l.markComponentRenderStarted&&l.markComponentRenderStarted(a)}function Pb(){null!==l&&"function"===typeof l.markComponentRenderStopped&&l.markComponentRenderStopped()}function bh(a){null!==l&&"function"===typeof l.markComponentLayoutEffectUnmountStarted&&
l.markComponentLayoutEffectUnmountStarted(a)}function ch(){null!==l&&"function"===typeof l.markComponentLayoutEffectUnmountStopped&&l.markComponentLayoutEffectUnmountStopped()}function dh(a){null!==l&&"function"===typeof l.markRenderStarted&&l.markRenderStarted(a)}function eh(){null!==l&&"function"===typeof l.markRenderStopped&&l.markRenderStopped()}function kd(a,b){null!==l&&"function"===typeof l.markStateUpdateScheduled&&l.markStateUpdateScheduled(a,b)}function ak(a){a>>>=0;return 0===a?32:31-(bk(a)/
ck|0)|0}function Zj(a){if(a&1)return"Sync";if(a&2)return"InputContinuousHydration";if(a&4)return"InputContinuous";if(a&8)return"DefaultHydration";if(a&16)return"Default";if(a&32)return"TransitionHydration";if(a&4194240)return"Transition";if(a&130023424)return"Retry";if(a&134217728)return"SelectiveHydration";if(a&268435456)return"IdleHydration";if(a&536870912)return"Idle";if(a&1073741824)return"Offscreen"}function vc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;
case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function ld(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=
0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=vc(h):(f&=g,0!==f&&(d=vc(f)))}else g=c&~e,0!==g?d=vc(g):0!==f&&(d=vc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-ka(b),e=1<<c,d|=a[c],b&=~e;return d}function dk(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+
5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ek(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-ka(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=dk(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function Qe(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function fh(){var a=md;md<<=1;
0===(md&4194240)&&(md=64);return a}function Re(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}function wc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-ka(b);a[b]=c}function fk(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-ka(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}function Se(a,
b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-ka(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}function gh(a,b,c){if(ua)for(a=a.pendingUpdatersLaneMap;0<c;){var d=31-ka(c),e=1<<d;a[d].add(b);c&=~e}}function hh(a,b){if(ua)for(var c=a.pendingUpdatersLaneMap,d=a.memoizedUpdaters;0<b;){var e=31-ka(b);a=1<<e;e=c[e];0<e.size&&(e.forEach(function(a){var b=a.alternate;null!==b&&d.has(b)||d.add(a)}),e.clear());b&=~a}}function ih(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}function jh(a,
b){switch(a){case "focusin":case "focusout":$a=null;break;case "dragenter":case "dragleave":ab=null;break;case "mouseover":case "mouseout":bb=null;break;case "pointerover":case "pointerout":xc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":yc.delete(b.pointerId)}}function zc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=rc(b),null!==b&&kh(b)),a;a.eventSystemFlags|=d;
b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}function gk(a,b,c,d,e){switch(b){case "focusin":return $a=zc($a,a,b,c,d,e),!0;case "dragenter":return ab=zc(ab,a,b,c,d,e),!0;case "mouseover":return bb=zc(bb,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;xc.set(f,zc(xc.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,yc.set(f,zc(yc.get(f)||null,a,b,c,d,e)),!0}return!1}function lh(a){var b=ub(a.target);if(null!==b){var c=sb(b);if(null!==c)if(b=
c.tag,13===b){if(b=Xg(c),null!==b){a.blockedOn=b;hk(a.priority,function(){ik(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function nd(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=Te(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);Ue=d;c.target.dispatchEvent(d);Ue=null}else return b=rc(c),
null!==b&&kh(b),a.blockedOn=c,!1;b.shift()}return!0}function mh(a,b,c){nd(a)&&c.delete(b)}function jk(){Ve=!1;null!==$a&&nd($a)&&($a=null);null!==ab&&nd(ab)&&(ab=null);null!==bb&&nd(bb)&&(bb=null);xc.forEach(mh);yc.forEach(mh)}function Ac(a,b){a.blockedOn===b&&(a.blockedOn=null,Ve||(Ve=!0,nh(oh,jk)))}function Bc(a){if(0<od.length){Ac(od[0],a);for(var b=1;b<od.length;b++){var c=od[b];c.blockedOn===a&&(c.blockedOn=null)}}null!==$a&&Ac($a,a);null!==ab&&Ac(ab,a);null!==bb&&Ac(bb,a);b=function(b){return Ac(b,
a)};xc.forEach(b);yc.forEach(b);for(b=0;b<cb.length;b++)c=cb[b],c.blockedOn===a&&(c.blockedOn=null);for(;0<cb.length&&(b=cb[0],null===b.blockedOn);)lh(b),null===b.blockedOn&&cb.shift()}function kk(a,b,c,d){var e=x,f=Qb.transition;Qb.transition=null;try{x=1,We(a,b,c,d)}finally{x=e,Qb.transition=f}}function lk(a,b,c,d){var e=x,f=Qb.transition;Qb.transition=null;try{x=4,We(a,b,c,d)}finally{x=e,Qb.transition=f}}function We(a,b,c,d){if(pd){var e=Te(a,b,c,d);if(null===e)Xe(a,b,d,qd,c),jh(a,d);else if(gk(e,
a,b,c,d))d.stopPropagation();else if(jh(a,d),b&4&&-1<mk.indexOf(a)){for(;null!==e;){var f=rc(e);null!==f&&nk(f);f=Te(a,b,c,d);null===f&&Xe(a,b,d,qd,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else Xe(a,b,d,null,c)}}function Te(a,b,c,d){qd=null;a=Ke(d);a=ub(a);if(null!==a)if(b=sb(a),null===b)a=null;else if(c=b.tag,13===c){a=Xg(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=
null);qd=a;return null}function ph(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;
case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;case "message":switch(ok()){case jd:return 1;case Oe:return 4;case tb:case pk:return 16;case Pe:return 536870912;default:return 16}default:return 16}}function qh(){if(rd)return rd;
var a,b=Ye,c=b.length,d,e="value"in db?db.value:db.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return rd=e.slice(a,1<d?1-d:void 0)}function sd(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function td(){return!0}function rh(){return!1}function la(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;
for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?td:rh;this.isPropagationStopped=rh;return this}D(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=td)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():
"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=td)},persist:function(){},isPersistent:td});return b}function qk(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=rk[a])?!!b[a]:!1}function Ze(a){return qk}function sh(a,b){switch(a){case "keyup":return-1!==sk.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function th(a){a=a.detail;return"object"===typeof a&&
"data"in a?a.data:null}function tk(a,b){switch(a){case "compositionend":return th(b);case "keypress":if(32!==b.which)return null;uh=!0;return vh;case "textInput":return a=b.data,a===vh&&uh?null:a;default:return null}}function uk(a,b){if(Rb)return"compositionend"===a||!$e&&sh(a,b)?(a=qh(),rd=Ye=db=null,Rb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;
case "compositionend":return wh&&"ko"!==b.locale?null:b.data;default:return null}}function xh(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!vk[a.type]:"textarea"===b?!0:!1}function wk(a){if(!La)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function yh(a,b,c,d){Sg(d);b=ud(b,"onChange");0<b.length&&(c=new af("onChange","change",null,c,d),a.push({event:c,listeners:b}))}function xk(a){zh(a,
0)}function vd(a){var b=Sb(a);if(Hg(b))return a}function yk(a,b){if("change"===a)return b}function Ah(){Cc&&(Cc.detachEvent("onpropertychange",Bh),Dc=Cc=null)}function Bh(a){if("value"===a.propertyName&&vd(Dc)){var b=[];yh(b,Dc,a,Ke(a));Ug(xk,b)}}function zk(a,b,c){"focusin"===a?(Ah(),Cc=b,Dc=c,Cc.attachEvent("onpropertychange",Bh)):"focusout"===a&&Ah()}function Ak(a,b){if("selectionchange"===a||"keyup"===a||"keydown"===a)return vd(Dc)}function Bk(a,b){if("click"===a)return vd(b)}function Ck(a,b){if("input"===
a||"change"===a)return vd(b)}function Dk(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function Ec(a,b){if(va(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!re.call(b,e)||!va(a[e],b[e]))return!1}return!0}function Ch(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function Dh(a,b){var c=Ch(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;
if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Ch(c)}}function Eh(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Eh(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function Fh(){for(var a=window,b=ed();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;
b=ed(a.document)}return b}function bf(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}function Ek(a){var b=Fh(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Eh(c.ownerDocument.documentElement,c)){if(null!==d&&bf(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);
else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Dh(c,f);var g=Dh(c,d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),
a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}function Gh(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;cf||null==Tb||Tb!==ed(d)||(d=Tb,"selectionStart"in d&&bf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d=
{anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Fc&&Ec(Fc,d)||(Fc=d,d=ud(df,"onSelect"),0<d.length&&(b=new af("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=Tb)))}function wd(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}function xd(a){if(ef[a])return ef[a];if(!Ub[a])return a;var b=Ub[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Hh)return ef[a]=b[c];return a}function eb(a,
b){Ih.set(a,b);rb(b,[a])}function Jh(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;Tj(d,b,void 0,a);a.currentTarget=null}function zh(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,n=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;Jh(e,h,n);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;n=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;
Jh(e,h,n);f=k}}}if(hd)throw a=Ne,hd=!1,Ne=null,a;}function A(a,b){var c=b[ff];void 0===c&&(c=b[ff]=new Set);var d=a+"__bubble";c.has(d)||(Kh(b,a,2,!1),c.add(d))}function gf(a,b,c){var d=0;b&&(d|=4);Kh(c,a,d,b)}function Gc(a){if(!a[yd]){a[yd]=!0;Ag.forEach(function(b){"selectionchange"!==b&&(Fk.has(b)||gf(b,!1,a),gf(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[yd]||(b[yd]=!0,gf("selectionchange",!1,b))}}function Kh(a,b,c,d,e){switch(ph(b)){case 1:e=kk;break;case 4:e=lk;break;default:e=
We}c=e.bind(null,b,c,a);e=void 0;!hf||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}function Xe(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;
if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=ub(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Ug(function(){var d=f,e=Ke(c),g=[];a:{var h=Ih.get(a);if(void 0!==h){var k=af,m=a;switch(a){case "keypress":if(0===sd(c))break a;case "keydown":case "keyup":k=Gk;break;case "focusin":m="focus";k=kf;break;case "focusout":m="blur";k=kf;break;case "beforeblur":case "afterblur":k=kf;break;
case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=Lh;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=Hk;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=Ik;break;case Mh:case Nh:case Oh:k=Jk;break;case Ph:k=Kk;break;case "scroll":k=Lk;break;case "wheel":k=Mk;break;case "copy":case "cut":case "paste":k=
Nk;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=Qh}var l=0!==(b&4),p=!l&&"scroll"===a,B=l?null!==h?h+"Capture":null:h;l=[];for(var y=d,r;null!==y;){r=y;var F=r.stateNode;5===r.tag&&null!==F&&(r=F,null!==B&&(F=sc(y,B),null!=F&&l.push(Hc(y,F,r))));if(p)break;y=y.return}0<l.length&&(h=new k(h,m,null,c,e),g.push({event:h,listeners:l}))}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===
a;k="mouseout"===a||"pointerout"===a;if(h&&c!==Ue&&(m=c.relatedTarget||c.fromElement)&&(ub(m)||m[Ma]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(m=c.relatedTarget||c.toElement,k=d,m=m?ub(m):null,null!==m&&(p=sb(m),m!==p||5!==m.tag&&6!==m.tag))m=null}else k=null,m=d;if(k!==m){l=Lh;F="onMouseLeave";B="onMouseEnter";y="mouse";if("pointerout"===a||"pointerover"===a)l=Qh,F="onPointerLeave",B="onPointerEnter",y="pointer";p=null==k?h:Sb(k);r=null==
m?h:Sb(m);h=new l(F,y+"leave",k,c,e);h.target=p;h.relatedTarget=r;F=null;ub(e)===d&&(l=new l(B,y+"enter",m,c,e),l.target=r,l.relatedTarget=p,F=l);p=F;if(k&&m)b:{l=k;B=m;y=0;for(r=l;r;r=Vb(r))y++;r=0;for(F=B;F;F=Vb(F))r++;for(;0<y-r;)l=Vb(l),y--;for(;0<r-y;)B=Vb(B),r--;for(;y--;){if(l===B||null!==B&&l===B.alternate)break b;l=Vb(l);B=Vb(B)}l=null}else l=null;null!==k&&Rh(g,h,k,l,!1);null!==m&&null!==p&&Rh(g,p,m,l,!0)}}}a:{h=d?Sb(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===
k&&"file"===h.type)var Na=yk;else if(xh(h))if(Sh)Na=Ck;else{Na=Ak;var wa=zk}else(k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(Na=Bk);if(Na&&(Na=Na(a,d))){yh(g,Na,c,e);break a}wa&&wa(a,h,d);"focusout"===a&&(wa=h._wrapperState)&&wa.controlled&&"number"===h.type&&Fe(h,"number",h.value)}wa=d?Sb(d):window;switch(a){case "focusin":if(xh(wa)||"true"===wa.contentEditable)Tb=wa,df=d,Fc=null;break;case "focusout":Fc=df=Tb=null;break;case "mousedown":cf=!0;break;case "contextmenu":case "mouseup":case "dragend":cf=
!1;Gh(g,c,e);break;case "selectionchange":if(Ok)break;case "keydown":case "keyup":Gh(g,c,e)}var fb;if($e)b:{switch(a){case "compositionstart":var da="onCompositionStart";break b;case "compositionend":da="onCompositionEnd";break b;case "compositionupdate":da="onCompositionUpdate";break b}da=void 0}else Rb?sh(a,c)&&(da="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(da="onCompositionStart");da&&(wh&&"ko"!==c.locale&&(Rb||"onCompositionStart"!==da?"onCompositionEnd"===da&&Rb&&(fb=qh()):(db=e,Ye=
"value"in db?db.value:db.textContent,Rb=!0)),wa=ud(d,da),0<wa.length&&(da=new Th(da,a,null,c,e),g.push({event:da,listeners:wa}),fb?da.data=fb:(fb=th(c),null!==fb&&(da.data=fb))));if(fb=Pk?tk(a,c):uk(a,c))d=ud(d,"onBeforeInput"),0<d.length&&(e=new Qk("onBeforeInput","beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=fb)}zh(g,b)})}function Hc(a,b,c){return{instance:a,listener:b,currentTarget:c}}function ud(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==
f&&(e=f,f=sc(a,c),null!=f&&d.unshift(Hc(a,f,e)),f=sc(a,b),null!=f&&d.push(Hc(a,f,e)));a=a.return}return d}function Vb(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}function Rh(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,n=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==n&&(h=n,e?(k=sc(c,f),null!=k&&g.unshift(Hc(c,k,h))):e||(k=sc(c,f),null!=k&&g.push(Hc(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}function Uh(a){return("string"===
typeof a?a:""+a).replace(Rk,"\n").replace(Sk,"")}function zd(a,b,c,d){b=Uh(b);if(Uh(a)!==b&&c)throw Error(m(425));}function Ad(){}function lf(a,b){return"textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}function Tk(a){setTimeout(function(){throw a;})}function mf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=
e.data,"/$"===c){if(0===d){a.removeChild(e);Bc(b);return}d--}else"$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e}while(c);Bc(b)}function Oa(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}function Vh(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--}else"/$"===c&&b++}a=a.previousSibling}return null}function ub(a){var b=a[Ea];
if(b)return b;for(var c=a.parentNode;c;){if(b=c[Ma]||c[Ea]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Vh(a);null!==a;){if(c=a[Ea])return c;a=Vh(a)}return b}a=c;c=a.parentNode}return null}function rc(a){a=a[Ea]||a[Ma];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Sb(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(m(33));}function fd(a){return a[Ic]||null}function gb(a){return{current:a}}function t(a,b){0>Wb||(a.current=nf[Wb],nf[Wb]=null,Wb--)}
function E(a,b,c){Wb++;nf[Wb]=a.current;a.current=b}function Xb(a,b){var c=a.type.contextTypes;if(!c)return hb;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function ea(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Wh(a,b,c){if(K.current!==hb)throw Error(m(168));
E(K,b);E(T,c)}function Xh(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(m(108,Nj(a)||"Unknown",e));return D({},c,d)}function Bd(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||hb;vb=K.current;E(K,a);E(T,T.current);return!0}function Yh(a,b,c){var d=a.stateNode;if(!d)throw Error(m(169));c?(a=Xh(a,b,vb),d.__reactInternalMemoizedMergedChildContext=a,t(T),t(K),E(K,a)):t(T);
E(T,c)}function Zh(a){null===Pa?Pa=[a]:Pa.push(a)}function Uk(a){Cd=!0;Zh(a)}function ib(){if(!of&&null!==Pa){of=!0;var a=0,b=x;try{var c=Pa;for(x=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}Pa=null;Cd=!1}catch(e){throw null!==Pa&&(Pa=Pa.slice(a+1)),$h(jd,ib),e;}finally{x=b,of=!1}}return null}function wb(a,b){Yb[Zb++]=Dd;Yb[Zb++]=Ed;Ed=a;Dd=b}function ai(a,b,c){oa[pa++]=Qa;oa[pa++]=Ra;oa[pa++]=xb;xb=a;var d=Qa;a=Ra;var e=32-ka(d)-1;d&=~(1<<e);c+=1;var f=32-ka(b)+e;if(30<f){var g=e-e%5;
f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;Qa=1<<32-ka(b)+e|c<<e|d;Ra=f+a}else Qa=1<<f|c<<e|d,Ra=a}function pf(a){null!==a.return&&(wb(a,1),ai(a,1,0))}function qf(a){for(;a===Ed;)Ed=Yb[--Zb],Yb[Zb]=null,Dd=Yb[--Zb],Yb[Zb]=null;for(;a===xb;)xb=oa[--pa],oa[pa]=null,Ra=oa[--pa],oa[pa]=null,Qa=oa[--pa],oa[pa]=null}function bi(a,b){var c=qa(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}function ci(a,b){switch(a.tag){case 5:var c=
a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,ma=a,fa=Oa(b.firstChild),!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,ma=a,fa=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==xb?{id:Qa,overflow:Ra}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=qa(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,ma=a,fa=null,!0):!1;default:return!1}}function rf(a){return 0!==
(a.mode&1)&&0===(a.flags&128)}function sf(a){if(C){var b=fa;if(b){var c=b;if(!ci(a,b)){if(rf(a))throw Error(m(418));b=Oa(c.nextSibling);var d=ma;b&&ci(a,b)?bi(d,c):(a.flags=a.flags&-4097|2,C=!1,ma=a)}}else{if(rf(a))throw Error(m(418));a.flags=a.flags&-4097|2;C=!1;ma=a}}}function di(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;ma=a}function Fd(a){if(a!==ma)return!1;if(!C)return di(a),C=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!lf(a.type,
a.memoizedProps));if(b&&(b=fa)){if(rf(a)){for(a=fa;a;)a=Oa(a.nextSibling);throw Error(m(418));}for(;b;)bi(a,b),b=Oa(b.nextSibling)}di(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(m(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){fa=Oa(a.nextSibling);break a}b--}else"$"!==c&&"$!"!==c&&"$?"!==c||b++}a=a.nextSibling}fa=null}}else fa=ma?Oa(a.stateNode.nextSibling):null;return!0}function $b(){fa=ma=null;C=!1}function tf(a){null===
xa?xa=[a]:xa.push(a)}function Jc(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(m(309));var d=c.stateNode}if(!d)throw Error(m(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if("string"!==typeof a)throw Error(m(284));if(!c._owner)throw Error(m(290,a));}return a}function Gd(a,b){a=
Object.prototype.toString.call(b);throw Error(m(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function ei(a){var b=a._init;return b(a._payload)}function fi(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=jb(a,b);a.index=
0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=uf(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===Kb)return l(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ya&&
ei(f)===b.type))return d=e(b,c.props),d.ref=Jc(a,b,c),d.return=a,d;d=Hd(c.type,c.key,c.props,null,a.mode,d);d.ref=Jc(a,b,c);d.return=a;return d}function n(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=vf(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function l(a,b,c,d,f){if(null===b||7!==b.tag)return b=yb(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function u(a,b,c){if("string"===
typeof b&&""!==b||"number"===typeof b)return b=uf(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case Id:return c=Hd(b.type,b.key,b.props,null,a.mode,c),c.ref=Jc(a,null,b),c.return=a,c;case Lb:return b=vf(b,a.mode,c),b.return=a,b;case Ya:var d=b._init;return u(a,d(b._payload),c)}if(pc(b)||nc(b))return b=yb(b,a.mode,c,null),b.return=a,b;Gd(a,b)}return null}function p(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==
e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Id:return c.key===e?k(a,b,c,d):null;case Lb:return c.key===e?n(a,b,c,d):null;case Ya:return e=c._init,p(a,b,e(c._payload),d)}if(pc(c)||nc(c))return null!==e?null:l(a,b,c,d,null);Gd(a,c)}return null}function jf(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Id:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,
e);case Lb:return a=a.get(null===d.key?c:d.key)||null,n(b,a,d,e);case Ya:var f=d._init;return jf(a,b,c,f(d._payload),e)}if(pc(d)||nc(d))return a=a.get(c)||null,l(b,a,d,e,null);Gd(b,d)}return null}function v(e,g,h,k){for(var n=null,m=null,l=g,r=g=0,y=null;null!==l&&r<h.length;r++){l.index>r?(y=l,l=null):y=l.sibling;var N=p(e,l,h[r],k);if(null===N){null===l&&(l=y);break}a&&l&&null===N.alternate&&b(e,l);g=f(N,g,r);null===m?n=N:m.sibling=N;m=N;l=y}if(r===h.length)return c(e,l),C&&wb(e,r),n;if(null===
l){for(;r<h.length;r++)l=u(e,h[r],k),null!==l&&(g=f(l,g,r),null===m?n=l:m.sibling=l,m=l);C&&wb(e,r);return n}for(l=d(e,l);r<h.length;r++)y=jf(l,e,r,h[r],k),null!==y&&(a&&null!==y.alternate&&l.delete(null===y.key?r:y.key),g=f(y,g,r),null===m?n=y:m.sibling=y,m=y);a&&l.forEach(function(a){return b(e,a)});C&&wb(e,r);return n}function w(e,g,h,k){var n=nc(h);if("function"!==typeof n)throw Error(m(150));h=n.call(h);if(null==h)throw Error(m(151));for(var l=n=null,r=g,N=g=0,y=null,q=h.next();null!==r&&!q.done;N++,
q=h.next()){r.index>N?(y=r,r=null):y=r.sibling;var B=p(e,r,q.value,k);if(null===B){null===r&&(r=y);break}a&&r&&null===B.alternate&&b(e,r);g=f(B,g,N);null===l?n=B:l.sibling=B;l=B;r=y}if(q.done)return c(e,r),C&&wb(e,N),n;if(null===r){for(;!q.done;N++,q=h.next())q=u(e,q.value,k),null!==q&&(g=f(q,g,N),null===l?n=q:l.sibling=q,l=q);C&&wb(e,N);return n}for(r=d(e,r);!q.done;N++,q=h.next())q=jf(r,e,N,q.value,k),null!==q&&(a&&null!==q.alternate&&r.delete(null===q.key?N:q.key),g=f(q,g,N),null===l?n=q:l.sibling=
q,l=q);a&&r.forEach(function(a){return b(e,a)});C&&wb(e,N);return n}function t(a,d,f,h){"object"===typeof f&&null!==f&&f.type===Kb&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case Id:a:{for(var k=f.key,n=d;null!==n;){if(n.key===k){k=f.type;if(k===Kb){if(7===n.tag){c(a,n.sibling);d=e(n,f.props.children);d.return=a;a=d;break a}}else if(n.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ya&&ei(k)===n.type){c(a,n.sibling);d=e(n,f.props);d.ref=Jc(a,
n,f);d.return=a;a=d;break a}c(a,n);break}else b(a,n);n=n.sibling}f.type===Kb?(d=yb(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Hd(f.type,f.key,f.props,null,a.mode,h),h.ref=Jc(a,d,f),h.return=a,a=h)}return g(a);case Lb:a:{for(n=f.key;null!==d;){if(d.key===n)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=vf(f,a.mode,h);d.return=a;
a=d}return g(a);case Ya:return n=f._init,t(a,d,n(f._payload),h)}if(pc(f))return v(a,d,f,h);if(nc(f))return w(a,d,f,h);Gd(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=uf(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return t}function wf(){xf=ac=Jd=null}function yf(a,b){b=Kd.current;t(Kd);a._currentValue=b}function zf(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=
b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}function bc(a,b){Jd=a;xf=ac=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(ha=!0),a.firstContext=null)}function ra(a){var b=a._currentValue;if(xf!==a)if(a={context:a,memoizedValue:b,next:null},null===ac){if(null===Jd)throw Error(m(308));ac=a;Jd.dependencies={lanes:0,firstContext:a}}else ac=ac.next=a;return b}function Af(a){null===zb?zb=[a]:zb.push(a)}function gi(a,b,c,d){var e=b.interleaved;
null===e?(c.next=c,Af(b)):(c.next=e.next,e.next=c);b.interleaved=c;return Sa(a,d)}function Sa(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}function Bf(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function hi(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue=
{baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Ta(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}function kb(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(w&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return Vk(a,c)}e=d.interleaved;null===e?(b.next=b,Af(d)):(b.next=e.next,e.next=b);d.interleaved=b;return Sa(a,c)}function Ld(a,b,c){b=
b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Se(a,c)}}function ii(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,
shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=b;c.lastBaseUpdate=b}function Md(a,b,c,d){var e=a.updateQueue;lb=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,n=k.next;k.next=null;null===g?f=n:g.next=n;g=k;var l=a.alternate;null!==l&&(l=l.updateQueue,h=l.lastBaseUpdate,h!==g&&(null===h?l.firstBaseUpdate=n:h.next=n,l.lastBaseUpdate=k))}if(null!==f){var m=e.baseState;g=0;l=
n=k=null;h=f;do{var q=h.lane,p=h.eventTime;if((d&q)===q){null!==l&&(l=l.next={eventTime:p,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,next:null});a:{var v=a,t=h;q=b;p=c;switch(t.tag){case 1:v=t.payload;if("function"===typeof v){m=v.call(p,m,q);break a}m=v;break a;case 3:v.flags=v.flags&-65537|128;case 0:v=t.payload;q="function"===typeof v?v.call(p,m,q):v;if(null===q||void 0===q)break a;m=D({},m,q);break a;case 2:lb=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,q=e.effects,null===q?e.effects=
[h]:q.push(h))}else p={eventTime:p,lane:q,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===l?(n=l=p,k=m):l=l.next=p,g|=q;h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else q=h,h=q.next,q.next=null,e.lastBaseUpdate=q,e.shared.pending=null}while(1);null===l&&(k=m);e.baseState=k;e.firstBaseUpdate=n;e.lastBaseUpdate=l;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);sa|=g;a.lanes=g;a.memoizedState=m}}function ji(a,
b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(m(191,e));e.call(d)}}}function Ab(a){if(a===Kc)throw Error(m(174));return a}function Cf(a,b){E(Lc,b);E(Mc,a);E(Fa,Kc);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:He(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=He(b,a)}t(Fa);E(Fa,b)}function cc(a){t(Fa);t(Mc);t(Lc)}function ki(a){Ab(Lc.current);
var b=Ab(Fa.current);var c=He(b,a.type);b!==c&&(E(Mc,a),E(Fa,c))}function Df(a){Mc.current===a&&(t(Fa),t(Mc))}function Nd(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=
b.return;b=b.sibling}return null}function Ef(){for(var a=0;a<Ff.length;a++)Ff[a]._workInProgressVersionPrimary=null;Ff.length=0}function X(){throw Error(m(321));}function Gf(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!va(a[c],b[c]))return!1;return!0}function Hf(a,b,c,d,e,f){Bb=f;z=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Od.current=null===a||null===a.memoizedState?Wk:Xk;a=c(d,e);if(Nc){f=0;do{Nc=!1;Oc=0;if(25<=f)throw Error(m(301));f+=1;O=L=null;b.updateQueue=null;
Od.current=Yk;a=c(d,e)}while(Nc)}Od.current=Pd;b=null!==L&&null!==L.next;Bb=0;O=L=z=null;Qd=!1;if(b)throw Error(m(300));return a}function If(){var a=0!==Oc;Oc=0;return a}function Ga(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===O?z.memoizedState=O=a:O=O.next=a;return O}function ta(){if(null===L){var a=z.alternate;a=null!==a?a.memoizedState:null}else a=L.next;var b=null===O?z.memoizedState:O.next;if(null!==b)O=b,L=a;else{if(null===a)throw Error(m(310));L=a;
a={memoizedState:L.memoizedState,baseState:L.baseState,baseQueue:L.baseQueue,queue:L.queue,next:null};null===O?z.memoizedState=O=a:O=O.next=a}return O}function Pc(a,b){return"function"===typeof b?b(a):b}function Jf(a,b,c){b=ta();c=b.queue;if(null===c)throw Error(m(311));c.lastRenderedReducer=a;var d=L,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,n=f;do{var l=n.lane;if((Bb&
l)===l)null!==k&&(k=k.next={lane:0,action:n.action,hasEagerState:n.hasEagerState,eagerState:n.eagerState,next:null}),d=n.hasEagerState?n.eagerState:a(d,n.action);else{var p={lane:l,action:n.action,hasEagerState:n.hasEagerState,eagerState:n.eagerState,next:null};null===k?(h=k=p,g=d):k=k.next=p;z.lanes|=l;sa|=l}n=n.next}while(null!==n&&n!==f);null===k?g=d:k.next=h;va(d,b.memoizedState)||(ha=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=
e.lane,z.lanes|=f,sa|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}function Kf(a,b,c){b=ta();c=b.queue;if(null===c)throw Error(m(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);va(f,b.memoizedState)||(ha=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function li(a,b,c){}function mi(a,b,c){c=z;var d=ta(),
e=b(),f=!va(d.memoizedState,e);f&&(d.memoizedState=e,ha=!0);d=d.queue;Lf(ni.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==O&&O.memoizedState.tag&1){c.flags|=2048;Qc(9,oi.bind(null,c,d,e,b),void 0,null);if(null===P)throw Error(m(349));0!==(Bb&30)||pi(c,b,e)}return e}function pi(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=z.updateQueue;null===b?(b={lastEffect:null,stores:null},z.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}function oi(a,b,c,d){b.value=c;b.getSnapshot=
d;qi(b)&&ri(a)}function ni(a,b,c){return c(function(){qi(b)&&ri(a)})}function qi(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!va(a,c)}catch(d){return!0}}function ri(a){var b=Sa(a,1);null!==b&&ya(b,a,1,-1)}function si(a){var b=Ga();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Pc,lastRenderedState:a};b.queue=a;a=a.dispatch=Zk.bind(null,z,a);return[b.memoizedState,a]}function Qc(a,b,c,d){a={tag:a,create:b,
destroy:c,deps:d,next:null};b=z.updateQueue;null===b?(b={lastEffect:null,stores:null},z.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function ti(a){return ta().memoizedState}function Rd(a,b,c,d){var e=Ga();z.flags|=a;e.memoizedState=Qc(1|b,c,void 0,void 0===d?null:d)}function Sd(a,b,c,d){var e=ta();d=void 0===d?null:d;var f=void 0;if(null!==L){var g=L.memoizedState;f=g.destroy;if(null!==d&&Gf(d,g.deps)){e.memoizedState=
Qc(b,c,f,d);return}}z.flags|=a;e.memoizedState=Qc(1|b,c,f,d)}function ui(a,b){return Rd(8390656,8,a,b)}function Lf(a,b){return Sd(2048,8,a,b)}function vi(a,b){return Sd(4,2,a,b)}function wi(a,b){return Sd(4,4,a,b)}function xi(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function yi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Sd(4,4,xi.bind(null,b,a),c)}function Mf(a,b){}function zi(a,b){var c=
ta();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Gf(b,d[1]))return d[0];c.memoizedState=[a,b];return a}function Ai(a,b){var c=ta();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Gf(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Bi(a,b,c){if(0===(Bb&21))return a.baseState&&(a.baseState=!1,ha=!0),a.memoizedState=c;va(c,b)||(c=fh(),z.lanes|=c,sa|=c,a.baseState=!0);return b}function $k(a,b,c){c=x;x=0!==c&&4>c?c:4;a(!0);var d=Nf.transition;Nf.transition=
{};try{a(!1),b()}finally{x=c,Nf.transition=d}}function Ci(){return ta().memoizedState}function al(a,b,c){var d=mb(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Di(a))Ei(b,c);else if(c=gi(a,b,c,d),null!==c){var e=aa();ya(c,a,d,e);Fi(c,b,d)}kd(a,d)}function Zk(a,b,c){var d=mb(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Di(a))Ei(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,
h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(va(h,g)){var k=b.interleaved;null===k?(e.next=e,Af(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(n){}finally{}c=gi(a,b,e,d);null!==c&&(e=aa(),ya(c,a,d,e),Fi(c,b,d))}kd(a,d)}function Di(a){var b=a.alternate;return a===z||null!==b&&b===z}function Ei(a,b){Nc=Qd=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Fi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Se(a,c)}}function Td(a,
b){if(0<=Cb){var c=na()-Cb;a.actualDuration+=c;b&&(a.selfBaseDuration=c);Cb=-1}}function Ha(a){if(0<=Ud){var b=na()-Ud;Ud=-1;for(a=a.return;null!==a;){switch(a.tag){case 3:a.stateNode.effectDuration+=b;return;case 12:a.stateNode.effectDuration+=b;return}a=a.return}}}function Of(a){if(0<=dc){var b=na()-dc;dc=-1;for(a=a.return;null!==a;){switch(a.tag){case 3:a=a.stateNode;null!==a&&(a.passiveEffectDuration+=b);return;case 12:a=a.stateNode;null!==a&&(a.passiveEffectDuration+=b);return}a=a.return}}}function Ia(){Ud=
na()}function Pf(a){for(var b=a.child;b;)a.actualDuration+=b.actualDuration,b=b.sibling}function za(a,b){if(a&&a.defaultProps){b=D({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function Qf(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:D({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}function Gi(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?
!Ec(c,d)||!Ec(e,f):!0}function Hi(a,b,c){var d=!1,e=hb;var f=b.contextType;"object"===typeof f&&null!==f?f=ra(f):(e=ea(b)?vb:K.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Xb(a,e):hb);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Vd;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}function Ii(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&
b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Vd.enqueueReplaceState(b,b.state,null)}function Rf(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs={};Bf(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=ra(f):(f=ea(b)?vb:K.current,e.context=Xb(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(Qf(a,b,f,c),e.state=a.memoizedState);"function"===
typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Vd.enqueueReplaceState(e,e.state,null),Md(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308)}function ec(a,b){try{var c=
"",d=b;do c+=Mj(d),d=d.return;while(d);var e=c}catch(f){e="\nError generating stack: "+f.message+"\n"+f.stack}return{value:a,source:b,stack:e,digest:null}}function Sf(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}function Tf(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}function Ji(a,b,c){c=Ta(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Wd||(Wd=!0,Uf=d);Tf(a,b)};return c}function Ki(a,b,c){c=Ta(-1,c);c.tag=
3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Tf(a,b)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){Tf(a,b);"function"!==typeof d&&(null===nb?nb=new Set([this]):nb.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}function Li(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new bl;var e=new Set;d.set(b,e)}else e=
d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),d=cl.bind(null,a,b,c),ua&&Rc(a,c),b.then(d,d))}function Mi(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}function Ni(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=Ta(-1,1),b.tag=2,kb(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}function ba(a,
b,c,d){b.child=null===a?Oi(b,null,c,d):fc(b,a.child,c,d)}function Pi(a,b,c,d,e){c=c.render;var f=b.ref;bc(b,e);uc(b);d=Hf(a,b,c,d,f,e);c=If();Pb();if(null!==a&&!ha)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Ua(a,b,e);C&&c&&pf(b);b.flags|=1;ba(a,b,d,e);return b.child}function Qi(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!Vf(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,Ri(a,b,f,d,e);a=Hd(c.type,null,d,b,b.mode,
e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ec;if(c(g,d)&&a.ref===b.ref)return Ua(a,b,e)}b.flags|=1;a=jb(f,d);a.ref=b.ref;a.return=b;return b.child=a}function Ri(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ec(f,d)&&a.ref===b.ref)if(ha=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(ha=!0);else return b.lanes=a.lanes,Ua(a,b,e)}return Wf(a,b,c,d,e)}function Si(a,b,c){var d=b.pendingProps,e=d.children,f=null!==
a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},E(Ja,U),U|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,E(Ja,U),U|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;E(Ja,U);U|=d}else null!==f?(d=f.baseLanes|c,b.memoizedState=null):d=c,E(Ja,U),U|=d;ba(a,
b,e,c);return b.child}function Ti(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function Wf(a,b,c,d,e){var f=ea(c)?vb:K.current;f=Xb(b,f);bc(b,e);uc(b);c=Hf(a,b,c,d,f,e);d=If();Pb();if(null!==a&&!ha)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Ua(a,b,e);C&&d&&pf(b);b.flags|=1;ba(a,b,c,e);return b.child}function Ui(a,b,c,d,e){if(ea(c)){var f=!0;Bd(b)}else f=!1;bc(b,e);if(null===b.stateNode)Xd(a,b),Hi(b,c,d),Rf(b,c,d,e),d=!0;else if(null===
a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,n=c.contextType;"object"===typeof n&&null!==n?n=ra(n):(n=ea(c)?vb:K.current,n=Xb(b,n));var l=c.getDerivedStateFromProps,m="function"===typeof l||"function"===typeof g.getSnapshotBeforeUpdate;m||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==n)&&Ii(b,g,d,n);lb=!1;var q=b.memoizedState;g.state=q;Md(b,d,g,e);k=b.memoizedState;h!==d||q!==k||T.current||lb?("function"===
typeof l&&(Qf(b,c,l,d),k=b.memoizedState),(h=lb||Gi(b,c,h,d,q,k,n))?(m||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=n,d=
h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;hi(a,b);h=b.memoizedProps;n=b.type===b.elementType?h:za(b.type,h);g.props=n;m=b.pendingProps;q=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=ra(k):(k=ea(c)?vb:K.current,k=Xb(b,k));var p=c.getDerivedStateFromProps;(l="function"===typeof p||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==m||
q!==k)&&Ii(b,g,d,k);lb=!1;q=b.memoizedState;g.state=q;Md(b,d,g,e);var v=b.memoizedState;h!==m||q!==v||T.current||lb?("function"===typeof p&&(Qf(b,c,p,d),v=b.memoizedState),(n=lb||Gi(b,c,n,d,q,v,k)||!1)?(l||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,v,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,v,k)),"function"===typeof g.componentDidUpdate&&
(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&q===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&q===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=v),g.props=d,g.state=v,g.context=k,d=n):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&q===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===
a.memoizedProps&&q===a.memoizedState||(b.flags|=1024),d=!1)}return Xf(a,b,c,d,f,e)}function Xf(a,b,c,d,e,f){Ti(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&Yh(b,c,!1),Ua(a,b,f);d=b.stateNode;dl.current=b;if(g&&"function"!==typeof c.getDerivedStateFromError){var h=null;Cb=-1}else uc(b),h=d.render(),Pb();b.flags|=1;null!==a&&g?(g=h,b.child=fc(b,a.child,null,f),b.child=fc(b,null,g,f)):ba(a,b,h,f);b.memoizedState=d.state;e&&Yh(b,c,!0);return b.child}function Vi(a){var b=a.stateNode;b.pendingContext?
Wh(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Wh(a,b.context,!1);Cf(a,b.containerInfo)}function Wi(a,b,c,d,e){$b();tf(e);b.flags|=256;ba(a,b,c,d);return b.child}function Yf(a){return{baseLanes:a,cachePool:null,transitions:null}}function Xi(a,b,c){var d=b.pendingProps,e=H.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;E(H,e&1);if(null===a){sf(b);a=b.memoizedState;if(null!==
a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=g,b.mode&2&&(f.actualDuration=0,f.actualStartTime=-1,f.selfBaseDuration=0,f.treeBaseDuration=0)):f=Yd(g,d,0,null),a=yb(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=Yf(c),b.memoizedState=Zf,a):$f(b,g)}e=a.memoizedState;if(null!==
e&&(h=e.dehydrated,null!==h))return el(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.mode&2&&(d.actualDuration=0,d.actualStartTime=-1,d.selfBaseDuration=e.selfBaseDuration,d.treeBaseDuration=e.treeBaseDuration),b.deletions=null):(d=jb(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=jb(h,f):(f=yb(f,g,c,null),f.flags|=2);f.return=b;d.return=b;d.sibling=f;b.child=d;
d=f;f=b.child;g=a.child.memoizedState;g=null===g?Yf(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=Zf;return d}f=a.child;a=f.sibling;d=jb(f,{mode:"visible",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}function $f(a,b,c){b=Yd({mode:"visible",children:b},a.mode,0,null);b.return=
a;return a.child=b}function Zd(a,b,c,d){null!==d&&tf(d);fc(b,a.child,null,c);a=$f(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}function el(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Sf(Error(m(422))),Zd(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=Yd({mode:"visible",children:d.children},e,0,null);f=yb(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&fc(b,a.child,null,g);
b.child.memoizedState=Yf(g);b.memoizedState=Zf;return f}if(0===(b.mode&1))return Zd(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;if(d)var h=d.dgst;d=h;f=Error(m(419));d=Sf(f,d,void 0);return Zd(a,b,g,d)}h=0!==(g&a.childLanes);if(ha||h){d=P;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=
32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;0!==e&&e!==f.retryLane&&(f.retryLane=e,Sa(a,e),ya(d,a,e,-1))}ag();d=Sf(Error(m(421)));return Zd(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=fl.bind(null,a),e._reactRetry=b,null;a=f.treeContext;fa=Oa(e.nextSibling);ma=b;C=!0;xa=null;null!==a&&(oa[pa++]=Qa,oa[pa++]=Ra,oa[pa++]=xb,Qa=a.id,Ra=a.overflow,xb=b);b=$f(b,d.children);b.flags|=4096;return b}function Yi(a,b,c){a.lanes|=b;var d=a.alternate;
null!==d&&(d.lanes|=b);zf(a.return,b,c)}function bg(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}function Zi(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;ba(a,b,d.children,c);d=H.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&
Yi(a,c,b);else if(19===a.tag)Yi(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}E(H,d);if(0===(b.mode&1))b.memoizedState=null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Nd(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);bg(b,!1,e,c,f);break;case "backwards":c=
null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Nd(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}bg(b,!0,c,null,f);break;case "together":bg(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}function Xd(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function Ua(a,b,c){null!==a&&(b.dependencies=a.dependencies);Cb=-1;sa|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(m(153));
if(null!==b.child){a=b.child;c=jb(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=jb(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}function gl(a,b,c){switch(b.tag){case 3:Vi(b);$b();break;case 5:ki(b);break;case 1:ea(b.type)&&Bd(b);break;case 4:Cf(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;E(Kd,d._currentValue);d._currentValue=e;break;case 12:0!==(c&b.childLanes)&&(b.flags|=4);d=b.stateNode;d.effectDuration=
0;d.passiveEffectDuration=0;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return E(H,H.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return Xi(a,b,c);E(H,H.current&1);a=Ua(a,b,c);return null!==a?a.sibling:null}E(H,H.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return Zi(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);E(H,H.current);if(d)break;else return null;case 22:case 23:return b.lanes=
0,Si(a,b,c)}return Ua(a,b,c)}function Sc(a,b){if(!C)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}function V(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)if(0!==(a.mode&2)){for(var e=a.selfBaseDuration,f=a.child;null!==
f;)c|=f.lanes|f.childLanes,d|=f.subtreeFlags&14680064,d|=f.flags&14680064,e+=f.treeBaseDuration,f=f.sibling;a.treeBaseDuration=e}else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else if(0!==(a.mode&2)){e=a.actualDuration;f=a.selfBaseDuration;for(var g=a.child;null!==g;)c|=g.lanes|g.childLanes,d|=g.subtreeFlags,d|=g.flags,e+=g.actualDuration,f+=g.treeBaseDuration,g=g.sibling;a.actualDuration=e;a.treeBaseDuration=f}else for(e=
a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}function $i(a,b,c){var d=b.pendingProps;qf(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return V(b),null;case 1:return ea(b.type)&&(t(T),t(K)),V(b),null;case 3:d=b.stateNode;cc();t(T);t(K);Ef();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Fd(b)?b.flags|=4:null===a||
a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==xa&&(cg(xa),xa=null));aj(a,b);V(b);return null;case 5:Df(b);var e=Ab(Lc.current);c=b.type;if(null!==a&&null!=b.stateNode)hl(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(m(166));V(b);return null}a=Ab(Fa.current);if(Fd(b)){d=b.stateNode;a=b.type;c=b.memoizedProps;d[Ea]=b;d[Ic]=c;var f=0!==(b.mode&1);switch(a){case "dialog":A("cancel",d);A("close",d);break;case "iframe":case "object":case "embed":A("load",
d);break;case "video":case "audio":for(e=0;e<Tc.length;e++)A(Tc[e],d);break;case "source":A("error",d);break;case "img":case "image":case "link":A("error",d);A("load",d);break;case "details":A("toggle",d);break;case "input":Ig(d,c);A("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!c.multiple};A("invalid",d);break;case "textarea":Lg(d,c),A("invalid",d)}Ie(a,c);e=null;for(var g in c)if(c.hasOwnProperty(g)){var h=c[g];"children"===g?"string"===typeof h?d.textContent!==h&&(!0!==c.suppressHydrationWarning&&
zd(d.textContent,h,f),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(!0!==c.suppressHydrationWarning&&zd(d.textContent,h,f),e=["children",""+h]):mc.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&A("scroll",d)}switch(a){case "input":dd(d);Kg(d,c,!0);break;case "textarea":dd(d);Ng(d);break;case "select":case "option":break;default:"function"===typeof c.onClick&&(d.onclick=Ad)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===
a&&(a=Og(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Ea]=b;a[Ic]=d;il(a,b,!1,!1);b.stateNode=a;a:{g=Je(c,d);switch(c){case "dialog":A("cancel",a);A("close",a);e=d;break;case "iframe":case "object":case "embed":A("load",a);e=d;break;
case "video":case "audio":for(e=0;e<Tc.length;e++)A(Tc[e],a);e=d;break;case "source":A("error",a);e=d;break;case "img":case "image":case "link":A("error",a);A("load",a);e=d;break;case "details":A("toggle",a);e=d;break;case "input":Ig(a,d);e=De(a,d);A("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=D({},d,{value:void 0});A("invalid",a);break;case "textarea":Lg(a,d);e=Ge(a,d);A("invalid",a);break;default:e=d}Ie(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=
h[f];"style"===f?Qg(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&bj(a,k)):"children"===f?"string"===typeof k?("textarea"!==c||""!==k)&&Uc(a,k):"number"===typeof k&&Uc(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(mc.hasOwnProperty(f)?null!=k&&"onScroll"===f&&A("scroll",a):null!=k&&se(a,f,k,g))}switch(c){case "input":dd(a);Kg(a,d,!1);break;case "textarea":dd(a);Ng(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Za(d.value));
break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?Mb(a,!!d.multiple,f,!1):null!=d.defaultValue&&Mb(a,!!d.multiple,d.defaultValue,!0);break;default:"function"===typeof e.onClick&&(a.onclick=Ad)}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}V(b);return null;case 6:if(a&&null!=b.stateNode)jl(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===
b.stateNode)throw Error(m(166));a=Ab(Lc.current);Ab(Fa.current);if(Fd(b)){d=b.stateNode;a=b.memoizedProps;d[Ea]=b;if(c=d.nodeValue!==a)if(f=ma,null!==f)switch(f.tag){case 3:zd(d.nodeValue,a,0!==(f.mode&1));break;case 5:!0!==f.memoizedProps.suppressHydrationWarning&&zd(d.nodeValue,a,0!==(f.mode&1))}c&&(b.flags|=4)}else d=(9===a.nodeType?a:a.ownerDocument).createTextNode(d),d[Ea]=b,b.stateNode=d}V(b);return null;case 13:t(H);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(C&&
null!==fa&&0!==(b.mode&1)&&0===(b.flags&128)){for(f=fa;f;)f=Oa(f.nextSibling);$b();b.flags|=98560;f=!1}else if(f=Fd(b),null!==d&&null!==d.dehydrated){if(null===a){if(!f)throw Error(m(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(m(317));f[Ea]=b;V(b);0!==(b.mode&2)&&null!==d&&(f=b.child,null!==f&&(b.treeBaseDuration-=f.treeBaseDuration))}else $b(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4,V(b),0!==(b.mode&2)&&null!==d&&(f=b.child,null!==f&&(b.treeBaseDuration-=f.treeBaseDuration));
f=!1}else null!==xa&&(cg(xa),xa=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,0!==(b.mode&2)&&Pf(b),b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(H.current&1)?0===G&&(G=3):ag()));null!==b.updateQueue&&(b.flags|=4);V(b);0!==(b.mode&2)&&d&&(d=b.child,null!==d&&(b.treeBaseDuration-=d.treeBaseDuration));return null;case 4:return cc(),aj(a,b),null===a&&Gc(b.stateNode.containerInfo),V(b),null;case 10:return yf(b.type._context),
V(b),null;case 17:return ea(b.type)&&(t(T),t(K)),V(b),null;case 19:t(H);f=b.memoizedState;if(null===f)return V(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Sc(f,!1);else{if(0!==G||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Nd(a);if(null!==g){b.flags|=128;Sc(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(a=b.child;null!==a;)c=a,g=d,c.flags&=14680066,f=c.alternate,null===f?(c.childLanes=0,c.lanes=g,c.child=null,c.subtreeFlags=0,c.memoizedProps=
null,c.memoizedState=null,c.updateQueue=null,c.dependencies=null,c.stateNode=null,c.selfBaseDuration=0,c.treeBaseDuration=0):(c.childLanes=f.childLanes,c.lanes=f.lanes,c.child=f.child,c.subtreeFlags=0,c.deletions=null,c.memoizedProps=f.memoizedProps,c.memoizedState=f.memoizedState,c.updateQueue=f.updateQueue,c.type=f.type,g=f.dependencies,c.dependencies=null===g?null:{lanes:g.lanes,firstContext:g.firstContext},c.selfBaseDuration=f.selfBaseDuration,c.treeBaseDuration=f.treeBaseDuration),a=a.sibling;
E(H,H.current&1|2);return b.child}a=a.sibling}null!==f.tail&&Q()>dg&&(b.flags|=128,d=!0,Sc(f,!1),b.lanes=4194304)}else{if(!d)if(a=Nd(g),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),Sc(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!C)return V(b),null}else 2*Q()-f.renderingStartTime>dg&&1073741824!==c&&(b.flags|=128,d=!0,Sc(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(a=f.last,null!==a?a.sibling=g:b.child=g,f.last=g)}if(null!==
f.tail)return b=f.tail,f.rendering=b,f.tail=b.sibling,f.renderingStartTime=Q(),b.sibling=null,a=H.current,E(H,d?a&1|2:a&1),b;V(b);return null;case 22:case 23:return U=Ja.current,t(Ja),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(U&1073741824)&&(V(b),b.subtreeFlags&6&&(b.flags|=8192)):V(b),null;case 24:return null;case 25:return null}throw Error(m(156,b.tag));}function kl(a,b,c){qf(b);switch(b.tag){case 1:return ea(b.type)&&(t(T),t(K)),a=b.flags,
a&65536?(b.flags=a&-65537|128,0!==(b.mode&2)&&Pf(b),b):null;case 3:return cc(),t(T),t(K),Ef(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Df(b),null;case 13:t(H);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(m(340));$b()}a=b.flags;return a&65536?(b.flags=a&-65537|128,0!==(b.mode&2)&&Pf(b),b):null;case 19:return t(H),null;case 4:return cc(),null;case 10:return yf(b.type._context),null;case 22:case 23:return U=Ja.current,t(Ja),
null;case 24:return null;default:return null}}function gc(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{if(a.mode&2)try{Ia(),c(null)}finally{Ha(a)}else c(null)}catch(d){I(a,b,d)}else c.current=null}function $d(a,b,c){try{c()}catch(d){I(a,b,d)}}function ll(a,b){eg=pd;a=Fh();if(bf(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;
var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,n=0,l=0,u=a,q=null;b:for(;;){for(var t;;){u!==c||0!==e&&3!==u.nodeType||(h=g+e);u!==f||0!==d&&3!==u.nodeType||(k=g+d);3===u.nodeType&&(g+=u.nodeValue.length);if(null===(t=u.firstChild))break;q=u;u=t}for(;;){if(u===a)break b;q===c&&++n===e&&(h=g);q===f&&++l===d&&(k=g);if(null!==(t=u.nextSibling))break;u=q;q=u.parentNode}u=t}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,
end:0}}else c=null;fg={focusedElem:a,selectionRange:c};pd=!1;for(p=b;null!==p;)if(b=p,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,p=a;else for(;null!==p;){b=p;try{var v=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;case 1:if(null!==v){var w=v.memoizedProps,x=v.memoizedState,B=b.stateNode,y=B.getSnapshotBeforeUpdate(b.elementType===b.type?w:za(b.type,w),x);B.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var r=b.stateNode.containerInfo;1===r.nodeType?
r.textContent="":9===r.nodeType&&r.documentElement&&r.removeChild(r.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(m(163));}}catch(F){I(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;p=a;break}p=b.return}v=cj;cj=!1;return v}function Va(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&(0!==(a&8)?null!==l&&"function"===typeof l.markComponentPassiveEffectUnmountStarted&&
l.markComponentPassiveEffectUnmountStarted(b):0!==(a&4)&&bh(b),$d(b,c,f),0!==(a&8)?null!==l&&"function"===typeof l.markComponentPassiveEffectUnmountStopped&&l.markComponentPassiveEffectUnmountStopped():0!==(a&4)&&ch())}e=e.next}while(e!==d)}}function Db(a,b){var c=b.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do{if((d.tag&a)===a){0!==(a&8)?null!==l&&"function"===typeof l.markComponentPassiveEffectMountStarted&&l.markComponentPassiveEffectMountStarted(b):0!==(a&4)&&null!==
l&&"function"===typeof l.markComponentLayoutEffectMountStarted&&l.markComponentLayoutEffectMountStarted(b);var e=d.create;d.destroy=e();0!==(a&8)?null!==l&&"function"===typeof l.markComponentPassiveEffectMountStopped&&l.markComponentPassiveEffectMountStopped():0!==(a&4)&&null!==l&&"function"===typeof l.markComponentLayoutEffectMountStopped&&l.markComponentLayoutEffectMountStopped()}d=d.next}while(d!==c)}}function gg(a){var b=a.ref;if(null!==b){var c=a.stateNode;if("function"===typeof b)if(a.mode&
2)try{Ia(),b(c)}finally{Ha(a)}else b(c);else b.current=c}}function dj(a){var b=a.alternate;null!==b&&(a.alternate=null,dj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Ea],delete b[Ic],delete b[ff],delete b[ml],delete b[nl]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function ej(a){return 5===a.tag||3===a.tag||4===a.tag}function fj(a){a:for(;;){for(;null===
a.sibling;){if(null===a.return||ej(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function hg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,
null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Ad));else if(4!==d&&(a=a.child,null!==a))for(hg(a,b,c),a=a.sibling;null!==a;)hg(a,b,c),a=a.sibling}function ig(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(ig(a,b,c),a=a.sibling;null!==a;)ig(a,b,c),a=a.sibling}function ob(a,b,c){for(c=c.child;null!==c;)gj(a,b,c),c=c.sibling}function gj(a,b,c){if(Da&&"function"===typeof Da.onCommitFiberUnmount)try{Da.onCommitFiberUnmount(id,
c)}catch(h){}switch(c.tag){case 5:Y||gc(c,b);case 6:var d=W,e=Aa;W=null;ob(a,b,c);W=d;Aa=e;null!==W&&(Aa?(a=W,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):W.removeChild(c.stateNode));break;case 18:null!==W&&(Aa?(a=W,c=c.stateNode,8===a.nodeType?mf(a.parentNode,c):1===a.nodeType&&mf(a,c),Bc(a)):mf(W,c.stateNode));break;case 4:d=W;e=Aa;W=c.stateNode.containerInfo;Aa=!0;ob(a,b,c);W=d;Aa=e;break;case 0:case 11:case 14:case 15:if(!Y&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,
null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?$d(c,b,g):0!==(f&4)&&(bh(c),c.mode&2?(Ia(),$d(c,b,g),Ha(c)):$d(c,b,g),ch()));e=e.next}while(e!==d)}ob(a,b,c);break;case 1:if(!Y&&(gc(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{hj(c,d)}catch(h){I(c,b,h)}ob(a,b,c);break;case 21:ob(a,b,c);break;case 22:c.mode&1?(Y=(d=Y)||null!==c.memoizedState,ob(a,b,c),Y=d):ob(a,b,c);break;default:ob(a,b,c)}}function ij(a){var b=a.updateQueue;if(null!==b){a.updateQueue=
null;var c=a.stateNode;null===c&&(c=a.stateNode=new ol);b.forEach(function(b){var d=pl.bind(null,a,b);if(!c.has(b)){c.add(b);if(ua)if(null!==hc&&null!==ic)Rc(ic,hc);else throw Error(m(413));b.then(d,d)}})}}function ql(a,b,c){hc=c;ic=a;jj(b,a);ic=hc=null}function Ba(a,b,c){c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:W=h.stateNode;Aa=!1;break a;case 3:W=h.stateNode.containerInfo;Aa=!0;break a;case 4:W=h.stateNode.containerInfo;
Aa=!0;break a}h=h.return}if(null===W)throw Error(m(160));gj(f,g,e);W=null;Aa=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(n){I(e,b,n)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)jj(b,a),b=b.sibling}function jj(a,b,c){var d=a.alternate;c=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:Ba(b,a);Ka(a);if(c&4){try{Va(3,a,a.return),Db(3,a)}catch(v){I(a,a.return,v)}if(a.mode&2){try{Ia(),Va(5,a,a.return)}catch(v){I(a,a.return,v)}Ha(a)}else try{Va(5,a,a.return)}catch(v){I(a,
a.return,v)}}break;case 1:Ba(b,a);Ka(a);c&512&&null!==d&&gc(d,d.return);break;case 5:Ba(b,a);Ka(a);c&512&&null!==d&&gc(d,d.return);if(a.flags&32){var e=a.stateNode;try{Uc(e,"")}catch(v){I(a,a.return,v)}}if(c&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==d?d.memoizedProps:f,h=a.type,k=a.updateQueue;a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&Jg(e,f);Je(h,g);var n=Je(h,f);for(g=0;g<k.length;g+=2){var l=k[g],u=k[g+1];"style"===l?Qg(e,u):"dangerouslySetInnerHTML"===
l?bj(e,u):"children"===l?Uc(e,u):se(e,l,u,n)}switch(h){case "input":Ee(e,f);break;case "textarea":Mg(e,f);break;case "select":var q=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var t=f.value;null!=t?Mb(e,!!f.multiple,t,!1):q!==!!f.multiple&&(null!=f.defaultValue?Mb(e,!!f.multiple,f.defaultValue,!0):Mb(e,!!f.multiple,f.multiple?[]:"",!1))}e[Ic]=f}catch(v){I(a,a.return,v)}}break;case 6:Ba(b,a);Ka(a);if(c&4){if(null===a.stateNode)throw Error(m(162));e=a.stateNode;f=a.memoizedProps;
try{e.nodeValue=f}catch(v){I(a,a.return,v)}}break;case 3:Ba(b,a);Ka(a);if(c&4&&null!==d&&d.memoizedState.isDehydrated)try{Bc(b.containerInfo)}catch(v){I(a,a.return,v)}break;case 4:Ba(b,a);Ka(a);break;case 13:Ba(b,a);Ka(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||null!==e.alternate&&null!==e.alternate.memoizedState||(jg=Q()));c&4&&ij(a);break;case 22:l=null!==d&&null!==d.memoizedState;a.mode&1?(Y=(n=Y)||l,Ba(b,a),Y=n):Ba(b,a);Ka(a);if(c&8192){n=null!==a.memoizedState;
if((a.stateNode.isHidden=n)&&!l&&0!==(a.mode&1))for(p=a,l=a.child;null!==l;){for(u=p=l;null!==p;){q=p;t=q.child;switch(q.tag){case 0:case 11:case 14:case 15:if(q.mode&2)try{Ia(),Va(4,q,q.return)}finally{Ha(q)}else Va(4,q,q.return);break;case 1:gc(q,q.return);c=q.stateNode;if("function"===typeof c.componentWillUnmount){b=q;d=q.return;try{hj(b,c)}catch(v){I(b,d,v)}}break;case 5:gc(q,q.return);break;case 22:if(null!==q.memoizedState){kj(u);continue}}null!==t?(t.return=q,p=t):kj(u)}l=l.sibling}a:for(l=
null,u=a;;){if(5===u.tag){if(null===l){l=u;try{e=u.stateNode,n?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=u.stateNode,k=u.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=Pg("display",g))}catch(v){I(a,a.return,v)}}}else if(6===u.tag){if(null===l)try{u.stateNode.nodeValue=n?"":u.memoizedProps}catch(v){I(a,a.return,v)}}else if((22!==u.tag&&23!==u.tag||null===u.memoizedState||u===
a)&&null!==u.child){u.child.return=u;u=u.child;continue}if(u===a)break a;for(;null===u.sibling;){if(null===u.return||u.return===a)break a;l===u&&(l=null);u=u.return}l===u&&(l=null);u.sibling.return=u.return;u=u.sibling}}break;case 19:Ba(b,a);Ka(a);c&4&&ij(a);break;case 21:break;default:Ba(b,a),Ka(a)}}function Ka(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(ej(c)){var d=c;break a}c=c.return}throw Error(m(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(Uc(e,""),d.flags&=
-33);var f=fj(a);ig(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=fj(a);hg(a,h,g);break;default:throw Error(m(161));}}catch(k){I(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function rl(a,b,c){hc=c;ic=b;p=a;lj(a,b,c);ic=hc=null}function lj(a,b,c){for(var d=0!==(a.mode&1);null!==p;){var e=p,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||ae;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||Y;h=ae;var l=Y;ae=g;if((Y=k)&&!l)for(p=e;null!==p;)g=p,k=g.child,22===
g.tag&&null!==g.memoizedState?mj(e):null!==k?(k.return=g,p=k):mj(e);for(;null!==f;)p=f,lj(f,b,c),f=f.sibling;p=e;ae=h;Y=l}nj(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,p=f):nj(a,b,c)}}function nj(a,b,c){for(;null!==p;){b=p;if(0!==(b.flags&8772)){var d=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:if(!Y)if(b.mode&2)try{Ia(),Db(5,b)}finally{Ha(b)}else Db(5,b);break;case 1:var e=b.stateNode;if(b.flags&4&&!Y)if(null===d)if(b.mode&2)try{Ia(),e.componentDidMount()}finally{Ha(b)}else e.componentDidMount();
else{var f=b.elementType===b.type?d.memoizedProps:za(b.type,d.memoizedProps),g=d.memoizedState;if(b.mode&2)try{Ia(),e.componentDidUpdate(f,g,e.__reactInternalSnapshotBeforeUpdate)}finally{Ha(b)}else e.componentDidUpdate(f,g,e.__reactInternalSnapshotBeforeUpdate)}var h=b.updateQueue;null!==h&&ji(b,h,e);break;case 3:var k=b.updateQueue;if(null!==k){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=b.child.stateNode;break;case 1:c=b.child.stateNode}ji(b,k,c)}break;case 5:var l=b.stateNode;if(null===
d&&b.flags&4){c=l;var t=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":t.autoFocus&&c.focus();break;case "img":t.src&&(c.src=t.src)}}break;case 6:break;case 4:break;case 12:var u=b.memoizedProps,q=u.onCommit,w=u.onRender,v=b.stateNode.effectDuration;c=be;d=null===d?"mount":"update";ce&&(d="nested-update");"function"===typeof w&&w(b.memoizedProps.id,d,b.actualDuration,b.treeBaseDuration,b.actualStartTime,c);"function"===typeof q&&q(b.memoizedProps.id,d,v,c);
sl(b);var x=b.return;a:for(;null!==x;){switch(x.tag){case 3:x.stateNode.effectDuration+=v;break a;case 12:x.stateNode.effectDuration+=v;break a}x=x.return}break;case 13:if(null===b.memoizedState){var z=b.alternate;if(null!==z){var B=z.memoizedState;if(null!==B){var y=B.dehydrated;null!==y&&Bc(y)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(m(163));}Y||b.flags&512&&gg(b)}catch(r){I(b,b.return,r)}}if(b===a){p=null;break}c=b.sibling;if(null!==c){c.return=b.return;
p=c;break}p=b.return}}function kj(a){for(;null!==p;){var b=p;if(b===a){p=null;break}var c=b.sibling;if(null!==c){c.return=b.return;p=c;break}p=b.return}}function mj(a){for(;null!==p;){var b=p;try{switch(b.tag){case 0:case 11:case 15:if(b.mode&2)try{Ia();var c=b.return;try{Db(4,b)}catch(n){I(b,c,n)}}finally{Ha(b)}else{var d=b.return;try{Db(4,b)}catch(n){I(b,d,n)}}break;case 1:var e=b.stateNode;if("function"===typeof e.componentDidMount){var f=b.return;try{e.componentDidMount()}catch(n){I(b,f,n)}}var g=
b.return;try{gg(b)}catch(n){I(b,g,n)}break;case 5:var h=b.return;try{gg(b)}catch(n){I(b,h,n)}}}catch(n){I(b,b.return,n)}if(b===a){p=null;break}var k=b.sibling;if(null!==k){k.return=b.return;p=k;break}p=b.return}}function Vc(){dg=Q()+500}function aa(){return 0!==(w&6)?Q():-1!==de?de:de=Q()}function mb(a){if(0===(a.mode&1))return 1;if(0!==(w&2)&&0!==J)return J&-J;if(null!==tl.transition)return 0===ee&&(ee=fh()),ee;a=x;if(0!==a)return a;a=window.event;a=void 0===a?16:ph(a.type);return a}function ya(a,
b,c,d){if(50<Wc)throw Wc=0,kg=null,Error(m(185));wc(a,c,d);if(0===(w&2)||a!==P)ua&&gh(a,b,c),a===P&&(0===(w&2)&&(fe|=c),4===G&&pb(a,J)),ia(a,d),1===c&&0===w&&0===(b.mode&1)&&(Vc(),Cd&&ib())}function ia(a,b){var c=a.callbackNode;ek(a,b);var d=ld(a,a===P?J:0);if(0===d)null!==c&&oj(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&oj(c);if(1===b)0===a.tag?Uk(pj.bind(null,a)):Zh(pj.bind(null,a)),ul(function(){0===(w&6)&&ib()}),c=null;else{switch(ih(d)){case 1:c=
jd;break;case 4:c=Oe;break;case 16:c=tb;break;case 536870912:c=Pe;break;default:c=tb}c=lg(c,qj.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}function qj(a,b){ge=ce=!1;de=-1;ee=0;if(0!==(w&6))throw Error(m(327));var c=a.callbackNode;if(Eb()&&a.callbackNode!==c)return null;var d=ld(a,a===P?J:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=he(a,d);else{b=d;var e=w;w|=2;var f=rj();if(P!==a||J!==b){if(ua){var g=a.memoizedUpdaters;0<g.size&&(Rc(a,J),g.clear());hh(a,b)}Wa=null;
Vc();Fb(a,b)}dh(b);do try{vl();break}catch(h){sj(a,h)}while(1);wf();ie.current=f;w=e;null!==M?(null!==l&&"function"===typeof l.markRenderYielded&&l.markRenderYielded(),b=0):(eh(),P=null,J=0,b=G)}if(0!==b){2===b&&(e=Qe(a),0!==e&&(d=e,b=mg(a,e)));if(1===b)throw c=Xc,Fb(a,0),pb(a,d),ia(a,Q()),c;if(6===b)pb(a,d);else{e=a.current.alternate;if(0===(d&30)&&!wl(e)&&(b=he(a,d),2===b&&(f=Qe(a),0!==f&&(d=f,b=mg(a,f))),1===b))throw c=Xc,Fb(a,0),pb(a,d),ia(a,Q()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(m(345));
case 2:Gb(a,ja,Wa);break;case 3:pb(a,d);if((d&130023424)===d&&(b=jg+500-Q(),10<b)){if(0!==ld(a,0))break;e=a.suspendedLanes;if((e&d)!==d){aa();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=ng(Gb.bind(null,a,ja,Wa),b);break}Gb(a,ja,Wa);break;case 4:pb(a,d);if((d&4194240)===d)break;b=a.eventTimes;for(e=-1;0<d;)g=31-ka(d),f=1<<g,g=b[g],g>e&&(e=g),d&=~f;d=e;d=Q()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*xl(d/1960))-d;if(10<d){a.timeoutHandle=ng(Gb.bind(null,
a,ja,Wa),d);break}Gb(a,ja,Wa);break;case 5:Gb(a,ja,Wa);break;default:throw Error(m(329));}}}ia(a,Q());return a.callbackNode===c?qj.bind(null,a):null}function mg(a,b){var c=Yc;a.current.memoizedState.isDehydrated&&(Fb(a,b).flags|=256);a=he(a,b);2!==a&&(b=ja,ja=c,null!==b&&cg(b));return a}function cg(a){null===ja?ja=a:ja.push.apply(ja,a)}function wl(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;
try{if(!va(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}function pb(a,b){b&=~og;b&=~fe;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-ka(b),d=1<<c;a[c]=-1;b&=~d}}function pj(a){ce=ge;ge=!1;if(0!==(w&6))throw Error(m(327));Eb();var b=ld(a,0);if(0===(b&1))return ia(a,Q()),null;
var c=he(a,b);if(0!==a.tag&&2===c){var d=Qe(a);0!==d&&(b=d,c=mg(a,d))}if(1===c)throw c=Xc,Fb(a,0),pb(a,b),ia(a,Q()),c;if(6===c)throw Error(m(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Gb(a,ja,Wa);ia(a,Q());return null}function pg(a,b){var c=w;w|=1;try{return a(b)}finally{w=c,0===w&&(Vc(),Cd&&ib())}}function Hb(a){null!==qb&&0===qb.tag&&0===(w&6)&&Eb();var b=w;w|=1;var c=ca.transition,d=x;try{if(ca.transition=null,x=1,a)return a()}finally{x=d,ca.transition=c,w=b,0===(w&6)&&ib()}}function Fb(a,
b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,yl(c));if(null!==M)for(c=M.return;null!==c;){var d=c;qf(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&(t(T),t(K));break;case 3:cc();t(T);t(K);Ef();break;case 5:Df(d);break;case 4:cc();break;case 13:t(H);break;case 19:t(H);break;case 10:yf(d.type._context);break;case 22:case 23:U=Ja.current,t(Ja)}c=c.return}P=a;M=a=jb(a.current,null);J=U=b;G=0;Xc=null;og=fe=sa=0;ja=Yc=null;if(null!==
zb){for(b=0;b<zb.length;b++)if(c=zb[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}zb=null}return a}function sj(a,b){do{var c=M;try{wf();Od.current=Pd;if(Qd){for(var d=z.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Qd=!1}Bb=0;O=L=z=null;Nc=!1;Oc=0;qg.current=null;if(null===c||null===c.return){G=1;Xc=b;M=null;break}c.mode&2&&Td(c,!0);Pb();if(null!==b&&"object"===typeof b&&"function"===typeof b.then){var f=
b;null!==l&&"function"===typeof l.markComponentSuspended&&l.markComponentSuspended(c,f,J)}else null!==l&&"function"===typeof l.markComponentErrored&&l.markComponentErrored(c,b,J);a:{var g=a,h=c.return,k=c;f=b;b=J;k.flags|=32768;ua&&Rc(g,b);if(null!==f&&"object"===typeof f&&"function"===typeof f.then){var n=f,p=k,u=p.tag;if(0===(p.mode&1)&&(0===u||11===u||15===u)){var q=p.alternate;q?(p.updateQueue=q.updateQueue,p.memoizedState=q.memoizedState,p.lanes=q.lanes):(p.updateQueue=null,p.memoizedState=null)}var t=
Mi(h);if(null!==t){t.flags&=-257;Ni(t,h,k,g,b);t.mode&1&&Li(g,n,b);b=t;f=n;var v=b.updateQueue;if(null===v){var x=new Set;x.add(f);b.updateQueue=x}else v.add(f);break a}else{if(0===(b&1)){Li(g,n,b);ag();break a}f=Error(m(426))}}else if(C&&k.mode&1){var w=Mi(h);if(null!==w){0===(w.flags&65536)&&(w.flags|=256);Ni(w,h,k,g,b);tf(ec(f,k));break a}}g=f=ec(f,k);4!==G&&(G=2);null===Yc?Yc=[g]:Yc.push(g);g=h;do{switch(g.tag){case 3:g.flags|=65536;b&=-b;g.lanes|=b;var B=Ji(g,f,b);ii(g,B);break a;case 1:k=f;
var y=g.type,r=g.stateNode;if(0===(g.flags&128)&&("function"===typeof y.getDerivedStateFromError||null!==r&&"function"===typeof r.componentDidCatch&&(null===nb||!nb.has(r)))){g.flags|=65536;b&=-b;g.lanes|=b;var F=Ki(g,k,b);ii(g,F);break a}}g=g.return}while(null!==g)}tj(c)}catch(Na){b=Na;M===c&&null!==c&&(M=c=c.return);continue}break}while(1)}function rj(){var a=ie.current;ie.current=Pd;return null===a?Pd:a}function ag(){if(0===G||3===G||2===G)G=4;null===P||0===(sa&268435455)&&0===(fe&268435455)||
pb(P,J)}function he(a,b){var c=w;w|=2;var d=rj();if(P!==a||J!==b){if(ua){var e=a.memoizedUpdaters;0<e.size&&(Rc(a,J),e.clear());hh(a,b)}Wa=null;Fb(a,b)}dh(b);do try{zl();break}catch(f){sj(a,f)}while(1);wf();w=c;ie.current=d;if(null!==M)throw Error(m(261));eh();P=null;J=0;return G}function zl(){for(;null!==M;)uj(M)}function vl(){for(;null!==M&&!Al();)uj(M)}function uj(a){var b=a.alternate;0!==(a.mode&2)?(Cb=na(),0>a.actualStartTime&&(a.actualStartTime=na()),b=vj(b,a,U),Td(a,!0)):b=vj(b,a,U);a.memoizedProps=
a.pendingProps;null===b?tj(a):M=b;qg.current=null}function tj(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(0===(b.mode&2))c=$i(c,b,U);else{var d=b;Cb=na();0>d.actualStartTime&&(d.actualStartTime=na());c=$i(c,b,U);Td(b,!1)}if(null!==c){M=c;return}}else{c=kl(c,b);if(null!==c){c.flags&=32767;M=c;return}if(0!==(b.mode&2)){Td(b,!1);c=b.actualDuration;for(d=b.child;null!==d;)c+=d.actualDuration,d=d.sibling;b.actualDuration=c}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=
null;else{G=6;M=null;return}}b=b.sibling;if(null!==b){M=b;return}M=b=a}while(null!==b);0===G&&(G=5)}function Gb(a,b,c){var d=x,e=ca.transition;try{ca.transition=null,x=1,Bl(a,b,c,d)}finally{ca.transition=e,x=d}return null}function Bl(a,b,c,d){do Eb();while(null!==qb);if(0!==(w&6))throw Error(m(327));c=a.finishedWork;var e=a.finishedLanes;null!==l&&"function"===typeof l.markCommitStarted&&l.markCommitStarted(e);if(null===c)return ah(),null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(m(177));
a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;fk(a,f);a===P&&(M=P=null,J=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||jc||(jc=!0,lg(tb,function(){Eb();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=ca.transition;ca.transition=null;var g=x;x=1;var h=w;w|=4;qg.current=null;ll(a,c);be=na();ql(a,c,e);Ek(fg);pd=!!eg;fg=eg=null;a.current=c;null!==l&&"function"===typeof l.markLayoutEffectsStarted&&l.markLayoutEffectsStarted(e);rl(c,a,e);null!==l&&"function"===
typeof l.markLayoutEffectsStopped&&l.markLayoutEffectsStopped();Cl();w=h;x=g;ca.transition=f}else a.current=c,be=na();jc&&(jc=!1,qb=a,Zc=e);f=a.pendingLanes;0===f&&(nb=null);Yj(c.stateNode,d);ua&&a.memoizedUpdaters.clear();ia(a,Q());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Wd)throw Wd=!1,a=Uf,Uf=null,a;0!==(Zc&1)&&0!==a.tag&&Eb();f=a.pendingLanes;0!==(f&1)?(ge=!0,a===kg?Wc++:(Wc=0,kg=a)):Wc=0;ib();ah();return null}function Eb(){if(null!==
qb){var a=ih(Zc),b=ca.transition,c=x;try{ca.transition=null;x=16>a?16:a;if(null===qb)var d=!1;else{a=qb;var e=Zc;qb=null;Zc=0;if(0!==(w&6))throw Error(m(331));null!==l&&"function"===typeof l.markPassiveEffectsStarted&&l.markPassiveEffectsStarted(e);e=w;w|=4;for(p=a.current;null!==p;){var f=p,g=f.child;if(0!==(p.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var n=h[k];for(p=n;null!==p;){var t=p,u=t;switch(u.tag){case 0:case 11:case 15:u.mode&2?(dc=na(),Va(8,u,f),Of(u)):Va(8,
u,f)}var q=t.child;if(null!==q)q.return=t,p=q;else for(;null!==p;){t=p;var z=t.sibling,v=t.return;dj(t);if(t===n){p=null;break}if(null!==z){z.return=v;p=z;break}p=v}}}var E=f.alternate;if(null!==E){var A=E.child;if(null!==A){E.child=null;do{var B=A.sibling;A.sibling=null;A=B}while(null!==A)}}p=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,p=g;else b:for(;null!==p;){f=p;if(0!==(f.flags&2048))switch(k=f,k.tag){case 0:case 11:case 15:k.mode&2?(dc=na(),Va(9,k,k.return),Of(k)):Va(9,k,k.return)}var y=
f.sibling;if(null!==y){y.return=f.return;p=y;break b}p=f.return}}var r=a.current;for(p=r;null!==p;){g=p;var F=g.child;if(0!==(g.subtreeFlags&2064)&&null!==F)F.return=g,p=F;else b:for(g=r;null!==p;){h=p;if(0!==(h.flags&2048))try{switch(n=h,n.tag){case 0:case 11:case 15:if(n.mode&2){dc=na();try{Db(9,n)}finally{Of(n)}}else Db(9,n)}}catch(wj){I(h,h.return,wj)}if(h===g){p=null;break b}var D=h.sibling;if(null!==D){D.return=h.return;p=D;break b}p=h.return}}r=rg;rg=[];for(F=0;F<r.length;F++){var C=r[F];if(0!==
(C.flags&4))switch(C.tag){case 12:var H=C.stateNode.passiveEffectDuration,J=C.memoizedProps,M=J.id,K=J.onPostCommit;D=be;var L=null===C.alternate?"mount":"update";ce&&(L="nested-update");"function"===typeof K&&K(M,L,H,D);var G=C.return;b:for(;null!==G;){switch(G.tag){case 3:G.stateNode.passiveEffectDuration+=H;break b;case 12:G.stateNode.passiveEffectDuration+=H;break b}G=G.return}}}null!==l&&"function"===typeof l.markPassiveEffectsStopped&&l.markPassiveEffectsStopped();w=e;ib();if(Da&&"function"===
typeof Da.onPostCommitFiberRoot)try{Da.onPostCommitFiberRoot(id,a)}catch(wj){}var O=a.current.stateNode;O.effectDuration=0;O.passiveEffectDuration=0;d=!0}return d}finally{x=c,ca.transition=b}}return!1}function sl(a){rg.push(a);jc||(jc=!0,lg(tb,function(){Eb();return null}))}function xj(a,b,c){b=ec(c,b);b=Ji(a,b,1);a=kb(a,b,1);b=aa();null!==a&&(wc(a,1,b),ia(a,b))}function I(a,b,c){if(3===a.tag)xj(a,a,c);else for(;null!==b;){if(3===b.tag){xj(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===
typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===nb||!nb.has(d))){a=ec(c,a);a=Ki(b,a,1);b=kb(b,a,1);a=aa();null!==b&&(wc(b,1,a),ia(b,a));break}}b=b.return}}function cl(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=aa();a.pingedLanes|=a.suspendedLanes&c;P===a&&(J&c)===c&&(4===G||3===G&&(J&130023424)===J&&500>Q()-jg?Fb(a,0):og|=c);ia(a,b)}function yj(a,b){0===b&&(0===(a.mode&1)?b=1:(b=je,je<<=1,0===(je&130023424)&&(je=4194304)));var c=aa();a=Sa(a,b);null!==
a&&(wc(a,b,c),ia(a,c))}function fl(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);yj(a,c)}function pl(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(m(314));}null!==d&&d.delete(b);yj(a,c)}function Rc(a,b){ua&&a.memoizedUpdaters.forEach(function(c){gh(a,c,b)})}function lg(a,b){return $h(a,b)}function Dl(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=
this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;this.actualDuration=0;this.actualStartTime=-1;this.treeBaseDuration=this.selfBaseDuration=0}function Vf(a){a=a.prototype;return!(!a||!a.isReactComponent)}function El(a){if("function"===typeof a)return Vf(a)?1:0;if(void 0!==a&&null!==
a){a=a.$$typeof;if(a===Be)return 11;if(a===Ce)return 14}return 2}function jb(a,b){var c=a.alternate;null===c?(c=qa(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null,c.actualDuration=0,c.actualStartTime=-1);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=
a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;c.selfBaseDuration=a.selfBaseDuration;c.treeBaseDuration=a.treeBaseDuration;return c}function Hd(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Vf(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case Kb:return yb(c.children,e,f,b);case ye:g=8;e|=8;break;case xe:return a=qa(12,c,b,e|2),a.elementType=xe,a.lanes=f,a.stateNode={effectDuration:0,
passiveEffectDuration:0},a;case ze:return a=qa(13,c,b,e),a.elementType=ze,a.lanes=f,a;case Ae:return a=qa(19,c,b,e),a.elementType=Ae,a.lanes=f,a;case zj:return Yd(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Fg:g=10;break a;case Eg:g=9;break a;case Be:g=11;break a;case Ce:g=14;break a;case Ya:g=16;d=null;break a}throw Error(m(130,null==a?a:typeof a,""));}b=qa(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function yb(a,b,c,d){a=qa(7,a,d,b);a.lanes=c;return a}function Yd(a,
b,c,d){a=qa(22,a,d,b);a.elementType=zj;a.lanes=c;a.stateNode={isHidden:!1};return a}function uf(a,b,c){a=qa(6,a,null,b);a.lanes=c;return a}function vf(a,b,c){b=qa(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function Fl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=
this.context=null;this.callbackPriority=0;this.eventTimes=Re(0);this.expirationTimes=Re(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Re(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=null;this.passiveEffectDuration=this.effectDuration=0;this.memoizedUpdaters=new Set;a=this.pendingUpdatersLaneMap=[];for(b=0;31>b;b++)a.push(new Set)}function sg(a,
b,c,d,e,f,g,h,k,l){a=new Fl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;ua&&(b|=2);f=qa(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};Bf(f);return a}function Gl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Lb,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}function Aj(a){if(!a)return hb;a=a._reactInternals;a:{if(sb(a)!==a||1!==a.tag)throw Error(m(170));
var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(ea(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(m(171));}if(1===a.tag){var c=a.type;if(ea(c))return Xh(a,c,b)}return b}function Bj(a,b,c,d,e,f,g,h,k,l){a=sg(c,d,!0,a,e,f,g,h,k);a.context=Aj(null);c=a.current;d=aa();e=mb(c);f=Ta(d,e);f.callback=void 0!==b&&null!==b?b:null;kb(c,f,e);a.current.lanes=e;wc(a,e,d);ia(a,d);return a}function ke(a,b,c,d){var e=b.current,
f=aa(),g=mb(e);null!==l&&"function"===typeof l.markRenderScheduled&&l.markRenderScheduled(g);c=Aj(c);null===b.context?b.context=c:b.pendingContext=c;b=Ta(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=kb(e,b,g);null!==a&&(ya(a,e,g,f),Ld(a,e,g));return g}function le(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Cj(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;
a.retryLane=0!==c&&c<b?c:b}}function tg(a,b){Cj(a,b);(a=a.alternate)&&Cj(a,b)}function Hl(a){a=Zg(a);return null===a?null:a.stateNode}function Il(a){return null}function ug(a){this._internalRoot=a}function me(a){this._internalRoot=a}function vg(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function ne(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function Dj(){}function Jl(a,b,c,d,e){if(e){if("function"===
typeof d){var f=d;d=function(){var a=le(g);f.call(a)}}var g=Bj(b,d,a,0,null,!1,!1,"",Dj);a._reactRootContainer=g;a[Ma]=g.current;Gc(8===a.nodeType?a.parentNode:a);Hb();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=le(k);h.call(a)}}var k=sg(a,0,!1,null,null,!1,!1,"",Dj);a._reactRootContainer=k;a[Ma]=k.current;Gc(8===a.nodeType?a.parentNode:a);Hb(function(){ke(b,k,c,d)});return k}function oe(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===
typeof e){var h=e;e=function(){var a=le(g);h.call(a)}}ke(b,g,a,e)}else g=Jl(c,b,a,e,d);return le(g)}var Ag=new Set,mc={},La=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),re=Object.prototype.hasOwnProperty,Jj=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,
Cg={},Bg={},S={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){S[a]=new Z(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];S[b]=new Z(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){S[a]=new Z(a,2,!1,a.toLowerCase(),null,
!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){S[a]=new Z(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){S[a]=new Z(a,3,!1,a.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(a){S[a]=
new Z(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){S[a]=new Z(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){S[a]=new Z(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){S[a]=new Z(a,5,!1,a.toLowerCase(),null,!1,!1)});var wg=/[\-:]([a-z])/g,xg=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
a.replace(wg,xg);S[b]=new Z(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(wg,xg);S[b]=new Z(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(wg,xg);S[b]=new Z(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){S[a]=new Z(a,1,!1,a.toLowerCase(),null,!1,!1)});S.xlinkHref=new Z("xlinkHref",
1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){S[a]=new Z(a,1,!1,a.toLowerCase(),null,!0,!0)});var Xa=Ib.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Id=Symbol.for("react.element"),Lb=Symbol.for("react.portal"),Kb=Symbol.for("react.fragment"),ye=Symbol.for("react.strict_mode"),xe=Symbol.for("react.profiler"),Fg=Symbol.for("react.provider"),Eg=Symbol.for("react.context"),Be=Symbol.for("react.forward_ref"),ze=Symbol.for("react.suspense"),
Ae=Symbol.for("react.suspense_list"),Ce=Symbol.for("react.memo"),Ya=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var zj=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var Dg=Symbol.iterator,D=Object.assign,te,ve=!1,pc=Array.isArray,pe,bj=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,
c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{pe=pe||document.createElement("div");pe.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=pe.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}),Uc=function(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b},qc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,
borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,
strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Kl=["Webkit","ms","Moz","O"];Object.keys(qc).forEach(function(a){Kl.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);qc[b]=qc[a]})});var Pj=D({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),Ue=null,Le=null,Nb=null,Ob=null,Vg=function(a,b){return a(b)},Wg=function(){},Me=!1,hf=!1;if(La)try{var $c={};Object.defineProperty($c,
"passive",{get:function(){hf=!0}});window.addEventListener("test",$c,$c);window.removeEventListener("test",$c,$c)}catch(a){hf=!1}var Rj=function(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(N){this.onError(N)}},tc=!1,gd=null,hd=!1,Ne=null,Sj={onError:function(a){tc=!0;gd=a}},Ca=Ib.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,Ej=Ca.unstable_now,nh=Ca.unstable_scheduleCallback,oh=Ca.unstable_NormalPriority,$h=nh,oj=Ca.unstable_cancelCallback,
Al=Ca.unstable_shouldYield,Cl=Ca.unstable_requestPaint,Q=Ej,ok=Ca.unstable_getCurrentPriorityLevel,jd=Ca.unstable_ImmediatePriority,Oe=Ca.unstable_UserBlockingPriority,tb=oh,pk=Ca.unstable_LowPriority,Pe=Ca.unstable_IdlePriority,id=null,Da=null,l=null,ua="undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__,ka=Math.clz32?Math.clz32:ak,bk=Math.log,ck=Math.LN2,md=64,je=4194304,x=0,Ve=!1,od=[],$a=null,ab=null,bb=null,xc=new Map,yc=new Map,cb=[],mk="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "),
Qb=Xa.ReactCurrentBatchConfig,pd=!0,qd=null,db=null,Ye=null,rd=null,kc={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},af=la(kc),ad=D({},kc,{view:0,detail:0}),Lk=la(ad),yg,zg,bd,qe=D({},ad,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ze,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:
a.relatedTarget},movementX:function(a){if("movementX"in a)return a.movementX;a!==bd&&(bd&&"mousemove"===a.type?(yg=a.screenX-bd.screenX,zg=a.screenY-bd.screenY):zg=yg=0,bd=a);return yg},movementY:function(a){return"movementY"in a?a.movementY:zg}}),Lh=la(qe),Ll=D({},qe,{dataTransfer:0}),Hk=la(Ll),Ml=D({},ad,{relatedTarget:0}),kf=la(Ml),Nl=D({},kc,{animationName:0,elapsedTime:0,pseudoElement:0}),Jk=la(Nl),Ol=D({},kc,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),
Nk=la(Ol),Pl=D({},kc,{data:0}),Th=la(Pl),Qk=Th,Ql={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Rl={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",
112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},rk={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},Sl=D({},ad,{key:function(a){if(a.key){var b=Ql[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=sd(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?Rl[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,
metaKey:0,repeat:0,locale:0,getModifierState:Ze,charCode:function(a){return"keypress"===a.type?sd(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?sd(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),Gk=la(Sl),Tl=D({},qe,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Qh=la(Tl),Ul=D({},ad,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,
ctrlKey:0,shiftKey:0,getModifierState:Ze}),Ik=la(Ul),Vl=D({},kc,{propertyName:0,elapsedTime:0,pseudoElement:0}),Kk=la(Vl),Wl=D({},qe,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Mk=la(Wl),sk=[9,13,27,32],$e=La&&"CompositionEvent"in window,cd=null;La&&"documentMode"in document&&(cd=document.documentMode);var Pk=La&&"TextEvent"in
window&&!cd,wh=La&&(!$e||cd&&8<cd&&11>=cd),vh=String.fromCharCode(32),uh=!1,Rb=!1,vk={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},Cc=null,Dc=null,Sh=!1;La&&(Sh=wk("input")&&(!document.documentMode||9<document.documentMode));var va="function"===typeof Object.is?Object.is:Dk,Ok=La&&"documentMode"in document&&11>=document.documentMode,Tb=null,df=null,Fc=null,cf=!1,Ub={animationend:wd("Animation","AnimationEnd"),
animationiteration:wd("Animation","AnimationIteration"),animationstart:wd("Animation","AnimationStart"),transitionend:wd("Transition","TransitionEnd")},ef={},Hh={};La&&(Hh=document.createElement("div").style,"AnimationEvent"in window||(delete Ub.animationend.animation,delete Ub.animationiteration.animation,delete Ub.animationstart.animation),"TransitionEvent"in window||delete Ub.transitionend.transition);var Mh=xd("animationend"),Nh=xd("animationiteration"),Oh=xd("animationstart"),Ph=xd("transitionend"),
Ih=new Map,Fj="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
(function(){for(var a=0;a<Fj.length;a++){var b=Fj[a],c=b.toLowerCase();b=b[0].toUpperCase()+b.slice(1);eb(c,"on"+b)}eb(Mh,"onAnimationEnd");eb(Nh,"onAnimationIteration");eb(Oh,"onAnimationStart");eb("dblclick","onDoubleClick");eb("focusin","onFocus");eb("focusout","onBlur");eb(Ph,"onTransitionEnd")})();Jb("onMouseEnter",["mouseout","mouseover"]);Jb("onMouseLeave",["mouseout","mouseover"]);Jb("onPointerEnter",["pointerout","pointerover"]);Jb("onPointerLeave",["pointerout","pointerover"]);rb("onChange",
"change click focusin focusout input keydown keyup selectionchange".split(" "));rb("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));rb("onBeforeInput",["compositionend","keypress","textInput","paste"]);rb("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));rb("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));rb("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));
var Tc="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Fk=new Set("cancel close invalid load scroll toggle".split(" ").concat(Tc)),yd="_reactListening"+Math.random().toString(36).slice(2),Rk=/\r\n?/g,Sk=/\u0000|\uFFFD/g,eg=null,fg=null,ng="function"===typeof setTimeout?setTimeout:void 0,yl="function"===typeof clearTimeout?
clearTimeout:void 0,Gj="function"===typeof Promise?Promise:void 0,ul="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof Gj?function(a){return Gj.resolve(null).then(a).catch(Tk)}:ng,lc=Math.random().toString(36).slice(2),Ea="__reactFiber$"+lc,Ic="__reactProps$"+lc,Ma="__reactContainer$"+lc,ff="__reactEvents$"+lc,ml="__reactListeners$"+lc,nl="__reactHandles$"+lc,nf=[],Wb=-1,hb={},K=gb(hb),T=gb(!1),vb=hb,Pa=null,Cd=!1,of=!1,Yb=[],Zb=0,Ed=null,Dd=0,oa=[],pa=0,xb=null,Qa=1,Ra="",ma=
null,fa=null,C=!1,xa=null,tl=Xa.ReactCurrentBatchConfig,fc=fi(!0),Oi=fi(!1),Kd=gb(null),Jd=null,ac=null,xf=null,zb=null,Vk=Sa,lb=!1,Kc={},Fa=gb(Kc),Mc=gb(Kc),Lc=gb(Kc),H=gb(0),Ff=[],Od=Xa.ReactCurrentDispatcher,Nf=Xa.ReactCurrentBatchConfig,Bb=0,z=null,L=null,O=null,Qd=!1,Nc=!1,Oc=0,Xl=0,Pd={readContext:ra,useCallback:X,useContext:X,useEffect:X,useImperativeHandle:X,useInsertionEffect:X,useLayoutEffect:X,useMemo:X,useReducer:X,useRef:X,useState:X,useDebugValue:X,useDeferredValue:X,useTransition:X,
useMutableSource:X,useSyncExternalStore:X,useId:X,unstable_isNewReconciler:!1},Wk={readContext:ra,useCallback:function(a,b){Ga().memoizedState=[a,void 0===b?null:b];return a},useContext:ra,useEffect:ui,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Rd(4194308,4,xi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Rd(4194308,4,a,b)},useInsertionEffect:function(a,b){return Rd(4,2,a,b)},useMemo:function(a,b){var c=Ga();b=void 0===b?null:b;a=a();c.memoizedState=
[a,b];return a},useReducer:function(a,b,c){var d=Ga();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=al.bind(null,z,a);return[d.memoizedState,a]},useRef:function(a){var b=Ga();a={current:a};return b.memoizedState=a},useState:si,useDebugValue:Mf,useDeferredValue:function(a){return Ga().memoizedState=a},useTransition:function(){var a=si(!1),b=a[0];a=$k.bind(null,a[1]);Ga().memoizedState=
a;return[b,a]},useMutableSource:function(a,b,c){},useSyncExternalStore:function(a,b,c){var d=z,e=Ga();if(C){if(void 0===c)throw Error(m(407));c=c()}else{c=b();if(null===P)throw Error(m(349));0!==(Bb&30)||pi(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;ui(ni.bind(null,d,f,a),[a]);d.flags|=2048;Qc(9,oi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Ga(),b=P.identifierPrefix;if(C){var c=Ra;var d=Qa;c=(d&~(1<<32-ka(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Oc++;0<c&&
(b+="H"+c.toString(32));b+=":"}else c=Xl++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:!1},Xk={readContext:ra,useCallback:zi,useContext:ra,useEffect:Lf,useImperativeHandle:yi,useInsertionEffect:vi,useLayoutEffect:wi,useMemo:Ai,useReducer:Jf,useRef:ti,useState:function(a){return Jf(Pc)},useDebugValue:Mf,useDeferredValue:function(a){var b=ta();return Bi(b,L.memoizedState,a)},useTransition:function(){var a=Jf(Pc)[0],b=ta().memoizedState;return[a,b]},useMutableSource:li,
useSyncExternalStore:mi,useId:Ci,unstable_isNewReconciler:!1},Yk={readContext:ra,useCallback:zi,useContext:ra,useEffect:Lf,useImperativeHandle:yi,useInsertionEffect:vi,useLayoutEffect:wi,useMemo:Ai,useReducer:Kf,useRef:ti,useState:function(a){return Kf(Pc)},useDebugValue:Mf,useDeferredValue:function(a){var b=ta();return null===L?b.memoizedState=a:Bi(b,L.memoizedState,a)},useTransition:function(){var a=Kf(Pc)[0],b=ta().memoizedState;return[a,b]},useMutableSource:li,useSyncExternalStore:mi,useId:Ci,
unstable_isNewReconciler:!1},na=Ej,be=0,Ud=-1,Cb=-1,dc=-1,ce=!1,ge=!1,Vd={isMounted:function(a){return(a=a._reactInternals)?sb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=aa(),e=mb(a),f=Ta(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=kb(a,f,e);null!==b&&(ya(b,a,e,d),Ld(b,a,e));kd(a,e)},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=aa(),e=mb(a),f=Ta(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=kb(a,f,e);null!==b&&(ya(b,a,e,d),Ld(b,
a,e));kd(a,e)},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=aa(),d=mb(a),e=Ta(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=kb(a,e,d);null!==b&&(ya(b,a,d,c),Ld(b,a,d));null!==l&&"function"===typeof l.markForceUpdateScheduled&&l.markForceUpdateScheduled(a,d)}},bl="function"===typeof WeakMap?WeakMap:Map,dl=Xa.ReactCurrentOwner,ha=!1,Zf={dehydrated:null,treeContext:null,retryLane:0};var il=function(a,b,c,d){for(c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);
else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};var aj=function(a,b){};var hl=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){a=b.stateNode;Ab(Fa.current);e=null;switch(c){case "input":f=De(a,f);d=De(a,d);e=[];break;case "select":f=D({},f,{value:void 0});d=D({},d,{value:void 0});e=[];break;case "textarea":f=Ge(a,f);d=Ge(a,d);e=[];break;default:"function"!==
typeof f.onClick&&"function"===typeof d.onClick&&(a.onclick=Ad)}Ie(c,d);var g;c=null;for(l in f)if(!d.hasOwnProperty(l)&&f.hasOwnProperty(l)&&null!=f[l])if("style"===l){var h=f[l];for(g in h)h.hasOwnProperty(g)&&(c||(c={}),c[g]="")}else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(mc.hasOwnProperty(l)?e||(e=[]):(e=e||[]).push(l,null));for(l in d){var k=d[l];h=null!=f?f[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&
(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(e||(e=[]),e.push(l,c)),c=k;else"dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(e=e||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(e=e||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(mc.hasOwnProperty(l)?
(null!=k&&"onScroll"===l&&A("scroll",a),e||h===k||(e=[])):(e=e||[]).push(l,k))}c&&(e=e||[]).push("style",c);var l=e;if(b.updateQueue=l)b.flags|=4}};var jl=function(a,b,c,d){c!==d&&(b.flags|=4)};var ae=!1,Y=!1,ol="function"===typeof WeakSet?WeakSet:Set,p=null,hc=null,ic=null,hj=function(a,b){b.props=a.memoizedProps;b.state=a.memoizedState;if(a.mode&2)try{Ia(),b.componentWillUnmount()}finally{Ha(a)}else b.componentWillUnmount()},cj=!1,W=null,Aa=!1,xl=Math.ceil,ie=Xa.ReactCurrentDispatcher,qg=Xa.ReactCurrentOwner,
ca=Xa.ReactCurrentBatchConfig,w=0,P=null,M=null,J=0,U=0,Ja=gb(0),G=0,Xc=null,sa=0,fe=0,og=0,Yc=null,ja=null,jg=0,dg=Infinity,Wa=null,Wd=!1,Uf=null,nb=null,jc=!1,qb=null,Zc=0,rg=[],Wc=0,kg=null,de=-1,ee=0;var vj=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||T.current)ha=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return ha=!1,gl(a,b,c);ha=0!==(a.flags&131072)?!0:!1}else ha=!1,C&&0!==(b.flags&1048576)&&ai(b,Dd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;Xd(a,b);a=b.pendingProps;
var e=Xb(b,K.current);bc(b,c);uc(b);e=Hf(null,b,d,a,e,c);var f=If();Pb();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=null,ea(d)?(f=!0,Bd(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,Bf(b),e.updater=Vd,b.stateNode=e,e._reactInternals=b,Rf(b,d,a,c),b=Xf(null,b,d,!0,f,c)):(b.tag=0,C&&f&&pf(b),ba(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{Xd(a,b);a=b.pendingProps;e=d._init;
d=e(d._payload);b.type=d;e=b.tag=El(d);a=za(d,a);switch(e){case 0:b=Wf(null,b,d,a,c);break a;case 1:b=Ui(null,b,d,a,c);break a;case 11:b=Pi(null,b,d,a,c);break a;case 14:b=Qi(null,b,d,za(d.type,a),c);break a}throw Error(m(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:za(d,e),Wf(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:za(d,e),Ui(a,b,d,e,c);case 3:a:{Vi(b);if(null===a)throw Error(m(387));d=b.pendingProps;f=b.memoizedState;e=f.element;
hi(a,b);Md(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=ec(Error(m(423)),b);b=Wi(a,b,d,c,e);break a}else if(d!==e){e=ec(Error(m(424)),b);b=Wi(a,b,d,c,e);break a}else for(fa=Oa(b.stateNode.containerInfo.firstChild),ma=b,C=!0,xa=null,c=Oi(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;
else{$b();if(d===e){b=Ua(a,b,c);break a}ba(a,b,d,c)}b=b.child}return b;case 5:return ki(b),null===a&&sf(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,lf(d,e)?g=null:null!==f&&lf(d,f)&&(b.flags|=32),Ti(a,b),ba(a,b,g,c),b.child;case 6:return null===a&&sf(b),null;case 13:return Xi(a,b,c);case 4:return Cf(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=fc(b,null,d,c):ba(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:za(d,e),Pi(a,
b,d,e,c);case 7:return ba(a,b,b.pendingProps,c),b.child;case 8:return ba(a,b,b.pendingProps.children,c),b.child;case 12:return b.flags|=4,d=b.stateNode,d.effectDuration=0,d.passiveEffectDuration=0,ba(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;E(Kd,d._currentValue);d._currentValue=g;if(null!==f)if(va(f.value,g)){if(f.children===e.children&&!T.current){b=Ua(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=
f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=Ta(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var p=l.pending;null===p?k.next=k:(k.next=p.next,p.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);zf(f.return,c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(m(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);zf(g,
c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}ba(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,bc(b,c),e=ra(e),uc(b),d=d(e),Pb(),b.flags|=1,ba(a,b,d,c),b.child;case 14:return d=b.type,e=za(d,b.pendingProps),e=za(d.type,e),Qi(a,b,d,e,c);case 15:return Ri(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===
d?e:za(d,e),Xd(a,b),b.tag=1,ea(d)?(a=!0,Bd(b)):a=!1,bc(b,c),Hi(b,d,e),Rf(b,d,e,c),Xf(null,b,d,!0,a,c);case 19:return Zi(a,b,c);case 22:return Si(a,b,c)}throw Error(m(156,b.tag));};var qa=function(a,b,c,d){return new Dl(a,b,c,d)},Hj="function"===typeof reportError?reportError:function(a){console.error(a)};me.prototype.render=ug.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(m(409));ke(a,b,null,null)};me.prototype.unmount=ug.prototype.unmount=function(){var a=this._internalRoot;
if(null!==a){this._internalRoot=null;var b=a.containerInfo;Hb(function(){ke(null,a,null,null)});b[Ma]=null}};me.prototype.unstable_scheduleHydration=function(a){if(a){var b=Yl();a={blockedOn:null,target:a,priority:b};for(var c=0;c<cb.length&&0!==b&&b<cb[c].priority;c++);cb.splice(c,0,a);0===c&&lh(a)}};var nk=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=vc(b.pendingLanes);0!==c&&(Se(b,c|1),ia(b,Q()),0===(w&6)&&(Vc(),ib()))}break;case 13:Hb(function(){var b=
Sa(a,1);if(null!==b){var c=aa();ya(b,a,1,c)}}),tg(a,1)}};var kh=function(a){if(13===a.tag){var b=Sa(a,134217728);if(null!==b){var c=aa();ya(b,a,134217728,c)}tg(a,134217728)}};var ik=function(a){if(13===a.tag){var b=mb(a),c=Sa(a,b);if(null!==c){var d=aa();ya(c,a,b,d)}tg(a,b)}};var Yl=function(){return x};var hk=function(a,b){var c=x;try{return x=a,b()}finally{x=c}};Le=function(a,b,c){switch(b){case "input":Ee(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+
JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=fd(d);if(!e)throw Error(m(90));Hg(d);Ee(d,e)}}}break;case "textarea":Mg(a,c);break;case "select":b=c.value,null!=b&&Mb(a,!!c.multiple,b,!1)}};(function(a,b,c){Vg=a;Wg=c})(pg,function(a,b,c,d,e){var f=x,g=ca.transition;try{return ca.transition=null,x=1,a(b,c,d,e)}finally{x=f,ca.transition=g,0===w&&Vc()}},Hb);var Zl={usingClientEntryPoint:!1,Events:[rc,Sb,fd,Sg,Tg,pg]};(function(a){return Vj({bundleType:a.bundleType,
version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Xa.ReactCurrentDispatcher,findHostInstanceByFiber:Hl,findFiberByHostInstance:a.findFiberByHostInstance||Il,findHostInstancesForRefresh:null,scheduleRefresh:null,
scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"})})({findFiberByHostInstance:ub,bundleType:0,version:"18.3.1-next-f1338f8080-20240426",rendererPackageName:"react-dom"});R.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Zl;R.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!vg(b))throw Error(m(200));return Gl(a,b,null,c)};R.createRoot=function(a,b){if(!vg(a))throw Error(m(299));var c=
!1,d="",e=Hj;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=sg(a,1,!1,null,null,c,!1,d,e);a[Ma]=b.current;Gc(8===a.nodeType?a.parentNode:a);return new ug(b)};R.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(m(188));a=Object.keys(a).join(",");throw Error(m(268,a));}a=Zg(b);
a=null===a?null:a.stateNode;return a};R.flushSync=function(a){return Hb(a)};R.hydrate=function(a,b,c){if(!ne(b))throw Error(m(200));return oe(null,a,b,!0,c)};R.hydrateRoot=function(a,b,c){if(!vg(a))throw Error(m(405));var d=null!=c&&c.hydratedSources||null,e=!1,f="",g=Hj;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=Bj(b,null,a,1,null!=c?c:null,e,!1,f,g);a[Ma]=b.current;Gc(a);
if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,e);return new me(b)};R.render=function(a,b,c){if(!ne(b))throw Error(m(200));return oe(null,a,b,!1,c)};R.unmountComponentAtNode=function(a){if(!ne(a))throw Error(m(40));return a._reactRootContainer?(Hb(function(){oe(null,null,a,!1,function(){a._reactRootContainer=null;a[Ma]=null})}),!0):!1};R.unstable_batchedUpdates=
pg;R.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!ne(c))throw Error(m(200));if(null==a||void 0===a._reactInternals)throw Error(m(38));return oe(a,b,c,!1,d)};R.version="18.3.1-next-f1338f8080-20240426"});
})();
/**
 * @license React
 * react-dom-server-legacy.browser.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');

var ReactVersion = '18.3.1';

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

function scheduleWork(callback) {
  callback();
}
function beginWriting(destination) {}
function writeChunk(destination, chunk) {
  writeChunkAndReturn(destination, chunk);
}
function writeChunkAndReturn(destination, chunk) {
  return destination.push(chunk);
}
function completeWriting(destination) {}
function close(destination) {
  destination.push(null);
}
function stringToChunk(content) {
  return content;
}
function stringToPrecomputedChunk(content) {
  return content;
}
function closeWithError(destination, error) {
  // $FlowFixMe: This is an Error object or the destination accepts other types.
  destination.destroy(error);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}

function checkAttributeStringCoercion(value, attributeName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkCSSPropertyStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkHtmlStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.

var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.

var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.

var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.

var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.

var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.

var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */

var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }

  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }

  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }

  illegalAttributeNameCache[attributeName] = true;

  {
    error('Invalid attribute name: `%s`', attributeName);
  }

  return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }

  switch (typeof value) {
    case 'function': // $FlowIssue symbol is perfectly valid here

    case 'symbol':
      // eslint-disable-line
      return true;

    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }

        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }

    default:
      return false;
  }
}
function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
  this.sanitizeURL = sanitizeURL;
  this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.


var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

reservedProps.forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.

[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).

['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.

['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML boolean attributes.

['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.

['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.

['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be positive numbers.

['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be numbers.

['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
});
var CAMELIZE = /[\-\:]([a-z])/g;

var capitalize = function (token) {
  return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.


['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // String SVG attributes with the xlink namespace.

['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  false);
}); // String SVG attributes with the xml namespace.

['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.

['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.

var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  true, // sanitizeURL
  true);
});

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  aspectRatio: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */

function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */


var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.

Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

var hasReadOnlyValue = {
  button: true,
  checkbox: true,
  image: true,
  hidden: true,
  radio: true,
  reset: true,
  submit: true
};
function checkControlledValueProps(tagName, props) {
  {
    if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
      error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }

    if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
      error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  }
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }

  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this list too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;

    default:
      return true;
  }
}

var ariaProperties = {
  'aria-current': 0,
  // state
  'aria-description': 0,
  'aria-details': 0,
  'aria-disabled': 0,
  // state
  'aria-hidden': 0,
  // state
  'aria-invalid': 0,
  // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

function validateProperty(tagName, name) {
  {
    if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
      return true;
    }

    if (rARIACamel.test(name)) {
      var ariaName = 'aria-' + name.slice(4).toLowerCase();
      var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (correctName == null) {
        error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

        warnedProperties[name] = true;
        return true;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== correctName) {
        error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

        warnedProperties[name] = true;
        return true;
      }
    }

    if (rARIA.test(name)) {
      var lowerCasedName = name.toLowerCase();
      var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (standardName == null) {
        warnedProperties[name] = true;
        return false;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== standardName) {
        error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties[name] = true;
        return true;
      }
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  {
    var invalidProps = [];

    for (var key in props) {
      var isValid = validateProperty(type, key);

      if (!isValid) {
        invalidProps.push(key);
      }
    }

    var unknownPropString = invalidProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (invalidProps.length === 1) {
      error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    } else if (invalidProps.length > 1) {
      error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    }
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;
function validateProperties$1(type, props) {
  {
    if (type !== 'input' && type !== 'textarea' && type !== 'select') {
      return;
    }

    if (props != null && props.value === null && !didWarnValueNull) {
      didWarnValueNull = true;

      if (type === 'select' && props.multiple) {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
      } else {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
      }
    }
  }
}

// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  disablepictureinpicture: 'disablePictureInPicture',
  disableremoteplayback: 'disableRemotePlayback',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  enterkeyhint: 'enterKeyHint',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  imagesizes: 'imageSizes',
  imagesrcset: 'imageSrcSet',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',
  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, eventRegistry) {
    if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();

    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

      warnedProperties$1[name] = true;
      return true;
    } // We can't rely on the event system being injected on the server.


    if (eventRegistry != null) {
      var registrationNameDependencies = eventRegistry.registrationNameDependencies,
          possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

      if (registrationNameDependencies.hasOwnProperty(name)) {
        return true;
      }

      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

      if (registrationName != null) {
        error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (EVENT_NAME_REGEX.test(name)) {
        error('Unknown event handler property `%s`. It will be ignored.', name);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Let the ARIA attribute hook validate ARIA attributes


    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];

      if (standardName !== name) {
        error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
      } else {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Now that we've validated casing, do not validate
    // data types for reserved props


    if (isReserved) {
      return true;
    } // Warn when a known attribute is a bad type


    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    } // Warn when passing the strings 'false' or 'true' into a boolean prop


    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
      error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

      warnedProperties$1[name] = true;
      return true;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, eventRegistry) {
  {
    var unknownProps = [];

    for (var key in props) {
      var isValid = validateProperty$1(type, key, props[key], eventRegistry);

      if (!isValid) {
        unknownProps.push(key);
      }
    }

    var unknownPropString = unknownProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (unknownProps.length === 1) {
      error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    } else if (unknownProps.length > 1) {
      error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    }
  }
};

function validateProperties$2(type, props, eventRegistry) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnUnknownProperties(type, props, eventRegistry);
}

var warnValidStyle = function () {};

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

  var badStyleValueWithSemicolonPattern = /;\s*$/;
  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var camelize = function (string) {
    return string.replace(hyphenPattern, function (_, character) {
      return character.toUpperCase();
    });
  };

  var warnHyphenatedStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
    // is converted to lowercase `ms`.
    camelize(name.replace(msPattern, 'ms-')));
  };

  var warnBadVendoredStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
  };

  var warnStyleValueWithSemicolon = function (name, value) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;

    error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
  };

  var warnStyleValueIsNaN = function (name, value) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;

    error('`NaN` is an invalid value for the `%s` css style property.', name);
  };

  var warnStyleValueIsInfinity = function (name, value) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;

    error('`Infinity` is an invalid value for the `%s` css style property.', name);
  };

  warnValidStyle = function (name, value) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

// code copied and modified from escape-html
var matchHtmlRegExp = /["'&<>]/;
/**
 * Escapes special characters and HTML entities in a given html string.
 *
 * @param  {string} string HTML string to escape for later insertion
 * @return {string}
 * @public
 */

function escapeHtml(string) {
  {
    checkHtmlStringCoercion(string);
  }

  var str = '' + string;
  var match = matchHtmlRegExp.exec(str);

  if (!match) {
    return str;
  }

  var escape;
  var html = '';
  var index;
  var lastIndex = 0;

  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        // "
        escape = '&quot;';
        break;

      case 38:
        // &
        escape = '&amp;';
        break;

      case 39:
        // '
        escape = '&#x27;'; // modified from escape-html; used to be '&#39'

        break;

      case 60:
        // <
        escape = '&lt;';
        break;

      case 62:
        // >
        escape = '&gt;';
        break;

      default:
        continue;
    }

    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }

    lastIndex = index + 1;
    html += escape;
  }

  return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
} // end code copied and modified from escape-html

/**
 * Escapes text to prevent scripting attacks.
 *
 * @param {*} text Text value to escape.
 * @return {string} An escaped string.
 */


function escapeTextForBrowser(text) {
  if (typeof text === 'boolean' || typeof text === 'number') {
    // this shortcircuit helps perf for types that we know will never have
    // special characters, especially given that this function is used often
    // for numeric dom ids.
    return '' + text;
  }

  return escapeHtml(text);
}

var uppercasePattern = /([A-Z])/g;
var msPattern$1 = /^ms-/;
/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */

function hyphenateStyleName(name) {
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
}

// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space

/* eslint-disable max-len */

var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;

function sanitizeURL(url) {
  {
    if (!didWarn && isJavaScriptProtocol.test(url)) {
      didWarn = true;

      error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var startInlineScript = stringToPrecomputedChunk('<script>');
var endInlineScript = stringToPrecomputedChunk('</script>');
var startScriptSrc = stringToPrecomputedChunk('<script src="');
var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
/**
 * This escaping function is designed to work with bootstrapScriptContent only.
 * because we know we are escaping the entire script. We can avoid for instance
 * escaping html comment string sequences that are valid javascript as well because
 * if there are no sebsequent <script sequences the html parser will never enter
 * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
 *
 * While untrusted script content should be made safe before using this api it will
 * ensure that the script cannot be early terminated or never terminated state
 */

function escapeBootstrapScriptContent(scriptText) {
  {
    checkHtmlStringCoercion(scriptText);
  }

  return ('' + scriptText).replace(scriptRegex, scriptReplacer);
}

var scriptRegex = /(<\/|<)(s)(cript)/gi;

var scriptReplacer = function (match, prefix, s, suffix) {
  return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
}; // Allows us to keep track of what we've already written so we can refer back to it.


function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
  var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
  var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
  var bootstrapChunks = [];

  if (bootstrapScriptContent !== undefined) {
    bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
  }

  if (bootstrapScripts !== undefined) {
    for (var i = 0; i < bootstrapScripts.length; i++) {
      bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
    }
  }

  if (bootstrapModules !== undefined) {
    for (var _i = 0; _i < bootstrapModules.length; _i++) {
      bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
    }
  }

  return {
    bootstrapChunks: bootstrapChunks,
    startInlineScript: inlineScriptWithNonce,
    placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
    segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
    boundaryPrefix: idPrefix + 'B:',
    idPrefix: idPrefix,
    nextSuspenseID: 0,
    sentCompleteSegmentFunction: false,
    sentCompleteBoundaryFunction: false,
    sentClientRenderFunction: false
  };
} // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
// modes. We only include the variants as they matter for the sake of our purposes.
// We don't actually provide the namespace therefore we use constants instead of the string.

var ROOT_HTML_MODE = 0; // Used for the root most element tag.

var HTML_MODE = 1;
var SVG_MODE = 2;
var MATHML_MODE = 3;
var HTML_TABLE_MODE = 4;
var HTML_TABLE_BODY_MODE = 5;
var HTML_TABLE_ROW_MODE = 6;
var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
// still makes sense

function createFormatContext(insertionMode, selectedValue) {
  return {
    insertionMode: insertionMode,
    selectedValue: selectedValue
  };
}
function getChildFormatContext(parentContext, type, props) {
  switch (type) {
    case 'select':
      return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

    case 'svg':
      return createFormatContext(SVG_MODE, null);

    case 'math':
      return createFormatContext(MATHML_MODE, null);

    case 'foreignObject':
      return createFormatContext(HTML_MODE, null);
    // Table parents are special in that their children can only be created at all if they're
    // wrapped in a table parent. So we need to encode that we're entering this mode.

    case 'table':
      return createFormatContext(HTML_TABLE_MODE, null);

    case 'thead':
    case 'tbody':
    case 'tfoot':
      return createFormatContext(HTML_TABLE_BODY_MODE, null);

    case 'colgroup':
      return createFormatContext(HTML_COLGROUP_MODE, null);

    case 'tr':
      return createFormatContext(HTML_TABLE_ROW_MODE, null);
  }

  if (parentContext.insertionMode >= HTML_TABLE_MODE) {
    // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
    // entered plain HTML again.
    return createFormatContext(HTML_MODE, null);
  }

  if (parentContext.insertionMode === ROOT_HTML_MODE) {
    // We've emitted the root and is now in plain HTML mode.
    return createFormatContext(HTML_MODE, null);
  }

  return parentContext;
}
var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
function assignSuspenseBoundaryID(responseState) {
  var generatedID = responseState.nextSuspenseID++;
  return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
}
function makeId(responseState, treeId, localId) {
  var idPrefix = responseState.idPrefix;
  var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
  // that represents the position of this useId hook among all the useId
  // hooks for this fiber.

  if (localId > 0) {
    id += 'H' + localId.toString(32);
  }

  return id + ':';
}

function encodeHTMLTextNode(text) {
  return escapeTextForBrowser(text);
}

var textSeparator = stringToPrecomputedChunk('<!-- -->');
function pushTextInstance(target, text, responseState, textEmbedded) {
  if (text === '') {
    // Empty text doesn't have a DOM node representation and the hydration is aware of this.
    return textEmbedded;
  }

  if (textEmbedded) {
    target.push(textSeparator);
  }

  target.push(stringToChunk(encodeHTMLTextNode(text)));
  return true;
} // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
// emit a text separator when we don't know for sure it is safe to omit

function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
  if (lastPushedText && textEmbedded) {
    target.push(textSeparator);
  }
}
var styleNameCache = new Map();

function processStyleName(styleName) {
  var chunk = styleNameCache.get(styleName);

  if (chunk !== undefined) {
    return chunk;
  }

  var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
  styleNameCache.set(styleName, result);
  return result;
}

var styleAttributeStart = stringToPrecomputedChunk(' style="');
var styleAssign = stringToPrecomputedChunk(':');
var styleSeparator = stringToPrecomputedChunk(';');

function pushStyle(target, responseState, style) {
  if (typeof style !== 'object') {
    throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
  }

  var isFirst = true;

  for (var styleName in style) {
    if (!hasOwnProperty.call(style, styleName)) {
      continue;
    } // If you provide unsafe user data here they can inject arbitrary CSS
    // which may be problematic (I couldn't repro this):
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
    // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
    // This is not an XSS hole but instead a potential CSS injection issue
    // which has lead to a greater discussion about how we're going to
    // trust URLs moving forward. See #2115901


    var styleValue = style[styleName];

    if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
      // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
      continue;
    }

    var nameChunk = void 0;
    var valueChunk = void 0;
    var isCustomProperty = styleName.indexOf('--') === 0;

    if (isCustomProperty) {
      nameChunk = stringToChunk(escapeTextForBrowser(styleName));

      {
        checkCSSPropertyStringCoercion(styleValue, styleName);
      }

      valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
    } else {
      {
        warnValidStyle$1(styleName, styleValue);
      }

      nameChunk = processStyleName(styleName);

      if (typeof styleValue === 'number') {
        if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
          valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
        } else {
          valueChunk = stringToChunk('' + styleValue);
        }
      } else {
        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      }
    }

    if (isFirst) {
      isFirst = false; // If it's first, we don't need any separators prefixed.

      target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
    } else {
      target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
    }
  }

  if (!isFirst) {
    target.push(attributeEnd);
  }
}

var attributeSeparator = stringToPrecomputedChunk(' ');
var attributeAssign = stringToPrecomputedChunk('="');
var attributeEnd = stringToPrecomputedChunk('"');
var attributeEmptyString = stringToPrecomputedChunk('=""');

function pushAttribute(target, responseState, name, value) {
  switch (name) {
    case 'style':
      {
        pushStyle(target, responseState, value);
        return;
      }

    case 'defaultValue':
    case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

    case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

    case 'suppressContentEditableWarning':
    case 'suppressHydrationWarning':
      // Ignored. These are built-in to React on the client.
      return;
  }

  if ( // shouldIgnoreAttribute
  // We have already filtered out null/undefined and reserved words.
  name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return;
  }

  var propertyInfo = getPropertyInfo(name);

  if (propertyInfo !== null) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          if (!propertyInfo.acceptsBooleans) {
            return;
          }
        }
    }

    var attributeName = propertyInfo.attributeName;
    var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

    switch (propertyInfo.type) {
      case BOOLEAN:
        if (value) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        }

        return;

      case OVERLOADED_BOOLEAN:
        if (value === true) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        } else if (value === false) ; else {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        return;

      case NUMERIC:
        if (!isNaN(value)) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      case POSITIVE_NUMERIC:
        if (!isNaN(value) && value >= 1) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      default:
        if (propertyInfo.sanitizeURL) {
          {
            checkAttributeStringCoercion(value, attributeName);
          }

          value = '' + value;
          sanitizeURL(value);
        }

        target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  } else if (isAttributeNameSafe(name)) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          var prefix = name.toLowerCase().slice(0, 5);

          if (prefix !== 'data-' && prefix !== 'aria-') {
            return;
          }
        }
    }

    target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
  }
}

var endOfStartTag = stringToPrecomputedChunk('>');
var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

function pushInnerHTML(target, innerHTML, children) {
  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      {
        checkHtmlStringCoercion(html);
      }

      target.push(stringToChunk('' + html));
    }
  }
} // TODO: Move these to ResponseState so that we warn for every request.
// It would help debugging in stateful servers (e.g. service worker).


var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnInvalidOptionInnerHTML = false;
var didWarnSelectedSetOnOption = false;

function checkSelectProp(props, propName) {
  {
    var value = props[propName];

    if (value != null) {
      var array = isArray(value);

      if (props.multiple && !array) {
        error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
      } else if (!props.multiple && array) {
        error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
      }
    }
  }
}

function pushStartSelect(target, props, responseState) {
  {
    checkControlledValueProps('select', props);
    checkSelectProp(props, 'value');
    checkSelectProp(props, 'defaultValue');

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
      error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultSelectValue = true;
    }
  }

  target.push(startChunkForTag('select'));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          // TODO: This doesn't really make sense for select since it can't use the controlled
          // value in the innerHTML.
          innerHTML = propValue;
          break;

        case 'defaultValue':
        case 'value':
          // These are set on the Context instead and applied to the nested options.
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function flattenOptionChildren(children) {
  var content = ''; // Flatten children and warn if they aren't strings or numbers;
  // invalid types are ignored.

  React.Children.forEach(children, function (child) {
    if (child == null) {
      return;
    }

    content += child;

    {
      if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
        didWarnInvalidOptionChildren = true;

        error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
      }
    }
  });
  return content;
}

var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

function pushStartOption(target, props, responseState, formatContext) {
  var selectedValue = formatContext.selectedValue;
  target.push(startChunkForTag('option'));
  var children = null;
  var value = null;
  var selected = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'selected':
          // ignore
          selected = propValue;

          {
            // TODO: Remove support for `selected` in <option>.
            if (!didWarnSelectedSetOnOption) {
              error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

              didWarnSelectedSetOnOption = true;
            }
          }

          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;
        // eslint-disable-next-line-no-fallthrough

        case 'value':
          value = propValue;
        // We intentionally fallthrough to also set the attribute on the node.
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (selectedValue != null) {
    var stringValue;

    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      stringValue = '' + value;
    } else {
      {
        if (innerHTML !== null) {
          if (!didWarnInvalidOptionInnerHTML) {
            didWarnInvalidOptionInnerHTML = true;

            error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
          }
        }
      }

      stringValue = flattenOptionChildren(children);
    }

    if (isArray(selectedValue)) {
      // multiple
      for (var i = 0; i < selectedValue.length; i++) {
        {
          checkAttributeStringCoercion(selectedValue[i], 'value');
        }

        var v = '' + selectedValue[i];

        if (v === stringValue) {
          target.push(selectedMarkerAttribute);
          break;
        }
      }
    } else {
      {
        checkAttributeStringCoercion(selectedValue, 'select.value');
      }

      if ('' + selectedValue === stringValue) {
        target.push(selectedMarkerAttribute);
      }
    }
  } else if (selected) {
    target.push(selectedMarkerAttribute);
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function pushInput(target, props, responseState) {
  {
    checkControlledValueProps('input', props);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
      error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultChecked = true;
    }

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
      error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultInputValue = true;
    }
  }

  target.push(startChunkForTag('input'));
  var value = null;
  var defaultValue = null;
  var checked = null;
  var defaultChecked = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        case 'defaultChecked':
          defaultChecked = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'checked':
          checked = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (checked !== null) {
    pushAttribute(target, responseState, 'checked', checked);
  } else if (defaultChecked !== null) {
    pushAttribute(target, responseState, 'checked', defaultChecked);
  }

  if (value !== null) {
    pushAttribute(target, responseState, 'value', value);
  } else if (defaultValue !== null) {
    pushAttribute(target, responseState, 'value', defaultValue);
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartTextArea(target, props, responseState) {
  {
    checkControlledValueProps('textarea', props);

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
      error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultTextareaValue = true;
    }
  }

  target.push(startChunkForTag('textarea'));
  var value = null;
  var defaultValue = null;
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (value === null && defaultValue !== null) {
    value = defaultValue;
  }

  target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

  if (children != null) {
    {
      error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
    }

    if (value != null) {
      throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
    }

    if (isArray(children)) {
      if (children.length > 1) {
        throw new Error('<textarea> can only have at most one child.');
      } // TODO: remove the coercion and the DEV check below because it will
      // always be overwritten by the coercion several lines below it. #22309


      {
        checkHtmlStringCoercion(children[0]);
      }

      value = '' + children[0];
    }

    {
      checkHtmlStringCoercion(children);
    }

    value = '' + children;
  }

  if (typeof value === 'string' && value[0] === '\n') {
    // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    target.push(leadingNewline);
  } // ToString and push directly instead of recurse over children.
  // We don't really support complex children in the value anyway.
  // This also currently avoids a trailing comment node which breaks textarea.


  if (value !== null) {
    {
      checkAttributeStringCoercion(value, 'value');
    }

    target.push(stringToChunk(encodeHTMLTextNode('' + value)));
  }

  return null;
}

function pushSelfClosing(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartMenuItem(target, props, responseState) {
  target.push(startChunkForTag('menuitem'));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  return null;
}

function pushStartTitle(target, props, responseState) {
  target.push(startChunkForTag('title'));
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);

  {
    var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

    if (Array.isArray(children) && children.length > 1) {
      error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && child.$$typeof != null) {
      error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
      error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    }
  }

  return children;
}

function pushStartGenericElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);

  if (typeof children === 'string') {
    // Special case children as a string to avoid the unnecessary comment.
    // TODO: Remove this special case after the general optimization is in place.
    target.push(stringToChunk(encodeHTMLTextNode(children)));
    return null;
  }

  return children;
}

function pushStartCustomElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        case 'style':
          pushStyle(target, responseState, propValue);
          break;

        case 'suppressContentEditableWarning':
        case 'suppressHydrationWarning':
          // Ignored. These are built-in to React on the client.
          break;

        default:
          if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
            target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
          }

          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

var leadingNewline = stringToPrecomputedChunk('\n');

function pushStartPreformattedElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
  // Prefer to break application/xml over text/html (for now) by adding
  // a newline specifically to get eaten by the parser. (Alternately for
  // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
  // \r is normalized out by HTMLTextAreaElement#value.)
  // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
  // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
  // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
  // See: Parsing of "textarea" "listing" and "pre" elements
  //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
  // TODO: This doesn't deal with the case where the child is an array
  // or component that returns a string.

  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
        target.push(leadingNewline, stringToChunk(html));
      } else {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  }

  if (typeof children === 'string' && children[0] === '\n') {
    target.push(leadingNewline);
  }

  return children;
} // We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name


var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

var validatedTagCache = new Map();

function startChunkForTag(tag) {
  var tagStartChunk = validatedTagCache.get(tag);

  if (tagStartChunk === undefined) {
    if (!VALID_TAG_REGEX.test(tag)) {
      throw new Error("Invalid tag: " + tag);
    }

    tagStartChunk = stringToPrecomputedChunk('<' + tag);
    validatedTagCache.set(tag, tagStartChunk);
  }

  return tagStartChunk;
}

var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
function pushStartInstance(target, type, props, responseState, formatContext) {
  {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, null);

    if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
      error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
    }

    if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
      if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
        error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
      }
    }
  }

  switch (type) {
    // Special tags
    case 'select':
      return pushStartSelect(target, props, responseState);

    case 'option':
      return pushStartOption(target, props, responseState, formatContext);

    case 'textarea':
      return pushStartTextArea(target, props, responseState);

    case 'input':
      return pushInput(target, props, responseState);

    case 'menuitem':
      return pushStartMenuItem(target, props, responseState);

    case 'title':
      return pushStartTitle(target, props, responseState);
    // Newline eating tags

    case 'listing':
    case 'pre':
      {
        return pushStartPreformattedElement(target, props, type, responseState);
      }
    // Omitted close tags

    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        return pushSelfClosing(target, props, type, responseState);
      }
    // These are reserved SVG and MathML elements, that are never custom elements.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      {
        return pushStartGenericElement(target, props, type, responseState);
      }

    case 'html':
      {
        if (formatContext.insertionMode === ROOT_HTML_MODE) {
          // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
          // then we also emit the DOCTYPE as part of the root content as a convenience for
          // rendering the whole document.
          target.push(DOCTYPE);
        }

        return pushStartGenericElement(target, props, type, responseState);
      }

    default:
      {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
          // Generic element
          return pushStartGenericElement(target, props, type, responseState);
        } else {
          // Custom element
          return pushStartCustomElement(target, props, type, responseState);
        }
      }
  }
}
var endTag1 = stringToPrecomputedChunk('</');
var endTag2 = stringToPrecomputedChunk('>');
function pushEndInstance(target, type, props) {
  switch (type) {
    // Omitted close tags
    // TODO: Instead of repeating this switch we could try to pass a flag from above.
    // That would require returning a tuple. Which might be ok if it gets inlined.
    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'input':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        // No close tag needed.
        break;
      }

    default:
      {
        target.push(endTag1, stringToChunk(type), endTag2);
      }
  }
}
function writeCompletedRoot(destination, responseState) {
  var bootstrapChunks = responseState.bootstrapChunks;
  var i = 0;

  for (; i < bootstrapChunks.length - 1; i++) {
    writeChunk(destination, bootstrapChunks[i]);
  }

  if (i < bootstrapChunks.length) {
    return writeChunkAndReturn(destination, bootstrapChunks[i]);
  }

  return true;
} // Structural Nodes
// A placeholder is a node inside a hidden partial tree that can be filled in later, but before
// display. It's never visible to users. We use the template tag because it can be used in every
// type of parent. <script> tags also work in every other tag except <colgroup>.

var placeholder1 = stringToPrecomputedChunk('<template id="');
var placeholder2 = stringToPrecomputedChunk('"></template>');
function writePlaceholder(destination, responseState, id) {
  writeChunk(destination, placeholder1);
  writeChunk(destination, responseState.placeholderPrefix);
  var formattedID = stringToChunk(id.toString(16));
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, placeholder2);
} // Suspense boundaries are encoded as comments.

var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
function writeStartCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
}
function writeStartPendingSuspenseBoundary(destination, responseState, id) {
  writeChunk(destination, startPendingSuspenseBoundary1);

  if (id === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, id);
  return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
}
function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
  var result;
  result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
  writeChunk(destination, clientRenderedSuspenseBoundaryError1);

  if (errorDigest) {
    writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
    writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
    writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
  }

  {
    if (errorMesssage) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }
  }

  result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
  return result;
}
function writeEndCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndPendingSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
var startSegmentHTML2 = stringToPrecomputedChunk('">');
var endSegmentHTML = stringToPrecomputedChunk('</div>');
var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
var startSegmentSVG2 = stringToPrecomputedChunk('">');
var endSegmentSVG = stringToPrecomputedChunk('</svg>');
var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
var startSegmentMathML2 = stringToPrecomputedChunk('">');
var endSegmentMathML = stringToPrecomputedChunk('</math>');
var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
var startSegmentTable2 = stringToPrecomputedChunk('">');
var endSegmentTable = stringToPrecomputedChunk('</table>');
var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
var startSegmentTableBody2 = stringToPrecomputedChunk('">');
var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
var startSegmentTableRow2 = stringToPrecomputedChunk('">');
var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
var startSegmentColGroup2 = stringToPrecomputedChunk('">');
var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
function writeStartSegment(destination, responseState, formatContext, id) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        writeChunk(destination, startSegmentHTML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentHTML2);
      }

    case SVG_MODE:
      {
        writeChunk(destination, startSegmentSVG);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentSVG2);
      }

    case MATHML_MODE:
      {
        writeChunk(destination, startSegmentMathML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentMathML2);
      }

    case HTML_TABLE_MODE:
      {
        writeChunk(destination, startSegmentTable);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTable2);
      }
    // TODO: For the rest of these, there will be extra wrapper nodes that never
    // get deleted from the document. We need to delete the table too as part
    // of the injected scripts. They are invisible though so it's not too terrible
    // and it's kind of an edge case to suspend in a table. Totally supported though.

    case HTML_TABLE_BODY_MODE:
      {
        writeChunk(destination, startSegmentTableBody);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableBody2);
      }

    case HTML_TABLE_ROW_MODE:
      {
        writeChunk(destination, startSegmentTableRow);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableRow2);
      }

    case HTML_COLGROUP_MODE:
      {
        writeChunk(destination, startSegmentColGroup);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentColGroup2);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
}
function writeEndSegment(destination, formatContext) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentHTML);
      }

    case SVG_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentSVG);
      }

    case MATHML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentMathML);
      }

    case HTML_TABLE_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTable);
      }

    case HTML_TABLE_BODY_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableBody);
      }

    case HTML_TABLE_ROW_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableRow);
      }

    case HTML_COLGROUP_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentColGroup);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
} // Instruction Set
// The following code is the source scripts that we then minify and inline below,
// with renamed function names that we hope don't collide:
// const COMMENT_NODE = 8;
// const SUSPENSE_START_DATA = '$';
// const SUSPENSE_END_DATA = '/$';
// const SUSPENSE_PENDING_START_DATA = '$?';
// const SUSPENSE_FALLBACK_START_DATA = '$!';
//
// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//   // Tag it to be client rendered.
//   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
//   // assign error metadata to first sibling
//   let dataset = suspenseIdNode.dataset;
//   if (errorDigest) dataset.dgst = errorDigest;
//   if (errorMsg) dataset.msg = errorMsg;
//   if (errorComponentStack) dataset.stck = errorComponentStack;
//   // Tell React to retry it if the parent already hydrated.
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeBoundary(suspenseBoundaryID, contentID) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   const contentNode = document.getElementById(contentID);
//   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
//   // This might also help by not causing recalcing each time we move a child from here to the target.
//   contentNode.parentNode.removeChild(contentNode);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated. That's fine there's nothing to do
//     // but we have to make sure that we already deleted the container node.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//
//   // Clear all the existing children. This is complicated because
//   // there can be embedded Suspense boundaries in the fallback.
//   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
//   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
//   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
//   const parentInstance = suspenseNode.parentNode;
//   let node = suspenseNode.nextSibling;
//   let depth = 0;
//   do {
//     if (node && node.nodeType === COMMENT_NODE) {
//       const data = node.data;
//       if (data === SUSPENSE_END_DATA) {
//         if (depth === 0) {
//           break;
//         } else {
//           depth--;
//         }
//       } else if (
//         data === SUSPENSE_START_DATA ||
//         data === SUSPENSE_PENDING_START_DATA ||
//         data === SUSPENSE_FALLBACK_START_DATA
//       ) {
//         depth++;
//       }
//     }
//
//     const nextNode = node.nextSibling;
//     parentInstance.removeChild(node);
//     node = nextNode;
//   } while (node);
//
//   const endOfBoundary = node;
//
//   // Insert all the children from the contentNode between the start and end of suspense boundary.
//   while (contentNode.firstChild) {
//     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
//   }
//   suspenseNode.data = SUSPENSE_START_DATA;
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeSegment(containerID, placeholderID) {
//   const segmentContainer = document.getElementById(containerID);
//   const placeholderNode = document.getElementById(placeholderID);
//   // We always expect both nodes to exist here because, while we might
//   // have navigated away from the main tree, we still expect the detached
//   // tree to exist.
//   segmentContainer.parentNode.removeChild(segmentContainer);
//   while (segmentContainer.firstChild) {
//     placeholderNode.parentNode.insertBefore(
//       segmentContainer.firstChild,
//       placeholderNode,
//     );
//   }
//   placeholderNode.parentNode.removeChild(placeholderNode);
// }

var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
var completeSegmentScript2 = stringToPrecomputedChunk('","');
var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteSegmentFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteSegmentFunction = true;
    writeChunk(destination, completeSegmentScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeSegmentScript1Partial);
  }

  writeChunk(destination, responseState.segmentPrefix);
  var formattedID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, formattedID);
  writeChunk(destination, completeSegmentScript2);
  writeChunk(destination, responseState.placeholderPrefix);
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, completeSegmentScript3);
}
var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
var completeBoundaryScript2 = stringToPrecomputedChunk('","');
var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteBoundaryFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteBoundaryFunction = true;
    writeChunk(destination, completeBoundaryScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeBoundaryScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  var formattedContentID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, boundaryID);
  writeChunk(destination, completeBoundaryScript2);
  writeChunk(destination, responseState.segmentPrefix);
  writeChunk(destination, formattedContentID);
  return writeChunkAndReturn(destination, completeBoundaryScript3);
}
var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
var clientRenderScript1A = stringToPrecomputedChunk('"');
var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentClientRenderFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentClientRenderFunction = true;
    writeChunk(destination, clientRenderScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, clientRenderScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, boundaryID);
  writeChunk(destination, clientRenderScript1A);

  if (errorDigest || errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
  }

  if (errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
  }

  if (errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
  }

  return writeChunkAndReturn(destination, clientRenderScript2);
}
var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

function escapeJSStringsForInstructionScripts(input) {
  var escaped = JSON.stringify(input);
  return escaped.replace(regexForJSStringsInScripts, function (match) {
    switch (match) {
      // santizing breaking out of strings and script tags
      case '<':
        return "\\u003c";

      case "\u2028":
        return "\\u2028";

      case "\u2029":
        return "\\u2029";

      default:
        {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
        }
    }
  });
}

function createResponseState$1(generateStaticMarkup, identifierPrefix) {
  var responseState = createResponseState(identifierPrefix, undefined);
  return {
    // Keep this in sync with ReactDOMServerFormatConfig
    bootstrapChunks: responseState.bootstrapChunks,
    startInlineScript: responseState.startInlineScript,
    placeholderPrefix: responseState.placeholderPrefix,
    segmentPrefix: responseState.segmentPrefix,
    boundaryPrefix: responseState.boundaryPrefix,
    idPrefix: responseState.idPrefix,
    nextSuspenseID: responseState.nextSuspenseID,
    sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction,
    sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction,
    sentClientRenderFunction: responseState.sentClientRenderFunction,
    // This is an extra field for the legacy renderer
    generateStaticMarkup: generateStaticMarkup
  };
}
function createRootFormatContext() {
  return {
    insertionMode: HTML_MODE,
    // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode.
    selectedValue: null
  };
}
function pushTextInstance$1(target, text, responseState, textEmbedded) {
  if (responseState.generateStaticMarkup) {
    target.push(stringToChunk(escapeTextForBrowser(text)));
    return false;
  } else {
    return pushTextInstance(target, text, responseState, textEmbedded);
  }
}
function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) {
  if (responseState.generateStaticMarkup) {
    return;
  } else {
    return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded);
  }
}
function writeStartCompletedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    // A completed boundary is done and doesn't need a representation in the HTML
    // if we're not going to be hydrating it.
    return true;
  }

  return writeStartCompletedSuspenseBoundary(destination);
}
function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format.
errorDigest, errorMessage, errorComponentStack) {
  if (responseState.generateStaticMarkup) {
    // A client rendered boundary is done and doesn't need a representation in the HTML
    // since we'll never hydrate it. This is arguably an error in static generation.
    return true;
  }

  return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack);
}
function writeEndCompletedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    return true;
  }

  return writeEndCompletedSuspenseBoundary(destination);
}
function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    return true;
  }

  return writeEndClientRenderedSuspenseBoundary(destination);
}

var assign = Object.assign;

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}

function describeClassComponentFrame(ctor, source, ownerFn) {
  {
    return describeNativeComponentFrame(ctor, true);
  }
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var warnedAboutMissingGetChildContext;

{
  warnedAboutMissingGetChildContext = {};
}

var emptyContextObject = {};

{
  Object.freeze(emptyContextObject);
}

function getMaskedContext(type, unmaskedContext) {
  {
    var contextTypes = type.contextTypes;

    if (!contextTypes) {
      return emptyContextObject;
    }

    var context = {};

    for (var key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(contextTypes, context, 'context', name);
    }

    return context;
  }
}
function processChildContext(instance, type, parentContext, childContextTypes) {
  {
    // TODO (bvaughn) Replace this behavior with an invariant() in the future.
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.
    if (typeof instance.getChildContext !== 'function') {
      {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!warnedAboutMissingGetChildContext[componentName]) {
          warnedAboutMissingGetChildContext[componentName] = true;

          error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
        }
      }

      return parentContext;
    }

    var childContext = instance.getChildContext();

    for (var contextKey in childContext) {
      if (!(contextKey in childContextTypes)) {
        throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
      }
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(childContextTypes, childContext, 'child context', name);
    }

    return assign({}, parentContext, childContext);
  }
}

var rendererSigil;

{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
} // Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.


var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are currently in.

var currentActiveSnapshot = null;

function popNode(prev) {
  {
    prev.context._currentValue2 = prev.parentValue;
  }
}

function pushNode(next) {
  {
    next.context._currentValue2 = next.value;
  }
}

function popToNearestCommonAncestor(prev, next) {
  if (prev === next) ; else {
    popNode(prev);
    var parentPrev = prev.parent;
    var parentNext = next.parent;

    if (parentPrev === null) {
      if (parentNext !== null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }
    } else {
      if (parentNext === null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }

      popToNearestCommonAncestor(parentPrev, parentNext);
    } // On the way back, we push the new ones that weren't common.


    pushNode(next);
  }
}

function popAllPrevious(prev) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev !== null) {
    popAllPrevious(parentPrev);
  }
}

function pushAllNext(next) {
  var parentNext = next.parent;

  if (parentNext !== null) {
    pushAllNext(parentNext);
  }

  pushNode(next);
}

function popPreviousToCommonLevel(prev, next) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (parentPrev.depth === next.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(parentPrev, next);
  } else {
    // We must still be deeper.
    popPreviousToCommonLevel(parentPrev, next);
  }
}

function popNextToCommonLevel(prev, next) {
  var parentNext = next.parent;

  if (parentNext === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (prev.depth === parentNext.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(prev, parentNext);
  } else {
    // We must still be deeper.
    popNextToCommonLevel(prev, parentNext);
  }

  pushNode(next);
} // Perform context switching to the new snapshot.
// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
// updating all the context's current values. That way reads, always just read the current value.
// At the cost of updating contexts even if they're never read by this subtree.


function switchContext(newSnapshot) {
  // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
  // We also need to update any new contexts that are now on the stack with the deepest value.
  // The easiest way to update new contexts is to just reapply them in reverse order from the
  // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
  // for that. Therefore this algorithm is recursive.
  // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
  // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
  // 3) Then we reapply new contexts on the way back up the stack.
  var prev = currentActiveSnapshot;
  var next = newSnapshot;

  if (prev !== next) {
    if (prev === null) {
      // $FlowFixMe: This has to be non-null since it's not equal to prev.
      pushAllNext(next);
    } else if (next === null) {
      popAllPrevious(prev);
    } else if (prev.depth === next.depth) {
      popToNearestCommonAncestor(prev, next);
    } else if (prev.depth > next.depth) {
      popPreviousToCommonLevel(prev, next);
    } else {
      popNextToCommonLevel(prev, next);
    }

    currentActiveSnapshot = next;
  }
}
function pushProvider(context, nextValue) {
  var prevValue;

  {
    prevValue = context._currentValue2;
    context._currentValue2 = nextValue;

    {
      if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer2 = rendererSigil;
    }
  }

  var prevNode = currentActiveSnapshot;
  var newNode = {
    parent: prevNode,
    depth: prevNode === null ? 0 : prevNode.depth + 1,
    context: context,
    parentValue: prevValue,
    value: nextValue
  };
  currentActiveSnapshot = newNode;
  return newNode;
}
function popProvider(context) {
  var prevSnapshot = currentActiveSnapshot;

  if (prevSnapshot === null) {
    throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
  }

  {
    if (prevSnapshot.context !== context) {
      error('The parent context is not the expected context. This is probably a bug in React.');
    }
  }

  {
    var _value = prevSnapshot.parentValue;

    if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
      prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;
    } else {
      prevSnapshot.context._currentValue2 = _value;
    }

    {
      if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer2 = rendererSigil;
    }
  }

  return currentActiveSnapshot = prevSnapshot.parent;
}
function getActiveContext() {
  return currentActiveSnapshot;
}
function readContext(context) {
  var value =  context._currentValue2;
  return value;
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}
function set(key, value) {
  key._reactInternals = value;
}

var didWarnAboutNoopUpdateForComponent = {};
var didWarnAboutDeprecatedWillMount = {};
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;

{
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutDirectlyAssigningPropsToState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();
  didWarnAboutContextTypeAndContextTypes = new Set();
  didWarnAboutInvalidateContextType = new Set();
  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }

    var key = callerName + '_' + callback;

    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);

      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (type, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentNameFromType(type) || 'Component';

      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);

        error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  };
}

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
    var warningKey = componentName + '.' + callerName;

    if (didWarnAboutNoopUpdateForComponent[warningKey]) {
      return;
    }

    error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

    didWarnAboutNoopUpdateForComponent[warningKey] = true;
  }
}

var classComponentUpdater = {
  isMounted: function (inst) {
    return false;
  },
  enqueueSetState: function (inst, payload, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'setState');
    } else {
      internals.queue.push(payload);

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var internals = get(inst);
    internals.replace = true;
    internals.queue = [payload];

    {
      if (callback !== undefined && callback !== null) {
        warnOnInvalidCallback(callback, 'setState');
      }
    }
  },
  enqueueForceUpdate: function (inst, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'forceUpdate');
    } else {
      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  }
};

function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    warnOnUndefinedDerivedState(ctor, partialState);
  } // Merge the partial state and the previous state.


  var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
  return newState;
}

function constructClassInstance(ctor, props, maskedLegacyContext) {
  var context = emptyContextObject;
  var contextType = ctor.contextType;

  {
    if ('contextType' in ctor) {
      var isValid = // Allow null for conditional declaration
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
        didWarnAboutInvalidateContextType.add(ctor);
        var addendum = '';

        if (contextType === undefined) {
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
        } else if (typeof contextType !== 'object') {
          addendum = ' However, it is set to a ' + typeof contextType + '.';
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
          addendum = ' Did you accidentally pass the Context.Provider instead?';
        } else if (contextType._context !== undefined) {
          // <Context.Consumer>
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
        } else {
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
        }

        error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
      }
    }
  }

  if (typeof contextType === 'object' && contextType !== null) {
    context = readContext(contextType);
  } else {
    context = maskedLegacyContext;
  }

  var instance = new ctor(props, context);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);

        error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
      }
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.


    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;

      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }

      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentNameFromType(ctor) || 'Component';

        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

          error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
        }
      }
    }
  }

  return instance;
}

function checkClassInstance(instance, ctor, newProps) {
  {
    var name = getComponentNameFromType(ctor) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
        error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
      error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
    }

    if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
    }

    if (instance.propTypes) {
      error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
    }

    if (instance.contextType) {
      error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
    }

    {
      if (instance.contextTypes) {
        error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
      }

      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
        didWarnAboutContextTypeAndContextTypes.add(ctor);

        error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
      }
    }

    if (typeof instance.componentShouldUpdate === 'function') {
      error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
    }

    if (typeof instance.componentDidUnmount === 'function') {
      error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
    }

    if (typeof instance.componentDidReceiveProps === 'function') {
      error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
    }

    if (typeof instance.componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
    }

    if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
    }

    var hasMutatedProps = instance.props !== newProps;

    if (instance.props !== undefined && hasMutatedProps) {
      error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
    }

    if (instance.defaultProps) {
      error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

      error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
    }

    if (typeof instance.getDerivedStateFromProps === 'function') {
      error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof instance.getDerivedStateFromError === 'function') {
      error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
      error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
    }

    var _state = instance.state;

    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      error('%s.state: must be set to an object or null', name);
    }

    if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
      error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
    }
  }
}

function callComponentWillMount(type, instance) {
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    {
      if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!didWarnAboutDeprecatedWillMount[componentName]) {
          warn( // keep this warning in sync with ReactStrictModeWarning.js
          'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

          didWarnAboutDeprecatedWillMount[componentName] = true;
        }
      }
    }

    instance.componentWillMount();
  }

  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  if (oldState !== instance.state) {
    {
      error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
  if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
    var oldQueue = internalInstance.queue;
    var oldReplace = internalInstance.replace;
    internalInstance.queue = null;
    internalInstance.replace = false;

    if (oldReplace && oldQueue.length === 1) {
      inst.state = oldQueue[0];
    } else {
      var nextState = oldReplace ? oldQueue[0] : inst.state;
      var dontMutate = true;

      for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
        var partial = oldQueue[i];
        var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

        if (partialState != null) {
          if (dontMutate) {
            dontMutate = false;
            nextState = assign({}, nextState, partialState);
          } else {
            assign(nextState, partialState);
          }
        }
      }

      inst.state = nextState;
    }
  } else {
    internalInstance.queue = null;
  }
} // Invokes the mount life-cycles on a previously never rendered instance.


function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
  {
    checkClassInstance(instance, ctor, newProps);
  }

  var initialState = instance.state !== undefined ? instance.state : null;
  instance.updater = classComponentUpdater;
  instance.props = newProps;
  instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
  // The internal instance will be used to manage updates that happen during this mount.

  var internalInstance = {
    queue: [],
    replace: false
  };
  set(instance, internalInstance);
  var contextType = ctor.contextType;

  if (typeof contextType === 'object' && contextType !== null) {
    instance.context = readContext(contextType);
  } else {
    instance.context = maskedLegacyContext;
  }

  {
    if (instance.state === newProps) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);

        error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
      }
    }
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

  if (typeof getDerivedStateFromProps === 'function') {
    instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
  } // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.


  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
    // process them now.

    processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
  }
}

// Ids are base 32 strings whose binary representation corresponds to the
// position of a node in a tree.
// Every time the tree forks into multiple children, we add additional bits to
// the left of the sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5. However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
// the zeroth id at a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in the
// sequence. It's treated as a transparent indirection. For example, these two
// trees produce the same ids:
//
// <>                          <>
//   <Indirection>               <A />
//     <A />                     <B />
//   </Indirection>            </>
//   <B />
// </>
//
// However, we cannot skip any node that materializes an id. Otherwise, a parent
// id that does not fork would be indistinguishable from its child id. For
// example, this tree does not fork, but the parent and child must have
// different ids.
//
// <Parent>
//   <Child />
// </Parent>
//
// To handle this scenario, every time we materialize an id, we allocate a
// new level with a single slot. You can think of this as a fork with only one
// prong, or an array of children with length 1.
//
// It's possible for the size of the sequence to exceed 32 bits, the max
// size for bitwise operations. When this happens, we make more room by
// converting the right part of the id to a string and storing it in an overflow
// variable. We use a base 32 string representation, because 32 is the largest
// power of 2 that is supported by toString(). We want the base to be large so
// that the resulting ids are compact, and we want the base to be a power of 2
// because every log2(base) bits corresponds to a single character, i.e. every
// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
// affecting the final result.
var emptyTreeContext = {
  id: 1,
  overflow: ''
};
function getTreeId(context) {
  var overflow = context.overflow;
  var idWithLeadingBit = context.id;
  var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
  return id.toString(32) + overflow;
}
function pushTreeContext(baseContext, totalChildren, index) {
  var baseIdWithLeadingBit = baseContext.id;
  var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
  // of the id; we use it to account for leading 0s.

  var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
  var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
  var slot = index + 1;
  var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
  // consideration the leading 1 we use to mark the end of the sequence.

  if (length > 30) {
    // We overflowed the bitwise-safe range. Fall back to slower algorithm.
    // This branch assumes the length of the base id is greater than 5; it won't
    // work for smaller ids, because you need 5 bits per character.
    //
    // We encode the id in multiple steps: first the base id, then the
    // remaining digits.
    //
    // Each 5 bit sequence corresponds to a single base 32 character. So for
    // example, if the current id is 23 bits long, we can convert 20 of those
    // bits into a string of 4 characters, with 3 bits left over.
    //
    // First calculate how many bits in the base id represent a complete
    // sequence of characters.
    var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

    var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

    var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

    var restOfBaseId = baseId >> numberOfOverflowBits;
    var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
    // we made more room, this time it won't overflow.

    var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
    var restOfNewBits = slot << restOfBaseLength;
    var id = restOfNewBits | restOfBaseId;
    var overflow = newOverflow + baseOverflow;
    return {
      id: 1 << restOfLength | id,
      overflow: overflow
    };
  } else {
    // Normal path
    var newBits = slot << baseLength;

    var _id = newBits | baseId;

    var _overflow = baseOverflow;
    return {
      id: 1 << length | _id,
      overflow: _overflow
    };
  }
}

function getBitLength(number) {
  return 32 - clz32(number);
}

function getLeadingBit(id) {
  return 1 << getBitLength(id) - 1;
} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

var log = Math.log;
var LN2 = Math.LN2;

function clz32Fallback(x) {
  var asUint = x >>> 0;

  if (asUint === 0) {
    return 32;
  }

  return 31 - (log(asUint) / LN2 | 0) | 0;
}

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  ;
}

var objectIs = typeof Object.is === 'function' ? Object.is : is;

var currentlyRenderingComponent = null;
var currentlyRenderingTask = null;
var firstWorkInProgressHook = null;
var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

var localIdCounter = 0; // Lazily created map of render-phase updates

var renderPhaseUpdates = null; // Counter to prevent infinite loops.

var numberOfReRenders = 0;
var RE_RENDER_LIMIT = 25;
var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

var currentHookNameInDev;

function resolveCurrentlyRenderingComponent() {
  if (currentlyRenderingComponent === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
  }

  {
    if (isInHookUserCodeInDev) {
      error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
    }
  }

  return currentlyRenderingComponent;
}

function areHookInputsEqual(nextDeps, prevDeps) {
  if (prevDeps === null) {
    {
      error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
    }

    return false;
  }

  {
    // Don't bother comparing lengths in prod because these arrays should be
    // passed inline.
    if (nextDeps.length !== prevDeps.length) {
      error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
    }
  }

  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (objectIs(nextDeps[i], prevDeps[i])) {
      continue;
    }

    return false;
  }

  return true;
}

function createHook() {
  if (numberOfReRenders > 0) {
    throw new Error('Rendered more hooks than during the previous render');
  }

  return {
    memoizedState: null,
    queue: null,
    next: null
  };
}

function createWorkInProgressHook() {
  if (workInProgressHook === null) {
    // This is the first hook in the list
    if (firstWorkInProgressHook === null) {
      isReRender = false;
      firstWorkInProgressHook = workInProgressHook = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = firstWorkInProgressHook;
    }
  } else {
    if (workInProgressHook.next === null) {
      isReRender = false; // Append to the end of the list

      workInProgressHook = workInProgressHook.next = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = workInProgressHook.next;
    }
  }

  return workInProgressHook;
}

function prepareToUseHooks(task, componentIdentity) {
  currentlyRenderingComponent = componentIdentity;
  currentlyRenderingTask = task;

  {
    isInHookUserCodeInDev = false;
  } // The following should have already been reset
  // didScheduleRenderPhaseUpdate = false;
  // localIdCounter = 0;
  // firstWorkInProgressHook = null;
  // numberOfReRenders = 0;
  // renderPhaseUpdates = null;
  // workInProgressHook = null;


  localIdCounter = 0;
}
function finishHooks(Component, props, children, refOrContext) {
  // This must be called after every function component to prevent hooks from
  // being used in classes.
  while (didScheduleRenderPhaseUpdate) {
    // Updates were scheduled during the render phase. They are stored in
    // the `renderPhaseUpdates` map. Call the component again, reusing the
    // work-in-progress hooks and applying the additional updates on top. Keep
    // restarting until no more updates are scheduled.
    didScheduleRenderPhaseUpdate = false;
    localIdCounter = 0;
    numberOfReRenders += 1; // Start over from the beginning of the list

    workInProgressHook = null;
    children = Component(props, refOrContext);
  }

  resetHooksState();
  return children;
}
function checkDidRenderIdHook() {
  // This should be called immediately after every finishHooks call.
  // Conceptually, it's part of the return value of finishHooks; it's only a
  // separate function to avoid using an array tuple.
  var didRenderIdHook = localIdCounter !== 0;
  return didRenderIdHook;
} // Reset the internal hooks state if an error occurs while rendering a component

function resetHooksState() {
  {
    isInHookUserCodeInDev = false;
  }

  currentlyRenderingComponent = null;
  currentlyRenderingTask = null;
  didScheduleRenderPhaseUpdate = false;
  firstWorkInProgressHook = null;
  numberOfReRenders = 0;
  renderPhaseUpdates = null;
  workInProgressHook = null;
}

function readContext$1(context) {
  {
    if (isInHookUserCodeInDev) {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    }
  }

  return readContext(context);
}

function useContext(context) {
  {
    currentHookNameInDev = 'useContext';
  }

  resolveCurrentlyRenderingComponent();
  return readContext(context);
}

function basicStateReducer(state, action) {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

function useState(initialState) {
  {
    currentHookNameInDev = 'useState';
  }

  return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
  initialState);
}
function useReducer(reducer, initialArg, init) {
  {
    if (reducer !== basicStateReducer) {
      currentHookNameInDev = 'useReducer';
    }
  }

  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();

  if (isReRender) {
    // This is a re-render. Apply the new render phase updates to the previous
    // current hook.
    var queue = workInProgressHook.queue;
    var dispatch = queue.dispatch;

    if (renderPhaseUpdates !== null) {
      // Render phase updates are stored in a map of queue -> linked list
      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate !== undefined) {
        renderPhaseUpdates.delete(queue);
        var newState = workInProgressHook.memoizedState;
        var update = firstRenderPhaseUpdate;

        do {
          // Process this render phase update. We don't have to check the
          // priority because it will always be the same as the current
          // render's.
          var action = update.action;

          {
            isInHookUserCodeInDev = true;
          }

          newState = reducer(newState, action);

          {
            isInHookUserCodeInDev = false;
          }

          update = update.next;
        } while (update !== null);

        workInProgressHook.memoizedState = newState;
        return [newState, dispatch];
      }
    }

    return [workInProgressHook.memoizedState, dispatch];
  } else {
    {
      isInHookUserCodeInDev = true;
    }

    var initialState;

    if (reducer === basicStateReducer) {
      // Special case for `useState`.
      initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
    } else {
      initialState = init !== undefined ? init(initialArg) : initialArg;
    }

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = initialState;

    var _queue = workInProgressHook.queue = {
      last: null,
      dispatch: null
    };

    var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

    return [workInProgressHook.memoizedState, _dispatch];
  }
}

function useMemo(nextCreate, deps) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;

  if (workInProgressHook !== null) {
    var prevState = workInProgressHook.memoizedState;

    if (prevState !== null) {
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }
  }

  {
    isInHookUserCodeInDev = true;
  }

  var nextValue = nextCreate();

  {
    isInHookUserCodeInDev = false;
  }

  workInProgressHook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function useRef(initialValue) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var previousRef = workInProgressHook.memoizedState;

  if (previousRef === null) {
    var ref = {
      current: initialValue
    };

    {
      Object.seal(ref);
    }

    workInProgressHook.memoizedState = ref;
    return ref;
  } else {
    return previousRef;
  }
}

function useLayoutEffect(create, inputs) {
  {
    currentHookNameInDev = 'useLayoutEffect';

    error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
  }
}

function dispatchAction(componentIdentity, queue, action) {
  if (numberOfReRenders >= RE_RENDER_LIMIT) {
    throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
  }

  if (componentIdentity === currentlyRenderingComponent) {
    // This is a render phase update. Stash it in a lazily-created map of
    // queue -> linked list of updates. After this render pass, we'll restart
    // and apply the stashed updates on top of the work-in-progress hook.
    didScheduleRenderPhaseUpdate = true;
    var update = {
      action: action,
      next: null
    };

    if (renderPhaseUpdates === null) {
      renderPhaseUpdates = new Map();
    }

    var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

    if (firstRenderPhaseUpdate === undefined) {
      renderPhaseUpdates.set(queue, update);
    } else {
      // Append the update to the end of the list.
      var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

      while (lastRenderPhaseUpdate.next !== null) {
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      }

      lastRenderPhaseUpdate.next = update;
    }
  }
}

function useCallback(callback, deps) {
  return useMemo(function () {
    return callback;
  }, deps);
} // TODO Decide on how to implement this hook for server rendering.
// If a mutation occurs during render, consider triggering a Suspense boundary
// and falling back to client rendering.

function useMutableSource(source, getSnapshot, subscribe) {
  resolveCurrentlyRenderingComponent();
  return getSnapshot(source._source);
}

function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  if (getServerSnapshot === undefined) {
    throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
  }

  return getServerSnapshot();
}

function useDeferredValue(value) {
  resolveCurrentlyRenderingComponent();
  return value;
}

function unsupportedStartTransition() {
  throw new Error('startTransition cannot be called during server rendering.');
}

function useTransition() {
  resolveCurrentlyRenderingComponent();
  return [false, unsupportedStartTransition];
}

function useId() {
  var task = currentlyRenderingTask;
  var treeId = getTreeId(task.treeContext);
  var responseState = currentResponseState;

  if (responseState === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
  }

  var localId = localIdCounter++;
  return makeId(responseState, treeId, localId);
}

function noop() {}

var Dispatcher = {
  readContext: readContext$1,
  useContext: useContext,
  useMemo: useMemo,
  useReducer: useReducer,
  useRef: useRef,
  useState: useState,
  useInsertionEffect: noop,
  useLayoutEffect: useLayoutEffect,
  useCallback: useCallback,
  // useImperativeHandle is not run in the server environment
  useImperativeHandle: noop,
  // Effects are not run in the server environment.
  useEffect: noop,
  // Debugging effect
  useDebugValue: noop,
  useDeferredValue: useDeferredValue,
  useTransition: useTransition,
  useId: useId,
  // Subscriptions are not setup in a server environment.
  useMutableSource: useMutableSource,
  useSyncExternalStore: useSyncExternalStore
};

var currentResponseState = null;
function setCurrentResponseState(responseState) {
  currentResponseState = responseState;
}

function getStackByComponentStackNode(componentStack) {
  try {
    var info = '';
    var node = componentStack;

    do {
      switch (node.tag) {
        case 0:
          info += describeBuiltInComponentFrame(node.type, null, null);
          break;

        case 1:
          info += describeFunctionComponentFrame(node.type, null, null);
          break;

        case 2:
          info += describeClassComponentFrame(node.type, null, null);
          break;
      }

      node = node.parent;
    } while (node);

    return info;
  } catch (x) {
    return '\nError generating stack: ' + x.message + '\n' + x.stack;
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
var PENDING = 0;
var COMPLETED = 1;
var FLUSHED = 2;
var ABORTED = 3;
var ERRORED = 4;
var OPEN = 0;
var CLOSING = 1;
var CLOSED = 2;
// This is a default heuristic for how to split up the HTML content into progressive
// loading. Our goal is to be able to display additional new content about every 500ms.
// Faster than that is unnecessary and should be throttled on the client. It also
// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
// end device but higher end suffer less from the overhead than lower end does from
// not getting small enough pieces. We error on the side of low end.
// We base this on low end 3G speeds which is about 500kbits per second. We assume
// that there can be a reasonable drop off from max bandwidth which leaves you with
// as little as 80%. We can receive half of that each 500ms - at best. In practice,
// a little bandwidth is lost to processing and contention - e.g. CSS and images that
// are downloaded along with the main content. So we estimate about half of that to be
// the lower end throughput. In other words, we expect that you can at least show
// about 12.5kb of content per 500ms. Not counting starting latency for the first
// paint.
// 500 * 1024 / 8 * .8 * 0.5 / 2
var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

function defaultErrorHandler(error) {
  console['error'](error); // Don't transform to our wrapper

  return null;
}

function noop$1() {}

function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
  var pingedTasks = [];
  var abortSet = new Set();
  var request = {
    destination: null,
    responseState: responseState,
    progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
    status: OPEN,
    fatalError: null,
    nextSegmentId: 0,
    allPendingTasks: 0,
    pendingRootTasks: 0,
    completedRootSegment: null,
    abortableTasks: abortSet,
    pingedTasks: pingedTasks,
    clientRenderedBoundaries: [],
    completedBoundaries: [],
    partialBoundaries: [],
    onError: onError === undefined ? defaultErrorHandler : onError,
    onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
    onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
    onShellError: onShellError === undefined ? noop$1 : onShellError,
    onFatalError: onFatalError === undefined ? noop$1 : onFatalError
  }; // This segment represents the root fallback.

  var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
  false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

  rootSegment.parentFlushed = true;
  var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
  pingedTasks.push(rootTask);
  return request;
}

function pingTask(request, task) {
  var pingedTasks = request.pingedTasks;
  pingedTasks.push(task);

  if (pingedTasks.length === 1) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
}

function createSuspenseBoundary(request, fallbackAbortableTasks) {
  return {
    id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
    rootSegmentID: -1,
    parentFlushed: false,
    pendingTasks: 0,
    forceClientRender: false,
    completedSegments: [],
    byteSize: 0,
    fallbackAbortableTasks: fallbackAbortableTasks,
    errorDigest: null
  };
}

function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
  request.allPendingTasks++;

  if (blockedBoundary === null) {
    request.pendingRootTasks++;
  } else {
    blockedBoundary.pendingTasks++;
  }

  var task = {
    node: node,
    ping: function () {
      return pingTask(request, task);
    },
    blockedBoundary: blockedBoundary,
    blockedSegment: blockedSegment,
    abortSet: abortSet,
    legacyContext: legacyContext,
    context: context,
    treeContext: treeContext
  };

  {
    task.componentStack = null;
  }

  abortSet.add(task);
  return task;
}

function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
  return {
    status: PENDING,
    id: -1,
    // lazily assigned later
    index: index,
    parentFlushed: false,
    chunks: [],
    children: [],
    formatContext: formatContext,
    boundary: boundary,
    lastPushedText: lastPushedText,
    textEmbedded: textEmbedded
  };
} // DEV-only global reference to the currently executing task


var currentTaskInDEV = null;

function getCurrentStackInDEV() {
  {
    if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
      return '';
    }

    return getStackByComponentStackNode(currentTaskInDEV.componentStack);
  }
}

function pushBuiltInComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 0,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushFunctionComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 1,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushClassComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 2,
      parent: task.componentStack,
      type: type
    };
  }
}

function popComponentStackInDEV(task) {
  {
    if (task.componentStack === null) {
      error('Unexpectedly popped too many stack frames. This is a bug in React.');
    } else {
      task.componentStack = task.componentStack.parent;
    }
  }
} // stash the component stack of an unwinding error until it is processed


var lastBoundaryErrorComponentStackDev = null;

function captureBoundaryErrorDetailsDev(boundary, error) {
  {
    var errorMessage;

    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error && typeof error.message === 'string') {
      errorMessage = error.message;
    } else {
      // eslint-disable-next-line react-internal/safe-string-coercion
      errorMessage = String(error);
    }

    var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
    lastBoundaryErrorComponentStackDev = null;
    boundary.errorMessage = errorMessage;
    boundary.errorComponentStack = errorComponentStack;
  }
}

function logRecoverableError(request, error) {
  // If this callback errors, we intentionally let that error bubble up to become a fatal error
  // so that someone fixes the error reporting instead of hiding it.
  var errorDigest = request.onError(error);

  if (errorDigest != null && typeof errorDigest !== 'string') {
    // eslint-disable-next-line react-internal/prod-error-codes
    throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
  }

  return errorDigest;
}

function fatalError(request, error) {
  // This is called outside error handling code such as if the root errors outside
  // a suspense boundary or if the root suspense boundary's fallback errors.
  // It's also called if React itself or its host configs errors.
  var onShellError = request.onShellError;
  onShellError(error);
  var onFatalError = request.onFatalError;
  onFatalError(error);

  if (request.destination !== null) {
    request.status = CLOSED;
    closeWithError(request.destination, error);
  } else {
    request.status = CLOSING;
    request.fatalError = error;
  }
}

function renderSuspenseBoundary(request, task, props) {
  pushBuiltInComponentStackInDEV(task, 'Suspense');
  var parentBoundary = task.blockedBoundary;
  var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
  // the fallback so that we can later replace that segment with the content.
  // This also lets us split out the main content even if it doesn't suspend,
  // in case it ends up generating a large subtree of content.

  var fallback = props.fallback;
  var content = props.children;
  var fallbackAbortSet = new Set();
  var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
  var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

  var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false);
  parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

  parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

  var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
  // no parent segment so there's nothing to wait on.

  contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
  // I suspect that there might be some efficiency benefits from not creating the suspended task
  // and instead just using the stack if possible.
  // TODO: Call this directly instead of messing with saving and restoring contexts.
  // We can reuse the current context and task to render the content immediately without
  // context switching. We just need to temporarily switch which boundary and which segment
  // we're writing to. If something suspends, it'll spawn new suspended task with that context.

  task.blockedBoundary = newBoundary;
  task.blockedSegment = contentRootSegment;

  try {
    // We use the safe form because we don't handle suspending here. Only error handling.
    renderNode(request, task, content);
    pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
    contentRootSegment.status = COMPLETED;
    queueCompletedSegment(newBoundary, contentRootSegment);

    if (newBoundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      // Therefore we won't need the fallback. We early return so that we don't have to create
      // the fallback.
      popComponentStackInDEV(task);
      return;
    }
  } catch (error) {
    contentRootSegment.status = ERRORED;
    newBoundary.forceClientRender = true;
    newBoundary.errorDigest = logRecoverableError(request, error);

    {
      captureBoundaryErrorDetailsDev(newBoundary, error);
    } // We don't need to decrement any task numbers because we didn't spawn any new task.
    // We don't need to schedule any task because we know the parent has written yet.
    // We do need to fallthrough to create the fallback though.

  } finally {
    task.blockedBoundary = parentBoundary;
    task.blockedSegment = parentSegment;
  } // We create suspended task for the fallback because we don't want to actually work
  // on it yet in case we finish the main content, so we queue for later.


  var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

  {
    suspendedFallbackTask.componentStack = task.componentStack;
  } // TODO: This should be queued at a separate lower priority queue so that we only work
  // on preparing fallbacks if we don't have any more main content to task on.


  request.pingedTasks.push(suspendedFallbackTask);
  popComponentStackInDEV(task);
}

function renderHostElement(request, task, type, props) {
  pushBuiltInComponentStackInDEV(task, type);
  var segment = task.blockedSegment;
  var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
  segment.lastPushedText = false;
  var prevContext = segment.formatContext;
  segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
  // need to pop back up and finish this subtree of HTML.

  renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
  // the correct context. Therefore this is not in a finally.

  segment.formatContext = prevContext;
  pushEndInstance(segment.chunks, type);
  segment.lastPushedText = false;
  popComponentStackInDEV(task);
}

function shouldConstruct$1(Component) {
  return Component.prototype && Component.prototype.isReactComponent;
}

function renderWithHooks(request, task, Component, props, secondArg) {
  var componentIdentity = {};
  prepareToUseHooks(task, componentIdentity);
  var result = Component(props, secondArg);
  return finishHooks(Component, props, result, secondArg);
}

function finishClassComponent(request, task, instance, Component, props) {
  var nextChildren = instance.render();

  {
    if (instance.props !== props) {
      if (!didWarnAboutReassigningProps) {
        error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
      }

      didWarnAboutReassigningProps = true;
    }
  }

  {
    var childContextTypes = Component.childContextTypes;

    if (childContextTypes !== null && childContextTypes !== undefined) {
      var previousContext = task.legacyContext;
      var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
      task.legacyContext = mergedContext;
      renderNodeDestructive(request, task, nextChildren);
      task.legacyContext = previousContext;
      return;
    }
  }

  renderNodeDestructive(request, task, nextChildren);
}

function renderClassComponent(request, task, Component, props) {
  pushClassComponentStackInDEV(task, Component);
  var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
  var instance = constructClassInstance(Component, props, maskedContext);
  mountClassInstance(instance, Component, props, maskedContext);
  finishClassComponent(request, task, instance, Component, props);
  popComponentStackInDEV(task);
}

var didWarnAboutBadClass = {};
var didWarnAboutModulePatternComponent = {};
var didWarnAboutContextTypeOnFunctionComponent = {};
var didWarnAboutGetDerivedStateOnFunctionComponent = {};
var didWarnAboutReassigningProps = false;
var didWarnAboutDefaultPropsOnFunctionComponent = {};
var didWarnAboutGenerators = false;
var didWarnAboutMaps = false;
var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
// components for some reason.

function renderIndeterminateComponent(request, task, Component, props) {
  var legacyContext;

  {
    legacyContext = getMaskedContext(Component, task.legacyContext);
  }

  pushFunctionComponentStackInDEV(task, Component);

  {
    if (Component.prototype && typeof Component.prototype.render === 'function') {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

        didWarnAboutBadClass[componentName] = true;
      }
    }
  }

  var value = renderWithHooks(request, task, Component, props, legacyContext);
  var hasId = checkDidRenderIdHook();

  {
    // Support for module components is deprecated and is removed behind a flag.
    // Whether or not it would crash later, we want to show a good message in DEV first.
    if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      var _componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

        didWarnAboutModulePatternComponent[_componentName] = true;
      }
    }
  }

  if ( // Run these checks in production only if the flag is off.
  // Eventually we'll delete this branch altogether.
   typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    {
      var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName2]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

        didWarnAboutModulePatternComponent[_componentName2] = true;
      }
    }

    mountClassInstance(value, Component, props, legacyContext);
    finishClassComponent(request, task, value, Component, props);
  } else {

    {
      validateFunctionComponentInDev(Component);
    } // We're now successfully past this task, and we don't have to pop back to
    // the previous task every again, so we can use the destructive recursive form.


    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, value);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, value);
    }
  }

  popComponentStackInDEV(task);
}

function validateFunctionComponentInDev(Component) {
  {
    if (Component) {
      if (Component.childContextTypes) {
        error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
      }
    }

    if ( Component.defaultProps !== undefined) {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
        error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

        didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
      }
    }

    if (typeof Component.getDerivedStateFromProps === 'function') {
      var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
        error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

        didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
      }
    }

    if (typeof Component.contextType === 'object' && Component.contextType !== null) {
      var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
        error('%s: Function components do not support contextType.', _componentName4);

        didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
      }
    }
  }
}

function resolveDefaultProps(Component, baseProps) {
  if (Component && Component.defaultProps) {
    // Resolve default props. Taken from ReactElement
    var props = assign({}, baseProps);
    var defaultProps = Component.defaultProps;

    for (var propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }

    return props;
  }

  return baseProps;
}

function renderForwardRef(request, task, type, props, ref) {
  pushFunctionComponentStackInDEV(task, type.render);
  var children = renderWithHooks(request, task, type.render, props, ref);
  var hasId = checkDidRenderIdHook();

  if (hasId) {
    // This component materialized an id. We treat this as its own level, with
    // a single "child" slot.
    var prevTreeContext = task.treeContext;
    var totalChildren = 1;
    var index = 0;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

    try {
      renderNodeDestructive(request, task, children);
    } finally {
      task.treeContext = prevTreeContext;
    }
  } else {
    renderNodeDestructive(request, task, children);
  }

  popComponentStackInDEV(task);
}

function renderMemo(request, task, type, props, ref) {
  var innerType = type.type;
  var resolvedProps = resolveDefaultProps(innerType, props);
  renderElement(request, task, innerType, resolvedProps, ref);
}

function renderContextConsumer(request, task, context, props) {
  // The logic below for Context differs depending on PROD or DEV mode. In
  // DEV mode, we create a separate object for Context.Consumer that acts
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
  // so we use the old behaviour (Context.Consumer references Context) to
  // reduce size and overhead. The separate object references context via
  // a property called "_context", which also gives us the ability to check
  // in DEV mode if this property exists or not and warn if it does not.
  {
    if (context._context === undefined) {
      // This may be because it's a Context (rather than a Consumer).
      // Or it may be because it's older React where they're the same thing.
      // We only want to warn if we're sure it's a new React.
      if (context !== context.Consumer) {
        if (!hasWarnedAboutUsingContextAsConsumer) {
          hasWarnedAboutUsingContextAsConsumer = true;

          error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
        }
      }
    } else {
      context = context._context;
    }
  }

  var render = props.children;

  {
    if (typeof render !== 'function') {
      error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
    }
  }

  var newValue = readContext(context);
  var newChildren = render(newValue);
  renderNodeDestructive(request, task, newChildren);
}

function renderContextProvider(request, task, type, props) {
  var context = type._context;
  var value = props.value;
  var children = props.children;
  var prevSnapshot;

  {
    prevSnapshot = task.context;
  }

  task.context = pushProvider(context, value);
  renderNodeDestructive(request, task, children);
  task.context = popProvider(context);

  {
    if (prevSnapshot !== task.context) {
      error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
    }
  }
}

function renderLazyComponent(request, task, lazyComponent, props, ref) {
  pushBuiltInComponentStackInDEV(task, 'Lazy');
  var payload = lazyComponent._payload;
  var init = lazyComponent._init;
  var Component = init(payload);
  var resolvedProps = resolveDefaultProps(Component, props);
  renderElement(request, task, Component, resolvedProps, ref);
  popComponentStackInDEV(task);
}

function renderElement(request, task, type, props, ref) {
  if (typeof type === 'function') {
    if (shouldConstruct$1(type)) {
      renderClassComponent(request, task, type, props);
      return;
    } else {
      renderIndeterminateComponent(request, task, type, props);
      return;
    }
  }

  if (typeof type === 'string') {
    renderHostElement(request, task, type, props);
    return;
  }

  switch (type) {
    // TODO: LegacyHidden acts the same as a fragment. This only works
    // because we currently assume that every instance of LegacyHidden is
    // accompanied by a host component wrapper. In the hidden mode, the host
    // component is given a `hidden` attribute, which ensures that the
    // initial HTML is not visible. To support the use of LegacyHidden as a
    // true fragment, without an extra DOM node, we would have to hide the
    // initial HTML in some other way.
    // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
    case REACT_LEGACY_HIDDEN_TYPE:
    case REACT_DEBUG_TRACING_MODE_TYPE:
    case REACT_STRICT_MODE_TYPE:
    case REACT_PROFILER_TYPE:
    case REACT_FRAGMENT_TYPE:
      {
        renderNodeDestructive(request, task, props.children);
        return;
      }

    case REACT_SUSPENSE_LIST_TYPE:
      {
        pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

        renderNodeDestructive(request, task, props.children);
        popComponentStackInDEV(task);
        return;
      }

    case REACT_SCOPE_TYPE:
      {

        throw new Error('ReactDOMServer does not yet support scope components.');
      }
    // eslint-disable-next-line-no-fallthrough

    case REACT_SUSPENSE_TYPE:
      {
        {
          renderSuspenseBoundary(request, task, props);
        }

        return;
      }
  }

  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        {
          renderForwardRef(request, task, type, props, ref);
          return;
        }

      case REACT_MEMO_TYPE:
        {
          renderMemo(request, task, type, props, ref);
          return;
        }

      case REACT_PROVIDER_TYPE:
        {
          renderContextProvider(request, task, type, props);
          return;
        }

      case REACT_CONTEXT_TYPE:
        {
          renderContextConsumer(request, task, type, props);
          return;
        }

      case REACT_LAZY_TYPE:
        {
          renderLazyComponent(request, task, type, props);
          return;
        }
    }
  }

  var info = '';

  {
    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
    }
  }

  throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
}

function validateIterable(iterable, iteratorFn) {
  {
    // We don't support rendering Generators because it's a mutation.
    // See https://github.com/facebook/react/issues/12995
    if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
    iterable[Symbol.toStringTag] === 'Generator') {
      if (!didWarnAboutGenerators) {
        error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
      }

      didWarnAboutGenerators = true;
    } // Warn about using Maps as children


    if (iterable.entries === iteratorFn) {
      if (!didWarnAboutMaps) {
        error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
      }

      didWarnAboutMaps = true;
    }
  }
}

function renderNodeDestructive(request, task, node) {
  {
    // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
    // a component stack at the right place in the tree. We don't do this in renderNode
    // becuase it is not called at every layer of the tree and we may lose frames
    try {
      return renderNodeDestructiveImpl(request, task, node);
    } catch (x) {
      if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
        // This is an error, stash the component stack if it is null.
        lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
      } // rethrow so normal suspense logic can handle thrown value accordingly


      throw x;
    }
  }
} // This function by it self renders a node and consumes the task by mutating it
// to update the current execution state.


function renderNodeDestructiveImpl(request, task, node) {
  // Stash the node we're working on. We'll pick up from this task in case
  // something suspends.
  task.node = node; // Handle object types

  if (typeof node === 'object' && node !== null) {
    switch (node.$$typeof) {
      case REACT_ELEMENT_TYPE:
        {
          var element = node;
          var type = element.type;
          var props = element.props;
          var ref = element.ref;
          renderElement(request, task, type, props, ref);
          return;
        }

      case REACT_PORTAL_TYPE:
        throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
      // eslint-disable-next-line-no-fallthrough

      case REACT_LAZY_TYPE:
        {
          var lazyNode = node;
          var payload = lazyNode._payload;
          var init = lazyNode._init;
          var resolvedNode;

          {
            try {
              resolvedNode = init(payload);
            } catch (x) {
              if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                // vs Component position. We do not want the frame for Errors so we exclusively do this in
                // the wakeable branch
                pushBuiltInComponentStackInDEV(task, 'Lazy');
              }

              throw x;
            }
          }

          renderNodeDestructive(request, task, resolvedNode);
          return;
        }
    }

    if (isArray(node)) {
      renderChildrenArray(request, task, node);
      return;
    }

    var iteratorFn = getIteratorFn(node);

    if (iteratorFn) {
      {
        validateIterable(node, iteratorFn);
      }

      var iterator = iteratorFn.call(node);

      if (iterator) {
        // We need to know how many total children are in this set, so that we
        // can allocate enough id slots to acommodate them. So we must exhaust
        // the iterator before we start recursively rendering the children.
        // TODO: This is not great but I think it's inherent to the id
        // generation algorithm.
        var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

        if (!step.done) {
          var children = [];

          do {
            children.push(step.value);
            step = iterator.next();
          } while (!step.done);

          renderChildrenArray(request, task, children);
          return;
        }

        return;
      }
    }

    var childString = Object.prototype.toString.call(node);
    throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
  }

  if (typeof node === 'string') {
    var segment = task.blockedSegment;
    segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
    return;
  }

  if (typeof node === 'number') {
    var _segment = task.blockedSegment;
    _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
    return;
  }

  {
    if (typeof node === 'function') {
      error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
    }
  }
}

function renderChildrenArray(request, task, children) {
  var totalChildren = children.length;

  for (var i = 0; i < totalChildren; i++) {
    var prevTreeContext = task.treeContext;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

    try {
      // We need to use the non-destructive form so that we can safely pop back
      // up and render the sibling if something suspends.
      renderNode(request, task, children[i]);
    } finally {
      task.treeContext = prevTreeContext;
    }
  }
}

function spawnNewSuspendedTask(request, task, x) {
  // Something suspended, we'll need to create a new segment and resolve it later.
  var segment = task.blockedSegment;
  var insertionIndex = segment.chunks.length;
  var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
  segment.lastPushedText, // Assume we are text embedded at the trailing edge
  true);
  segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

  segment.lastPushedText = false;
  var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

  {
    if (task.componentStack !== null) {
      // We pop one task off the stack because the node that suspended will be tried again,
      // which will add it back onto the stack.
      newTask.componentStack = task.componentStack.parent;
    }
  }

  var ping = newTask.ping;
  x.then(ping, ping);
} // This is a non-destructive form of rendering a node. If it suspends it spawns
// a new task and restores the context of this task to what it was before.


function renderNode(request, task, node) {
  // TODO: Store segment.children.length here and reset it in case something
  // suspended partially through writing something.
  // Snapshot the current context in case something throws to interrupt the
  // process.
  var previousFormatContext = task.blockedSegment.formatContext;
  var previousLegacyContext = task.legacyContext;
  var previousContext = task.context;
  var previousComponentStack = null;

  {
    previousComponentStack = task.componentStack;
  }

  try {
    return renderNodeDestructive(request, task, node);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.

      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      }

      return;
    } else {
      // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.
      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      } // We assume that we don't need the correct context.
      // Let's terminate the rest of the tree and don't render any siblings.


      throw x;
    }
  }
}

function erroredTask(request, boundary, segment, error) {
  // Report the error to a global handler.
  var errorDigest = logRecoverableError(request, error);

  if (boundary === null) {
    fatalError(request, error);
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;
      boundary.errorDigest = errorDigest;

      {
        captureBoundaryErrorDetailsDev(boundary, error);
      } // Regardless of what happens next, this boundary won't be displayed,
      // so we can flush it, if the parent already flushed.


      if (boundary.parentFlushed) {
        // We don't have a preference where in the queue this goes since it's likely
        // to error on the client anyway. However, intentionally client-rendered
        // boundaries should be flushed earlier so that they can start on the client.
        // We reuse the same queue for errors.
        request.clientRenderedBoundaries.push(boundary);
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function abortTaskSoft(task) {
  // This aborts task without aborting the parent boundary that it blocks.
  // It's used for when we didn't need this task to complete the tree.
  // If task was needed, then it should use abortTask instead.
  var request = this;
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;
  finishedTask(request, boundary, segment);
}

function abortTask(task, request, reason) {
  // This aborts the task and aborts the parent that it blocks, putting it into
  // client rendered mode.
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;

  if (boundary === null) {
    request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
    // the request;

    if (request.status !== CLOSED) {
      request.status = CLOSED;

      if (request.destination !== null) {
        close(request.destination);
      }
    }
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;

      var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

      boundary.errorDigest = request.onError(_error);

      {
        var errorPrefix = 'The server did not finish this Suspense boundary: ';

        if (_error && typeof _error.message === 'string') {
          _error = errorPrefix + _error.message;
        } else {
          // eslint-disable-next-line react-internal/safe-string-coercion
          _error = errorPrefix + String(_error);
        }

        var previousTaskInDev = currentTaskInDEV;
        currentTaskInDEV = task;

        try {
          captureBoundaryErrorDetailsDev(boundary, _error);
        } finally {
          currentTaskInDEV = previousTaskInDev;
        }
      }

      if (boundary.parentFlushed) {
        request.clientRenderedBoundaries.push(boundary);
      }
    } // If this boundary was still pending then we haven't already cancelled its fallbacks.
    // We'll need to abort the fallbacks, which will also error that parent boundary.


    boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
      return abortTask(fallbackTask, request, reason);
    });
    boundary.fallbackAbortableTasks.clear();
    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }
}

function queueCompletedSegment(boundary, segment) {
  if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
    // This is an empty segment. There's nothing to write, so we can instead transfer the ID
    // to the child. That way any existing references point to the child.
    var childSegment = segment.children[0];
    childSegment.id = segment.id;
    childSegment.parentFlushed = true;

    if (childSegment.status === COMPLETED) {
      queueCompletedSegment(boundary, childSegment);
    }
  } else {
    var completedSegments = boundary.completedSegments;
    completedSegments.push(segment);
  }
}

function finishedTask(request, boundary, segment) {
  if (boundary === null) {
    if (segment.parentFlushed) {
      if (request.completedRootSegment !== null) {
        throw new Error('There can only be one root segment. This is a bug in React.');
      }

      request.completedRootSegment = segment;
    }

    request.pendingRootTasks--;

    if (request.pendingRootTasks === 0) {
      // We have completed the shell so the shell can't error anymore.
      request.onShellError = noop$1;
      var onShellReady = request.onShellReady;
      onShellReady();
    }
  } else {
    boundary.pendingTasks--;

    if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      if (segment.parentFlushed) {
        // Our parent segment already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
        }
      }

      if (boundary.parentFlushed) {
        // The segment might be part of a segment that didn't flush yet, but if the boundary's
        // parent flushed, we need to schedule the boundary to be emitted.
        request.completedBoundaries.push(boundary);
      } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
      // This needs to happen after we read the parentFlushed flags because aborting can finish
      // work which can trigger user code, which can start flushing, which can change those flags.


      boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
      boundary.fallbackAbortableTasks.clear();
    } else {
      if (segment.parentFlushed) {
        // Our parent already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
          var completedSegments = boundary.completedSegments;

          if (completedSegments.length === 1) {
            // This is the first time since we last flushed that we completed anything.
            // We can schedule this boundary to emit its partially completed segments early
            // in case the parent has already been flushed.
            if (boundary.parentFlushed) {
              request.partialBoundaries.push(boundary);
            }
          }
        }
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    // This needs to be called at the very end so that we can synchronously write the result
    // in the callback if needed.
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function retryTask(request, task) {
  var segment = task.blockedSegment;

  if (segment.status !== PENDING) {
    // We completed this by other means before we had a chance to retry it.
    return;
  } // We restore the context to what it was when we suspended.
  // We don't restore it after we leave because it's likely that we'll end up
  // needing a very similar context soon again.


  switchContext(task.context);
  var prevTaskInDEV = null;

  {
    prevTaskInDEV = currentTaskInDEV;
    currentTaskInDEV = task;
  }

  try {
    // We call the destructive form that mutates this task. That way if something
    // suspends again, we can reuse the same task instead of spawning a new one.
    renderNodeDestructive(request, task, task.node);
    pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
    task.abortSet.delete(task);
    segment.status = COMPLETED;
    finishedTask(request, task.blockedBoundary, segment);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      // Something suspended again, let's pick it back up later.
      var ping = task.ping;
      x.then(ping, ping);
    } else {
      task.abortSet.delete(task);
      segment.status = ERRORED;
      erroredTask(request, task.blockedBoundary, segment, x);
    }
  } finally {
    {
      currentTaskInDEV = prevTaskInDEV;
    }
  }
}

function performWork(request) {
  if (request.status === CLOSED) {
    return;
  }

  var prevContext = getActiveContext();
  var prevDispatcher = ReactCurrentDispatcher$1.current;
  ReactCurrentDispatcher$1.current = Dispatcher;
  var prevGetCurrentStackImpl;

  {
    prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
    ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
  }

  var prevResponseState = currentResponseState;
  setCurrentResponseState(request.responseState);

  try {
    var pingedTasks = request.pingedTasks;
    var i;

    for (i = 0; i < pingedTasks.length; i++) {
      var task = pingedTasks[i];
      retryTask(request, task);
    }

    pingedTasks.splice(0, i);

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  } finally {
    setCurrentResponseState(prevResponseState);
    ReactCurrentDispatcher$1.current = prevDispatcher;

    {
      ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
    }

    if (prevDispatcher === Dispatcher) {
      // This means that we were in a reentrant work loop. This could happen
      // in a renderer that supports synchronous work like renderToString,
      // when it's called from within another renderer.
      // Normally we don't bother switching the contexts to their root/default
      // values when leaving because we'll likely need the same or similar
      // context again. However, when we're inside a synchronous loop like this
      // we'll to restore the context to what it was before returning.
      switchContext(prevContext);
    }
  }
}

function flushSubtree(request, destination, segment) {
  segment.parentFlushed = true;

  switch (segment.status) {
    case PENDING:
      {
        // We're emitting a placeholder for this segment to be filled in later.
        // Therefore we'll need to assign it an ID - to refer to it by.
        var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

        segment.lastPushedText = false;
        segment.textEmbedded = false;
        return writePlaceholder(destination, request.responseState, segmentID);
      }

    case COMPLETED:
      {
        segment.status = FLUSHED;
        var r = true;
        var chunks = segment.chunks;
        var chunkIdx = 0;
        var children = segment.children;

        for (var childIdx = 0; childIdx < children.length; childIdx++) {
          var nextChild = children[childIdx]; // Write all the chunks up until the next child.

          for (; chunkIdx < nextChild.index; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          r = flushSegment(request, destination, nextChild);
        } // Finally just write all the remaining chunks


        for (; chunkIdx < chunks.length - 1; chunkIdx++) {
          writeChunk(destination, chunks[chunkIdx]);
        }

        if (chunkIdx < chunks.length) {
          r = writeChunkAndReturn(destination, chunks[chunkIdx]);
        }

        return r;
      }

    default:
      {
        throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
      }
  }
}

function flushSegment(request, destination, segment) {
  var boundary = segment.boundary;

  if (boundary === null) {
    // Not a suspense boundary.
    return flushSubtree(request, destination, segment);
  }

  boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
  // emit the content or the fallback now.

  if (boundary.forceClientRender) {
    // Emit a client rendered suspense boundary wrapper.
    // We never queue the inner boundary so we'll never emit its content or partial segments.
    writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState);
  } else if (boundary.pendingTasks > 0) {
    // This boundary is still loading. Emit a pending suspense boundary wrapper.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;

    if (boundary.completedSegments.length > 0) {
      // If this is at least partially complete, we can queue it to be partially emitted early.
      request.partialBoundaries.push(boundary);
    } /// This is the first time we should have referenced this ID.


    var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
    writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else if (boundary.byteSize > request.progressiveChunkSize) {
    // This boundary is large and will be emitted separately so that we can progressively show
    // other content. We add it to the queue during the flush because we have to ensure that
    // the parent flushes first so that there's something to inject it into.
    // We also have to make sure that it's emitted into the queue in a deterministic slot.
    // I.e. we can't insert it here when it completes.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;
    request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

    writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else {
    // We can inline this boundary's content as a complete boundary.
    writeStartCompletedSuspenseBoundary$1(destination, request.responseState);
    var completedSegments = boundary.completedSegments;

    if (completedSegments.length !== 1) {
      throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
    }

    var contentSegment = completedSegments[0];
    flushSegment(request, destination, contentSegment);
    return writeEndCompletedSuspenseBoundary$1(destination, request.responseState);
  }
}

function flushClientRenderedBoundary(request, destination, boundary) {
  return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
}

function flushSegmentContainer(request, destination, segment) {
  writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
  flushSegment(request, destination, segment);
  return writeEndSegment(destination, segment.formatContext);
}

function flushCompletedBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];
    flushPartiallyCompletedSegment(request, destination, boundary, segment);
  }

  completedSegments.length = 0;
  return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
}

function flushPartialBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];

    if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
      i++;
      completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
      // might want to write later.

      return false;
    }
  }

  completedSegments.splice(0, i);
  return true;
}

function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
  if (segment.status === FLUSHED) {
    // We've already flushed this inline.
    return true;
  }

  var segmentID = segment.id;

  if (segmentID === -1) {
    // This segment wasn't previously referred to. This happens at the root of
    // a boundary. We make kind of a leap here and assume this is the root.
    var rootSegmentID = segment.id = boundary.rootSegmentID;

    if (rootSegmentID === -1) {
      throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
    }

    return flushSegmentContainer(request, destination, segment);
  } else {
    flushSegmentContainer(request, destination, segment);
    return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
  }
}

function flushCompletedQueues(request, destination) {

  try {
    // The structure of this is to go through each queue one by one and write
    // until the sink tells us to stop. When we should stop, we still finish writing
    // that item fully and then yield. At that point we remove the already completed
    // items up until the point we completed them.
    // TODO: Emit preloading.
    // TODO: It's kind of unfortunate to keep checking this array after we've already
    // emitted the root.
    var completedRootSegment = request.completedRootSegment;

    if (completedRootSegment !== null && request.pendingRootTasks === 0) {
      flushSegment(request, destination, completedRootSegment);
      request.completedRootSegment = null;
      writeCompletedRoot(destination, request.responseState);
    } // We emit client rendering instructions for already emitted boundaries first.
    // This is so that we can signal to the client to start client rendering them as
    // soon as possible.


    var clientRenderedBoundaries = request.clientRenderedBoundaries;
    var i;

    for (i = 0; i < clientRenderedBoundaries.length; i++) {
      var boundary = clientRenderedBoundaries[i];

      if (!flushClientRenderedBoundary(request, destination, boundary)) {
        request.destination = null;
        i++;
        clientRenderedBoundaries.splice(0, i);
        return;
      }
    }

    clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
    // that are completely done since we can actually show them, than it is to emit
    // any individual segments from a partially complete boundary.

    var completedBoundaries = request.completedBoundaries;

    for (i = 0; i < completedBoundaries.length; i++) {
      var _boundary = completedBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary)) {
        request.destination = null;
        i++;
        completedBoundaries.splice(0, i);
        return;
      }
    }

    completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
    // we continue with lower priorities.

    completeWriting(destination);
    beginWriting(destination); // TODO: Here we'll emit data used by hydration.
    // Next we emit any segments of any boundaries that are partially complete
    // but not deeply complete.

    var partialBoundaries = request.partialBoundaries;

    for (i = 0; i < partialBoundaries.length; i++) {
      var _boundary2 = partialBoundaries[i];

      if (!flushPartialBoundary(request, destination, _boundary2)) {
        request.destination = null;
        i++;
        partialBoundaries.splice(0, i);
        return;
      }
    }

    partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
    // boundaries added to it in case they were too larged to be inlined.
    // New ones might be added in this loop.

    var largeBoundaries = request.completedBoundaries;

    for (i = 0; i < largeBoundaries.length; i++) {
      var _boundary3 = largeBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary3)) {
        request.destination = null;
        i++;
        largeBoundaries.splice(0, i);
        return;
      }
    }

    largeBoundaries.splice(0, i);
  } finally {

    if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
    // either they have pending task or they're complete.
    ) {
        {
          if (request.abortableTasks.size !== 0) {
            error('There was still abortable task at the root when we closed. This is a bug in React.');
          }
        } // We're done.


        close(destination);
      }
  }
}

function startWork(request) {
  scheduleWork(function () {
    return performWork(request);
  });
}
function startFlowing(request, destination) {
  if (request.status === CLOSING) {
    request.status = CLOSED;
    closeWithError(destination, request.fatalError);
    return;
  }

  if (request.status === CLOSED) {
    return;
  }

  if (request.destination !== null) {
    // We're already flowing.
    return;
  }

  request.destination = destination;

  try {
    flushCompletedQueues(request, destination);
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

function abort(request, reason) {
  try {
    var abortableTasks = request.abortableTasks;
    abortableTasks.forEach(function (task) {
      return abortTask(task, request, reason);
    });
    abortableTasks.clear();

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
}

function onError() {// Non-fatal errors are ignored.
}

function renderToStringImpl(children, options, generateStaticMarkup, abortReason) {
  var didFatal = false;
  var fatalError = null;
  var result = '';
  var destination = {
    push: function (chunk) {
      if (chunk !== null) {
        result += chunk;
      }

      return true;
    },
    destroy: function (error) {
      didFatal = true;
      fatalError = error;
    }
  };
  var readyToStream = false;

  function onShellReady() {
    readyToStream = true;
  }

  var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined);
  startWork(request); // If anything suspended and is still pending, we'll abort it before writing.
  // That way we write only client-rendered boundaries from the start.

  abort(request, abortReason);
  startFlowing(request, destination);

  if (didFatal) {
    throw fatalError;
  }

  if (!readyToStream) {
    // Note: This error message is the one we use on the client. It doesn't
    // really make sense here. But this is the legacy server renderer, anyway.
    // We're going to delete it soon.
    throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.');
  }

  return result;
}

function renderToString(children, options) {
  return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
}

function renderToStaticMarkup(children, options) {
  return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
}

function renderToNodeStream() {
  throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.');
}

function renderToStaticNodeStream() {
  throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.');
}

exports.renderToNodeStream = renderToNodeStream;
exports.renderToStaticMarkup = renderToStaticMarkup;
exports.renderToStaticNodeStream = renderToStaticNodeStream;
exports.renderToString = renderToString;
exports.version = ReactVersion;
  })();
}
/**
 * @license React
 * react-dom-server-legacy.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var aa=require("react");function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
var p=Object.prototype.hasOwnProperty,fa=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ha={},ia={};
function ja(a){if(p.call(ia,a))return!0;if(p.call(ha,a))return!1;if(fa.test(a))return ia[a]=!0;ha[a]=!0;return!1}function r(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}var t={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){t[a]=new r(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];t[b]=new r(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){t[a]=new r(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){t[a]=new r(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){t[a]=new r(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){t[a]=new r(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){t[a]=new r(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){t[a]=new r(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){t[a]=new r(a,5,!1,a.toLowerCase(),null,!1,!1)});var ka=/[\-:]([a-z])/g;function la(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ka,
la);t[b]=new r(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ka,la);t[b]=new r(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ka,la);t[b]=new r(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){t[a]=new r(a,1,!1,a.toLowerCase(),null,!1,!1)});
t.xlinkHref=new r("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){t[a]=new r(a,1,!1,a.toLowerCase(),null,!0,!0)});
var u={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,
fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ma=["Webkit","ms","Moz","O"];Object.keys(u).forEach(function(a){ma.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);u[b]=u[a]})});var na=/["'&<>]/;
function v(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=na.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}var oa=/([A-Z])/g,pa=/^ms-/,qa=Array.isArray;function w(a,b){return{insertionMode:a,selectedValue:b}}
function ra(a,b,c){switch(b){case "select":return w(1,null!=c.value?c.value:c.defaultValue);case "svg":return w(2,null);case "math":return w(3,null);case "foreignObject":return w(1,null);case "table":return w(4,null);case "thead":case "tbody":case "tfoot":return w(5,null);case "colgroup":return w(7,null);case "tr":return w(6,null)}return 4<=a.insertionMode||0===a.insertionMode?w(1,null):a}var sa=new Map;
function ta(a,b,c){if("object"!==typeof c)throw Error(l(62));b=!0;for(var d in c)if(p.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=v(d);f=v((""+f).trim())}else{e=d;var g=sa.get(e);void 0!==g?e=g:(g=v(e.replace(oa,"-$1").toLowerCase().replace(pa,"-ms-")),sa.set(e,g),e=g);f="number"===typeof f?0===f||p.call(u,d)?""+f:f+"px":v((""+f).trim())}b?(b=!1,a.push(' style="',e,":",f)):a.push(";",e,":",f)}}b||a.push('"')}
function x(a,b,c,d){switch(c){case "style":ta(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=t.hasOwnProperty(c)?t[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=b.attributeName;switch(b.type){case 3:d&&a.push(" ",c,'=""');break;case 4:!0===d?a.push(" ",c,'=""'):
!1!==d&&a.push(" ",c,'="',v(d),'"');break;case 5:isNaN(d)||a.push(" ",c,'="',v(d),'"');break;case 6:!isNaN(d)&&1<=d&&a.push(" ",c,'="',v(d),'"');break;default:b.sanitizeURL&&(d=""+d),a.push(" ",c,'="',v(d),'"')}}else if(ja(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(" ",c,'="',v(d),'"')}}
function y(a,b,c){if(null!=b){if(null!=c)throw Error(l(60));if("object"!==typeof b||!("__html"in b))throw Error(l(61));b=b.__html;null!==b&&void 0!==b&&a.push(""+b)}}function ua(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}
function va(a,b,c,d){a.push(A(c));var f=c=null,e;for(e in b)if(p.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:x(a,d,e,g)}}a.push(">");y(a,f,c);return"string"===typeof c?(a.push(v(c)),null):c}var wa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,xa=new Map;function A(a){var b=xa.get(a);if(void 0===b){if(!wa.test(a))throw Error(l(65,a));b="<"+a;xa.set(a,b)}return b}
function ya(a,b,c,d,f){switch(b){case "select":a.push(A("select"));var e=null,g=null;for(n in c)if(p.call(c,n)){var h=c[n];if(null!=h)switch(n){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:x(a,d,n,h)}}a.push(">");y(a,g,e);return e;case "option":g=f.selectedValue;a.push(A("option"));var k=h=null,m=null;var n=null;for(e in c)if(p.call(c,e)){var q=c[e];if(null!=q)switch(e){case "children":h=q;break;case "selected":m=q;break;case "dangerouslySetInnerHTML":n=
q;break;case "value":k=q;default:x(a,d,e,q)}}if(null!=g)if(c=null!==k?""+k:ua(h),qa(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(' selected=""');break}}else""+g===c&&a.push(' selected=""');else m&&a.push(' selected=""');a.push(">");y(a,n,h);return h;case "textarea":a.push(A("textarea"));n=g=e=null;for(h in c)if(p.call(c,h)&&(k=c[h],null!=k))switch(h){case "children":n=k;break;case "value":e=k;break;case "defaultValue":g=k;break;case "dangerouslySetInnerHTML":throw Error(l(91));default:x(a,d,
h,k)}null===e&&null!==g&&(e=g);a.push(">");if(null!=n){if(null!=e)throw Error(l(92));if(qa(n)&&1<n.length)throw Error(l(93));e=""+n}"string"===typeof e&&"\n"===e[0]&&a.push("\n");null!==e&&a.push(v(""+e));return null;case "input":a.push(A("input"));k=n=h=e=null;for(g in c)if(p.call(c,g)&&(m=c[g],null!=m))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error(l(399,"input"));case "defaultChecked":k=m;break;case "defaultValue":h=m;break;case "checked":n=m;break;case "value":e=m;break;
default:x(a,d,g,m)}null!==n?x(a,d,"checked",n):null!==k&&x(a,d,"checked",k);null!==e?x(a,d,"value",e):null!==h&&x(a,d,"value",h);a.push("/>");return null;case "menuitem":a.push(A("menuitem"));for(var C in c)if(p.call(c,C)&&(e=c[C],null!=e))switch(C){case "children":case "dangerouslySetInnerHTML":throw Error(l(400));default:x(a,d,C,e)}a.push(">");return null;case "title":a.push(A("title"));e=null;for(q in c)if(p.call(c,q)&&(g=c[q],null!=g))switch(q){case "children":e=g;break;case "dangerouslySetInnerHTML":throw Error(l(434));
default:x(a,d,q,g)}a.push(">");return e;case "listing":case "pre":a.push(A(b));g=e=null;for(k in c)if(p.call(c,k)&&(h=c[k],null!=h))switch(k){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:x(a,d,k,h)}a.push(">");if(null!=g){if(null!=e)throw Error(l(60));if("object"!==typeof g||!("__html"in g))throw Error(l(61));c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push("\n",c):a.push(""+c))}"string"===typeof e&&"\n"===e[0]&&a.push("\n");return e;
case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(A(b));for(var D in c)if(p.call(c,D)&&(e=c[D],null!=e))switch(D){case "children":case "dangerouslySetInnerHTML":throw Error(l(399,b));default:x(a,d,D,e)}a.push("/>");return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return va(a,
c,b,d);case "html":return 0===f.insertionMode&&a.push("<!DOCTYPE html>"),va(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return va(a,c,b,d);a.push(A(b));g=e=null;for(m in c)if(p.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "style":ta(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ja(m)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(" ",m,'="',v(h),'"')}a.push(">");
y(a,g,e);return e}}function za(a,b,c){a.push('\x3c!--$?--\x3e<template id="');if(null===c)throw Error(l(395));a.push(c);return a.push('"></template>')}
function Aa(a,b,c,d){switch(c.insertionMode){case 0:case 1:return a.push('<div hidden id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 2:return a.push('<svg aria-hidden="true" style="display:none" id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 3:return a.push('<math aria-hidden="true" style="display:none" id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 4:return a.push('<table hidden id="'),a.push(b.segmentPrefix),
b=d.toString(16),a.push(b),a.push('">');case 5:return a.push('<table hidden><tbody id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 6:return a.push('<table hidden><tr id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 7:return a.push('<table hidden><colgroup id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');default:throw Error(l(397));}}
function Ba(a,b){switch(b.insertionMode){case 0:case 1:return a.push("</div>");case 2:return a.push("</svg>");case 3:return a.push("</math>");case 4:return a.push("</table>");case 5:return a.push("</tbody></table>");case 6:return a.push("</tr></table>");case 7:return a.push("</colgroup></table>");default:throw Error(l(397));}}var Ca=/[<\u2028\u2029]/g;
function Da(a){return JSON.stringify(a).replace(Ca,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}
function Ea(a,b){b=void 0===b?"":b;return{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:b+"P:",segmentPrefix:b+"S:",boundaryPrefix:b+"B:",idPrefix:b,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:a}}function Fa(a,b,c,d){if(c.generateStaticMarkup)return a.push(v(b)),!1;""===b?a=d:(d&&a.push("\x3c!-- --\x3e"),a.push(v(b)),a=!0);return a}
var B=Object.assign,Ga=Symbol.for("react.element"),Ha=Symbol.for("react.portal"),Ia=Symbol.for("react.fragment"),Ja=Symbol.for("react.strict_mode"),Ka=Symbol.for("react.profiler"),La=Symbol.for("react.provider"),Ma=Symbol.for("react.context"),Na=Symbol.for("react.forward_ref"),Oa=Symbol.for("react.suspense"),Pa=Symbol.for("react.suspense_list"),Qa=Symbol.for("react.memo"),Ra=Symbol.for("react.lazy"),Sa=Symbol.for("react.scope"),Ta=Symbol.for("react.debug_trace_mode"),Ua=Symbol.for("react.legacy_hidden"),
Va=Symbol.for("react.default_value"),Wa=Symbol.iterator;
function Xa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Ia:return"Fragment";case Ha:return"Portal";case Ka:return"Profiler";case Ja:return"StrictMode";case Oa:return"Suspense";case Pa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ma:return(a.displayName||"Context")+".Consumer";case La:return(a._context.displayName||"Context")+".Provider";case Na:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Qa:return b=a.displayName||null,null!==b?b:Xa(a.type)||"Memo";case Ra:b=a._payload;a=a._init;try{return Xa(a(b))}catch(c){}}return null}var Ya={};function Za(a,b){a=a.contextTypes;if(!a)return Ya;var c={},d;for(d in a)c[d]=b[d];return c}var E=null;
function F(a,b){if(a!==b){a.context._currentValue2=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error(l(401));}else{if(null===c)throw Error(l(401));F(a,c)}b.context._currentValue2=b.value}}function $a(a){a.context._currentValue2=a.parentValue;a=a.parent;null!==a&&$a(a)}function ab(a){var b=a.parent;null!==b&&ab(b);a.context._currentValue2=a.value}
function bb(a,b){a.context._currentValue2=a.parentValue;a=a.parent;if(null===a)throw Error(l(402));a.depth===b.depth?F(a,b):bb(a,b)}function cb(a,b){var c=b.parent;if(null===c)throw Error(l(402));a.depth===c.depth?F(a,c):cb(a,c);b.context._currentValue2=b.value}function G(a){var b=E;b!==a&&(null===b?ab(a):null===a?$a(b):b.depth===a.depth?F(b,a):b.depth>a.depth?bb(b,a):cb(b,a),E=a)}
var db={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}};
function eb(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=db;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue2:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:B({},f,g),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=
a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&db.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=B({},e,h)):B(e,h))}a.state=e}else e.queue=null}
var fb={id:1,overflow:""};function gb(a,b,c){var d=a.id;a=a.overflow;var f=32-H(d)-1;d&=~(1<<f);c+=1;var e=32-H(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-H(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}var H=Math.clz32?Math.clz32:hb,ib=Math.log,jb=Math.LN2;function hb(a){a>>>=0;return 0===a?32:31-(ib(a)/jb|0)|0}function kb(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}
var lb="function"===typeof Object.is?Object.is:kb,I=null,ob=null,J=null,K=null,L=!1,M=!1,N=0,O=null,P=0;function Q(){if(null===I)throw Error(l(321));return I}function pb(){if(0<P)throw Error(l(312));return{memoizedState:null,queue:null,next:null}}function qb(){null===K?null===J?(L=!1,J=K=pb()):(L=!0,K=J):null===K.next?(L=!1,K=K.next=pb()):(L=!0,K=K.next);return K}function rb(){ob=I=null;M=!1;J=null;P=0;K=O=null}function sb(a,b){return"function"===typeof b?b(a):b}
function tb(a,b,c){I=Q();K=qb();if(L){var d=K.queue;b=d.dispatch;if(null!==O&&(c=O.get(d),void 0!==c)){O.delete(d);d=K.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);K.memoizedState=d;return[d,b]}return[K.memoizedState,b]}a=a===sb?"function"===typeof b?b():b:void 0!==c?c(b):b;K.memoizedState=a;a=K.queue={last:null,dispatch:null};a=a.dispatch=ub.bind(null,I,a);return[K.memoizedState,a]}
function vb(a,b){I=Q();K=qb();b=void 0===b?null:b;if(null!==K){var c=K.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!lb(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();K.memoizedState=[a,b];return a}function ub(a,b,c){if(25<=P)throw Error(l(301));if(a===I)if(M=!0,a={action:c,next:null},null===O&&(O=new Map),c=O.get(b),void 0===c)O.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function wb(){throw Error(l(394));}
function R(){}
var xb={readContext:function(a){return a._currentValue2},useContext:function(a){Q();return a._currentValue2},useMemo:vb,useReducer:tb,useRef:function(a){I=Q();K=qb();var b=K.memoizedState;return null===b?(a={current:a},K.memoizedState=a):b},useState:function(a){return tb(sb,a)},useInsertionEffect:R,useLayoutEffect:function(){},useCallback:function(a,b){return vb(function(){return a},b)},useImperativeHandle:R,useEffect:R,useDebugValue:R,useDeferredValue:function(a){Q();return a},useTransition:function(){Q();return[!1,
wb]},useId:function(){var a=ob.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-H(a)-1)).toString(32)+b;var c=S;if(null===c)throw Error(l(404));b=N++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b){Q();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error(l(407));return c()}},S=null,yb=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function zb(a){console.error(a);return null}
function T(){}
function Ab(a,b,c,d,f,e,g,h,k){var m=[],n=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:n,pingedTasks:m,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?zb:f,onAllReady:void 0===e?T:e,onShellReady:void 0===g?T:g,onShellError:void 0===h?T:h,onFatalError:void 0===k?T:k};c=U(b,0,null,c,!1,!1);c.parentFlushed=
!0;a=Bb(b,a,null,c,n,Ya,null,fb);m.push(a);return b}function Bb(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var k={node:b,ping:function(){var b=a.pingedTasks;b.push(k);1===b.length&&Cb(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(k);return k}function U(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}
function V(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function W(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,a.destination.destroy(b)):(a.status=1,a.fatalError=b)}
function Db(a,b,c,d,f){I={};ob=b;N=0;for(a=c(d,f);M;)M=!1,N=0,P+=1,K=null,a=c(d,f);rb();return a}function Eb(a,b,c,d){var f=c.render(),e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error(l(108,Xa(d)||"Unknown",h));d=B({},g,c)}b.legacyContext=d;X(a,b,f);b.legacyContext=g}else X(a,b,f)}
function Fb(a,b){if(a&&a.defaultProps){b=B({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}
function Gb(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=Za(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue2:f);eb(e,c,d,f);Eb(a,b,e,c)}else{e=Za(c,b.legacyContext);f=Db(a,b,c,d,e);var g=0!==N;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)eb(f,c,d,e),Eb(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=gb(d,1,0);try{X(a,b,f)}finally{b.treeContext=d}}else X(a,b,f)}else if("string"===
typeof c){f=b.blockedSegment;e=ya(f.chunks,c,d,a.responseState,f.formatContext);f.lastPushedText=!1;g=f.formatContext;f.formatContext=ra(g,c,d);Hb(a,b,e);f.formatContext=g;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push("</",c,">")}f.lastPushedText=!1}else{switch(c){case Ua:case Ta:case Ja:case Ka:case Ia:X(a,b,d.children);return;
case Pa:X(a,b,d.children);return;case Sa:throw Error(l(343));case Oa:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null},k=U(a,f.chunks.length,h,f.formatContext,!1,!1);f.children.push(k);f.lastPushedText=!1;var m=U(a,0,null,f.formatContext,!1,!1);m.parentFlushed=!0;b.blockedBoundary=h;b.blockedSegment=m;try{if(Hb(a,
b,d),a.responseState.generateStaticMarkup||m.lastPushedText&&m.textEmbedded&&m.chunks.push("\x3c!-- --\x3e"),m.status=1,Y(h,m),0===h.pendingTasks)break a}catch(n){m.status=4,h.forceClientRender=!0,h.errorDigest=V(a,n)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=Bb(a,e,c,k,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case Na:d=Db(a,b,c.render,d,f);if(0!==N){c=b.treeContext;b.treeContext=gb(c,1,0);try{X(a,b,d)}finally{b.treeContext=
c}}else X(a,b,d);return;case Qa:c=c.type;d=Fb(c,d);Gb(a,b,c,d,f);return;case La:f=d.children;c=c._context;d=d.value;e=c._currentValue2;c._currentValue2=d;g=E;E=d={parent:g,depth:null===g?0:g.depth+1,context:c,parentValue:e,value:d};b.context=d;X(a,b,f);a=E;if(null===a)throw Error(l(403));d=a.parentValue;a.context._currentValue2=d===Va?a.context._defaultValue:d;a=E=a.parent;b.context=a;return;case Ma:d=d.children;d=d(c._currentValue2);X(a,b,d);return;case Ra:f=c._init;c=f(c._payload);d=Fb(c,d);Gb(a,
b,c,d,void 0);return}throw Error(l(130,null==c?c:typeof c,""));}}
function X(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Ga:Gb(a,b,c.type,c.props,c.ref);return;case Ha:throw Error(l(257));case Ra:var d=c._init;c=d(c._payload);X(a,b,c);return}if(qa(c)){Ib(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=Wa&&c[Wa]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=[];do f.push(c.value),c=d.next();while(!c.done);Ib(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error(l(31,"[object Object]"===
a?"object with keys {"+Object.keys(c).join(", ")+"}":a));}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=Fa(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=Fa(b.blockedSegment.chunks,""+c,a.responseState,d.lastPushedText))}function Ib(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=gb(e,d,f);try{Hb(a,b,c[f])}finally{b.treeContext=e}}}
function Hb(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return X(a,b,c)}catch(k){if(rb(),"object"===typeof k&&null!==k&&"function"===typeof k.then){c=k;var g=b.blockedSegment,h=U(a,g.chunks.length,null,g.formatContext,g.lastPushedText,!0);g.children.push(h);g.lastPushedText=!1;a=Bb(a,b.node,b.blockedBoundary,h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;G(e)}else throw b.blockedSegment.formatContext=
d,b.legacyContext=f,b.context=e,G(e),k;}}function Jb(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;Kb(this,b,a)}
function Lb(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.push(null))):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,a=void 0===c?Error(l(432)):c,d.errorDigest=b.onError(a),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return Lb(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,0===b.allPendingTasks&&(d=b.onAllReady,
d()))}function Y(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&Y(a,c)}else a.completedSegments.push(b)}
function Kb(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error(l(389));a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=T,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&Y(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(Jb,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&1===c.status&&(Y(b,c),1===b.completedSegments.length&&
b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}
function Cb(a){if(2!==a.status){var b=E,c=yb.current;yb.current=xb;var d=S;S=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,k=g.blockedSegment;if(0===k.status){G(g.context);try{X(h,g,g.node),h.responseState.generateStaticMarkup||k.lastPushedText&&k.textEmbedded&&k.chunks.push("\x3c!-- --\x3e"),g.abortSet.delete(g),k.status=1,Kb(h,g.blockedBoundary,k)}catch(z){if(rb(),"object"===typeof z&&null!==z&&"function"===typeof z.then){var m=g.ping;z.then(m,m)}else{g.abortSet.delete(g);
k.status=4;var n=g.blockedBoundary,q=z,C=V(h,q);null===n?W(h,q):(n.pendingTasks--,n.forceClientRender||(n.forceClientRender=!0,n.errorDigest=C,n.parentFlushed&&h.clientRenderedBoundaries.push(n)));h.allPendingTasks--;if(0===h.allPendingTasks){var D=h.onAllReady;D()}}}finally{}}}f.splice(0,e);null!==a.destination&&Mb(a,a.destination)}catch(z){V(a,z),W(a,z)}finally{S=d,yb.current=c,c===xb&&G(b)}}}
function Z(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;b.push('<template id="');b.push(a.placeholderPrefix);a=d.toString(16);b.push(a);return b.push('"></template>');case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)b.push(d[e]);f=Nb(a,b,f)}for(;e<d.length-1;e++)b.push(d[e]);e<d.length&&(f=b.push(d[e]));return f;default:throw Error(l(390));}}
function Nb(a,b,c){var d=c.boundary;if(null===d)return Z(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)return a.responseState.generateStaticMarkup||(d=d.errorDigest,b.push("\x3c!--$!--\x3e"),b.push("<template"),d&&(b.push(' data-dgst="'),d=v(d),b.push(d),b.push('"')),b.push("></template>")),Z(a,b,c),a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e"),a;if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;
var e=f.nextSuspenseID++;f=f.boundaryPrefix+e.toString(16);d=d.id=f;za(b,a.responseState,d);Z(a,b,c);return b.push("\x3c!--/$--\x3e")}if(d.byteSize>a.progressiveChunkSize)return d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),za(b,a.responseState,d.id),Z(a,b,c),b.push("\x3c!--/$--\x3e");a.responseState.generateStaticMarkup||b.push("\x3c!--$--\x3e");c=d.completedSegments;if(1!==c.length)throw Error(l(391));Nb(a,b,c[0]);a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e");
return a}function Ob(a,b,c){Aa(b,a.responseState,c.formatContext,c.id);Nb(a,b,c);return Ba(b,c.formatContext)}
function Pb(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)Qb(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;b.push(a.startInlineScript);a.sentCompleteBoundaryFunction?b.push('$RC("'):(a.sentCompleteBoundaryFunction=!0,b.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'));if(null===
d)throw Error(l(395));c=c.toString(16);b.push(d);b.push('","');b.push(a.segmentPrefix);b.push(c);return b.push('")\x3c/script>')}
function Qb(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error(l(392));return Ob(a,b,d)}Ob(a,b,d);a=a.responseState;b.push(a.startInlineScript);a.sentCompleteSegmentFunction?b.push('$RS("'):(a.sentCompleteSegmentFunction=!0,b.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'));b.push(a.segmentPrefix);
f=f.toString(16);b.push(f);b.push('","');b.push(a.placeholderPrefix);b.push(f);return b.push('")\x3c/script>')}
function Mb(a,b){try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){Nb(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)b.push(d[c]);c<d.length&&b.push(d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var h=a.responseState,k=g.id,m=g.errorDigest,n=g.errorMessage,q=g.errorComponentStack;d.push(h.startInlineScript);h.sentClientRenderFunction?d.push('$RX("'):(h.sentClientRenderFunction=!0,d.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'));
if(null===k)throw Error(l(395));d.push(k);d.push('"');if(m||n||q){d.push(",");var C=Da(m||"");d.push(C)}if(n||q){d.push(",");var D=Da(n||"");d.push(D)}if(q){d.push(",");var z=Da(q);d.push(z)}if(!d.push(")\x3c/script>")){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e);var ba=a.completedBoundaries;for(e=0;e<ba.length;e++)if(!Pb(a,b,ba[e])){a.destination=null;e++;ba.splice(0,e);return}ba.splice(0,e);var ca=a.partialBoundaries;for(e=0;e<ca.length;e++){var mb=ca[e];a:{f=a;g=b;var da=mb.completedSegments;
for(h=0;h<da.length;h++)if(!Qb(f,g,mb,da[h])){h++;da.splice(0,h);var nb=!1;break a}da.splice(0,h);nb=!0}if(!nb){a.destination=null;e++;ca.splice(0,e);return}}ca.splice(0,e);var ea=a.completedBoundaries;for(e=0;e<ea.length;e++)if(!Pb(a,b,ea[e])){a.destination=null;e++;ea.splice(0,e);return}ea.splice(0,e)}finally{0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&b.push(null)}}
function Rb(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return Lb(c,a,b)});c.clear();null!==a.destination&&Mb(a,a.destination)}catch(d){V(a,d),W(a,d)}}function Sb(){}
function Tb(a,b,c,d){var f=!1,e=null,g="",h={push:function(a){null!==a&&(g+=a);return!0},destroy:function(a){f=!0;e=a}},k=!1;a=Ab(a,Ea(c,b?b.identifierPrefix:void 0),{insertionMode:1,selectedValue:null},Infinity,Sb,void 0,function(){k=!0},void 0,void 0);Cb(a);Rb(a,d);if(1===a.status)a.status=2,h.destroy(a.fatalError);else if(2!==a.status&&null===a.destination){a.destination=h;try{Mb(a,h)}catch(m){V(a,m),W(a,m)}}if(f)throw e;if(!k)throw Error(l(426));return g}
exports.renderToNodeStream=function(){throw Error(l(207));};exports.renderToStaticMarkup=function(a,b){return Tb(a,b,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')};exports.renderToStaticNodeStream=function(){throw Error(l(208));};exports.renderToString=function(a,b){return Tb(a,b,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')};
exports.version="18.3.1";
/**
 * @license React
 * react-dom-server-legacy.node.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');
var stream = require('stream');

var ReactVersion = '18.3.1';

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

function scheduleWork(callback) {
  callback();
}
function beginWriting(destination) {}
function writeChunk(destination, chunk) {
  writeChunkAndReturn(destination, chunk);
}
function writeChunkAndReturn(destination, chunk) {
  return destination.push(chunk);
}
function completeWriting(destination) {}
function close(destination) {
  destination.push(null);
}
function stringToChunk(content) {
  return content;
}
function stringToPrecomputedChunk(content) {
  return content;
}
function closeWithError(destination, error) {
  // $FlowFixMe: This is an Error object or the destination accepts other types.
  destination.destroy(error);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}

function checkAttributeStringCoercion(value, attributeName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkCSSPropertyStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkHtmlStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.

var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.

var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.

var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.

var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.

var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.

var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */

var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }

  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }

  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }

  illegalAttributeNameCache[attributeName] = true;

  {
    error('Invalid attribute name: `%s`', attributeName);
  }

  return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }

  switch (typeof value) {
    case 'function': // $FlowIssue symbol is perfectly valid here

    case 'symbol':
      // eslint-disable-line
      return true;

    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }

        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }

    default:
      return false;
  }
}
function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
  this.sanitizeURL = sanitizeURL;
  this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.


var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

reservedProps.forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.

[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).

['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.

['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML boolean attributes.

['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.

['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.

['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be positive numbers.

['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be numbers.

['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
});
var CAMELIZE = /[\-\:]([a-z])/g;

var capitalize = function (token) {
  return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.


['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // String SVG attributes with the xlink namespace.

['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  false);
}); // String SVG attributes with the xml namespace.

['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.

['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.

var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  true, // sanitizeURL
  true);
});

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  aspectRatio: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */

function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */


var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.

Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

var hasReadOnlyValue = {
  button: true,
  checkbox: true,
  image: true,
  hidden: true,
  radio: true,
  reset: true,
  submit: true
};
function checkControlledValueProps(tagName, props) {
  {
    if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
      error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }

    if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
      error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  }
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }

  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this list too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;

    default:
      return true;
  }
}

var ariaProperties = {
  'aria-current': 0,
  // state
  'aria-description': 0,
  'aria-details': 0,
  'aria-disabled': 0,
  // state
  'aria-hidden': 0,
  // state
  'aria-invalid': 0,
  // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

function validateProperty(tagName, name) {
  {
    if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
      return true;
    }

    if (rARIACamel.test(name)) {
      var ariaName = 'aria-' + name.slice(4).toLowerCase();
      var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (correctName == null) {
        error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

        warnedProperties[name] = true;
        return true;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== correctName) {
        error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

        warnedProperties[name] = true;
        return true;
      }
    }

    if (rARIA.test(name)) {
      var lowerCasedName = name.toLowerCase();
      var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (standardName == null) {
        warnedProperties[name] = true;
        return false;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== standardName) {
        error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties[name] = true;
        return true;
      }
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  {
    var invalidProps = [];

    for (var key in props) {
      var isValid = validateProperty(type, key);

      if (!isValid) {
        invalidProps.push(key);
      }
    }

    var unknownPropString = invalidProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (invalidProps.length === 1) {
      error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    } else if (invalidProps.length > 1) {
      error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    }
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;
function validateProperties$1(type, props) {
  {
    if (type !== 'input' && type !== 'textarea' && type !== 'select') {
      return;
    }

    if (props != null && props.value === null && !didWarnValueNull) {
      didWarnValueNull = true;

      if (type === 'select' && props.multiple) {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
      } else {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
      }
    }
  }
}

// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  disablepictureinpicture: 'disablePictureInPicture',
  disableremoteplayback: 'disableRemotePlayback',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  enterkeyhint: 'enterKeyHint',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  imagesizes: 'imageSizes',
  imagesrcset: 'imageSrcSet',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',
  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, eventRegistry) {
    if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();

    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

      warnedProperties$1[name] = true;
      return true;
    } // We can't rely on the event system being injected on the server.


    if (eventRegistry != null) {
      var registrationNameDependencies = eventRegistry.registrationNameDependencies,
          possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

      if (registrationNameDependencies.hasOwnProperty(name)) {
        return true;
      }

      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

      if (registrationName != null) {
        error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (EVENT_NAME_REGEX.test(name)) {
        error('Unknown event handler property `%s`. It will be ignored.', name);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Let the ARIA attribute hook validate ARIA attributes


    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];

      if (standardName !== name) {
        error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
      } else {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Now that we've validated casing, do not validate
    // data types for reserved props


    if (isReserved) {
      return true;
    } // Warn when a known attribute is a bad type


    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    } // Warn when passing the strings 'false' or 'true' into a boolean prop


    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
      error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

      warnedProperties$1[name] = true;
      return true;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, eventRegistry) {
  {
    var unknownProps = [];

    for (var key in props) {
      var isValid = validateProperty$1(type, key, props[key], eventRegistry);

      if (!isValid) {
        unknownProps.push(key);
      }
    }

    var unknownPropString = unknownProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (unknownProps.length === 1) {
      error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    } else if (unknownProps.length > 1) {
      error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    }
  }
};

function validateProperties$2(type, props, eventRegistry) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnUnknownProperties(type, props, eventRegistry);
}

var warnValidStyle = function () {};

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

  var badStyleValueWithSemicolonPattern = /;\s*$/;
  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var camelize = function (string) {
    return string.replace(hyphenPattern, function (_, character) {
      return character.toUpperCase();
    });
  };

  var warnHyphenatedStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
    // is converted to lowercase `ms`.
    camelize(name.replace(msPattern, 'ms-')));
  };

  var warnBadVendoredStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
  };

  var warnStyleValueWithSemicolon = function (name, value) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;

    error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
  };

  var warnStyleValueIsNaN = function (name, value) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;

    error('`NaN` is an invalid value for the `%s` css style property.', name);
  };

  var warnStyleValueIsInfinity = function (name, value) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;

    error('`Infinity` is an invalid value for the `%s` css style property.', name);
  };

  warnValidStyle = function (name, value) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

// code copied and modified from escape-html
var matchHtmlRegExp = /["'&<>]/;
/**
 * Escapes special characters and HTML entities in a given html string.
 *
 * @param  {string} string HTML string to escape for later insertion
 * @return {string}
 * @public
 */

function escapeHtml(string) {
  {
    checkHtmlStringCoercion(string);
  }

  var str = '' + string;
  var match = matchHtmlRegExp.exec(str);

  if (!match) {
    return str;
  }

  var escape;
  var html = '';
  var index;
  var lastIndex = 0;

  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        // "
        escape = '&quot;';
        break;

      case 38:
        // &
        escape = '&amp;';
        break;

      case 39:
        // '
        escape = '&#x27;'; // modified from escape-html; used to be '&#39'

        break;

      case 60:
        // <
        escape = '&lt;';
        break;

      case 62:
        // >
        escape = '&gt;';
        break;

      default:
        continue;
    }

    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }

    lastIndex = index + 1;
    html += escape;
  }

  return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
} // end code copied and modified from escape-html

/**
 * Escapes text to prevent scripting attacks.
 *
 * @param {*} text Text value to escape.
 * @return {string} An escaped string.
 */


function escapeTextForBrowser(text) {
  if (typeof text === 'boolean' || typeof text === 'number') {
    // this shortcircuit helps perf for types that we know will never have
    // special characters, especially given that this function is used often
    // for numeric dom ids.
    return '' + text;
  }

  return escapeHtml(text);
}

var uppercasePattern = /([A-Z])/g;
var msPattern$1 = /^ms-/;
/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */

function hyphenateStyleName(name) {
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
}

// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space

/* eslint-disable max-len */

var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;

function sanitizeURL(url) {
  {
    if (!didWarn && isJavaScriptProtocol.test(url)) {
      didWarn = true;

      error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var startInlineScript = stringToPrecomputedChunk('<script>');
var endInlineScript = stringToPrecomputedChunk('</script>');
var startScriptSrc = stringToPrecomputedChunk('<script src="');
var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
/**
 * This escaping function is designed to work with bootstrapScriptContent only.
 * because we know we are escaping the entire script. We can avoid for instance
 * escaping html comment string sequences that are valid javascript as well because
 * if there are no sebsequent <script sequences the html parser will never enter
 * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
 *
 * While untrusted script content should be made safe before using this api it will
 * ensure that the script cannot be early terminated or never terminated state
 */

function escapeBootstrapScriptContent(scriptText) {
  {
    checkHtmlStringCoercion(scriptText);
  }

  return ('' + scriptText).replace(scriptRegex, scriptReplacer);
}

var scriptRegex = /(<\/|<)(s)(cript)/gi;

var scriptReplacer = function (match, prefix, s, suffix) {
  return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
}; // Allows us to keep track of what we've already written so we can refer back to it.


function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
  var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
  var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
  var bootstrapChunks = [];

  if (bootstrapScriptContent !== undefined) {
    bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
  }

  if (bootstrapScripts !== undefined) {
    for (var i = 0; i < bootstrapScripts.length; i++) {
      bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
    }
  }

  if (bootstrapModules !== undefined) {
    for (var _i = 0; _i < bootstrapModules.length; _i++) {
      bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
    }
  }

  return {
    bootstrapChunks: bootstrapChunks,
    startInlineScript: inlineScriptWithNonce,
    placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
    segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
    boundaryPrefix: idPrefix + 'B:',
    idPrefix: idPrefix,
    nextSuspenseID: 0,
    sentCompleteSegmentFunction: false,
    sentCompleteBoundaryFunction: false,
    sentClientRenderFunction: false
  };
} // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
// modes. We only include the variants as they matter for the sake of our purposes.
// We don't actually provide the namespace therefore we use constants instead of the string.

var ROOT_HTML_MODE = 0; // Used for the root most element tag.

var HTML_MODE = 1;
var SVG_MODE = 2;
var MATHML_MODE = 3;
var HTML_TABLE_MODE = 4;
var HTML_TABLE_BODY_MODE = 5;
var HTML_TABLE_ROW_MODE = 6;
var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
// still makes sense

function createFormatContext(insertionMode, selectedValue) {
  return {
    insertionMode: insertionMode,
    selectedValue: selectedValue
  };
}
function getChildFormatContext(parentContext, type, props) {
  switch (type) {
    case 'select':
      return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

    case 'svg':
      return createFormatContext(SVG_MODE, null);

    case 'math':
      return createFormatContext(MATHML_MODE, null);

    case 'foreignObject':
      return createFormatContext(HTML_MODE, null);
    // Table parents are special in that their children can only be created at all if they're
    // wrapped in a table parent. So we need to encode that we're entering this mode.

    case 'table':
      return createFormatContext(HTML_TABLE_MODE, null);

    case 'thead':
    case 'tbody':
    case 'tfoot':
      return createFormatContext(HTML_TABLE_BODY_MODE, null);

    case 'colgroup':
      return createFormatContext(HTML_COLGROUP_MODE, null);

    case 'tr':
      return createFormatContext(HTML_TABLE_ROW_MODE, null);
  }

  if (parentContext.insertionMode >= HTML_TABLE_MODE) {
    // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
    // entered plain HTML again.
    return createFormatContext(HTML_MODE, null);
  }

  if (parentContext.insertionMode === ROOT_HTML_MODE) {
    // We've emitted the root and is now in plain HTML mode.
    return createFormatContext(HTML_MODE, null);
  }

  return parentContext;
}
var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
function assignSuspenseBoundaryID(responseState) {
  var generatedID = responseState.nextSuspenseID++;
  return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
}
function makeId(responseState, treeId, localId) {
  var idPrefix = responseState.idPrefix;
  var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
  // that represents the position of this useId hook among all the useId
  // hooks for this fiber.

  if (localId > 0) {
    id += 'H' + localId.toString(32);
  }

  return id + ':';
}

function encodeHTMLTextNode(text) {
  return escapeTextForBrowser(text);
}

var textSeparator = stringToPrecomputedChunk('<!-- -->');
function pushTextInstance(target, text, responseState, textEmbedded) {
  if (text === '') {
    // Empty text doesn't have a DOM node representation and the hydration is aware of this.
    return textEmbedded;
  }

  if (textEmbedded) {
    target.push(textSeparator);
  }

  target.push(stringToChunk(encodeHTMLTextNode(text)));
  return true;
} // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
// emit a text separator when we don't know for sure it is safe to omit

function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
  if (lastPushedText && textEmbedded) {
    target.push(textSeparator);
  }
}
var styleNameCache = new Map();

function processStyleName(styleName) {
  var chunk = styleNameCache.get(styleName);

  if (chunk !== undefined) {
    return chunk;
  }

  var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
  styleNameCache.set(styleName, result);
  return result;
}

var styleAttributeStart = stringToPrecomputedChunk(' style="');
var styleAssign = stringToPrecomputedChunk(':');
var styleSeparator = stringToPrecomputedChunk(';');

function pushStyle(target, responseState, style) {
  if (typeof style !== 'object') {
    throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
  }

  var isFirst = true;

  for (var styleName in style) {
    if (!hasOwnProperty.call(style, styleName)) {
      continue;
    } // If you provide unsafe user data here they can inject arbitrary CSS
    // which may be problematic (I couldn't repro this):
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
    // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
    // This is not an XSS hole but instead a potential CSS injection issue
    // which has lead to a greater discussion about how we're going to
    // trust URLs moving forward. See #2115901


    var styleValue = style[styleName];

    if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
      // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
      continue;
    }

    var nameChunk = void 0;
    var valueChunk = void 0;
    var isCustomProperty = styleName.indexOf('--') === 0;

    if (isCustomProperty) {
      nameChunk = stringToChunk(escapeTextForBrowser(styleName));

      {
        checkCSSPropertyStringCoercion(styleValue, styleName);
      }

      valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
    } else {
      {
        warnValidStyle$1(styleName, styleValue);
      }

      nameChunk = processStyleName(styleName);

      if (typeof styleValue === 'number') {
        if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
          valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
        } else {
          valueChunk = stringToChunk('' + styleValue);
        }
      } else {
        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      }
    }

    if (isFirst) {
      isFirst = false; // If it's first, we don't need any separators prefixed.

      target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
    } else {
      target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
    }
  }

  if (!isFirst) {
    target.push(attributeEnd);
  }
}

var attributeSeparator = stringToPrecomputedChunk(' ');
var attributeAssign = stringToPrecomputedChunk('="');
var attributeEnd = stringToPrecomputedChunk('"');
var attributeEmptyString = stringToPrecomputedChunk('=""');

function pushAttribute(target, responseState, name, value) {
  switch (name) {
    case 'style':
      {
        pushStyle(target, responseState, value);
        return;
      }

    case 'defaultValue':
    case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

    case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

    case 'suppressContentEditableWarning':
    case 'suppressHydrationWarning':
      // Ignored. These are built-in to React on the client.
      return;
  }

  if ( // shouldIgnoreAttribute
  // We have already filtered out null/undefined and reserved words.
  name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return;
  }

  var propertyInfo = getPropertyInfo(name);

  if (propertyInfo !== null) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          if (!propertyInfo.acceptsBooleans) {
            return;
          }
        }
    }

    var attributeName = propertyInfo.attributeName;
    var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

    switch (propertyInfo.type) {
      case BOOLEAN:
        if (value) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        }

        return;

      case OVERLOADED_BOOLEAN:
        if (value === true) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        } else if (value === false) ; else {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        return;

      case NUMERIC:
        if (!isNaN(value)) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      case POSITIVE_NUMERIC:
        if (!isNaN(value) && value >= 1) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      default:
        if (propertyInfo.sanitizeURL) {
          {
            checkAttributeStringCoercion(value, attributeName);
          }

          value = '' + value;
          sanitizeURL(value);
        }

        target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  } else if (isAttributeNameSafe(name)) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          var prefix = name.toLowerCase().slice(0, 5);

          if (prefix !== 'data-' && prefix !== 'aria-') {
            return;
          }
        }
    }

    target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
  }
}

var endOfStartTag = stringToPrecomputedChunk('>');
var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

function pushInnerHTML(target, innerHTML, children) {
  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      {
        checkHtmlStringCoercion(html);
      }

      target.push(stringToChunk('' + html));
    }
  }
} // TODO: Move these to ResponseState so that we warn for every request.
// It would help debugging in stateful servers (e.g. service worker).


var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnInvalidOptionInnerHTML = false;
var didWarnSelectedSetOnOption = false;

function checkSelectProp(props, propName) {
  {
    var value = props[propName];

    if (value != null) {
      var array = isArray(value);

      if (props.multiple && !array) {
        error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
      } else if (!props.multiple && array) {
        error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
      }
    }
  }
}

function pushStartSelect(target, props, responseState) {
  {
    checkControlledValueProps('select', props);
    checkSelectProp(props, 'value');
    checkSelectProp(props, 'defaultValue');

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
      error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultSelectValue = true;
    }
  }

  target.push(startChunkForTag('select'));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          // TODO: This doesn't really make sense for select since it can't use the controlled
          // value in the innerHTML.
          innerHTML = propValue;
          break;

        case 'defaultValue':
        case 'value':
          // These are set on the Context instead and applied to the nested options.
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function flattenOptionChildren(children) {
  var content = ''; // Flatten children and warn if they aren't strings or numbers;
  // invalid types are ignored.

  React.Children.forEach(children, function (child) {
    if (child == null) {
      return;
    }

    content += child;

    {
      if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
        didWarnInvalidOptionChildren = true;

        error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
      }
    }
  });
  return content;
}

var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

function pushStartOption(target, props, responseState, formatContext) {
  var selectedValue = formatContext.selectedValue;
  target.push(startChunkForTag('option'));
  var children = null;
  var value = null;
  var selected = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'selected':
          // ignore
          selected = propValue;

          {
            // TODO: Remove support for `selected` in <option>.
            if (!didWarnSelectedSetOnOption) {
              error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

              didWarnSelectedSetOnOption = true;
            }
          }

          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;
        // eslint-disable-next-line-no-fallthrough

        case 'value':
          value = propValue;
        // We intentionally fallthrough to also set the attribute on the node.
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (selectedValue != null) {
    var stringValue;

    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      stringValue = '' + value;
    } else {
      {
        if (innerHTML !== null) {
          if (!didWarnInvalidOptionInnerHTML) {
            didWarnInvalidOptionInnerHTML = true;

            error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
          }
        }
      }

      stringValue = flattenOptionChildren(children);
    }

    if (isArray(selectedValue)) {
      // multiple
      for (var i = 0; i < selectedValue.length; i++) {
        {
          checkAttributeStringCoercion(selectedValue[i], 'value');
        }

        var v = '' + selectedValue[i];

        if (v === stringValue) {
          target.push(selectedMarkerAttribute);
          break;
        }
      }
    } else {
      {
        checkAttributeStringCoercion(selectedValue, 'select.value');
      }

      if ('' + selectedValue === stringValue) {
        target.push(selectedMarkerAttribute);
      }
    }
  } else if (selected) {
    target.push(selectedMarkerAttribute);
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function pushInput(target, props, responseState) {
  {
    checkControlledValueProps('input', props);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
      error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultChecked = true;
    }

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
      error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultInputValue = true;
    }
  }

  target.push(startChunkForTag('input'));
  var value = null;
  var defaultValue = null;
  var checked = null;
  var defaultChecked = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        case 'defaultChecked':
          defaultChecked = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'checked':
          checked = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (checked !== null) {
    pushAttribute(target, responseState, 'checked', checked);
  } else if (defaultChecked !== null) {
    pushAttribute(target, responseState, 'checked', defaultChecked);
  }

  if (value !== null) {
    pushAttribute(target, responseState, 'value', value);
  } else if (defaultValue !== null) {
    pushAttribute(target, responseState, 'value', defaultValue);
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartTextArea(target, props, responseState) {
  {
    checkControlledValueProps('textarea', props);

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
      error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultTextareaValue = true;
    }
  }

  target.push(startChunkForTag('textarea'));
  var value = null;
  var defaultValue = null;
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (value === null && defaultValue !== null) {
    value = defaultValue;
  }

  target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

  if (children != null) {
    {
      error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
    }

    if (value != null) {
      throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
    }

    if (isArray(children)) {
      if (children.length > 1) {
        throw new Error('<textarea> can only have at most one child.');
      } // TODO: remove the coercion and the DEV check below because it will
      // always be overwritten by the coercion several lines below it. #22309


      {
        checkHtmlStringCoercion(children[0]);
      }

      value = '' + children[0];
    }

    {
      checkHtmlStringCoercion(children);
    }

    value = '' + children;
  }

  if (typeof value === 'string' && value[0] === '\n') {
    // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    target.push(leadingNewline);
  } // ToString and push directly instead of recurse over children.
  // We don't really support complex children in the value anyway.
  // This also currently avoids a trailing comment node which breaks textarea.


  if (value !== null) {
    {
      checkAttributeStringCoercion(value, 'value');
    }

    target.push(stringToChunk(encodeHTMLTextNode('' + value)));
  }

  return null;
}

function pushSelfClosing(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartMenuItem(target, props, responseState) {
  target.push(startChunkForTag('menuitem'));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  return null;
}

function pushStartTitle(target, props, responseState) {
  target.push(startChunkForTag('title'));
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);

  {
    var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

    if (Array.isArray(children) && children.length > 1) {
      error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && child.$$typeof != null) {
      error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
      error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    }
  }

  return children;
}

function pushStartGenericElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);

  if (typeof children === 'string') {
    // Special case children as a string to avoid the unnecessary comment.
    // TODO: Remove this special case after the general optimization is in place.
    target.push(stringToChunk(encodeHTMLTextNode(children)));
    return null;
  }

  return children;
}

function pushStartCustomElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        case 'style':
          pushStyle(target, responseState, propValue);
          break;

        case 'suppressContentEditableWarning':
        case 'suppressHydrationWarning':
          // Ignored. These are built-in to React on the client.
          break;

        default:
          if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
            target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
          }

          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

var leadingNewline = stringToPrecomputedChunk('\n');

function pushStartPreformattedElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
  // Prefer to break application/xml over text/html (for now) by adding
  // a newline specifically to get eaten by the parser. (Alternately for
  // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
  // \r is normalized out by HTMLTextAreaElement#value.)
  // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
  // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
  // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
  // See: Parsing of "textarea" "listing" and "pre" elements
  //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
  // TODO: This doesn't deal with the case where the child is an array
  // or component that returns a string.

  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
        target.push(leadingNewline, stringToChunk(html));
      } else {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  }

  if (typeof children === 'string' && children[0] === '\n') {
    target.push(leadingNewline);
  }

  return children;
} // We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name


var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

var validatedTagCache = new Map();

function startChunkForTag(tag) {
  var tagStartChunk = validatedTagCache.get(tag);

  if (tagStartChunk === undefined) {
    if (!VALID_TAG_REGEX.test(tag)) {
      throw new Error("Invalid tag: " + tag);
    }

    tagStartChunk = stringToPrecomputedChunk('<' + tag);
    validatedTagCache.set(tag, tagStartChunk);
  }

  return tagStartChunk;
}

var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
function pushStartInstance(target, type, props, responseState, formatContext) {
  {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, null);

    if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
      error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
    }

    if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
      if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
        error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
      }
    }
  }

  switch (type) {
    // Special tags
    case 'select':
      return pushStartSelect(target, props, responseState);

    case 'option':
      return pushStartOption(target, props, responseState, formatContext);

    case 'textarea':
      return pushStartTextArea(target, props, responseState);

    case 'input':
      return pushInput(target, props, responseState);

    case 'menuitem':
      return pushStartMenuItem(target, props, responseState);

    case 'title':
      return pushStartTitle(target, props, responseState);
    // Newline eating tags

    case 'listing':
    case 'pre':
      {
        return pushStartPreformattedElement(target, props, type, responseState);
      }
    // Omitted close tags

    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        return pushSelfClosing(target, props, type, responseState);
      }
    // These are reserved SVG and MathML elements, that are never custom elements.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      {
        return pushStartGenericElement(target, props, type, responseState);
      }

    case 'html':
      {
        if (formatContext.insertionMode === ROOT_HTML_MODE) {
          // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
          // then we also emit the DOCTYPE as part of the root content as a convenience for
          // rendering the whole document.
          target.push(DOCTYPE);
        }

        return pushStartGenericElement(target, props, type, responseState);
      }

    default:
      {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
          // Generic element
          return pushStartGenericElement(target, props, type, responseState);
        } else {
          // Custom element
          return pushStartCustomElement(target, props, type, responseState);
        }
      }
  }
}
var endTag1 = stringToPrecomputedChunk('</');
var endTag2 = stringToPrecomputedChunk('>');
function pushEndInstance(target, type, props) {
  switch (type) {
    // Omitted close tags
    // TODO: Instead of repeating this switch we could try to pass a flag from above.
    // That would require returning a tuple. Which might be ok if it gets inlined.
    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'input':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        // No close tag needed.
        break;
      }

    default:
      {
        target.push(endTag1, stringToChunk(type), endTag2);
      }
  }
}
function writeCompletedRoot(destination, responseState) {
  var bootstrapChunks = responseState.bootstrapChunks;
  var i = 0;

  for (; i < bootstrapChunks.length - 1; i++) {
    writeChunk(destination, bootstrapChunks[i]);
  }

  if (i < bootstrapChunks.length) {
    return writeChunkAndReturn(destination, bootstrapChunks[i]);
  }

  return true;
} // Structural Nodes
// A placeholder is a node inside a hidden partial tree that can be filled in later, but before
// display. It's never visible to users. We use the template tag because it can be used in every
// type of parent. <script> tags also work in every other tag except <colgroup>.

var placeholder1 = stringToPrecomputedChunk('<template id="');
var placeholder2 = stringToPrecomputedChunk('"></template>');
function writePlaceholder(destination, responseState, id) {
  writeChunk(destination, placeholder1);
  writeChunk(destination, responseState.placeholderPrefix);
  var formattedID = stringToChunk(id.toString(16));
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, placeholder2);
} // Suspense boundaries are encoded as comments.

var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
function writeStartCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
}
function writeStartPendingSuspenseBoundary(destination, responseState, id) {
  writeChunk(destination, startPendingSuspenseBoundary1);

  if (id === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, id);
  return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
}
function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
  var result;
  result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
  writeChunk(destination, clientRenderedSuspenseBoundaryError1);

  if (errorDigest) {
    writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
    writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
    writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
  }

  {
    if (errorMesssage) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }
  }

  result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
  return result;
}
function writeEndCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndPendingSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
var startSegmentHTML2 = stringToPrecomputedChunk('">');
var endSegmentHTML = stringToPrecomputedChunk('</div>');
var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
var startSegmentSVG2 = stringToPrecomputedChunk('">');
var endSegmentSVG = stringToPrecomputedChunk('</svg>');
var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
var startSegmentMathML2 = stringToPrecomputedChunk('">');
var endSegmentMathML = stringToPrecomputedChunk('</math>');
var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
var startSegmentTable2 = stringToPrecomputedChunk('">');
var endSegmentTable = stringToPrecomputedChunk('</table>');
var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
var startSegmentTableBody2 = stringToPrecomputedChunk('">');
var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
var startSegmentTableRow2 = stringToPrecomputedChunk('">');
var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
var startSegmentColGroup2 = stringToPrecomputedChunk('">');
var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
function writeStartSegment(destination, responseState, formatContext, id) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        writeChunk(destination, startSegmentHTML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentHTML2);
      }

    case SVG_MODE:
      {
        writeChunk(destination, startSegmentSVG);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentSVG2);
      }

    case MATHML_MODE:
      {
        writeChunk(destination, startSegmentMathML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentMathML2);
      }

    case HTML_TABLE_MODE:
      {
        writeChunk(destination, startSegmentTable);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTable2);
      }
    // TODO: For the rest of these, there will be extra wrapper nodes that never
    // get deleted from the document. We need to delete the table too as part
    // of the injected scripts. They are invisible though so it's not too terrible
    // and it's kind of an edge case to suspend in a table. Totally supported though.

    case HTML_TABLE_BODY_MODE:
      {
        writeChunk(destination, startSegmentTableBody);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableBody2);
      }

    case HTML_TABLE_ROW_MODE:
      {
        writeChunk(destination, startSegmentTableRow);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableRow2);
      }

    case HTML_COLGROUP_MODE:
      {
        writeChunk(destination, startSegmentColGroup);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentColGroup2);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
}
function writeEndSegment(destination, formatContext) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentHTML);
      }

    case SVG_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentSVG);
      }

    case MATHML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentMathML);
      }

    case HTML_TABLE_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTable);
      }

    case HTML_TABLE_BODY_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableBody);
      }

    case HTML_TABLE_ROW_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableRow);
      }

    case HTML_COLGROUP_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentColGroup);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
} // Instruction Set
// The following code is the source scripts that we then minify and inline below,
// with renamed function names that we hope don't collide:
// const COMMENT_NODE = 8;
// const SUSPENSE_START_DATA = '$';
// const SUSPENSE_END_DATA = '/$';
// const SUSPENSE_PENDING_START_DATA = '$?';
// const SUSPENSE_FALLBACK_START_DATA = '$!';
//
// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//   // Tag it to be client rendered.
//   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
//   // assign error metadata to first sibling
//   let dataset = suspenseIdNode.dataset;
//   if (errorDigest) dataset.dgst = errorDigest;
//   if (errorMsg) dataset.msg = errorMsg;
//   if (errorComponentStack) dataset.stck = errorComponentStack;
//   // Tell React to retry it if the parent already hydrated.
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeBoundary(suspenseBoundaryID, contentID) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   const contentNode = document.getElementById(contentID);
//   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
//   // This might also help by not causing recalcing each time we move a child from here to the target.
//   contentNode.parentNode.removeChild(contentNode);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated. That's fine there's nothing to do
//     // but we have to make sure that we already deleted the container node.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//
//   // Clear all the existing children. This is complicated because
//   // there can be embedded Suspense boundaries in the fallback.
//   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
//   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
//   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
//   const parentInstance = suspenseNode.parentNode;
//   let node = suspenseNode.nextSibling;
//   let depth = 0;
//   do {
//     if (node && node.nodeType === COMMENT_NODE) {
//       const data = node.data;
//       if (data === SUSPENSE_END_DATA) {
//         if (depth === 0) {
//           break;
//         } else {
//           depth--;
//         }
//       } else if (
//         data === SUSPENSE_START_DATA ||
//         data === SUSPENSE_PENDING_START_DATA ||
//         data === SUSPENSE_FALLBACK_START_DATA
//       ) {
//         depth++;
//       }
//     }
//
//     const nextNode = node.nextSibling;
//     parentInstance.removeChild(node);
//     node = nextNode;
//   } while (node);
//
//   const endOfBoundary = node;
//
//   // Insert all the children from the contentNode between the start and end of suspense boundary.
//   while (contentNode.firstChild) {
//     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
//   }
//   suspenseNode.data = SUSPENSE_START_DATA;
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeSegment(containerID, placeholderID) {
//   const segmentContainer = document.getElementById(containerID);
//   const placeholderNode = document.getElementById(placeholderID);
//   // We always expect both nodes to exist here because, while we might
//   // have navigated away from the main tree, we still expect the detached
//   // tree to exist.
//   segmentContainer.parentNode.removeChild(segmentContainer);
//   while (segmentContainer.firstChild) {
//     placeholderNode.parentNode.insertBefore(
//       segmentContainer.firstChild,
//       placeholderNode,
//     );
//   }
//   placeholderNode.parentNode.removeChild(placeholderNode);
// }

var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
var completeSegmentScript2 = stringToPrecomputedChunk('","');
var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteSegmentFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteSegmentFunction = true;
    writeChunk(destination, completeSegmentScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeSegmentScript1Partial);
  }

  writeChunk(destination, responseState.segmentPrefix);
  var formattedID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, formattedID);
  writeChunk(destination, completeSegmentScript2);
  writeChunk(destination, responseState.placeholderPrefix);
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, completeSegmentScript3);
}
var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
var completeBoundaryScript2 = stringToPrecomputedChunk('","');
var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteBoundaryFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteBoundaryFunction = true;
    writeChunk(destination, completeBoundaryScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeBoundaryScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  var formattedContentID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, boundaryID);
  writeChunk(destination, completeBoundaryScript2);
  writeChunk(destination, responseState.segmentPrefix);
  writeChunk(destination, formattedContentID);
  return writeChunkAndReturn(destination, completeBoundaryScript3);
}
var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
var clientRenderScript1A = stringToPrecomputedChunk('"');
var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentClientRenderFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentClientRenderFunction = true;
    writeChunk(destination, clientRenderScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, clientRenderScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, boundaryID);
  writeChunk(destination, clientRenderScript1A);

  if (errorDigest || errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
  }

  if (errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
  }

  if (errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
  }

  return writeChunkAndReturn(destination, clientRenderScript2);
}
var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

function escapeJSStringsForInstructionScripts(input) {
  var escaped = JSON.stringify(input);
  return escaped.replace(regexForJSStringsInScripts, function (match) {
    switch (match) {
      // santizing breaking out of strings and script tags
      case '<':
        return "\\u003c";

      case "\u2028":
        return "\\u2028";

      case "\u2029":
        return "\\u2029";

      default:
        {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
        }
    }
  });
}

function createResponseState$1(generateStaticMarkup, identifierPrefix) {
  var responseState = createResponseState(identifierPrefix, undefined);
  return {
    // Keep this in sync with ReactDOMServerFormatConfig
    bootstrapChunks: responseState.bootstrapChunks,
    startInlineScript: responseState.startInlineScript,
    placeholderPrefix: responseState.placeholderPrefix,
    segmentPrefix: responseState.segmentPrefix,
    boundaryPrefix: responseState.boundaryPrefix,
    idPrefix: responseState.idPrefix,
    nextSuspenseID: responseState.nextSuspenseID,
    sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction,
    sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction,
    sentClientRenderFunction: responseState.sentClientRenderFunction,
    // This is an extra field for the legacy renderer
    generateStaticMarkup: generateStaticMarkup
  };
}
function createRootFormatContext() {
  return {
    insertionMode: HTML_MODE,
    // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode.
    selectedValue: null
  };
}
function pushTextInstance$1(target, text, responseState, textEmbedded) {
  if (responseState.generateStaticMarkup) {
    target.push(stringToChunk(escapeTextForBrowser(text)));
    return false;
  } else {
    return pushTextInstance(target, text, responseState, textEmbedded);
  }
}
function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) {
  if (responseState.generateStaticMarkup) {
    return;
  } else {
    return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded);
  }
}
function writeStartCompletedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    // A completed boundary is done and doesn't need a representation in the HTML
    // if we're not going to be hydrating it.
    return true;
  }

  return writeStartCompletedSuspenseBoundary(destination);
}
function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format.
errorDigest, errorMessage, errorComponentStack) {
  if (responseState.generateStaticMarkup) {
    // A client rendered boundary is done and doesn't need a representation in the HTML
    // since we'll never hydrate it. This is arguably an error in static generation.
    return true;
  }

  return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack);
}
function writeEndCompletedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    return true;
  }

  return writeEndCompletedSuspenseBoundary(destination);
}
function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) {
  if (responseState.generateStaticMarkup) {
    return true;
  }

  return writeEndClientRenderedSuspenseBoundary(destination);
}

var assign = Object.assign;

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}

function describeClassComponentFrame(ctor, source, ownerFn) {
  {
    return describeNativeComponentFrame(ctor, true);
  }
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var warnedAboutMissingGetChildContext;

{
  warnedAboutMissingGetChildContext = {};
}

var emptyContextObject = {};

{
  Object.freeze(emptyContextObject);
}

function getMaskedContext(type, unmaskedContext) {
  {
    var contextTypes = type.contextTypes;

    if (!contextTypes) {
      return emptyContextObject;
    }

    var context = {};

    for (var key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(contextTypes, context, 'context', name);
    }

    return context;
  }
}
function processChildContext(instance, type, parentContext, childContextTypes) {
  {
    // TODO (bvaughn) Replace this behavior with an invariant() in the future.
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.
    if (typeof instance.getChildContext !== 'function') {
      {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!warnedAboutMissingGetChildContext[componentName]) {
          warnedAboutMissingGetChildContext[componentName] = true;

          error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
        }
      }

      return parentContext;
    }

    var childContext = instance.getChildContext();

    for (var contextKey in childContext) {
      if (!(contextKey in childContextTypes)) {
        throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
      }
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(childContextTypes, childContext, 'child context', name);
    }

    return assign({}, parentContext, childContext);
  }
}

var rendererSigil;

{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
} // Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.


var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are currently in.

var currentActiveSnapshot = null;

function popNode(prev) {
  {
    prev.context._currentValue2 = prev.parentValue;
  }
}

function pushNode(next) {
  {
    next.context._currentValue2 = next.value;
  }
}

function popToNearestCommonAncestor(prev, next) {
  if (prev === next) ; else {
    popNode(prev);
    var parentPrev = prev.parent;
    var parentNext = next.parent;

    if (parentPrev === null) {
      if (parentNext !== null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }
    } else {
      if (parentNext === null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }

      popToNearestCommonAncestor(parentPrev, parentNext);
    } // On the way back, we push the new ones that weren't common.


    pushNode(next);
  }
}

function popAllPrevious(prev) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev !== null) {
    popAllPrevious(parentPrev);
  }
}

function pushAllNext(next) {
  var parentNext = next.parent;

  if (parentNext !== null) {
    pushAllNext(parentNext);
  }

  pushNode(next);
}

function popPreviousToCommonLevel(prev, next) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (parentPrev.depth === next.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(parentPrev, next);
  } else {
    // We must still be deeper.
    popPreviousToCommonLevel(parentPrev, next);
  }
}

function popNextToCommonLevel(prev, next) {
  var parentNext = next.parent;

  if (parentNext === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (prev.depth === parentNext.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(prev, parentNext);
  } else {
    // We must still be deeper.
    popNextToCommonLevel(prev, parentNext);
  }

  pushNode(next);
} // Perform context switching to the new snapshot.
// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
// updating all the context's current values. That way reads, always just read the current value.
// At the cost of updating contexts even if they're never read by this subtree.


function switchContext(newSnapshot) {
  // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
  // We also need to update any new contexts that are now on the stack with the deepest value.
  // The easiest way to update new contexts is to just reapply them in reverse order from the
  // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
  // for that. Therefore this algorithm is recursive.
  // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
  // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
  // 3) Then we reapply new contexts on the way back up the stack.
  var prev = currentActiveSnapshot;
  var next = newSnapshot;

  if (prev !== next) {
    if (prev === null) {
      // $FlowFixMe: This has to be non-null since it's not equal to prev.
      pushAllNext(next);
    } else if (next === null) {
      popAllPrevious(prev);
    } else if (prev.depth === next.depth) {
      popToNearestCommonAncestor(prev, next);
    } else if (prev.depth > next.depth) {
      popPreviousToCommonLevel(prev, next);
    } else {
      popNextToCommonLevel(prev, next);
    }

    currentActiveSnapshot = next;
  }
}
function pushProvider(context, nextValue) {
  var prevValue;

  {
    prevValue = context._currentValue2;
    context._currentValue2 = nextValue;

    {
      if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer2 = rendererSigil;
    }
  }

  var prevNode = currentActiveSnapshot;
  var newNode = {
    parent: prevNode,
    depth: prevNode === null ? 0 : prevNode.depth + 1,
    context: context,
    parentValue: prevValue,
    value: nextValue
  };
  currentActiveSnapshot = newNode;
  return newNode;
}
function popProvider(context) {
  var prevSnapshot = currentActiveSnapshot;

  if (prevSnapshot === null) {
    throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
  }

  {
    if (prevSnapshot.context !== context) {
      error('The parent context is not the expected context. This is probably a bug in React.');
    }
  }

  {
    var _value = prevSnapshot.parentValue;

    if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
      prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;
    } else {
      prevSnapshot.context._currentValue2 = _value;
    }

    {
      if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer2 = rendererSigil;
    }
  }

  return currentActiveSnapshot = prevSnapshot.parent;
}
function getActiveContext() {
  return currentActiveSnapshot;
}
function readContext(context) {
  var value =  context._currentValue2;
  return value;
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}
function set(key, value) {
  key._reactInternals = value;
}

var didWarnAboutNoopUpdateForComponent = {};
var didWarnAboutDeprecatedWillMount = {};
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;

{
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutDirectlyAssigningPropsToState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();
  didWarnAboutContextTypeAndContextTypes = new Set();
  didWarnAboutInvalidateContextType = new Set();
  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }

    var key = callerName + '_' + callback;

    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);

      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (type, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentNameFromType(type) || 'Component';

      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);

        error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  };
}

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
    var warningKey = componentName + '.' + callerName;

    if (didWarnAboutNoopUpdateForComponent[warningKey]) {
      return;
    }

    error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

    didWarnAboutNoopUpdateForComponent[warningKey] = true;
  }
}

var classComponentUpdater = {
  isMounted: function (inst) {
    return false;
  },
  enqueueSetState: function (inst, payload, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'setState');
    } else {
      internals.queue.push(payload);

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var internals = get(inst);
    internals.replace = true;
    internals.queue = [payload];

    {
      if (callback !== undefined && callback !== null) {
        warnOnInvalidCallback(callback, 'setState');
      }
    }
  },
  enqueueForceUpdate: function (inst, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'forceUpdate');
    } else {
      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  }
};

function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    warnOnUndefinedDerivedState(ctor, partialState);
  } // Merge the partial state and the previous state.


  var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
  return newState;
}

function constructClassInstance(ctor, props, maskedLegacyContext) {
  var context = emptyContextObject;
  var contextType = ctor.contextType;

  {
    if ('contextType' in ctor) {
      var isValid = // Allow null for conditional declaration
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
        didWarnAboutInvalidateContextType.add(ctor);
        var addendum = '';

        if (contextType === undefined) {
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
        } else if (typeof contextType !== 'object') {
          addendum = ' However, it is set to a ' + typeof contextType + '.';
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
          addendum = ' Did you accidentally pass the Context.Provider instead?';
        } else if (contextType._context !== undefined) {
          // <Context.Consumer>
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
        } else {
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
        }

        error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
      }
    }
  }

  if (typeof contextType === 'object' && contextType !== null) {
    context = readContext(contextType);
  } else {
    context = maskedLegacyContext;
  }

  var instance = new ctor(props, context);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);

        error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
      }
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.


    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;

      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }

      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentNameFromType(ctor) || 'Component';

        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

          error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
        }
      }
    }
  }

  return instance;
}

function checkClassInstance(instance, ctor, newProps) {
  {
    var name = getComponentNameFromType(ctor) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
        error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
      error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
    }

    if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
    }

    if (instance.propTypes) {
      error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
    }

    if (instance.contextType) {
      error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
    }

    {
      if (instance.contextTypes) {
        error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
      }

      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
        didWarnAboutContextTypeAndContextTypes.add(ctor);

        error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
      }
    }

    if (typeof instance.componentShouldUpdate === 'function') {
      error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
    }

    if (typeof instance.componentDidUnmount === 'function') {
      error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
    }

    if (typeof instance.componentDidReceiveProps === 'function') {
      error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
    }

    if (typeof instance.componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
    }

    if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
    }

    var hasMutatedProps = instance.props !== newProps;

    if (instance.props !== undefined && hasMutatedProps) {
      error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
    }

    if (instance.defaultProps) {
      error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

      error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
    }

    if (typeof instance.getDerivedStateFromProps === 'function') {
      error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof instance.getDerivedStateFromError === 'function') {
      error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
      error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
    }

    var _state = instance.state;

    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      error('%s.state: must be set to an object or null', name);
    }

    if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
      error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
    }
  }
}

function callComponentWillMount(type, instance) {
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    {
      if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!didWarnAboutDeprecatedWillMount[componentName]) {
          warn( // keep this warning in sync with ReactStrictModeWarning.js
          'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

          didWarnAboutDeprecatedWillMount[componentName] = true;
        }
      }
    }

    instance.componentWillMount();
  }

  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  if (oldState !== instance.state) {
    {
      error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
  if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
    var oldQueue = internalInstance.queue;
    var oldReplace = internalInstance.replace;
    internalInstance.queue = null;
    internalInstance.replace = false;

    if (oldReplace && oldQueue.length === 1) {
      inst.state = oldQueue[0];
    } else {
      var nextState = oldReplace ? oldQueue[0] : inst.state;
      var dontMutate = true;

      for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
        var partial = oldQueue[i];
        var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

        if (partialState != null) {
          if (dontMutate) {
            dontMutate = false;
            nextState = assign({}, nextState, partialState);
          } else {
            assign(nextState, partialState);
          }
        }
      }

      inst.state = nextState;
    }
  } else {
    internalInstance.queue = null;
  }
} // Invokes the mount life-cycles on a previously never rendered instance.


function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
  {
    checkClassInstance(instance, ctor, newProps);
  }

  var initialState = instance.state !== undefined ? instance.state : null;
  instance.updater = classComponentUpdater;
  instance.props = newProps;
  instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
  // The internal instance will be used to manage updates that happen during this mount.

  var internalInstance = {
    queue: [],
    replace: false
  };
  set(instance, internalInstance);
  var contextType = ctor.contextType;

  if (typeof contextType === 'object' && contextType !== null) {
    instance.context = readContext(contextType);
  } else {
    instance.context = maskedLegacyContext;
  }

  {
    if (instance.state === newProps) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);

        error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
      }
    }
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

  if (typeof getDerivedStateFromProps === 'function') {
    instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
  } // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.


  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
    // process them now.

    processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
  }
}

// Ids are base 32 strings whose binary representation corresponds to the
// position of a node in a tree.
// Every time the tree forks into multiple children, we add additional bits to
// the left of the sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5. However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
// the zeroth id at a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in the
// sequence. It's treated as a transparent indirection. For example, these two
// trees produce the same ids:
//
// <>                          <>
//   <Indirection>               <A />
//     <A />                     <B />
//   </Indirection>            </>
//   <B />
// </>
//
// However, we cannot skip any node that materializes an id. Otherwise, a parent
// id that does not fork would be indistinguishable from its child id. For
// example, this tree does not fork, but the parent and child must have
// different ids.
//
// <Parent>
//   <Child />
// </Parent>
//
// To handle this scenario, every time we materialize an id, we allocate a
// new level with a single slot. You can think of this as a fork with only one
// prong, or an array of children with length 1.
//
// It's possible for the size of the sequence to exceed 32 bits, the max
// size for bitwise operations. When this happens, we make more room by
// converting the right part of the id to a string and storing it in an overflow
// variable. We use a base 32 string representation, because 32 is the largest
// power of 2 that is supported by toString(). We want the base to be large so
// that the resulting ids are compact, and we want the base to be a power of 2
// because every log2(base) bits corresponds to a single character, i.e. every
// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
// affecting the final result.
var emptyTreeContext = {
  id: 1,
  overflow: ''
};
function getTreeId(context) {
  var overflow = context.overflow;
  var idWithLeadingBit = context.id;
  var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
  return id.toString(32) + overflow;
}
function pushTreeContext(baseContext, totalChildren, index) {
  var baseIdWithLeadingBit = baseContext.id;
  var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
  // of the id; we use it to account for leading 0s.

  var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
  var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
  var slot = index + 1;
  var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
  // consideration the leading 1 we use to mark the end of the sequence.

  if (length > 30) {
    // We overflowed the bitwise-safe range. Fall back to slower algorithm.
    // This branch assumes the length of the base id is greater than 5; it won't
    // work for smaller ids, because you need 5 bits per character.
    //
    // We encode the id in multiple steps: first the base id, then the
    // remaining digits.
    //
    // Each 5 bit sequence corresponds to a single base 32 character. So for
    // example, if the current id is 23 bits long, we can convert 20 of those
    // bits into a string of 4 characters, with 3 bits left over.
    //
    // First calculate how many bits in the base id represent a complete
    // sequence of characters.
    var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

    var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

    var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

    var restOfBaseId = baseId >> numberOfOverflowBits;
    var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
    // we made more room, this time it won't overflow.

    var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
    var restOfNewBits = slot << restOfBaseLength;
    var id = restOfNewBits | restOfBaseId;
    var overflow = newOverflow + baseOverflow;
    return {
      id: 1 << restOfLength | id,
      overflow: overflow
    };
  } else {
    // Normal path
    var newBits = slot << baseLength;

    var _id = newBits | baseId;

    var _overflow = baseOverflow;
    return {
      id: 1 << length | _id,
      overflow: _overflow
    };
  }
}

function getBitLength(number) {
  return 32 - clz32(number);
}

function getLeadingBit(id) {
  return 1 << getBitLength(id) - 1;
} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

var log = Math.log;
var LN2 = Math.LN2;

function clz32Fallback(x) {
  var asUint = x >>> 0;

  if (asUint === 0) {
    return 32;
  }

  return 31 - (log(asUint) / LN2 | 0) | 0;
}

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  ;
}

var objectIs = typeof Object.is === 'function' ? Object.is : is;

var currentlyRenderingComponent = null;
var currentlyRenderingTask = null;
var firstWorkInProgressHook = null;
var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

var localIdCounter = 0; // Lazily created map of render-phase updates

var renderPhaseUpdates = null; // Counter to prevent infinite loops.

var numberOfReRenders = 0;
var RE_RENDER_LIMIT = 25;
var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

var currentHookNameInDev;

function resolveCurrentlyRenderingComponent() {
  if (currentlyRenderingComponent === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
  }

  {
    if (isInHookUserCodeInDev) {
      error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
    }
  }

  return currentlyRenderingComponent;
}

function areHookInputsEqual(nextDeps, prevDeps) {
  if (prevDeps === null) {
    {
      error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
    }

    return false;
  }

  {
    // Don't bother comparing lengths in prod because these arrays should be
    // passed inline.
    if (nextDeps.length !== prevDeps.length) {
      error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
    }
  }

  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (objectIs(nextDeps[i], prevDeps[i])) {
      continue;
    }

    return false;
  }

  return true;
}

function createHook() {
  if (numberOfReRenders > 0) {
    throw new Error('Rendered more hooks than during the previous render');
  }

  return {
    memoizedState: null,
    queue: null,
    next: null
  };
}

function createWorkInProgressHook() {
  if (workInProgressHook === null) {
    // This is the first hook in the list
    if (firstWorkInProgressHook === null) {
      isReRender = false;
      firstWorkInProgressHook = workInProgressHook = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = firstWorkInProgressHook;
    }
  } else {
    if (workInProgressHook.next === null) {
      isReRender = false; // Append to the end of the list

      workInProgressHook = workInProgressHook.next = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = workInProgressHook.next;
    }
  }

  return workInProgressHook;
}

function prepareToUseHooks(task, componentIdentity) {
  currentlyRenderingComponent = componentIdentity;
  currentlyRenderingTask = task;

  {
    isInHookUserCodeInDev = false;
  } // The following should have already been reset
  // didScheduleRenderPhaseUpdate = false;
  // localIdCounter = 0;
  // firstWorkInProgressHook = null;
  // numberOfReRenders = 0;
  // renderPhaseUpdates = null;
  // workInProgressHook = null;


  localIdCounter = 0;
}
function finishHooks(Component, props, children, refOrContext) {
  // This must be called after every function component to prevent hooks from
  // being used in classes.
  while (didScheduleRenderPhaseUpdate) {
    // Updates were scheduled during the render phase. They are stored in
    // the `renderPhaseUpdates` map. Call the component again, reusing the
    // work-in-progress hooks and applying the additional updates on top. Keep
    // restarting until no more updates are scheduled.
    didScheduleRenderPhaseUpdate = false;
    localIdCounter = 0;
    numberOfReRenders += 1; // Start over from the beginning of the list

    workInProgressHook = null;
    children = Component(props, refOrContext);
  }

  resetHooksState();
  return children;
}
function checkDidRenderIdHook() {
  // This should be called immediately after every finishHooks call.
  // Conceptually, it's part of the return value of finishHooks; it's only a
  // separate function to avoid using an array tuple.
  var didRenderIdHook = localIdCounter !== 0;
  return didRenderIdHook;
} // Reset the internal hooks state if an error occurs while rendering a component

function resetHooksState() {
  {
    isInHookUserCodeInDev = false;
  }

  currentlyRenderingComponent = null;
  currentlyRenderingTask = null;
  didScheduleRenderPhaseUpdate = false;
  firstWorkInProgressHook = null;
  numberOfReRenders = 0;
  renderPhaseUpdates = null;
  workInProgressHook = null;
}

function readContext$1(context) {
  {
    if (isInHookUserCodeInDev) {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    }
  }

  return readContext(context);
}

function useContext(context) {
  {
    currentHookNameInDev = 'useContext';
  }

  resolveCurrentlyRenderingComponent();
  return readContext(context);
}

function basicStateReducer(state, action) {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

function useState(initialState) {
  {
    currentHookNameInDev = 'useState';
  }

  return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
  initialState);
}
function useReducer(reducer, initialArg, init) {
  {
    if (reducer !== basicStateReducer) {
      currentHookNameInDev = 'useReducer';
    }
  }

  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();

  if (isReRender) {
    // This is a re-render. Apply the new render phase updates to the previous
    // current hook.
    var queue = workInProgressHook.queue;
    var dispatch = queue.dispatch;

    if (renderPhaseUpdates !== null) {
      // Render phase updates are stored in a map of queue -> linked list
      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate !== undefined) {
        renderPhaseUpdates.delete(queue);
        var newState = workInProgressHook.memoizedState;
        var update = firstRenderPhaseUpdate;

        do {
          // Process this render phase update. We don't have to check the
          // priority because it will always be the same as the current
          // render's.
          var action = update.action;

          {
            isInHookUserCodeInDev = true;
          }

          newState = reducer(newState, action);

          {
            isInHookUserCodeInDev = false;
          }

          update = update.next;
        } while (update !== null);

        workInProgressHook.memoizedState = newState;
        return [newState, dispatch];
      }
    }

    return [workInProgressHook.memoizedState, dispatch];
  } else {
    {
      isInHookUserCodeInDev = true;
    }

    var initialState;

    if (reducer === basicStateReducer) {
      // Special case for `useState`.
      initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
    } else {
      initialState = init !== undefined ? init(initialArg) : initialArg;
    }

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = initialState;

    var _queue = workInProgressHook.queue = {
      last: null,
      dispatch: null
    };

    var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

    return [workInProgressHook.memoizedState, _dispatch];
  }
}

function useMemo(nextCreate, deps) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;

  if (workInProgressHook !== null) {
    var prevState = workInProgressHook.memoizedState;

    if (prevState !== null) {
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }
  }

  {
    isInHookUserCodeInDev = true;
  }

  var nextValue = nextCreate();

  {
    isInHookUserCodeInDev = false;
  }

  workInProgressHook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function useRef(initialValue) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var previousRef = workInProgressHook.memoizedState;

  if (previousRef === null) {
    var ref = {
      current: initialValue
    };

    {
      Object.seal(ref);
    }

    workInProgressHook.memoizedState = ref;
    return ref;
  } else {
    return previousRef;
  }
}

function useLayoutEffect(create, inputs) {
  {
    currentHookNameInDev = 'useLayoutEffect';

    error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
  }
}

function dispatchAction(componentIdentity, queue, action) {
  if (numberOfReRenders >= RE_RENDER_LIMIT) {
    throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
  }

  if (componentIdentity === currentlyRenderingComponent) {
    // This is a render phase update. Stash it in a lazily-created map of
    // queue -> linked list of updates. After this render pass, we'll restart
    // and apply the stashed updates on top of the work-in-progress hook.
    didScheduleRenderPhaseUpdate = true;
    var update = {
      action: action,
      next: null
    };

    if (renderPhaseUpdates === null) {
      renderPhaseUpdates = new Map();
    }

    var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

    if (firstRenderPhaseUpdate === undefined) {
      renderPhaseUpdates.set(queue, update);
    } else {
      // Append the update to the end of the list.
      var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

      while (lastRenderPhaseUpdate.next !== null) {
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      }

      lastRenderPhaseUpdate.next = update;
    }
  }
}

function useCallback(callback, deps) {
  return useMemo(function () {
    return callback;
  }, deps);
} // TODO Decide on how to implement this hook for server rendering.
// If a mutation occurs during render, consider triggering a Suspense boundary
// and falling back to client rendering.

function useMutableSource(source, getSnapshot, subscribe) {
  resolveCurrentlyRenderingComponent();
  return getSnapshot(source._source);
}

function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  if (getServerSnapshot === undefined) {
    throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
  }

  return getServerSnapshot();
}

function useDeferredValue(value) {
  resolveCurrentlyRenderingComponent();
  return value;
}

function unsupportedStartTransition() {
  throw new Error('startTransition cannot be called during server rendering.');
}

function useTransition() {
  resolveCurrentlyRenderingComponent();
  return [false, unsupportedStartTransition];
}

function useId() {
  var task = currentlyRenderingTask;
  var treeId = getTreeId(task.treeContext);
  var responseState = currentResponseState;

  if (responseState === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
  }

  var localId = localIdCounter++;
  return makeId(responseState, treeId, localId);
}

function noop() {}

var Dispatcher = {
  readContext: readContext$1,
  useContext: useContext,
  useMemo: useMemo,
  useReducer: useReducer,
  useRef: useRef,
  useState: useState,
  useInsertionEffect: noop,
  useLayoutEffect: useLayoutEffect,
  useCallback: useCallback,
  // useImperativeHandle is not run in the server environment
  useImperativeHandle: noop,
  // Effects are not run in the server environment.
  useEffect: noop,
  // Debugging effect
  useDebugValue: noop,
  useDeferredValue: useDeferredValue,
  useTransition: useTransition,
  useId: useId,
  // Subscriptions are not setup in a server environment.
  useMutableSource: useMutableSource,
  useSyncExternalStore: useSyncExternalStore
};

var currentResponseState = null;
function setCurrentResponseState(responseState) {
  currentResponseState = responseState;
}

function getStackByComponentStackNode(componentStack) {
  try {
    var info = '';
    var node = componentStack;

    do {
      switch (node.tag) {
        case 0:
          info += describeBuiltInComponentFrame(node.type, null, null);
          break;

        case 1:
          info += describeFunctionComponentFrame(node.type, null, null);
          break;

        case 2:
          info += describeClassComponentFrame(node.type, null, null);
          break;
      }

      node = node.parent;
    } while (node);

    return info;
  } catch (x) {
    return '\nError generating stack: ' + x.message + '\n' + x.stack;
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
var PENDING = 0;
var COMPLETED = 1;
var FLUSHED = 2;
var ABORTED = 3;
var ERRORED = 4;
var OPEN = 0;
var CLOSING = 1;
var CLOSED = 2;
// This is a default heuristic for how to split up the HTML content into progressive
// loading. Our goal is to be able to display additional new content about every 500ms.
// Faster than that is unnecessary and should be throttled on the client. It also
// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
// end device but higher end suffer less from the overhead than lower end does from
// not getting small enough pieces. We error on the side of low end.
// We base this on low end 3G speeds which is about 500kbits per second. We assume
// that there can be a reasonable drop off from max bandwidth which leaves you with
// as little as 80%. We can receive half of that each 500ms - at best. In practice,
// a little bandwidth is lost to processing and contention - e.g. CSS and images that
// are downloaded along with the main content. So we estimate about half of that to be
// the lower end throughput. In other words, we expect that you can at least show
// about 12.5kb of content per 500ms. Not counting starting latency for the first
// paint.
// 500 * 1024 / 8 * .8 * 0.5 / 2
var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

function defaultErrorHandler(error) {
  console['error'](error); // Don't transform to our wrapper

  return null;
}

function noop$1() {}

function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
  var pingedTasks = [];
  var abortSet = new Set();
  var request = {
    destination: null,
    responseState: responseState,
    progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
    status: OPEN,
    fatalError: null,
    nextSegmentId: 0,
    allPendingTasks: 0,
    pendingRootTasks: 0,
    completedRootSegment: null,
    abortableTasks: abortSet,
    pingedTasks: pingedTasks,
    clientRenderedBoundaries: [],
    completedBoundaries: [],
    partialBoundaries: [],
    onError: onError === undefined ? defaultErrorHandler : onError,
    onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
    onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
    onShellError: onShellError === undefined ? noop$1 : onShellError,
    onFatalError: onFatalError === undefined ? noop$1 : onFatalError
  }; // This segment represents the root fallback.

  var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
  false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

  rootSegment.parentFlushed = true;
  var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
  pingedTasks.push(rootTask);
  return request;
}

function pingTask(request, task) {
  var pingedTasks = request.pingedTasks;
  pingedTasks.push(task);

  if (pingedTasks.length === 1) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
}

function createSuspenseBoundary(request, fallbackAbortableTasks) {
  return {
    id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
    rootSegmentID: -1,
    parentFlushed: false,
    pendingTasks: 0,
    forceClientRender: false,
    completedSegments: [],
    byteSize: 0,
    fallbackAbortableTasks: fallbackAbortableTasks,
    errorDigest: null
  };
}

function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
  request.allPendingTasks++;

  if (blockedBoundary === null) {
    request.pendingRootTasks++;
  } else {
    blockedBoundary.pendingTasks++;
  }

  var task = {
    node: node,
    ping: function () {
      return pingTask(request, task);
    },
    blockedBoundary: blockedBoundary,
    blockedSegment: blockedSegment,
    abortSet: abortSet,
    legacyContext: legacyContext,
    context: context,
    treeContext: treeContext
  };

  {
    task.componentStack = null;
  }

  abortSet.add(task);
  return task;
}

function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
  return {
    status: PENDING,
    id: -1,
    // lazily assigned later
    index: index,
    parentFlushed: false,
    chunks: [],
    children: [],
    formatContext: formatContext,
    boundary: boundary,
    lastPushedText: lastPushedText,
    textEmbedded: textEmbedded
  };
} // DEV-only global reference to the currently executing task


var currentTaskInDEV = null;

function getCurrentStackInDEV() {
  {
    if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
      return '';
    }

    return getStackByComponentStackNode(currentTaskInDEV.componentStack);
  }
}

function pushBuiltInComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 0,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushFunctionComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 1,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushClassComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 2,
      parent: task.componentStack,
      type: type
    };
  }
}

function popComponentStackInDEV(task) {
  {
    if (task.componentStack === null) {
      error('Unexpectedly popped too many stack frames. This is a bug in React.');
    } else {
      task.componentStack = task.componentStack.parent;
    }
  }
} // stash the component stack of an unwinding error until it is processed


var lastBoundaryErrorComponentStackDev = null;

function captureBoundaryErrorDetailsDev(boundary, error) {
  {
    var errorMessage;

    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error && typeof error.message === 'string') {
      errorMessage = error.message;
    } else {
      // eslint-disable-next-line react-internal/safe-string-coercion
      errorMessage = String(error);
    }

    var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
    lastBoundaryErrorComponentStackDev = null;
    boundary.errorMessage = errorMessage;
    boundary.errorComponentStack = errorComponentStack;
  }
}

function logRecoverableError(request, error) {
  // If this callback errors, we intentionally let that error bubble up to become a fatal error
  // so that someone fixes the error reporting instead of hiding it.
  var errorDigest = request.onError(error);

  if (errorDigest != null && typeof errorDigest !== 'string') {
    // eslint-disable-next-line react-internal/prod-error-codes
    throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
  }

  return errorDigest;
}

function fatalError(request, error) {
  // This is called outside error handling code such as if the root errors outside
  // a suspense boundary or if the root suspense boundary's fallback errors.
  // It's also called if React itself or its host configs errors.
  var onShellError = request.onShellError;
  onShellError(error);
  var onFatalError = request.onFatalError;
  onFatalError(error);

  if (request.destination !== null) {
    request.status = CLOSED;
    closeWithError(request.destination, error);
  } else {
    request.status = CLOSING;
    request.fatalError = error;
  }
}

function renderSuspenseBoundary(request, task, props) {
  pushBuiltInComponentStackInDEV(task, 'Suspense');
  var parentBoundary = task.blockedBoundary;
  var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
  // the fallback so that we can later replace that segment with the content.
  // This also lets us split out the main content even if it doesn't suspend,
  // in case it ends up generating a large subtree of content.

  var fallback = props.fallback;
  var content = props.children;
  var fallbackAbortSet = new Set();
  var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
  var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

  var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false);
  parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

  parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

  var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
  // no parent segment so there's nothing to wait on.

  contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
  // I suspect that there might be some efficiency benefits from not creating the suspended task
  // and instead just using the stack if possible.
  // TODO: Call this directly instead of messing with saving and restoring contexts.
  // We can reuse the current context and task to render the content immediately without
  // context switching. We just need to temporarily switch which boundary and which segment
  // we're writing to. If something suspends, it'll spawn new suspended task with that context.

  task.blockedBoundary = newBoundary;
  task.blockedSegment = contentRootSegment;

  try {
    // We use the safe form because we don't handle suspending here. Only error handling.
    renderNode(request, task, content);
    pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
    contentRootSegment.status = COMPLETED;
    queueCompletedSegment(newBoundary, contentRootSegment);

    if (newBoundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      // Therefore we won't need the fallback. We early return so that we don't have to create
      // the fallback.
      popComponentStackInDEV(task);
      return;
    }
  } catch (error) {
    contentRootSegment.status = ERRORED;
    newBoundary.forceClientRender = true;
    newBoundary.errorDigest = logRecoverableError(request, error);

    {
      captureBoundaryErrorDetailsDev(newBoundary, error);
    } // We don't need to decrement any task numbers because we didn't spawn any new task.
    // We don't need to schedule any task because we know the parent has written yet.
    // We do need to fallthrough to create the fallback though.

  } finally {
    task.blockedBoundary = parentBoundary;
    task.blockedSegment = parentSegment;
  } // We create suspended task for the fallback because we don't want to actually work
  // on it yet in case we finish the main content, so we queue for later.


  var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

  {
    suspendedFallbackTask.componentStack = task.componentStack;
  } // TODO: This should be queued at a separate lower priority queue so that we only work
  // on preparing fallbacks if we don't have any more main content to task on.


  request.pingedTasks.push(suspendedFallbackTask);
  popComponentStackInDEV(task);
}

function renderHostElement(request, task, type, props) {
  pushBuiltInComponentStackInDEV(task, type);
  var segment = task.blockedSegment;
  var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
  segment.lastPushedText = false;
  var prevContext = segment.formatContext;
  segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
  // need to pop back up and finish this subtree of HTML.

  renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
  // the correct context. Therefore this is not in a finally.

  segment.formatContext = prevContext;
  pushEndInstance(segment.chunks, type);
  segment.lastPushedText = false;
  popComponentStackInDEV(task);
}

function shouldConstruct$1(Component) {
  return Component.prototype && Component.prototype.isReactComponent;
}

function renderWithHooks(request, task, Component, props, secondArg) {
  var componentIdentity = {};
  prepareToUseHooks(task, componentIdentity);
  var result = Component(props, secondArg);
  return finishHooks(Component, props, result, secondArg);
}

function finishClassComponent(request, task, instance, Component, props) {
  var nextChildren = instance.render();

  {
    if (instance.props !== props) {
      if (!didWarnAboutReassigningProps) {
        error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
      }

      didWarnAboutReassigningProps = true;
    }
  }

  {
    var childContextTypes = Component.childContextTypes;

    if (childContextTypes !== null && childContextTypes !== undefined) {
      var previousContext = task.legacyContext;
      var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
      task.legacyContext = mergedContext;
      renderNodeDestructive(request, task, nextChildren);
      task.legacyContext = previousContext;
      return;
    }
  }

  renderNodeDestructive(request, task, nextChildren);
}

function renderClassComponent(request, task, Component, props) {
  pushClassComponentStackInDEV(task, Component);
  var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
  var instance = constructClassInstance(Component, props, maskedContext);
  mountClassInstance(instance, Component, props, maskedContext);
  finishClassComponent(request, task, instance, Component, props);
  popComponentStackInDEV(task);
}

var didWarnAboutBadClass = {};
var didWarnAboutModulePatternComponent = {};
var didWarnAboutContextTypeOnFunctionComponent = {};
var didWarnAboutGetDerivedStateOnFunctionComponent = {};
var didWarnAboutReassigningProps = false;
var didWarnAboutDefaultPropsOnFunctionComponent = {};
var didWarnAboutGenerators = false;
var didWarnAboutMaps = false;
var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
// components for some reason.

function renderIndeterminateComponent(request, task, Component, props) {
  var legacyContext;

  {
    legacyContext = getMaskedContext(Component, task.legacyContext);
  }

  pushFunctionComponentStackInDEV(task, Component);

  {
    if (Component.prototype && typeof Component.prototype.render === 'function') {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

        didWarnAboutBadClass[componentName] = true;
      }
    }
  }

  var value = renderWithHooks(request, task, Component, props, legacyContext);
  var hasId = checkDidRenderIdHook();

  {
    // Support for module components is deprecated and is removed behind a flag.
    // Whether or not it would crash later, we want to show a good message in DEV first.
    if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      var _componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

        didWarnAboutModulePatternComponent[_componentName] = true;
      }
    }
  }

  if ( // Run these checks in production only if the flag is off.
  // Eventually we'll delete this branch altogether.
   typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    {
      var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName2]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

        didWarnAboutModulePatternComponent[_componentName2] = true;
      }
    }

    mountClassInstance(value, Component, props, legacyContext);
    finishClassComponent(request, task, value, Component, props);
  } else {

    {
      validateFunctionComponentInDev(Component);
    } // We're now successfully past this task, and we don't have to pop back to
    // the previous task every again, so we can use the destructive recursive form.


    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, value);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, value);
    }
  }

  popComponentStackInDEV(task);
}

function validateFunctionComponentInDev(Component) {
  {
    if (Component) {
      if (Component.childContextTypes) {
        error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
      }
    }

    if ( Component.defaultProps !== undefined) {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
        error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

        didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
      }
    }

    if (typeof Component.getDerivedStateFromProps === 'function') {
      var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
        error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

        didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
      }
    }

    if (typeof Component.contextType === 'object' && Component.contextType !== null) {
      var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
        error('%s: Function components do not support contextType.', _componentName4);

        didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
      }
    }
  }
}

function resolveDefaultProps(Component, baseProps) {
  if (Component && Component.defaultProps) {
    // Resolve default props. Taken from ReactElement
    var props = assign({}, baseProps);
    var defaultProps = Component.defaultProps;

    for (var propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }

    return props;
  }

  return baseProps;
}

function renderForwardRef(request, task, type, props, ref) {
  pushFunctionComponentStackInDEV(task, type.render);
  var children = renderWithHooks(request, task, type.render, props, ref);
  var hasId = checkDidRenderIdHook();

  if (hasId) {
    // This component materialized an id. We treat this as its own level, with
    // a single "child" slot.
    var prevTreeContext = task.treeContext;
    var totalChildren = 1;
    var index = 0;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

    try {
      renderNodeDestructive(request, task, children);
    } finally {
      task.treeContext = prevTreeContext;
    }
  } else {
    renderNodeDestructive(request, task, children);
  }

  popComponentStackInDEV(task);
}

function renderMemo(request, task, type, props, ref) {
  var innerType = type.type;
  var resolvedProps = resolveDefaultProps(innerType, props);
  renderElement(request, task, innerType, resolvedProps, ref);
}

function renderContextConsumer(request, task, context, props) {
  // The logic below for Context differs depending on PROD or DEV mode. In
  // DEV mode, we create a separate object for Context.Consumer that acts
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
  // so we use the old behaviour (Context.Consumer references Context) to
  // reduce size and overhead. The separate object references context via
  // a property called "_context", which also gives us the ability to check
  // in DEV mode if this property exists or not and warn if it does not.
  {
    if (context._context === undefined) {
      // This may be because it's a Context (rather than a Consumer).
      // Or it may be because it's older React where they're the same thing.
      // We only want to warn if we're sure it's a new React.
      if (context !== context.Consumer) {
        if (!hasWarnedAboutUsingContextAsConsumer) {
          hasWarnedAboutUsingContextAsConsumer = true;

          error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
        }
      }
    } else {
      context = context._context;
    }
  }

  var render = props.children;

  {
    if (typeof render !== 'function') {
      error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
    }
  }

  var newValue = readContext(context);
  var newChildren = render(newValue);
  renderNodeDestructive(request, task, newChildren);
}

function renderContextProvider(request, task, type, props) {
  var context = type._context;
  var value = props.value;
  var children = props.children;
  var prevSnapshot;

  {
    prevSnapshot = task.context;
  }

  task.context = pushProvider(context, value);
  renderNodeDestructive(request, task, children);
  task.context = popProvider(context);

  {
    if (prevSnapshot !== task.context) {
      error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
    }
  }
}

function renderLazyComponent(request, task, lazyComponent, props, ref) {
  pushBuiltInComponentStackInDEV(task, 'Lazy');
  var payload = lazyComponent._payload;
  var init = lazyComponent._init;
  var Component = init(payload);
  var resolvedProps = resolveDefaultProps(Component, props);
  renderElement(request, task, Component, resolvedProps, ref);
  popComponentStackInDEV(task);
}

function renderElement(request, task, type, props, ref) {
  if (typeof type === 'function') {
    if (shouldConstruct$1(type)) {
      renderClassComponent(request, task, type, props);
      return;
    } else {
      renderIndeterminateComponent(request, task, type, props);
      return;
    }
  }

  if (typeof type === 'string') {
    renderHostElement(request, task, type, props);
    return;
  }

  switch (type) {
    // TODO: LegacyHidden acts the same as a fragment. This only works
    // because we currently assume that every instance of LegacyHidden is
    // accompanied by a host component wrapper. In the hidden mode, the host
    // component is given a `hidden` attribute, which ensures that the
    // initial HTML is not visible. To support the use of LegacyHidden as a
    // true fragment, without an extra DOM node, we would have to hide the
    // initial HTML in some other way.
    // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
    case REACT_LEGACY_HIDDEN_TYPE:
    case REACT_DEBUG_TRACING_MODE_TYPE:
    case REACT_STRICT_MODE_TYPE:
    case REACT_PROFILER_TYPE:
    case REACT_FRAGMENT_TYPE:
      {
        renderNodeDestructive(request, task, props.children);
        return;
      }

    case REACT_SUSPENSE_LIST_TYPE:
      {
        pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

        renderNodeDestructive(request, task, props.children);
        popComponentStackInDEV(task);
        return;
      }

    case REACT_SCOPE_TYPE:
      {

        throw new Error('ReactDOMServer does not yet support scope components.');
      }
    // eslint-disable-next-line-no-fallthrough

    case REACT_SUSPENSE_TYPE:
      {
        {
          renderSuspenseBoundary(request, task, props);
        }

        return;
      }
  }

  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        {
          renderForwardRef(request, task, type, props, ref);
          return;
        }

      case REACT_MEMO_TYPE:
        {
          renderMemo(request, task, type, props, ref);
          return;
        }

      case REACT_PROVIDER_TYPE:
        {
          renderContextProvider(request, task, type, props);
          return;
        }

      case REACT_CONTEXT_TYPE:
        {
          renderContextConsumer(request, task, type, props);
          return;
        }

      case REACT_LAZY_TYPE:
        {
          renderLazyComponent(request, task, type, props);
          return;
        }
    }
  }

  var info = '';

  {
    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
    }
  }

  throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
}

function validateIterable(iterable, iteratorFn) {
  {
    // We don't support rendering Generators because it's a mutation.
    // See https://github.com/facebook/react/issues/12995
    if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
    iterable[Symbol.toStringTag] === 'Generator') {
      if (!didWarnAboutGenerators) {
        error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
      }

      didWarnAboutGenerators = true;
    } // Warn about using Maps as children


    if (iterable.entries === iteratorFn) {
      if (!didWarnAboutMaps) {
        error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
      }

      didWarnAboutMaps = true;
    }
  }
}

function renderNodeDestructive(request, task, node) {
  {
    // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
    // a component stack at the right place in the tree. We don't do this in renderNode
    // becuase it is not called at every layer of the tree and we may lose frames
    try {
      return renderNodeDestructiveImpl(request, task, node);
    } catch (x) {
      if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
        // This is an error, stash the component stack if it is null.
        lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
      } // rethrow so normal suspense logic can handle thrown value accordingly


      throw x;
    }
  }
} // This function by it self renders a node and consumes the task by mutating it
// to update the current execution state.


function renderNodeDestructiveImpl(request, task, node) {
  // Stash the node we're working on. We'll pick up from this task in case
  // something suspends.
  task.node = node; // Handle object types

  if (typeof node === 'object' && node !== null) {
    switch (node.$$typeof) {
      case REACT_ELEMENT_TYPE:
        {
          var element = node;
          var type = element.type;
          var props = element.props;
          var ref = element.ref;
          renderElement(request, task, type, props, ref);
          return;
        }

      case REACT_PORTAL_TYPE:
        throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
      // eslint-disable-next-line-no-fallthrough

      case REACT_LAZY_TYPE:
        {
          var lazyNode = node;
          var payload = lazyNode._payload;
          var init = lazyNode._init;
          var resolvedNode;

          {
            try {
              resolvedNode = init(payload);
            } catch (x) {
              if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                // vs Component position. We do not want the frame for Errors so we exclusively do this in
                // the wakeable branch
                pushBuiltInComponentStackInDEV(task, 'Lazy');
              }

              throw x;
            }
          }

          renderNodeDestructive(request, task, resolvedNode);
          return;
        }
    }

    if (isArray(node)) {
      renderChildrenArray(request, task, node);
      return;
    }

    var iteratorFn = getIteratorFn(node);

    if (iteratorFn) {
      {
        validateIterable(node, iteratorFn);
      }

      var iterator = iteratorFn.call(node);

      if (iterator) {
        // We need to know how many total children are in this set, so that we
        // can allocate enough id slots to acommodate them. So we must exhaust
        // the iterator before we start recursively rendering the children.
        // TODO: This is not great but I think it's inherent to the id
        // generation algorithm.
        var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

        if (!step.done) {
          var children = [];

          do {
            children.push(step.value);
            step = iterator.next();
          } while (!step.done);

          renderChildrenArray(request, task, children);
          return;
        }

        return;
      }
    }

    var childString = Object.prototype.toString.call(node);
    throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
  }

  if (typeof node === 'string') {
    var segment = task.blockedSegment;
    segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
    return;
  }

  if (typeof node === 'number') {
    var _segment = task.blockedSegment;
    _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
    return;
  }

  {
    if (typeof node === 'function') {
      error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
    }
  }
}

function renderChildrenArray(request, task, children) {
  var totalChildren = children.length;

  for (var i = 0; i < totalChildren; i++) {
    var prevTreeContext = task.treeContext;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

    try {
      // We need to use the non-destructive form so that we can safely pop back
      // up and render the sibling if something suspends.
      renderNode(request, task, children[i]);
    } finally {
      task.treeContext = prevTreeContext;
    }
  }
}

function spawnNewSuspendedTask(request, task, x) {
  // Something suspended, we'll need to create a new segment and resolve it later.
  var segment = task.blockedSegment;
  var insertionIndex = segment.chunks.length;
  var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
  segment.lastPushedText, // Assume we are text embedded at the trailing edge
  true);
  segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

  segment.lastPushedText = false;
  var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

  {
    if (task.componentStack !== null) {
      // We pop one task off the stack because the node that suspended will be tried again,
      // which will add it back onto the stack.
      newTask.componentStack = task.componentStack.parent;
    }
  }

  var ping = newTask.ping;
  x.then(ping, ping);
} // This is a non-destructive form of rendering a node. If it suspends it spawns
// a new task and restores the context of this task to what it was before.


function renderNode(request, task, node) {
  // TODO: Store segment.children.length here and reset it in case something
  // suspended partially through writing something.
  // Snapshot the current context in case something throws to interrupt the
  // process.
  var previousFormatContext = task.blockedSegment.formatContext;
  var previousLegacyContext = task.legacyContext;
  var previousContext = task.context;
  var previousComponentStack = null;

  {
    previousComponentStack = task.componentStack;
  }

  try {
    return renderNodeDestructive(request, task, node);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.

      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      }

      return;
    } else {
      // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.
      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      } // We assume that we don't need the correct context.
      // Let's terminate the rest of the tree and don't render any siblings.


      throw x;
    }
  }
}

function erroredTask(request, boundary, segment, error) {
  // Report the error to a global handler.
  var errorDigest = logRecoverableError(request, error);

  if (boundary === null) {
    fatalError(request, error);
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;
      boundary.errorDigest = errorDigest;

      {
        captureBoundaryErrorDetailsDev(boundary, error);
      } // Regardless of what happens next, this boundary won't be displayed,
      // so we can flush it, if the parent already flushed.


      if (boundary.parentFlushed) {
        // We don't have a preference where in the queue this goes since it's likely
        // to error on the client anyway. However, intentionally client-rendered
        // boundaries should be flushed earlier so that they can start on the client.
        // We reuse the same queue for errors.
        request.clientRenderedBoundaries.push(boundary);
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function abortTaskSoft(task) {
  // This aborts task without aborting the parent boundary that it blocks.
  // It's used for when we didn't need this task to complete the tree.
  // If task was needed, then it should use abortTask instead.
  var request = this;
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;
  finishedTask(request, boundary, segment);
}

function abortTask(task, request, reason) {
  // This aborts the task and aborts the parent that it blocks, putting it into
  // client rendered mode.
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;

  if (boundary === null) {
    request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
    // the request;

    if (request.status !== CLOSED) {
      request.status = CLOSED;

      if (request.destination !== null) {
        close(request.destination);
      }
    }
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;

      var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

      boundary.errorDigest = request.onError(_error);

      {
        var errorPrefix = 'The server did not finish this Suspense boundary: ';

        if (_error && typeof _error.message === 'string') {
          _error = errorPrefix + _error.message;
        } else {
          // eslint-disable-next-line react-internal/safe-string-coercion
          _error = errorPrefix + String(_error);
        }

        var previousTaskInDev = currentTaskInDEV;
        currentTaskInDEV = task;

        try {
          captureBoundaryErrorDetailsDev(boundary, _error);
        } finally {
          currentTaskInDEV = previousTaskInDev;
        }
      }

      if (boundary.parentFlushed) {
        request.clientRenderedBoundaries.push(boundary);
      }
    } // If this boundary was still pending then we haven't already cancelled its fallbacks.
    // We'll need to abort the fallbacks, which will also error that parent boundary.


    boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
      return abortTask(fallbackTask, request, reason);
    });
    boundary.fallbackAbortableTasks.clear();
    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }
}

function queueCompletedSegment(boundary, segment) {
  if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
    // This is an empty segment. There's nothing to write, so we can instead transfer the ID
    // to the child. That way any existing references point to the child.
    var childSegment = segment.children[0];
    childSegment.id = segment.id;
    childSegment.parentFlushed = true;

    if (childSegment.status === COMPLETED) {
      queueCompletedSegment(boundary, childSegment);
    }
  } else {
    var completedSegments = boundary.completedSegments;
    completedSegments.push(segment);
  }
}

function finishedTask(request, boundary, segment) {
  if (boundary === null) {
    if (segment.parentFlushed) {
      if (request.completedRootSegment !== null) {
        throw new Error('There can only be one root segment. This is a bug in React.');
      }

      request.completedRootSegment = segment;
    }

    request.pendingRootTasks--;

    if (request.pendingRootTasks === 0) {
      // We have completed the shell so the shell can't error anymore.
      request.onShellError = noop$1;
      var onShellReady = request.onShellReady;
      onShellReady();
    }
  } else {
    boundary.pendingTasks--;

    if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      if (segment.parentFlushed) {
        // Our parent segment already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
        }
      }

      if (boundary.parentFlushed) {
        // The segment might be part of a segment that didn't flush yet, but if the boundary's
        // parent flushed, we need to schedule the boundary to be emitted.
        request.completedBoundaries.push(boundary);
      } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
      // This needs to happen after we read the parentFlushed flags because aborting can finish
      // work which can trigger user code, which can start flushing, which can change those flags.


      boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
      boundary.fallbackAbortableTasks.clear();
    } else {
      if (segment.parentFlushed) {
        // Our parent already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
          var completedSegments = boundary.completedSegments;

          if (completedSegments.length === 1) {
            // This is the first time since we last flushed that we completed anything.
            // We can schedule this boundary to emit its partially completed segments early
            // in case the parent has already been flushed.
            if (boundary.parentFlushed) {
              request.partialBoundaries.push(boundary);
            }
          }
        }
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    // This needs to be called at the very end so that we can synchronously write the result
    // in the callback if needed.
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function retryTask(request, task) {
  var segment = task.blockedSegment;

  if (segment.status !== PENDING) {
    // We completed this by other means before we had a chance to retry it.
    return;
  } // We restore the context to what it was when we suspended.
  // We don't restore it after we leave because it's likely that we'll end up
  // needing a very similar context soon again.


  switchContext(task.context);
  var prevTaskInDEV = null;

  {
    prevTaskInDEV = currentTaskInDEV;
    currentTaskInDEV = task;
  }

  try {
    // We call the destructive form that mutates this task. That way if something
    // suspends again, we can reuse the same task instead of spawning a new one.
    renderNodeDestructive(request, task, task.node);
    pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
    task.abortSet.delete(task);
    segment.status = COMPLETED;
    finishedTask(request, task.blockedBoundary, segment);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      // Something suspended again, let's pick it back up later.
      var ping = task.ping;
      x.then(ping, ping);
    } else {
      task.abortSet.delete(task);
      segment.status = ERRORED;
      erroredTask(request, task.blockedBoundary, segment, x);
    }
  } finally {
    {
      currentTaskInDEV = prevTaskInDEV;
    }
  }
}

function performWork(request) {
  if (request.status === CLOSED) {
    return;
  }

  var prevContext = getActiveContext();
  var prevDispatcher = ReactCurrentDispatcher$1.current;
  ReactCurrentDispatcher$1.current = Dispatcher;
  var prevGetCurrentStackImpl;

  {
    prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
    ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
  }

  var prevResponseState = currentResponseState;
  setCurrentResponseState(request.responseState);

  try {
    var pingedTasks = request.pingedTasks;
    var i;

    for (i = 0; i < pingedTasks.length; i++) {
      var task = pingedTasks[i];
      retryTask(request, task);
    }

    pingedTasks.splice(0, i);

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  } finally {
    setCurrentResponseState(prevResponseState);
    ReactCurrentDispatcher$1.current = prevDispatcher;

    {
      ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
    }

    if (prevDispatcher === Dispatcher) {
      // This means that we were in a reentrant work loop. This could happen
      // in a renderer that supports synchronous work like renderToString,
      // when it's called from within another renderer.
      // Normally we don't bother switching the contexts to their root/default
      // values when leaving because we'll likely need the same or similar
      // context again. However, when we're inside a synchronous loop like this
      // we'll to restore the context to what it was before returning.
      switchContext(prevContext);
    }
  }
}

function flushSubtree(request, destination, segment) {
  segment.parentFlushed = true;

  switch (segment.status) {
    case PENDING:
      {
        // We're emitting a placeholder for this segment to be filled in later.
        // Therefore we'll need to assign it an ID - to refer to it by.
        var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

        segment.lastPushedText = false;
        segment.textEmbedded = false;
        return writePlaceholder(destination, request.responseState, segmentID);
      }

    case COMPLETED:
      {
        segment.status = FLUSHED;
        var r = true;
        var chunks = segment.chunks;
        var chunkIdx = 0;
        var children = segment.children;

        for (var childIdx = 0; childIdx < children.length; childIdx++) {
          var nextChild = children[childIdx]; // Write all the chunks up until the next child.

          for (; chunkIdx < nextChild.index; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          r = flushSegment(request, destination, nextChild);
        } // Finally just write all the remaining chunks


        for (; chunkIdx < chunks.length - 1; chunkIdx++) {
          writeChunk(destination, chunks[chunkIdx]);
        }

        if (chunkIdx < chunks.length) {
          r = writeChunkAndReturn(destination, chunks[chunkIdx]);
        }

        return r;
      }

    default:
      {
        throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
      }
  }
}

function flushSegment(request, destination, segment) {
  var boundary = segment.boundary;

  if (boundary === null) {
    // Not a suspense boundary.
    return flushSubtree(request, destination, segment);
  }

  boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
  // emit the content or the fallback now.

  if (boundary.forceClientRender) {
    // Emit a client rendered suspense boundary wrapper.
    // We never queue the inner boundary so we'll never emit its content or partial segments.
    writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState);
  } else if (boundary.pendingTasks > 0) {
    // This boundary is still loading. Emit a pending suspense boundary wrapper.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;

    if (boundary.completedSegments.length > 0) {
      // If this is at least partially complete, we can queue it to be partially emitted early.
      request.partialBoundaries.push(boundary);
    } /// This is the first time we should have referenced this ID.


    var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
    writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else if (boundary.byteSize > request.progressiveChunkSize) {
    // This boundary is large and will be emitted separately so that we can progressively show
    // other content. We add it to the queue during the flush because we have to ensure that
    // the parent flushes first so that there's something to inject it into.
    // We also have to make sure that it's emitted into the queue in a deterministic slot.
    // I.e. we can't insert it here when it completes.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;
    request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

    writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else {
    // We can inline this boundary's content as a complete boundary.
    writeStartCompletedSuspenseBoundary$1(destination, request.responseState);
    var completedSegments = boundary.completedSegments;

    if (completedSegments.length !== 1) {
      throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
    }

    var contentSegment = completedSegments[0];
    flushSegment(request, destination, contentSegment);
    return writeEndCompletedSuspenseBoundary$1(destination, request.responseState);
  }
}

function flushClientRenderedBoundary(request, destination, boundary) {
  return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
}

function flushSegmentContainer(request, destination, segment) {
  writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
  flushSegment(request, destination, segment);
  return writeEndSegment(destination, segment.formatContext);
}

function flushCompletedBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];
    flushPartiallyCompletedSegment(request, destination, boundary, segment);
  }

  completedSegments.length = 0;
  return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
}

function flushPartialBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];

    if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
      i++;
      completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
      // might want to write later.

      return false;
    }
  }

  completedSegments.splice(0, i);
  return true;
}

function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
  if (segment.status === FLUSHED) {
    // We've already flushed this inline.
    return true;
  }

  var segmentID = segment.id;

  if (segmentID === -1) {
    // This segment wasn't previously referred to. This happens at the root of
    // a boundary. We make kind of a leap here and assume this is the root.
    var rootSegmentID = segment.id = boundary.rootSegmentID;

    if (rootSegmentID === -1) {
      throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
    }

    return flushSegmentContainer(request, destination, segment);
  } else {
    flushSegmentContainer(request, destination, segment);
    return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
  }
}

function flushCompletedQueues(request, destination) {

  try {
    // The structure of this is to go through each queue one by one and write
    // until the sink tells us to stop. When we should stop, we still finish writing
    // that item fully and then yield. At that point we remove the already completed
    // items up until the point we completed them.
    // TODO: Emit preloading.
    // TODO: It's kind of unfortunate to keep checking this array after we've already
    // emitted the root.
    var completedRootSegment = request.completedRootSegment;

    if (completedRootSegment !== null && request.pendingRootTasks === 0) {
      flushSegment(request, destination, completedRootSegment);
      request.completedRootSegment = null;
      writeCompletedRoot(destination, request.responseState);
    } // We emit client rendering instructions for already emitted boundaries first.
    // This is so that we can signal to the client to start client rendering them as
    // soon as possible.


    var clientRenderedBoundaries = request.clientRenderedBoundaries;
    var i;

    for (i = 0; i < clientRenderedBoundaries.length; i++) {
      var boundary = clientRenderedBoundaries[i];

      if (!flushClientRenderedBoundary(request, destination, boundary)) {
        request.destination = null;
        i++;
        clientRenderedBoundaries.splice(0, i);
        return;
      }
    }

    clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
    // that are completely done since we can actually show them, than it is to emit
    // any individual segments from a partially complete boundary.

    var completedBoundaries = request.completedBoundaries;

    for (i = 0; i < completedBoundaries.length; i++) {
      var _boundary = completedBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary)) {
        request.destination = null;
        i++;
        completedBoundaries.splice(0, i);
        return;
      }
    }

    completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
    // we continue with lower priorities.

    completeWriting(destination);
    beginWriting(destination); // TODO: Here we'll emit data used by hydration.
    // Next we emit any segments of any boundaries that are partially complete
    // but not deeply complete.

    var partialBoundaries = request.partialBoundaries;

    for (i = 0; i < partialBoundaries.length; i++) {
      var _boundary2 = partialBoundaries[i];

      if (!flushPartialBoundary(request, destination, _boundary2)) {
        request.destination = null;
        i++;
        partialBoundaries.splice(0, i);
        return;
      }
    }

    partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
    // boundaries added to it in case they were too larged to be inlined.
    // New ones might be added in this loop.

    var largeBoundaries = request.completedBoundaries;

    for (i = 0; i < largeBoundaries.length; i++) {
      var _boundary3 = largeBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary3)) {
        request.destination = null;
        i++;
        largeBoundaries.splice(0, i);
        return;
      }
    }

    largeBoundaries.splice(0, i);
  } finally {

    if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
    // either they have pending task or they're complete.
    ) {
        {
          if (request.abortableTasks.size !== 0) {
            error('There was still abortable task at the root when we closed. This is a bug in React.');
          }
        } // We're done.


        close(destination);
      }
  }
}

function startWork(request) {
  scheduleWork(function () {
    return performWork(request);
  });
}
function startFlowing(request, destination) {
  if (request.status === CLOSING) {
    request.status = CLOSED;
    closeWithError(destination, request.fatalError);
    return;
  }

  if (request.status === CLOSED) {
    return;
  }

  if (request.destination !== null) {
    // We're already flowing.
    return;
  }

  request.destination = destination;

  try {
    flushCompletedQueues(request, destination);
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

function abort(request, reason) {
  try {
    var abortableTasks = request.abortableTasks;
    abortableTasks.forEach(function (task) {
      return abortTask(task, request, reason);
    });
    abortableTasks.clear();

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
}

function onError() {// Non-fatal errors are ignored.
}

function renderToStringImpl(children, options, generateStaticMarkup, abortReason) {
  var didFatal = false;
  var fatalError = null;
  var result = '';
  var destination = {
    push: function (chunk) {
      if (chunk !== null) {
        result += chunk;
      }

      return true;
    },
    destroy: function (error) {
      didFatal = true;
      fatalError = error;
    }
  };
  var readyToStream = false;

  function onShellReady() {
    readyToStream = true;
  }

  var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined);
  startWork(request); // If anything suspended and is still pending, we'll abort it before writing.
  // That way we write only client-rendered boundaries from the start.

  abort(request, abortReason);
  startFlowing(request, destination);

  if (didFatal) {
    throw fatalError;
  }

  if (!readyToStream) {
    // Note: This error message is the one we use on the client. It doesn't
    // really make sense here. But this is the legacy server renderer, anyway.
    // We're going to delete it soon.
    throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.');
  }

  return result;
}

function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}

var ReactMarkupReadableStream = /*#__PURE__*/function (_Readable) {
  _inheritsLoose(ReactMarkupReadableStream, _Readable);

  function ReactMarkupReadableStream() {
    var _this;

    // Calls the stream.Readable(options) constructor. Consider exposing built-in
    // features like highWaterMark in the future.
    _this = _Readable.call(this, {}) || this;
    _this.request = null;
    _this.startedFlowing = false;
    return _this;
  }

  var _proto = ReactMarkupReadableStream.prototype;

  _proto._destroy = function _destroy(err, callback) {
    abort(this.request); // $FlowFixMe: The type definition for the callback should allow undefined and null.

    callback(err);
  };

  _proto._read = function _read(size) {
    if (this.startedFlowing) {
      startFlowing(this.request, this);
    }
  };

  return ReactMarkupReadableStream;
}(stream.Readable);

function onError$1() {// Non-fatal errors are ignored.
}

function renderToNodeStreamImpl(children, options, generateStaticMarkup) {
  function onAllReady() {
    // We wait until everything has loaded before starting to write.
    // That way we only end up with fully resolved HTML even if we suspend.
    destination.startedFlowing = true;
    startFlowing(request, destination);
  }

  var destination = new ReactMarkupReadableStream();
  var request = createRequest(children, createResponseState$1(false, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError$1, onAllReady, undefined, undefined);
  destination.request = request;
  startWork(request);
  return destination;
}

function renderToNodeStream(children, options) {
  {
    error('renderToNodeStream is deprecated. Use renderToPipeableStream instead.');
  }

  return renderToNodeStreamImpl(children, options);
}

function renderToStaticNodeStream(children, options) {
  {
    error('ReactDOMServer.renderToStaticNodeStream() is deprecated.' + ' Use ReactDOMServer.renderToPipeableStream() and wait to `pipe` until the `onAllReady`' + ' callback has been called instead.');
  }

  return renderToNodeStreamImpl(children, options);
}

function renderToString(children, options) {
  return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server');
}

function renderToStaticMarkup(children, options) {
  return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server');
}

exports.renderToNodeStream = renderToNodeStream;
exports.renderToStaticMarkup = renderToStaticMarkup;
exports.renderToStaticNodeStream = renderToStaticNodeStream;
exports.renderToString = renderToString;
exports.version = ReactVersion;
  })();
}
/**
 * @license React
 * react-dom-server-legacy.node.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var ea=require("react"),fa=require("stream"),n=Object.prototype.hasOwnProperty,ha=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ia={},ja={};
function ka(a){if(n.call(ja,a))return!0;if(n.call(ia,a))return!1;if(ha.test(a))return ja[a]=!0;ia[a]=!0;return!1}function q(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}var r={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){r[a]=new q(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];r[b]=new q(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){r[a]=new q(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){r[a]=new q(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){r[a]=new q(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){r[a]=new q(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){r[a]=new q(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){r[a]=new q(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){r[a]=new q(a,5,!1,a.toLowerCase(),null,!1,!1)});var la=/[\-:]([a-z])/g;function ma(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(la,
ma);r[b]=new q(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(la,ma);r[b]=new q(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(la,ma);r[b]=new q(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){r[a]=new q(a,1,!1,a.toLowerCase(),null,!1,!1)});
r.xlinkHref=new q("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){r[a]=new q(a,1,!1,a.toLowerCase(),null,!0,!0)});
var t={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,
fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},na=["Webkit","ms","Moz","O"];Object.keys(t).forEach(function(a){na.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);t[b]=t[a]})});var oa=/["'&<>]/;
function u(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=oa.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}var pa=/([A-Z])/g,qa=/^ms-/,ra=Array.isArray;function v(a,b){return{insertionMode:a,selectedValue:b}}
function sa(a,b,c){switch(b){case "select":return v(1,null!=c.value?c.value:c.defaultValue);case "svg":return v(2,null);case "math":return v(3,null);case "foreignObject":return v(1,null);case "table":return v(4,null);case "thead":case "tbody":case "tfoot":return v(5,null);case "colgroup":return v(7,null);case "tr":return v(6,null)}return 4<=a.insertionMode||0===a.insertionMode?v(1,null):a}var ta=new Map;
function ua(a,b,c){if("object"!==typeof c)throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");b=!0;for(var d in c)if(n.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=u(d);f=u((""+f).trim())}else{e=d;var g=ta.get(e);void 0!==g?e=g:(g=u(e.replace(pa,"-$1").toLowerCase().replace(qa,"-ms-")),ta.set(e,g),e=g);f="number"===typeof f?0===f||n.call(t,
d)?""+f:f+"px":u((""+f).trim())}b?(b=!1,a.push(' style="',e,":",f)):a.push(";",e,":",f)}}b||a.push('"')}
function w(a,b,c,d){switch(c){case "style":ua(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=r.hasOwnProperty(c)?r[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=b.attributeName;switch(b.type){case 3:d&&a.push(" ",c,'=""');break;case 4:!0===d?a.push(" ",c,'=""'):
!1!==d&&a.push(" ",c,'="',u(d),'"');break;case 5:isNaN(d)||a.push(" ",c,'="',u(d),'"');break;case 6:!isNaN(d)&&1<=d&&a.push(" ",c,'="',u(d),'"');break;default:b.sanitizeURL&&(d=""+d),a.push(" ",c,'="',u(d),'"')}}else if(ka(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(" ",c,'="',u(d),'"')}}
function x(a,b,c){if(null!=b){if(null!=c)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!==typeof b||!("__html"in b))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");b=b.__html;null!==b&&void 0!==b&&a.push(""+b)}}function va(a){var b="";ea.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}
function wa(a,b,c,d){a.push(z(c));var f=c=null,e;for(e in b)if(n.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:w(a,d,e,g)}}a.push(">");x(a,f,c);return"string"===typeof c?(a.push(u(c)),null):c}var xa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,ya=new Map;function z(a){var b=ya.get(a);if(void 0===b){if(!xa.test(a))throw Error("Invalid tag: "+a);b="<"+a;ya.set(a,b)}return b}
function za(a,b,c,d,f){switch(b){case "select":a.push(z("select"));var e=null,g=null;for(l in c)if(n.call(c,l)){var h=c[l];if(null!=h)switch(l){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:w(a,d,l,h)}}a.push(">");x(a,g,e);return e;case "option":g=f.selectedValue;a.push(z("option"));var k=h=null,m=null;var l=null;for(e in c)if(n.call(c,e)){var p=c[e];if(null!=p)switch(e){case "children":h=p;break;case "selected":m=p;break;case "dangerouslySetInnerHTML":l=
p;break;case "value":k=p;default:w(a,d,e,p)}}if(null!=g)if(c=null!==k?""+k:va(h),ra(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(' selected=""');break}}else""+g===c&&a.push(' selected=""');else m&&a.push(' selected=""');a.push(">");x(a,l,h);return h;case "textarea":a.push(z("textarea"));l=g=e=null;for(h in c)if(n.call(c,h)&&(k=c[h],null!=k))switch(h){case "children":l=k;break;case "value":e=k;break;case "defaultValue":g=k;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
default:w(a,d,h,k)}null===e&&null!==g&&(e=g);a.push(">");if(null!=l){if(null!=e)throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");if(ra(l)&&1<l.length)throw Error("<textarea> can only have at most one child.");e=""+l}"string"===typeof e&&"\n"===e[0]&&a.push("\n");null!==e&&a.push(u(""+e));return null;case "input":a.push(z("input"));k=l=h=e=null;for(g in c)if(n.call(c,g)&&(m=c[g],null!=m))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error("input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");
case "defaultChecked":k=m;break;case "defaultValue":h=m;break;case "checked":l=m;break;case "value":e=m;break;default:w(a,d,g,m)}null!==l?w(a,d,"checked",l):null!==k&&w(a,d,"checked",k);null!==e?w(a,d,"value",e):null!==h&&w(a,d,"value",h);a.push("/>");return null;case "menuitem":a.push(z("menuitem"));for(var B in c)if(n.call(c,B)&&(e=c[B],null!=e))switch(B){case "children":case "dangerouslySetInnerHTML":throw Error("menuitems cannot have `children` nor `dangerouslySetInnerHTML`.");default:w(a,d,B,
e)}a.push(">");return null;case "title":a.push(z("title"));e=null;for(p in c)if(n.call(c,p)&&(g=c[p],null!=g))switch(p){case "children":e=g;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <title>.");default:w(a,d,p,g)}a.push(">");return e;case "listing":case "pre":a.push(z(b));g=e=null;for(k in c)if(n.call(c,k)&&(h=c[k],null!=h))switch(k){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:w(a,d,k,h)}a.push(">");if(null!=g){if(null!=
e)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!==typeof g||!("__html"in g))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push("\n",c):a.push(""+c))}"string"===typeof e&&"\n"===e[0]&&a.push("\n");return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(z(b));
for(var C in c)if(n.call(c,C)&&(e=c[C],null!=e))switch(C){case "children":case "dangerouslySetInnerHTML":throw Error(b+" is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:w(a,d,C,e)}a.push("/>");return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return wa(a,c,b,d);case "html":return 0===f.insertionMode&&a.push("<!DOCTYPE html>"),
wa(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return wa(a,c,b,d);a.push(z(b));g=e=null;for(m in c)if(n.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "style":ua(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ka(m)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(" ",m,'="',u(h),'"')}a.push(">");x(a,g,e);return e}}
function Aa(a,b,c){a.push('\x3c!--$?--\x3e<template id="');if(null===c)throw Error("An ID must have been assigned before we can complete the boundary.");a.push(c);return a.push('"></template>')}
function Ba(a,b,c,d){switch(c.insertionMode){case 0:case 1:return a.push('<div hidden id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 2:return a.push('<svg aria-hidden="true" style="display:none" id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 3:return a.push('<math aria-hidden="true" style="display:none" id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 4:return a.push('<table hidden id="'),a.push(b.segmentPrefix),
b=d.toString(16),a.push(b),a.push('">');case 5:return a.push('<table hidden><tbody id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 6:return a.push('<table hidden><tr id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');case 7:return a.push('<table hidden><colgroup id="'),a.push(b.segmentPrefix),b=d.toString(16),a.push(b),a.push('">');default:throw Error("Unknown insertion mode. This is a bug in React.");}}
function Ca(a,b){switch(b.insertionMode){case 0:case 1:return a.push("</div>");case 2:return a.push("</svg>");case 3:return a.push("</math>");case 4:return a.push("</table>");case 5:return a.push("</tbody></table>");case 6:return a.push("</tr></table>");case 7:return a.push("</colgroup></table>");default:throw Error("Unknown insertion mode. This is a bug in React.");}}var Da=/[<\u2028\u2029]/g;
function Ea(a){return JSON.stringify(a).replace(Da,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}
function Fa(a,b){b=void 0===b?"":b;return{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:b+"P:",segmentPrefix:b+"S:",boundaryPrefix:b+"B:",idPrefix:b,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:a}}function Ga(){return{insertionMode:1,selectedValue:null}}function Ha(a,b,c,d){if(c.generateStaticMarkup)return a.push(u(b)),!1;""===b?a=d:(d&&a.push("\x3c!-- --\x3e"),a.push(u(b)),a=!0);return a}
var A=Object.assign,Ia=Symbol.for("react.element"),Ja=Symbol.for("react.portal"),Ka=Symbol.for("react.fragment"),La=Symbol.for("react.strict_mode"),Ma=Symbol.for("react.profiler"),Na=Symbol.for("react.provider"),Oa=Symbol.for("react.context"),Pa=Symbol.for("react.forward_ref"),Qa=Symbol.for("react.suspense"),Ra=Symbol.for("react.suspense_list"),Sa=Symbol.for("react.memo"),Ta=Symbol.for("react.lazy"),Ua=Symbol.for("react.scope"),Va=Symbol.for("react.debug_trace_mode"),Wa=Symbol.for("react.legacy_hidden"),
Xa=Symbol.for("react.default_value"),Ya=Symbol.iterator;
function Za(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Ka:return"Fragment";case Ja:return"Portal";case Ma:return"Profiler";case La:return"StrictMode";case Qa:return"Suspense";case Ra:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Oa:return(a.displayName||"Context")+".Consumer";case Na:return(a._context.displayName||"Context")+".Provider";case Pa:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Sa:return b=a.displayName||null,null!==b?b:Za(a.type)||"Memo";case Ta:b=a._payload;a=a._init;try{return Za(a(b))}catch(c){}}return null}var $a={};function ab(a,b){a=a.contextTypes;if(!a)return $a;var c={},d;for(d in a)c[d]=b[d];return c}var D=null;
function E(a,b){if(a!==b){a.context._currentValue2=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");}else{if(null===c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");E(a,c)}b.context._currentValue2=b.value}}function bb(a){a.context._currentValue2=a.parentValue;a=a.parent;null!==a&&bb(a)}
function cb(a){var b=a.parent;null!==b&&cb(b);a.context._currentValue2=a.value}function db(a,b){a.context._currentValue2=a.parentValue;a=a.parent;if(null===a)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===b.depth?E(a,b):db(a,b)}
function eb(a,b){var c=b.parent;if(null===c)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===c.depth?E(a,c):eb(a,c);b.context._currentValue2=b.value}function F(a){var b=D;b!==a&&(null===b?cb(a):null===a?bb(b):b.depth===a.depth?E(b,a):b.depth>a.depth?db(b,a):eb(b,a),D=a)}
var fb={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}};
function gb(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=fb;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue2:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:A({},f,g),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=
a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&fb.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=A({},e,h)):A(e,h))}a.state=e}else e.queue=null}
var hb={id:1,overflow:""};function ib(a,b,c){var d=a.id;a=a.overflow;var f=32-G(d)-1;d&=~(1<<f);c+=1;var e=32-G(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-G(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}var G=Math.clz32?Math.clz32:jb,kb=Math.log,lb=Math.LN2;function jb(a){a>>>=0;return 0===a?32:31-(kb(a)/lb|0)|0}function mb(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}
var nb="function"===typeof Object.is?Object.is:mb,H=null,ob=null,I=null,J=null,K=!1,L=!1,M=0,N=null,O=0;
function P(){if(null===H)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");return H}
function rb(){if(0<O)throw Error("Rendered more hooks than during the previous render");return{memoizedState:null,queue:null,next:null}}function sb(){null===J?null===I?(K=!1,I=J=rb()):(K=!0,J=I):null===J.next?(K=!1,J=J.next=rb()):(K=!0,J=J.next);return J}function tb(){ob=H=null;L=!1;I=null;O=0;J=N=null}function ub(a,b){return"function"===typeof b?b(a):b}
function vb(a,b,c){H=P();J=sb();if(K){var d=J.queue;b=d.dispatch;if(null!==N&&(c=N.get(d),void 0!==c)){N.delete(d);d=J.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);J.memoizedState=d;return[d,b]}return[J.memoizedState,b]}a=a===ub?"function"===typeof b?b():b:void 0!==c?c(b):b;J.memoizedState=a;a=J.queue={last:null,dispatch:null};a=a.dispatch=wb.bind(null,H,a);return[J.memoizedState,a]}
function xb(a,b){H=P();J=sb();b=void 0===b?null:b;if(null!==J){var c=J.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!nb(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();J.memoizedState=[a,b];return a}
function wb(a,b,c){if(25<=O)throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");if(a===H)if(L=!0,a={action:c,next:null},null===N&&(N=new Map),c=N.get(b),void 0===c)N.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function yb(){throw Error("startTransition cannot be called during server rendering.");}function Q(){}
var zb={readContext:function(a){return a._currentValue2},useContext:function(a){P();return a._currentValue2},useMemo:xb,useReducer:vb,useRef:function(a){H=P();J=sb();var b=J.memoizedState;return null===b?(a={current:a},J.memoizedState=a):b},useState:function(a){return vb(ub,a)},useInsertionEffect:Q,useLayoutEffect:function(){},useCallback:function(a,b){return xb(function(){return a},b)},useImperativeHandle:Q,useEffect:Q,useDebugValue:Q,useDeferredValue:function(a){P();return a},useTransition:function(){P();
return[!1,yb]},useId:function(){var a=ob.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-G(a)-1)).toString(32)+b;var c=R;if(null===c)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");b=M++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b){P();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
return c()}},R=null,Ab=ea.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function Bb(a){console.error(a);return null}function S(){}
function Cb(a,b,c,d,f,e,g,h,k){var m=[],l=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:l,pingedTasks:m,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?Bb:f,onAllReady:void 0===e?S:e,onShellReady:void 0===g?S:g,onShellError:void 0===h?S:h,onFatalError:void 0===k?S:k};c=T(b,0,null,c,!1,!1);c.parentFlushed=
!0;a=Db(b,a,null,c,l,$a,null,hb);m.push(a);return b}function Db(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var k={node:b,ping:function(){var b=a.pingedTasks;b.push(k);1===b.length&&Eb(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(k);return k}function T(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}
function U(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function V(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,a.destination.destroy(b)):(a.status=1,a.fatalError=b)}
function Fb(a,b,c,d,f){H={};ob=b;M=0;for(a=c(d,f);L;)L=!1,M=0,O+=1,J=null,a=c(d,f);tb();return a}function Gb(a,b,c,d){var f=c.render(),e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error((Za(d)||"Unknown")+'.getChildContext(): key "'+h+'" is not defined in childContextTypes.');d=A({},g,c)}b.legacyContext=d;W(a,b,f);b.legacyContext=g}else W(a,b,f)}
function Hb(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}
function Ib(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=ab(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue2:f);gb(e,c,d,f);Gb(a,b,e,c)}else{e=ab(c,b.legacyContext);f=Fb(a,b,c,d,e);var g=0!==M;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)gb(f,c,d,e),Gb(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=ib(d,1,0);try{W(a,b,f)}finally{b.treeContext=d}}else W(a,b,f)}else if("string"===
typeof c){f=b.blockedSegment;e=za(f.chunks,c,d,a.responseState,f.formatContext);f.lastPushedText=!1;g=f.formatContext;f.formatContext=sa(g,c,d);Jb(a,b,e);f.formatContext=g;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push("</",c,">")}f.lastPushedText=!1}else{switch(c){case Wa:case Va:case La:case Ma:case Ka:W(a,b,d.children);return;
case Ra:W(a,b,d.children);return;case Ua:throw Error("ReactDOMServer does not yet support scope components.");case Qa:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null},k=T(a,f.chunks.length,h,f.formatContext,!1,!1);f.children.push(k);f.lastPushedText=!1;var m=T(a,0,null,f.formatContext,!1,!1);m.parentFlushed=!0;
b.blockedBoundary=h;b.blockedSegment=m;try{if(Jb(a,b,d),a.responseState.generateStaticMarkup||m.lastPushedText&&m.textEmbedded&&m.chunks.push("\x3c!-- --\x3e"),m.status=1,X(h,m),0===h.pendingTasks)break a}catch(l){m.status=4,h.forceClientRender=!0,h.errorDigest=U(a,l)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=Db(a,e,c,k,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case Pa:d=Fb(a,b,c.render,d,f);if(0!==M){c=b.treeContext;
b.treeContext=ib(c,1,0);try{W(a,b,d)}finally{b.treeContext=c}}else W(a,b,d);return;case Sa:c=c.type;d=Hb(c,d);Ib(a,b,c,d,f);return;case Na:f=d.children;c=c._context;d=d.value;e=c._currentValue2;c._currentValue2=d;g=D;D=d={parent:g,depth:null===g?0:g.depth+1,context:c,parentValue:e,value:d};b.context=d;W(a,b,f);a=D;if(null===a)throw Error("Tried to pop a Context at the root of the app. This is a bug in React.");d=a.parentValue;a.context._currentValue2=d===Xa?a.context._defaultValue:d;a=D=a.parent;
b.context=a;return;case Oa:d=d.children;d=d(c._currentValue2);W(a,b,d);return;case Ta:f=c._init;c=f(c._payload);d=Hb(c,d);Ib(a,b,c,d,void 0);return}throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+((null==c?c:typeof c)+"."));}}
function W(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Ia:Ib(a,b,c.type,c.props,c.ref);return;case Ja:throw Error("Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.");case Ta:var d=c._init;c=d(c._payload);W(a,b,c);return}if(ra(c)){Kb(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=Ya&&c[Ya]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=
[];do f.push(c.value),c=d.next();while(!c.done);Kb(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error("Objects are not valid as a React child (found: "+("[object Object]"===a?"object with keys {"+Object.keys(c).join(", ")+"}":a)+"). If you meant to render a collection of children, use an array instead.");}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=Ha(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=Ha(b.blockedSegment.chunks,
""+c,a.responseState,d.lastPushedText))}function Kb(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=ib(e,d,f);try{Jb(a,b,c[f])}finally{b.treeContext=e}}}
function Jb(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return W(a,b,c)}catch(k){if(tb(),"object"===typeof k&&null!==k&&"function"===typeof k.then){c=k;var g=b.blockedSegment,h=T(a,g.chunks.length,null,g.formatContext,g.lastPushedText,!0);g.children.push(h);g.lastPushedText=!1;a=Db(a,b.node,b.blockedBoundary,h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;F(e)}else throw b.blockedSegment.formatContext=
d,b.legacyContext=f,b.context=e,F(e),k;}}function Lb(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;Mb(this,b,a)}
function Nb(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.push(null))):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,d.errorDigest=b.onError(void 0===c?Error("The render was aborted by the server without a reason."):c),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return Nb(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,
0===b.allPendingTasks&&(a=b.onAllReady,a()))}function X(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&X(a,c)}else a.completedSegments.push(b)}
function Mb(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error("There can only be one root segment. This is a bug in React.");a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=S,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&X(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(Lb,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&
1===c.status&&(X(b,c),1===b.completedSegments.length&&b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}
function Eb(a){if(2!==a.status){var b=D,c=Ab.current;Ab.current=zb;var d=R;R=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,k=g.blockedSegment;if(0===k.status){F(g.context);try{W(h,g,g.node),h.responseState.generateStaticMarkup||k.lastPushedText&&k.textEmbedded&&k.chunks.push("\x3c!-- --\x3e"),g.abortSet.delete(g),k.status=1,Mb(h,g.blockedBoundary,k)}catch(y){if(tb(),"object"===typeof y&&null!==y&&"function"===typeof y.then){var m=g.ping;y.then(m,m)}else{g.abortSet.delete(g);
k.status=4;var l=g.blockedBoundary,p=y,B=U(h,p);null===l?V(h,p):(l.pendingTasks--,l.forceClientRender||(l.forceClientRender=!0,l.errorDigest=B,l.parentFlushed&&h.clientRenderedBoundaries.push(l)));h.allPendingTasks--;if(0===h.allPendingTasks){var C=h.onAllReady;C()}}}finally{}}}f.splice(0,e);null!==a.destination&&Ob(a,a.destination)}catch(y){U(a,y),V(a,y)}finally{R=d,Ab.current=c,c===zb&&F(b)}}}
function Y(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;b.push('<template id="');b.push(a.placeholderPrefix);a=d.toString(16);b.push(a);return b.push('"></template>');case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)b.push(d[e]);f=Z(a,b,f)}for(;e<d.length-1;e++)b.push(d[e]);e<d.length&&(f=b.push(d[e]));return f;default:throw Error("Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.");
}}
function Z(a,b,c){var d=c.boundary;if(null===d)return Y(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)return a.responseState.generateStaticMarkup||(d=d.errorDigest,b.push("\x3c!--$!--\x3e"),b.push("<template"),d&&(b.push(' data-dgst="'),d=u(d),b.push(d),b.push('"')),b.push("></template>")),Y(a,b,c),a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e"),a;if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;var e=
f.nextSuspenseID++;f=f.boundaryPrefix+e.toString(16);d=d.id=f;Aa(b,a.responseState,d);Y(a,b,c);return b.push("\x3c!--/$--\x3e")}if(d.byteSize>a.progressiveChunkSize)return d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),Aa(b,a.responseState,d.id),Y(a,b,c),b.push("\x3c!--/$--\x3e");a.responseState.generateStaticMarkup||b.push("\x3c!--$--\x3e");c=d.completedSegments;if(1!==c.length)throw Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");
Z(a,b,c[0]);a=a.responseState.generateStaticMarkup?!0:b.push("\x3c!--/$--\x3e");return a}function Pb(a,b,c){Ba(b,a.responseState,c.formatContext,c.id);Z(a,b,c);return Ca(b,c.formatContext)}
function Qb(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)Rb(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;b.push(a.startInlineScript);a.sentCompleteBoundaryFunction?b.push('$RC("'):(a.sentCompleteBoundaryFunction=!0,b.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'));if(null===
d)throw Error("An ID must have been assigned before we can complete the boundary.");c=c.toString(16);b.push(d);b.push('","');b.push(a.segmentPrefix);b.push(c);return b.push('")\x3c/script>')}
function Rb(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error("A root segment ID must have been assigned by now. This is a bug in React.");return Pb(a,b,d)}Pb(a,b,d);a=a.responseState;b.push(a.startInlineScript);a.sentCompleteSegmentFunction?b.push('$RS("'):(a.sentCompleteSegmentFunction=!0,b.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'));
b.push(a.segmentPrefix);f=f.toString(16);b.push(f);b.push('","');b.push(a.placeholderPrefix);b.push(f);return b.push('")\x3c/script>')}
function Ob(a,b){try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){Z(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)b.push(d[c]);c<d.length&&b.push(d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var h=a.responseState,k=g.id,m=g.errorDigest,l=g.errorMessage,p=g.errorComponentStack;d.push(h.startInlineScript);h.sentClientRenderFunction?d.push('$RX("'):(h.sentClientRenderFunction=!0,d.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'));
if(null===k)throw Error("An ID must have been assigned before we can complete the boundary.");d.push(k);d.push('"');if(m||l||p){d.push(",");var B=Ea(m||"");d.push(B)}if(l||p){d.push(",");var C=Ea(l||"");d.push(C)}if(p){d.push(",");var y=Ea(p);d.push(y)}if(!d.push(")\x3c/script>")){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e);var aa=a.completedBoundaries;for(e=0;e<aa.length;e++)if(!Qb(a,b,aa[e])){a.destination=null;e++;aa.splice(0,e);return}aa.splice(0,e);var ba=a.partialBoundaries;for(e=
0;e<ba.length;e++){var pb=ba[e];a:{f=a;g=b;var ca=pb.completedSegments;for(h=0;h<ca.length;h++)if(!Rb(f,g,pb,ca[h])){h++;ca.splice(0,h);var qb=!1;break a}ca.splice(0,h);qb=!0}if(!qb){a.destination=null;e++;ba.splice(0,e);return}}ba.splice(0,e);var da=a.completedBoundaries;for(e=0;e<da.length;e++)if(!Qb(a,b,da[e])){a.destination=null;e++;da.splice(0,e);return}da.splice(0,e)}finally{0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&
b.push(null)}}function Sb(a,b){if(1===a.status)a.status=2,b.destroy(a.fatalError);else if(2!==a.status&&null===a.destination){a.destination=b;try{Ob(a,b)}catch(c){U(a,c),V(a,c)}}}function Tb(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return Nb(c,a,b)});c.clear();null!==a.destination&&Ob(a,a.destination)}catch(d){U(a,d),V(a,d)}}function Ub(){}
function Vb(a,b,c,d){var f=!1,e=null,g="",h=!1;a=Cb(a,Fa(c,b?b.identifierPrefix:void 0),Ga(),Infinity,Ub,void 0,function(){h=!0},void 0,void 0);Eb(a);Tb(a,d);Sb(a,{push:function(a){null!==a&&(g+=a);return!0},destroy:function(a){f=!0;e=a}});if(f)throw e;if(!h)throw Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.");return g}
function Wb(a,b){a.prototype=Object.create(b.prototype);a.prototype.constructor=a;a.__proto__=b}var Xb=function(a){function b(){var b=a.call(this,{})||this;b.request=null;b.startedFlowing=!1;return b}Wb(b,a);var c=b.prototype;c._destroy=function(a,b){Tb(this.request);b(a)};c._read=function(){this.startedFlowing&&Sb(this.request,this)};return b}(fa.Readable);function Yb(){}
function Zb(a,b){var c=new Xb,d=Cb(a,Fa(!1,b?b.identifierPrefix:void 0),Ga(),Infinity,Yb,function(){c.startedFlowing=!0;Sb(d,c)},void 0,void 0);c.request=d;Eb(d);return c}exports.renderToNodeStream=function(a,b){return Zb(a,b)};exports.renderToStaticMarkup=function(a,b){return Vb(a,b,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server')};
exports.renderToStaticNodeStream=function(a,b){return Zb(a,b)};exports.renderToString=function(a,b){return Vb(a,b,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server')};
exports.version="18.3.1";
/**
 * @license React
 * react-dom-server.browser.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');

var ReactVersion = '18.3.1';

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

function scheduleWork(callback) {
  callback();
}
var VIEW_SIZE = 512;
var currentView = null;
var writtenBytes = 0;
function beginWriting(destination) {
  currentView = new Uint8Array(VIEW_SIZE);
  writtenBytes = 0;
}
function writeChunk(destination, chunk) {
  if (chunk.length === 0) {
    return;
  }

  if (chunk.length > VIEW_SIZE) {
    // this chunk may overflow a single view which implies it was not
    // one that is cached by the streaming renderer. We will enqueu
    // it directly and expect it is not re-used
    if (writtenBytes > 0) {
      destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
      currentView = new Uint8Array(VIEW_SIZE);
      writtenBytes = 0;
    }

    destination.enqueue(chunk);
    return;
  }

  var bytesToWrite = chunk;
  var allowableBytes = currentView.length - writtenBytes;

  if (allowableBytes < bytesToWrite.length) {
    // this chunk would overflow the current view. We enqueue a full view
    // and start a new view with the remaining chunk
    if (allowableBytes === 0) {
      // the current view is already full, send it
      destination.enqueue(currentView);
    } else {
      // fill up the current view and apply the remaining chunk bytes
      // to a new view.
      currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view

      destination.enqueue(currentView);
      bytesToWrite = bytesToWrite.subarray(allowableBytes);
    }

    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = 0;
  }

  currentView.set(bytesToWrite, writtenBytes);
  writtenBytes += bytesToWrite.length;
}
function writeChunkAndReturn(destination, chunk) {
  writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more

  return true;
}
function completeWriting(destination) {
  if (currentView && writtenBytes > 0) {
    destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
    currentView = null;
    writtenBytes = 0;
  }
}
function close(destination) {
  destination.close();
}
var textEncoder = new TextEncoder();
function stringToChunk(content) {
  return textEncoder.encode(content);
}
function stringToPrecomputedChunk(content) {
  return textEncoder.encode(content);
}
function closeWithError(destination, error) {
  if (typeof destination.error === 'function') {
    // $FlowFixMe: This is an Error object or the destination accepts other types.
    destination.error(error);
  } else {
    // Earlier implementations doesn't support this method. In that environment you're
    // supposed to throw from a promise returned but we don't return a promise in our
    // approach. We could fork this implementation but this is environment is an edge
    // case to begin with. It's even less common to run this in an older environment.
    // Even then, this is not where errors are supposed to happen and they get reported
    // to a global callback in addition to this anyway. So it's fine just to close this.
    destination.close();
  }
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}

function checkAttributeStringCoercion(value, attributeName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkCSSPropertyStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkHtmlStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.

var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.

var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.

var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.

var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.

var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.

var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */

var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }

  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }

  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }

  illegalAttributeNameCache[attributeName] = true;

  {
    error('Invalid attribute name: `%s`', attributeName);
  }

  return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }

  switch (typeof value) {
    case 'function': // $FlowIssue symbol is perfectly valid here

    case 'symbol':
      // eslint-disable-line
      return true;

    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }

        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }

    default:
      return false;
  }
}
function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
  this.sanitizeURL = sanitizeURL;
  this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.


var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

reservedProps.forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.

[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).

['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.

['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML boolean attributes.

['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.

['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.

['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be positive numbers.

['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be numbers.

['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
});
var CAMELIZE = /[\-\:]([a-z])/g;

var capitalize = function (token) {
  return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.


['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // String SVG attributes with the xlink namespace.

['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  false);
}); // String SVG attributes with the xml namespace.

['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.

['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.

var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  true, // sanitizeURL
  true);
});

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  aspectRatio: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */

function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */


var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.

Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

var hasReadOnlyValue = {
  button: true,
  checkbox: true,
  image: true,
  hidden: true,
  radio: true,
  reset: true,
  submit: true
};
function checkControlledValueProps(tagName, props) {
  {
    if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
      error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }

    if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
      error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  }
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }

  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this list too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;

    default:
      return true;
  }
}

var ariaProperties = {
  'aria-current': 0,
  // state
  'aria-description': 0,
  'aria-details': 0,
  'aria-disabled': 0,
  // state
  'aria-hidden': 0,
  // state
  'aria-invalid': 0,
  // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

function validateProperty(tagName, name) {
  {
    if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
      return true;
    }

    if (rARIACamel.test(name)) {
      var ariaName = 'aria-' + name.slice(4).toLowerCase();
      var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (correctName == null) {
        error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

        warnedProperties[name] = true;
        return true;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== correctName) {
        error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

        warnedProperties[name] = true;
        return true;
      }
    }

    if (rARIA.test(name)) {
      var lowerCasedName = name.toLowerCase();
      var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (standardName == null) {
        warnedProperties[name] = true;
        return false;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== standardName) {
        error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties[name] = true;
        return true;
      }
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  {
    var invalidProps = [];

    for (var key in props) {
      var isValid = validateProperty(type, key);

      if (!isValid) {
        invalidProps.push(key);
      }
    }

    var unknownPropString = invalidProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (invalidProps.length === 1) {
      error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    } else if (invalidProps.length > 1) {
      error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    }
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;
function validateProperties$1(type, props) {
  {
    if (type !== 'input' && type !== 'textarea' && type !== 'select') {
      return;
    }

    if (props != null && props.value === null && !didWarnValueNull) {
      didWarnValueNull = true;

      if (type === 'select' && props.multiple) {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
      } else {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
      }
    }
  }
}

// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  disablepictureinpicture: 'disablePictureInPicture',
  disableremoteplayback: 'disableRemotePlayback',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  enterkeyhint: 'enterKeyHint',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  imagesizes: 'imageSizes',
  imagesrcset: 'imageSrcSet',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',
  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, eventRegistry) {
    if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();

    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

      warnedProperties$1[name] = true;
      return true;
    } // We can't rely on the event system being injected on the server.


    if (eventRegistry != null) {
      var registrationNameDependencies = eventRegistry.registrationNameDependencies,
          possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

      if (registrationNameDependencies.hasOwnProperty(name)) {
        return true;
      }

      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

      if (registrationName != null) {
        error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (EVENT_NAME_REGEX.test(name)) {
        error('Unknown event handler property `%s`. It will be ignored.', name);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Let the ARIA attribute hook validate ARIA attributes


    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];

      if (standardName !== name) {
        error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
      } else {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Now that we've validated casing, do not validate
    // data types for reserved props


    if (isReserved) {
      return true;
    } // Warn when a known attribute is a bad type


    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    } // Warn when passing the strings 'false' or 'true' into a boolean prop


    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
      error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

      warnedProperties$1[name] = true;
      return true;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, eventRegistry) {
  {
    var unknownProps = [];

    for (var key in props) {
      var isValid = validateProperty$1(type, key, props[key], eventRegistry);

      if (!isValid) {
        unknownProps.push(key);
      }
    }

    var unknownPropString = unknownProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (unknownProps.length === 1) {
      error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    } else if (unknownProps.length > 1) {
      error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    }
  }
};

function validateProperties$2(type, props, eventRegistry) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnUnknownProperties(type, props, eventRegistry);
}

var warnValidStyle = function () {};

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

  var badStyleValueWithSemicolonPattern = /;\s*$/;
  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var camelize = function (string) {
    return string.replace(hyphenPattern, function (_, character) {
      return character.toUpperCase();
    });
  };

  var warnHyphenatedStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
    // is converted to lowercase `ms`.
    camelize(name.replace(msPattern, 'ms-')));
  };

  var warnBadVendoredStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
  };

  var warnStyleValueWithSemicolon = function (name, value) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;

    error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
  };

  var warnStyleValueIsNaN = function (name, value) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;

    error('`NaN` is an invalid value for the `%s` css style property.', name);
  };

  var warnStyleValueIsInfinity = function (name, value) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;

    error('`Infinity` is an invalid value for the `%s` css style property.', name);
  };

  warnValidStyle = function (name, value) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

// code copied and modified from escape-html
var matchHtmlRegExp = /["'&<>]/;
/**
 * Escapes special characters and HTML entities in a given html string.
 *
 * @param  {string} string HTML string to escape for later insertion
 * @return {string}
 * @public
 */

function escapeHtml(string) {
  {
    checkHtmlStringCoercion(string);
  }

  var str = '' + string;
  var match = matchHtmlRegExp.exec(str);

  if (!match) {
    return str;
  }

  var escape;
  var html = '';
  var index;
  var lastIndex = 0;

  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        // "
        escape = '&quot;';
        break;

      case 38:
        // &
        escape = '&amp;';
        break;

      case 39:
        // '
        escape = '&#x27;'; // modified from escape-html; used to be '&#39'

        break;

      case 60:
        // <
        escape = '&lt;';
        break;

      case 62:
        // >
        escape = '&gt;';
        break;

      default:
        continue;
    }

    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }

    lastIndex = index + 1;
    html += escape;
  }

  return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
} // end code copied and modified from escape-html

/**
 * Escapes text to prevent scripting attacks.
 *
 * @param {*} text Text value to escape.
 * @return {string} An escaped string.
 */


function escapeTextForBrowser(text) {
  if (typeof text === 'boolean' || typeof text === 'number') {
    // this shortcircuit helps perf for types that we know will never have
    // special characters, especially given that this function is used often
    // for numeric dom ids.
    return '' + text;
  }

  return escapeHtml(text);
}

var uppercasePattern = /([A-Z])/g;
var msPattern$1 = /^ms-/;
/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */

function hyphenateStyleName(name) {
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
}

// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space

/* eslint-disable max-len */

var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;

function sanitizeURL(url) {
  {
    if (!didWarn && isJavaScriptProtocol.test(url)) {
      didWarn = true;

      error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var startInlineScript = stringToPrecomputedChunk('<script>');
var endInlineScript = stringToPrecomputedChunk('</script>');
var startScriptSrc = stringToPrecomputedChunk('<script src="');
var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
/**
 * This escaping function is designed to work with bootstrapScriptContent only.
 * because we know we are escaping the entire script. We can avoid for instance
 * escaping html comment string sequences that are valid javascript as well because
 * if there are no sebsequent <script sequences the html parser will never enter
 * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
 *
 * While untrusted script content should be made safe before using this api it will
 * ensure that the script cannot be early terminated or never terminated state
 */

function escapeBootstrapScriptContent(scriptText) {
  {
    checkHtmlStringCoercion(scriptText);
  }

  return ('' + scriptText).replace(scriptRegex, scriptReplacer);
}

var scriptRegex = /(<\/|<)(s)(cript)/gi;

var scriptReplacer = function (match, prefix, s, suffix) {
  return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
}; // Allows us to keep track of what we've already written so we can refer back to it.


function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
  var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
  var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
  var bootstrapChunks = [];

  if (bootstrapScriptContent !== undefined) {
    bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
  }

  if (bootstrapScripts !== undefined) {
    for (var i = 0; i < bootstrapScripts.length; i++) {
      bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
    }
  }

  if (bootstrapModules !== undefined) {
    for (var _i = 0; _i < bootstrapModules.length; _i++) {
      bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
    }
  }

  return {
    bootstrapChunks: bootstrapChunks,
    startInlineScript: inlineScriptWithNonce,
    placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
    segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
    boundaryPrefix: idPrefix + 'B:',
    idPrefix: idPrefix,
    nextSuspenseID: 0,
    sentCompleteSegmentFunction: false,
    sentCompleteBoundaryFunction: false,
    sentClientRenderFunction: false
  };
} // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
// modes. We only include the variants as they matter for the sake of our purposes.
// We don't actually provide the namespace therefore we use constants instead of the string.

var ROOT_HTML_MODE = 0; // Used for the root most element tag.

var HTML_MODE = 1;
var SVG_MODE = 2;
var MATHML_MODE = 3;
var HTML_TABLE_MODE = 4;
var HTML_TABLE_BODY_MODE = 5;
var HTML_TABLE_ROW_MODE = 6;
var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
// still makes sense

function createFormatContext(insertionMode, selectedValue) {
  return {
    insertionMode: insertionMode,
    selectedValue: selectedValue
  };
}

function createRootFormatContext(namespaceURI) {
  var insertionMode = namespaceURI === 'http://www.w3.org/2000/svg' ? SVG_MODE : namespaceURI === 'http://www.w3.org/1998/Math/MathML' ? MATHML_MODE : ROOT_HTML_MODE;
  return createFormatContext(insertionMode, null);
}
function getChildFormatContext(parentContext, type, props) {
  switch (type) {
    case 'select':
      return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

    case 'svg':
      return createFormatContext(SVG_MODE, null);

    case 'math':
      return createFormatContext(MATHML_MODE, null);

    case 'foreignObject':
      return createFormatContext(HTML_MODE, null);
    // Table parents are special in that their children can only be created at all if they're
    // wrapped in a table parent. So we need to encode that we're entering this mode.

    case 'table':
      return createFormatContext(HTML_TABLE_MODE, null);

    case 'thead':
    case 'tbody':
    case 'tfoot':
      return createFormatContext(HTML_TABLE_BODY_MODE, null);

    case 'colgroup':
      return createFormatContext(HTML_COLGROUP_MODE, null);

    case 'tr':
      return createFormatContext(HTML_TABLE_ROW_MODE, null);
  }

  if (parentContext.insertionMode >= HTML_TABLE_MODE) {
    // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
    // entered plain HTML again.
    return createFormatContext(HTML_MODE, null);
  }

  if (parentContext.insertionMode === ROOT_HTML_MODE) {
    // We've emitted the root and is now in plain HTML mode.
    return createFormatContext(HTML_MODE, null);
  }

  return parentContext;
}
var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
function assignSuspenseBoundaryID(responseState) {
  var generatedID = responseState.nextSuspenseID++;
  return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
}
function makeId(responseState, treeId, localId) {
  var idPrefix = responseState.idPrefix;
  var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
  // that represents the position of this useId hook among all the useId
  // hooks for this fiber.

  if (localId > 0) {
    id += 'H' + localId.toString(32);
  }

  return id + ':';
}

function encodeHTMLTextNode(text) {
  return escapeTextForBrowser(text);
}

var textSeparator = stringToPrecomputedChunk('<!-- -->');
function pushTextInstance(target, text, responseState, textEmbedded) {
  if (text === '') {
    // Empty text doesn't have a DOM node representation and the hydration is aware of this.
    return textEmbedded;
  }

  if (textEmbedded) {
    target.push(textSeparator);
  }

  target.push(stringToChunk(encodeHTMLTextNode(text)));
  return true;
} // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
// emit a text separator when we don't know for sure it is safe to omit

function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
  if (lastPushedText && textEmbedded) {
    target.push(textSeparator);
  }
}
var styleNameCache = new Map();

function processStyleName(styleName) {
  var chunk = styleNameCache.get(styleName);

  if (chunk !== undefined) {
    return chunk;
  }

  var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
  styleNameCache.set(styleName, result);
  return result;
}

var styleAttributeStart = stringToPrecomputedChunk(' style="');
var styleAssign = stringToPrecomputedChunk(':');
var styleSeparator = stringToPrecomputedChunk(';');

function pushStyle(target, responseState, style) {
  if (typeof style !== 'object') {
    throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
  }

  var isFirst = true;

  for (var styleName in style) {
    if (!hasOwnProperty.call(style, styleName)) {
      continue;
    } // If you provide unsafe user data here they can inject arbitrary CSS
    // which may be problematic (I couldn't repro this):
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
    // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
    // This is not an XSS hole but instead a potential CSS injection issue
    // which has lead to a greater discussion about how we're going to
    // trust URLs moving forward. See #2115901


    var styleValue = style[styleName];

    if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
      // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
      continue;
    }

    var nameChunk = void 0;
    var valueChunk = void 0;
    var isCustomProperty = styleName.indexOf('--') === 0;

    if (isCustomProperty) {
      nameChunk = stringToChunk(escapeTextForBrowser(styleName));

      {
        checkCSSPropertyStringCoercion(styleValue, styleName);
      }

      valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
    } else {
      {
        warnValidStyle$1(styleName, styleValue);
      }

      nameChunk = processStyleName(styleName);

      if (typeof styleValue === 'number') {
        if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
          valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
        } else {
          valueChunk = stringToChunk('' + styleValue);
        }
      } else {
        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      }
    }

    if (isFirst) {
      isFirst = false; // If it's first, we don't need any separators prefixed.

      target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
    } else {
      target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
    }
  }

  if (!isFirst) {
    target.push(attributeEnd);
  }
}

var attributeSeparator = stringToPrecomputedChunk(' ');
var attributeAssign = stringToPrecomputedChunk('="');
var attributeEnd = stringToPrecomputedChunk('"');
var attributeEmptyString = stringToPrecomputedChunk('=""');

function pushAttribute(target, responseState, name, value) {
  switch (name) {
    case 'style':
      {
        pushStyle(target, responseState, value);
        return;
      }

    case 'defaultValue':
    case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

    case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

    case 'suppressContentEditableWarning':
    case 'suppressHydrationWarning':
      // Ignored. These are built-in to React on the client.
      return;
  }

  if ( // shouldIgnoreAttribute
  // We have already filtered out null/undefined and reserved words.
  name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return;
  }

  var propertyInfo = getPropertyInfo(name);

  if (propertyInfo !== null) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          if (!propertyInfo.acceptsBooleans) {
            return;
          }
        }
    }

    var attributeName = propertyInfo.attributeName;
    var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

    switch (propertyInfo.type) {
      case BOOLEAN:
        if (value) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        }

        return;

      case OVERLOADED_BOOLEAN:
        if (value === true) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        } else if (value === false) ; else {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        return;

      case NUMERIC:
        if (!isNaN(value)) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      case POSITIVE_NUMERIC:
        if (!isNaN(value) && value >= 1) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      default:
        if (propertyInfo.sanitizeURL) {
          {
            checkAttributeStringCoercion(value, attributeName);
          }

          value = '' + value;
          sanitizeURL(value);
        }

        target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  } else if (isAttributeNameSafe(name)) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          var prefix = name.toLowerCase().slice(0, 5);

          if (prefix !== 'data-' && prefix !== 'aria-') {
            return;
          }
        }
    }

    target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
  }
}

var endOfStartTag = stringToPrecomputedChunk('>');
var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

function pushInnerHTML(target, innerHTML, children) {
  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      {
        checkHtmlStringCoercion(html);
      }

      target.push(stringToChunk('' + html));
    }
  }
} // TODO: Move these to ResponseState so that we warn for every request.
// It would help debugging in stateful servers (e.g. service worker).


var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnInvalidOptionInnerHTML = false;
var didWarnSelectedSetOnOption = false;

function checkSelectProp(props, propName) {
  {
    var value = props[propName];

    if (value != null) {
      var array = isArray(value);

      if (props.multiple && !array) {
        error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
      } else if (!props.multiple && array) {
        error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
      }
    }
  }
}

function pushStartSelect(target, props, responseState) {
  {
    checkControlledValueProps('select', props);
    checkSelectProp(props, 'value');
    checkSelectProp(props, 'defaultValue');

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
      error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultSelectValue = true;
    }
  }

  target.push(startChunkForTag('select'));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          // TODO: This doesn't really make sense for select since it can't use the controlled
          // value in the innerHTML.
          innerHTML = propValue;
          break;

        case 'defaultValue':
        case 'value':
          // These are set on the Context instead and applied to the nested options.
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function flattenOptionChildren(children) {
  var content = ''; // Flatten children and warn if they aren't strings or numbers;
  // invalid types are ignored.

  React.Children.forEach(children, function (child) {
    if (child == null) {
      return;
    }

    content += child;

    {
      if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
        didWarnInvalidOptionChildren = true;

        error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
      }
    }
  });
  return content;
}

var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

function pushStartOption(target, props, responseState, formatContext) {
  var selectedValue = formatContext.selectedValue;
  target.push(startChunkForTag('option'));
  var children = null;
  var value = null;
  var selected = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'selected':
          // ignore
          selected = propValue;

          {
            // TODO: Remove support for `selected` in <option>.
            if (!didWarnSelectedSetOnOption) {
              error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

              didWarnSelectedSetOnOption = true;
            }
          }

          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;
        // eslint-disable-next-line-no-fallthrough

        case 'value':
          value = propValue;
        // We intentionally fallthrough to also set the attribute on the node.
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (selectedValue != null) {
    var stringValue;

    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      stringValue = '' + value;
    } else {
      {
        if (innerHTML !== null) {
          if (!didWarnInvalidOptionInnerHTML) {
            didWarnInvalidOptionInnerHTML = true;

            error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
          }
        }
      }

      stringValue = flattenOptionChildren(children);
    }

    if (isArray(selectedValue)) {
      // multiple
      for (var i = 0; i < selectedValue.length; i++) {
        {
          checkAttributeStringCoercion(selectedValue[i], 'value');
        }

        var v = '' + selectedValue[i];

        if (v === stringValue) {
          target.push(selectedMarkerAttribute);
          break;
        }
      }
    } else {
      {
        checkAttributeStringCoercion(selectedValue, 'select.value');
      }

      if ('' + selectedValue === stringValue) {
        target.push(selectedMarkerAttribute);
      }
    }
  } else if (selected) {
    target.push(selectedMarkerAttribute);
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function pushInput(target, props, responseState) {
  {
    checkControlledValueProps('input', props);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
      error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultChecked = true;
    }

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
      error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultInputValue = true;
    }
  }

  target.push(startChunkForTag('input'));
  var value = null;
  var defaultValue = null;
  var checked = null;
  var defaultChecked = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        case 'defaultChecked':
          defaultChecked = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'checked':
          checked = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (checked !== null) {
    pushAttribute(target, responseState, 'checked', checked);
  } else if (defaultChecked !== null) {
    pushAttribute(target, responseState, 'checked', defaultChecked);
  }

  if (value !== null) {
    pushAttribute(target, responseState, 'value', value);
  } else if (defaultValue !== null) {
    pushAttribute(target, responseState, 'value', defaultValue);
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartTextArea(target, props, responseState) {
  {
    checkControlledValueProps('textarea', props);

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
      error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultTextareaValue = true;
    }
  }

  target.push(startChunkForTag('textarea'));
  var value = null;
  var defaultValue = null;
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (value === null && defaultValue !== null) {
    value = defaultValue;
  }

  target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

  if (children != null) {
    {
      error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
    }

    if (value != null) {
      throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
    }

    if (isArray(children)) {
      if (children.length > 1) {
        throw new Error('<textarea> can only have at most one child.');
      } // TODO: remove the coercion and the DEV check below because it will
      // always be overwritten by the coercion several lines below it. #22309


      {
        checkHtmlStringCoercion(children[0]);
      }

      value = '' + children[0];
    }

    {
      checkHtmlStringCoercion(children);
    }

    value = '' + children;
  }

  if (typeof value === 'string' && value[0] === '\n') {
    // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    target.push(leadingNewline);
  } // ToString and push directly instead of recurse over children.
  // We don't really support complex children in the value anyway.
  // This also currently avoids a trailing comment node which breaks textarea.


  if (value !== null) {
    {
      checkAttributeStringCoercion(value, 'value');
    }

    target.push(stringToChunk(encodeHTMLTextNode('' + value)));
  }

  return null;
}

function pushSelfClosing(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartMenuItem(target, props, responseState) {
  target.push(startChunkForTag('menuitem'));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  return null;
}

function pushStartTitle(target, props, responseState) {
  target.push(startChunkForTag('title'));
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);

  {
    var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

    if (Array.isArray(children) && children.length > 1) {
      error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && child.$$typeof != null) {
      error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
      error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    }
  }

  return children;
}

function pushStartGenericElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);

  if (typeof children === 'string') {
    // Special case children as a string to avoid the unnecessary comment.
    // TODO: Remove this special case after the general optimization is in place.
    target.push(stringToChunk(encodeHTMLTextNode(children)));
    return null;
  }

  return children;
}

function pushStartCustomElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        case 'style':
          pushStyle(target, responseState, propValue);
          break;

        case 'suppressContentEditableWarning':
        case 'suppressHydrationWarning':
          // Ignored. These are built-in to React on the client.
          break;

        default:
          if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
            target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
          }

          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

var leadingNewline = stringToPrecomputedChunk('\n');

function pushStartPreformattedElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
  // Prefer to break application/xml over text/html (for now) by adding
  // a newline specifically to get eaten by the parser. (Alternately for
  // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
  // \r is normalized out by HTMLTextAreaElement#value.)
  // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
  // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
  // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
  // See: Parsing of "textarea" "listing" and "pre" elements
  //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
  // TODO: This doesn't deal with the case where the child is an array
  // or component that returns a string.

  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
        target.push(leadingNewline, stringToChunk(html));
      } else {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  }

  if (typeof children === 'string' && children[0] === '\n') {
    target.push(leadingNewline);
  }

  return children;
} // We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name


var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

var validatedTagCache = new Map();

function startChunkForTag(tag) {
  var tagStartChunk = validatedTagCache.get(tag);

  if (tagStartChunk === undefined) {
    if (!VALID_TAG_REGEX.test(tag)) {
      throw new Error("Invalid tag: " + tag);
    }

    tagStartChunk = stringToPrecomputedChunk('<' + tag);
    validatedTagCache.set(tag, tagStartChunk);
  }

  return tagStartChunk;
}

var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
function pushStartInstance(target, type, props, responseState, formatContext) {
  {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, null);

    if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
      error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
    }

    if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
      if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
        error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
      }
    }
  }

  switch (type) {
    // Special tags
    case 'select':
      return pushStartSelect(target, props, responseState);

    case 'option':
      return pushStartOption(target, props, responseState, formatContext);

    case 'textarea':
      return pushStartTextArea(target, props, responseState);

    case 'input':
      return pushInput(target, props, responseState);

    case 'menuitem':
      return pushStartMenuItem(target, props, responseState);

    case 'title':
      return pushStartTitle(target, props, responseState);
    // Newline eating tags

    case 'listing':
    case 'pre':
      {
        return pushStartPreformattedElement(target, props, type, responseState);
      }
    // Omitted close tags

    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        return pushSelfClosing(target, props, type, responseState);
      }
    // These are reserved SVG and MathML elements, that are never custom elements.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      {
        return pushStartGenericElement(target, props, type, responseState);
      }

    case 'html':
      {
        if (formatContext.insertionMode === ROOT_HTML_MODE) {
          // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
          // then we also emit the DOCTYPE as part of the root content as a convenience for
          // rendering the whole document.
          target.push(DOCTYPE);
        }

        return pushStartGenericElement(target, props, type, responseState);
      }

    default:
      {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
          // Generic element
          return pushStartGenericElement(target, props, type, responseState);
        } else {
          // Custom element
          return pushStartCustomElement(target, props, type, responseState);
        }
      }
  }
}
var endTag1 = stringToPrecomputedChunk('</');
var endTag2 = stringToPrecomputedChunk('>');
function pushEndInstance(target, type, props) {
  switch (type) {
    // Omitted close tags
    // TODO: Instead of repeating this switch we could try to pass a flag from above.
    // That would require returning a tuple. Which might be ok if it gets inlined.
    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'input':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        // No close tag needed.
        break;
      }

    default:
      {
        target.push(endTag1, stringToChunk(type), endTag2);
      }
  }
}
function writeCompletedRoot(destination, responseState) {
  var bootstrapChunks = responseState.bootstrapChunks;
  var i = 0;

  for (; i < bootstrapChunks.length - 1; i++) {
    writeChunk(destination, bootstrapChunks[i]);
  }

  if (i < bootstrapChunks.length) {
    return writeChunkAndReturn(destination, bootstrapChunks[i]);
  }

  return true;
} // Structural Nodes
// A placeholder is a node inside a hidden partial tree that can be filled in later, but before
// display. It's never visible to users. We use the template tag because it can be used in every
// type of parent. <script> tags also work in every other tag except <colgroup>.

var placeholder1 = stringToPrecomputedChunk('<template id="');
var placeholder2 = stringToPrecomputedChunk('"></template>');
function writePlaceholder(destination, responseState, id) {
  writeChunk(destination, placeholder1);
  writeChunk(destination, responseState.placeholderPrefix);
  var formattedID = stringToChunk(id.toString(16));
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, placeholder2);
} // Suspense boundaries are encoded as comments.

var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
function writeStartCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
}
function writeStartPendingSuspenseBoundary(destination, responseState, id) {
  writeChunk(destination, startPendingSuspenseBoundary1);

  if (id === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, id);
  return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
}
function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
  var result;
  result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
  writeChunk(destination, clientRenderedSuspenseBoundaryError1);

  if (errorDigest) {
    writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
    writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
    writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
  }

  {
    if (errorMesssage) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }
  }

  result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
  return result;
}
function writeEndCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndPendingSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
var startSegmentHTML2 = stringToPrecomputedChunk('">');
var endSegmentHTML = stringToPrecomputedChunk('</div>');
var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
var startSegmentSVG2 = stringToPrecomputedChunk('">');
var endSegmentSVG = stringToPrecomputedChunk('</svg>');
var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
var startSegmentMathML2 = stringToPrecomputedChunk('">');
var endSegmentMathML = stringToPrecomputedChunk('</math>');
var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
var startSegmentTable2 = stringToPrecomputedChunk('">');
var endSegmentTable = stringToPrecomputedChunk('</table>');
var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
var startSegmentTableBody2 = stringToPrecomputedChunk('">');
var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
var startSegmentTableRow2 = stringToPrecomputedChunk('">');
var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
var startSegmentColGroup2 = stringToPrecomputedChunk('">');
var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
function writeStartSegment(destination, responseState, formatContext, id) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        writeChunk(destination, startSegmentHTML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentHTML2);
      }

    case SVG_MODE:
      {
        writeChunk(destination, startSegmentSVG);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentSVG2);
      }

    case MATHML_MODE:
      {
        writeChunk(destination, startSegmentMathML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentMathML2);
      }

    case HTML_TABLE_MODE:
      {
        writeChunk(destination, startSegmentTable);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTable2);
      }
    // TODO: For the rest of these, there will be extra wrapper nodes that never
    // get deleted from the document. We need to delete the table too as part
    // of the injected scripts. They are invisible though so it's not too terrible
    // and it's kind of an edge case to suspend in a table. Totally supported though.

    case HTML_TABLE_BODY_MODE:
      {
        writeChunk(destination, startSegmentTableBody);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableBody2);
      }

    case HTML_TABLE_ROW_MODE:
      {
        writeChunk(destination, startSegmentTableRow);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableRow2);
      }

    case HTML_COLGROUP_MODE:
      {
        writeChunk(destination, startSegmentColGroup);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentColGroup2);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
}
function writeEndSegment(destination, formatContext) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentHTML);
      }

    case SVG_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentSVG);
      }

    case MATHML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentMathML);
      }

    case HTML_TABLE_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTable);
      }

    case HTML_TABLE_BODY_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableBody);
      }

    case HTML_TABLE_ROW_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableRow);
      }

    case HTML_COLGROUP_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentColGroup);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
} // Instruction Set
// The following code is the source scripts that we then minify and inline below,
// with renamed function names that we hope don't collide:
// const COMMENT_NODE = 8;
// const SUSPENSE_START_DATA = '$';
// const SUSPENSE_END_DATA = '/$';
// const SUSPENSE_PENDING_START_DATA = '$?';
// const SUSPENSE_FALLBACK_START_DATA = '$!';
//
// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//   // Tag it to be client rendered.
//   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
//   // assign error metadata to first sibling
//   let dataset = suspenseIdNode.dataset;
//   if (errorDigest) dataset.dgst = errorDigest;
//   if (errorMsg) dataset.msg = errorMsg;
//   if (errorComponentStack) dataset.stck = errorComponentStack;
//   // Tell React to retry it if the parent already hydrated.
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeBoundary(suspenseBoundaryID, contentID) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   const contentNode = document.getElementById(contentID);
//   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
//   // This might also help by not causing recalcing each time we move a child from here to the target.
//   contentNode.parentNode.removeChild(contentNode);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated. That's fine there's nothing to do
//     // but we have to make sure that we already deleted the container node.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//
//   // Clear all the existing children. This is complicated because
//   // there can be embedded Suspense boundaries in the fallback.
//   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
//   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
//   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
//   const parentInstance = suspenseNode.parentNode;
//   let node = suspenseNode.nextSibling;
//   let depth = 0;
//   do {
//     if (node && node.nodeType === COMMENT_NODE) {
//       const data = node.data;
//       if (data === SUSPENSE_END_DATA) {
//         if (depth === 0) {
//           break;
//         } else {
//           depth--;
//         }
//       } else if (
//         data === SUSPENSE_START_DATA ||
//         data === SUSPENSE_PENDING_START_DATA ||
//         data === SUSPENSE_FALLBACK_START_DATA
//       ) {
//         depth++;
//       }
//     }
//
//     const nextNode = node.nextSibling;
//     parentInstance.removeChild(node);
//     node = nextNode;
//   } while (node);
//
//   const endOfBoundary = node;
//
//   // Insert all the children from the contentNode between the start and end of suspense boundary.
//   while (contentNode.firstChild) {
//     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
//   }
//   suspenseNode.data = SUSPENSE_START_DATA;
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeSegment(containerID, placeholderID) {
//   const segmentContainer = document.getElementById(containerID);
//   const placeholderNode = document.getElementById(placeholderID);
//   // We always expect both nodes to exist here because, while we might
//   // have navigated away from the main tree, we still expect the detached
//   // tree to exist.
//   segmentContainer.parentNode.removeChild(segmentContainer);
//   while (segmentContainer.firstChild) {
//     placeholderNode.parentNode.insertBefore(
//       segmentContainer.firstChild,
//       placeholderNode,
//     );
//   }
//   placeholderNode.parentNode.removeChild(placeholderNode);
// }

var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
var completeSegmentScript2 = stringToPrecomputedChunk('","');
var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteSegmentFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteSegmentFunction = true;
    writeChunk(destination, completeSegmentScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeSegmentScript1Partial);
  }

  writeChunk(destination, responseState.segmentPrefix);
  var formattedID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, formattedID);
  writeChunk(destination, completeSegmentScript2);
  writeChunk(destination, responseState.placeholderPrefix);
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, completeSegmentScript3);
}
var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
var completeBoundaryScript2 = stringToPrecomputedChunk('","');
var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteBoundaryFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteBoundaryFunction = true;
    writeChunk(destination, completeBoundaryScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeBoundaryScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  var formattedContentID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, boundaryID);
  writeChunk(destination, completeBoundaryScript2);
  writeChunk(destination, responseState.segmentPrefix);
  writeChunk(destination, formattedContentID);
  return writeChunkAndReturn(destination, completeBoundaryScript3);
}
var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
var clientRenderScript1A = stringToPrecomputedChunk('"');
var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentClientRenderFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentClientRenderFunction = true;
    writeChunk(destination, clientRenderScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, clientRenderScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, boundaryID);
  writeChunk(destination, clientRenderScript1A);

  if (errorDigest || errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
  }

  if (errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
  }

  if (errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
  }

  return writeChunkAndReturn(destination, clientRenderScript2);
}
var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

function escapeJSStringsForInstructionScripts(input) {
  var escaped = JSON.stringify(input);
  return escaped.replace(regexForJSStringsInScripts, function (match) {
    switch (match) {
      // santizing breaking out of strings and script tags
      case '<':
        return "\\u003c";

      case "\u2028":
        return "\\u2028";

      case "\u2029":
        return "\\u2029";

      default:
        {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
        }
    }
  });
}

var assign = Object.assign;

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}

function describeClassComponentFrame(ctor, source, ownerFn) {
  {
    return describeNativeComponentFrame(ctor, true);
  }
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var warnedAboutMissingGetChildContext;

{
  warnedAboutMissingGetChildContext = {};
}

var emptyContextObject = {};

{
  Object.freeze(emptyContextObject);
}

function getMaskedContext(type, unmaskedContext) {
  {
    var contextTypes = type.contextTypes;

    if (!contextTypes) {
      return emptyContextObject;
    }

    var context = {};

    for (var key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(contextTypes, context, 'context', name);
    }

    return context;
  }
}
function processChildContext(instance, type, parentContext, childContextTypes) {
  {
    // TODO (bvaughn) Replace this behavior with an invariant() in the future.
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.
    if (typeof instance.getChildContext !== 'function') {
      {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!warnedAboutMissingGetChildContext[componentName]) {
          warnedAboutMissingGetChildContext[componentName] = true;

          error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
        }
      }

      return parentContext;
    }

    var childContext = instance.getChildContext();

    for (var contextKey in childContext) {
      if (!(contextKey in childContextTypes)) {
        throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
      }
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(childContextTypes, childContext, 'child context', name);
    }

    return assign({}, parentContext, childContext);
  }
}

var rendererSigil;

{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
} // Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.


var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are currently in.

var currentActiveSnapshot = null;

function popNode(prev) {
  {
    prev.context._currentValue = prev.parentValue;
  }
}

function pushNode(next) {
  {
    next.context._currentValue = next.value;
  }
}

function popToNearestCommonAncestor(prev, next) {
  if (prev === next) ; else {
    popNode(prev);
    var parentPrev = prev.parent;
    var parentNext = next.parent;

    if (parentPrev === null) {
      if (parentNext !== null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }
    } else {
      if (parentNext === null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }

      popToNearestCommonAncestor(parentPrev, parentNext);
    } // On the way back, we push the new ones that weren't common.


    pushNode(next);
  }
}

function popAllPrevious(prev) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev !== null) {
    popAllPrevious(parentPrev);
  }
}

function pushAllNext(next) {
  var parentNext = next.parent;

  if (parentNext !== null) {
    pushAllNext(parentNext);
  }

  pushNode(next);
}

function popPreviousToCommonLevel(prev, next) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (parentPrev.depth === next.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(parentPrev, next);
  } else {
    // We must still be deeper.
    popPreviousToCommonLevel(parentPrev, next);
  }
}

function popNextToCommonLevel(prev, next) {
  var parentNext = next.parent;

  if (parentNext === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (prev.depth === parentNext.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(prev, parentNext);
  } else {
    // We must still be deeper.
    popNextToCommonLevel(prev, parentNext);
  }

  pushNode(next);
} // Perform context switching to the new snapshot.
// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
// updating all the context's current values. That way reads, always just read the current value.
// At the cost of updating contexts even if they're never read by this subtree.


function switchContext(newSnapshot) {
  // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
  // We also need to update any new contexts that are now on the stack with the deepest value.
  // The easiest way to update new contexts is to just reapply them in reverse order from the
  // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
  // for that. Therefore this algorithm is recursive.
  // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
  // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
  // 3) Then we reapply new contexts on the way back up the stack.
  var prev = currentActiveSnapshot;
  var next = newSnapshot;

  if (prev !== next) {
    if (prev === null) {
      // $FlowFixMe: This has to be non-null since it's not equal to prev.
      pushAllNext(next);
    } else if (next === null) {
      popAllPrevious(prev);
    } else if (prev.depth === next.depth) {
      popToNearestCommonAncestor(prev, next);
    } else if (prev.depth > next.depth) {
      popPreviousToCommonLevel(prev, next);
    } else {
      popNextToCommonLevel(prev, next);
    }

    currentActiveSnapshot = next;
  }
}
function pushProvider(context, nextValue) {
  var prevValue;

  {
    prevValue = context._currentValue;
    context._currentValue = nextValue;

    {
      if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer = rendererSigil;
    }
  }

  var prevNode = currentActiveSnapshot;
  var newNode = {
    parent: prevNode,
    depth: prevNode === null ? 0 : prevNode.depth + 1,
    context: context,
    parentValue: prevValue,
    value: nextValue
  };
  currentActiveSnapshot = newNode;
  return newNode;
}
function popProvider(context) {
  var prevSnapshot = currentActiveSnapshot;

  if (prevSnapshot === null) {
    throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
  }

  {
    if (prevSnapshot.context !== context) {
      error('The parent context is not the expected context. This is probably a bug in React.');
    }
  }

  {
    var value = prevSnapshot.parentValue;

    if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
      prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
    } else {
      prevSnapshot.context._currentValue = value;
    }

    {
      if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer = rendererSigil;
    }
  }

  return currentActiveSnapshot = prevSnapshot.parent;
}
function getActiveContext() {
  return currentActiveSnapshot;
}
function readContext(context) {
  var value =  context._currentValue ;
  return value;
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}
function set(key, value) {
  key._reactInternals = value;
}

var didWarnAboutNoopUpdateForComponent = {};
var didWarnAboutDeprecatedWillMount = {};
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;

{
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutDirectlyAssigningPropsToState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();
  didWarnAboutContextTypeAndContextTypes = new Set();
  didWarnAboutInvalidateContextType = new Set();
  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }

    var key = callerName + '_' + callback;

    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);

      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (type, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentNameFromType(type) || 'Component';

      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);

        error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  };
}

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
    var warningKey = componentName + '.' + callerName;

    if (didWarnAboutNoopUpdateForComponent[warningKey]) {
      return;
    }

    error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

    didWarnAboutNoopUpdateForComponent[warningKey] = true;
  }
}

var classComponentUpdater = {
  isMounted: function (inst) {
    return false;
  },
  enqueueSetState: function (inst, payload, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'setState');
    } else {
      internals.queue.push(payload);

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var internals = get(inst);
    internals.replace = true;
    internals.queue = [payload];

    {
      if (callback !== undefined && callback !== null) {
        warnOnInvalidCallback(callback, 'setState');
      }
    }
  },
  enqueueForceUpdate: function (inst, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'forceUpdate');
    } else {
      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  }
};

function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    warnOnUndefinedDerivedState(ctor, partialState);
  } // Merge the partial state and the previous state.


  var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
  return newState;
}

function constructClassInstance(ctor, props, maskedLegacyContext) {
  var context = emptyContextObject;
  var contextType = ctor.contextType;

  {
    if ('contextType' in ctor) {
      var isValid = // Allow null for conditional declaration
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
        didWarnAboutInvalidateContextType.add(ctor);
        var addendum = '';

        if (contextType === undefined) {
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
        } else if (typeof contextType !== 'object') {
          addendum = ' However, it is set to a ' + typeof contextType + '.';
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
          addendum = ' Did you accidentally pass the Context.Provider instead?';
        } else if (contextType._context !== undefined) {
          // <Context.Consumer>
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
        } else {
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
        }

        error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
      }
    }
  }

  if (typeof contextType === 'object' && contextType !== null) {
    context = readContext(contextType);
  } else {
    context = maskedLegacyContext;
  }

  var instance = new ctor(props, context);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);

        error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
      }
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.


    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;

      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }

      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentNameFromType(ctor) || 'Component';

        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

          error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
        }
      }
    }
  }

  return instance;
}

function checkClassInstance(instance, ctor, newProps) {
  {
    var name = getComponentNameFromType(ctor) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
        error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
      error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
    }

    if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
    }

    if (instance.propTypes) {
      error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
    }

    if (instance.contextType) {
      error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
    }

    {
      if (instance.contextTypes) {
        error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
      }

      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
        didWarnAboutContextTypeAndContextTypes.add(ctor);

        error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
      }
    }

    if (typeof instance.componentShouldUpdate === 'function') {
      error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
    }

    if (typeof instance.componentDidUnmount === 'function') {
      error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
    }

    if (typeof instance.componentDidReceiveProps === 'function') {
      error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
    }

    if (typeof instance.componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
    }

    if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
    }

    var hasMutatedProps = instance.props !== newProps;

    if (instance.props !== undefined && hasMutatedProps) {
      error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
    }

    if (instance.defaultProps) {
      error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

      error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
    }

    if (typeof instance.getDerivedStateFromProps === 'function') {
      error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof instance.getDerivedStateFromError === 'function') {
      error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
      error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
    }

    var _state = instance.state;

    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      error('%s.state: must be set to an object or null', name);
    }

    if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
      error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
    }
  }
}

function callComponentWillMount(type, instance) {
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    {
      if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!didWarnAboutDeprecatedWillMount[componentName]) {
          warn( // keep this warning in sync with ReactStrictModeWarning.js
          'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

          didWarnAboutDeprecatedWillMount[componentName] = true;
        }
      }
    }

    instance.componentWillMount();
  }

  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  if (oldState !== instance.state) {
    {
      error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
  if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
    var oldQueue = internalInstance.queue;
    var oldReplace = internalInstance.replace;
    internalInstance.queue = null;
    internalInstance.replace = false;

    if (oldReplace && oldQueue.length === 1) {
      inst.state = oldQueue[0];
    } else {
      var nextState = oldReplace ? oldQueue[0] : inst.state;
      var dontMutate = true;

      for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
        var partial = oldQueue[i];
        var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

        if (partialState != null) {
          if (dontMutate) {
            dontMutate = false;
            nextState = assign({}, nextState, partialState);
          } else {
            assign(nextState, partialState);
          }
        }
      }

      inst.state = nextState;
    }
  } else {
    internalInstance.queue = null;
  }
} // Invokes the mount life-cycles on a previously never rendered instance.


function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
  {
    checkClassInstance(instance, ctor, newProps);
  }

  var initialState = instance.state !== undefined ? instance.state : null;
  instance.updater = classComponentUpdater;
  instance.props = newProps;
  instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
  // The internal instance will be used to manage updates that happen during this mount.

  var internalInstance = {
    queue: [],
    replace: false
  };
  set(instance, internalInstance);
  var contextType = ctor.contextType;

  if (typeof contextType === 'object' && contextType !== null) {
    instance.context = readContext(contextType);
  } else {
    instance.context = maskedLegacyContext;
  }

  {
    if (instance.state === newProps) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);

        error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
      }
    }
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

  if (typeof getDerivedStateFromProps === 'function') {
    instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
  } // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.


  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
    // process them now.

    processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
  }
}

// Ids are base 32 strings whose binary representation corresponds to the
// position of a node in a tree.
// Every time the tree forks into multiple children, we add additional bits to
// the left of the sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5. However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
// the zeroth id at a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in the
// sequence. It's treated as a transparent indirection. For example, these two
// trees produce the same ids:
//
// <>                          <>
//   <Indirection>               <A />
//     <A />                     <B />
//   </Indirection>            </>
//   <B />
// </>
//
// However, we cannot skip any node that materializes an id. Otherwise, a parent
// id that does not fork would be indistinguishable from its child id. For
// example, this tree does not fork, but the parent and child must have
// different ids.
//
// <Parent>
//   <Child />
// </Parent>
//
// To handle this scenario, every time we materialize an id, we allocate a
// new level with a single slot. You can think of this as a fork with only one
// prong, or an array of children with length 1.
//
// It's possible for the size of the sequence to exceed 32 bits, the max
// size for bitwise operations. When this happens, we make more room by
// converting the right part of the id to a string and storing it in an overflow
// variable. We use a base 32 string representation, because 32 is the largest
// power of 2 that is supported by toString(). We want the base to be large so
// that the resulting ids are compact, and we want the base to be a power of 2
// because every log2(base) bits corresponds to a single character, i.e. every
// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
// affecting the final result.
var emptyTreeContext = {
  id: 1,
  overflow: ''
};
function getTreeId(context) {
  var overflow = context.overflow;
  var idWithLeadingBit = context.id;
  var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
  return id.toString(32) + overflow;
}
function pushTreeContext(baseContext, totalChildren, index) {
  var baseIdWithLeadingBit = baseContext.id;
  var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
  // of the id; we use it to account for leading 0s.

  var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
  var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
  var slot = index + 1;
  var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
  // consideration the leading 1 we use to mark the end of the sequence.

  if (length > 30) {
    // We overflowed the bitwise-safe range. Fall back to slower algorithm.
    // This branch assumes the length of the base id is greater than 5; it won't
    // work for smaller ids, because you need 5 bits per character.
    //
    // We encode the id in multiple steps: first the base id, then the
    // remaining digits.
    //
    // Each 5 bit sequence corresponds to a single base 32 character. So for
    // example, if the current id is 23 bits long, we can convert 20 of those
    // bits into a string of 4 characters, with 3 bits left over.
    //
    // First calculate how many bits in the base id represent a complete
    // sequence of characters.
    var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

    var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

    var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

    var restOfBaseId = baseId >> numberOfOverflowBits;
    var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
    // we made more room, this time it won't overflow.

    var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
    var restOfNewBits = slot << restOfBaseLength;
    var id = restOfNewBits | restOfBaseId;
    var overflow = newOverflow + baseOverflow;
    return {
      id: 1 << restOfLength | id,
      overflow: overflow
    };
  } else {
    // Normal path
    var newBits = slot << baseLength;

    var _id = newBits | baseId;

    var _overflow = baseOverflow;
    return {
      id: 1 << length | _id,
      overflow: _overflow
    };
  }
}

function getBitLength(number) {
  return 32 - clz32(number);
}

function getLeadingBit(id) {
  return 1 << getBitLength(id) - 1;
} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

var log = Math.log;
var LN2 = Math.LN2;

function clz32Fallback(x) {
  var asUint = x >>> 0;

  if (asUint === 0) {
    return 32;
  }

  return 31 - (log(asUint) / LN2 | 0) | 0;
}

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  ;
}

var objectIs = typeof Object.is === 'function' ? Object.is : is;

var currentlyRenderingComponent = null;
var currentlyRenderingTask = null;
var firstWorkInProgressHook = null;
var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

var localIdCounter = 0; // Lazily created map of render-phase updates

var renderPhaseUpdates = null; // Counter to prevent infinite loops.

var numberOfReRenders = 0;
var RE_RENDER_LIMIT = 25;
var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

var currentHookNameInDev;

function resolveCurrentlyRenderingComponent() {
  if (currentlyRenderingComponent === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
  }

  {
    if (isInHookUserCodeInDev) {
      error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
    }
  }

  return currentlyRenderingComponent;
}

function areHookInputsEqual(nextDeps, prevDeps) {
  if (prevDeps === null) {
    {
      error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
    }

    return false;
  }

  {
    // Don't bother comparing lengths in prod because these arrays should be
    // passed inline.
    if (nextDeps.length !== prevDeps.length) {
      error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
    }
  }

  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (objectIs(nextDeps[i], prevDeps[i])) {
      continue;
    }

    return false;
  }

  return true;
}

function createHook() {
  if (numberOfReRenders > 0) {
    throw new Error('Rendered more hooks than during the previous render');
  }

  return {
    memoizedState: null,
    queue: null,
    next: null
  };
}

function createWorkInProgressHook() {
  if (workInProgressHook === null) {
    // This is the first hook in the list
    if (firstWorkInProgressHook === null) {
      isReRender = false;
      firstWorkInProgressHook = workInProgressHook = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = firstWorkInProgressHook;
    }
  } else {
    if (workInProgressHook.next === null) {
      isReRender = false; // Append to the end of the list

      workInProgressHook = workInProgressHook.next = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = workInProgressHook.next;
    }
  }

  return workInProgressHook;
}

function prepareToUseHooks(task, componentIdentity) {
  currentlyRenderingComponent = componentIdentity;
  currentlyRenderingTask = task;

  {
    isInHookUserCodeInDev = false;
  } // The following should have already been reset
  // didScheduleRenderPhaseUpdate = false;
  // localIdCounter = 0;
  // firstWorkInProgressHook = null;
  // numberOfReRenders = 0;
  // renderPhaseUpdates = null;
  // workInProgressHook = null;


  localIdCounter = 0;
}
function finishHooks(Component, props, children, refOrContext) {
  // This must be called after every function component to prevent hooks from
  // being used in classes.
  while (didScheduleRenderPhaseUpdate) {
    // Updates were scheduled during the render phase. They are stored in
    // the `renderPhaseUpdates` map. Call the component again, reusing the
    // work-in-progress hooks and applying the additional updates on top. Keep
    // restarting until no more updates are scheduled.
    didScheduleRenderPhaseUpdate = false;
    localIdCounter = 0;
    numberOfReRenders += 1; // Start over from the beginning of the list

    workInProgressHook = null;
    children = Component(props, refOrContext);
  }

  resetHooksState();
  return children;
}
function checkDidRenderIdHook() {
  // This should be called immediately after every finishHooks call.
  // Conceptually, it's part of the return value of finishHooks; it's only a
  // separate function to avoid using an array tuple.
  var didRenderIdHook = localIdCounter !== 0;
  return didRenderIdHook;
} // Reset the internal hooks state if an error occurs while rendering a component

function resetHooksState() {
  {
    isInHookUserCodeInDev = false;
  }

  currentlyRenderingComponent = null;
  currentlyRenderingTask = null;
  didScheduleRenderPhaseUpdate = false;
  firstWorkInProgressHook = null;
  numberOfReRenders = 0;
  renderPhaseUpdates = null;
  workInProgressHook = null;
}

function readContext$1(context) {
  {
    if (isInHookUserCodeInDev) {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    }
  }

  return readContext(context);
}

function useContext(context) {
  {
    currentHookNameInDev = 'useContext';
  }

  resolveCurrentlyRenderingComponent();
  return readContext(context);
}

function basicStateReducer(state, action) {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

function useState(initialState) {
  {
    currentHookNameInDev = 'useState';
  }

  return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
  initialState);
}
function useReducer(reducer, initialArg, init) {
  {
    if (reducer !== basicStateReducer) {
      currentHookNameInDev = 'useReducer';
    }
  }

  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();

  if (isReRender) {
    // This is a re-render. Apply the new render phase updates to the previous
    // current hook.
    var queue = workInProgressHook.queue;
    var dispatch = queue.dispatch;

    if (renderPhaseUpdates !== null) {
      // Render phase updates are stored in a map of queue -> linked list
      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate !== undefined) {
        renderPhaseUpdates.delete(queue);
        var newState = workInProgressHook.memoizedState;
        var update = firstRenderPhaseUpdate;

        do {
          // Process this render phase update. We don't have to check the
          // priority because it will always be the same as the current
          // render's.
          var action = update.action;

          {
            isInHookUserCodeInDev = true;
          }

          newState = reducer(newState, action);

          {
            isInHookUserCodeInDev = false;
          }

          update = update.next;
        } while (update !== null);

        workInProgressHook.memoizedState = newState;
        return [newState, dispatch];
      }
    }

    return [workInProgressHook.memoizedState, dispatch];
  } else {
    {
      isInHookUserCodeInDev = true;
    }

    var initialState;

    if (reducer === basicStateReducer) {
      // Special case for `useState`.
      initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
    } else {
      initialState = init !== undefined ? init(initialArg) : initialArg;
    }

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = initialState;

    var _queue = workInProgressHook.queue = {
      last: null,
      dispatch: null
    };

    var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

    return [workInProgressHook.memoizedState, _dispatch];
  }
}

function useMemo(nextCreate, deps) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;

  if (workInProgressHook !== null) {
    var prevState = workInProgressHook.memoizedState;

    if (prevState !== null) {
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }
  }

  {
    isInHookUserCodeInDev = true;
  }

  var nextValue = nextCreate();

  {
    isInHookUserCodeInDev = false;
  }

  workInProgressHook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function useRef(initialValue) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var previousRef = workInProgressHook.memoizedState;

  if (previousRef === null) {
    var ref = {
      current: initialValue
    };

    {
      Object.seal(ref);
    }

    workInProgressHook.memoizedState = ref;
    return ref;
  } else {
    return previousRef;
  }
}

function useLayoutEffect(create, inputs) {
  {
    currentHookNameInDev = 'useLayoutEffect';

    error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
  }
}

function dispatchAction(componentIdentity, queue, action) {
  if (numberOfReRenders >= RE_RENDER_LIMIT) {
    throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
  }

  if (componentIdentity === currentlyRenderingComponent) {
    // This is a render phase update. Stash it in a lazily-created map of
    // queue -> linked list of updates. After this render pass, we'll restart
    // and apply the stashed updates on top of the work-in-progress hook.
    didScheduleRenderPhaseUpdate = true;
    var update = {
      action: action,
      next: null
    };

    if (renderPhaseUpdates === null) {
      renderPhaseUpdates = new Map();
    }

    var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

    if (firstRenderPhaseUpdate === undefined) {
      renderPhaseUpdates.set(queue, update);
    } else {
      // Append the update to the end of the list.
      var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

      while (lastRenderPhaseUpdate.next !== null) {
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      }

      lastRenderPhaseUpdate.next = update;
    }
  }
}

function useCallback(callback, deps) {
  return useMemo(function () {
    return callback;
  }, deps);
} // TODO Decide on how to implement this hook for server rendering.
// If a mutation occurs during render, consider triggering a Suspense boundary
// and falling back to client rendering.

function useMutableSource(source, getSnapshot, subscribe) {
  resolveCurrentlyRenderingComponent();
  return getSnapshot(source._source);
}

function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  if (getServerSnapshot === undefined) {
    throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
  }

  return getServerSnapshot();
}

function useDeferredValue(value) {
  resolveCurrentlyRenderingComponent();
  return value;
}

function unsupportedStartTransition() {
  throw new Error('startTransition cannot be called during server rendering.');
}

function useTransition() {
  resolveCurrentlyRenderingComponent();
  return [false, unsupportedStartTransition];
}

function useId() {
  var task = currentlyRenderingTask;
  var treeId = getTreeId(task.treeContext);
  var responseState = currentResponseState;

  if (responseState === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
  }

  var localId = localIdCounter++;
  return makeId(responseState, treeId, localId);
}

function noop() {}

var Dispatcher = {
  readContext: readContext$1,
  useContext: useContext,
  useMemo: useMemo,
  useReducer: useReducer,
  useRef: useRef,
  useState: useState,
  useInsertionEffect: noop,
  useLayoutEffect: useLayoutEffect,
  useCallback: useCallback,
  // useImperativeHandle is not run in the server environment
  useImperativeHandle: noop,
  // Effects are not run in the server environment.
  useEffect: noop,
  // Debugging effect
  useDebugValue: noop,
  useDeferredValue: useDeferredValue,
  useTransition: useTransition,
  useId: useId,
  // Subscriptions are not setup in a server environment.
  useMutableSource: useMutableSource,
  useSyncExternalStore: useSyncExternalStore
};

var currentResponseState = null;
function setCurrentResponseState(responseState) {
  currentResponseState = responseState;
}

function getStackByComponentStackNode(componentStack) {
  try {
    var info = '';
    var node = componentStack;

    do {
      switch (node.tag) {
        case 0:
          info += describeBuiltInComponentFrame(node.type, null, null);
          break;

        case 1:
          info += describeFunctionComponentFrame(node.type, null, null);
          break;

        case 2:
          info += describeClassComponentFrame(node.type, null, null);
          break;
      }

      node = node.parent;
    } while (node);

    return info;
  } catch (x) {
    return '\nError generating stack: ' + x.message + '\n' + x.stack;
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
var PENDING = 0;
var COMPLETED = 1;
var FLUSHED = 2;
var ABORTED = 3;
var ERRORED = 4;
var OPEN = 0;
var CLOSING = 1;
var CLOSED = 2;
// This is a default heuristic for how to split up the HTML content into progressive
// loading. Our goal is to be able to display additional new content about every 500ms.
// Faster than that is unnecessary and should be throttled on the client. It also
// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
// end device but higher end suffer less from the overhead than lower end does from
// not getting small enough pieces. We error on the side of low end.
// We base this on low end 3G speeds which is about 500kbits per second. We assume
// that there can be a reasonable drop off from max bandwidth which leaves you with
// as little as 80%. We can receive half of that each 500ms - at best. In practice,
// a little bandwidth is lost to processing and contention - e.g. CSS and images that
// are downloaded along with the main content. So we estimate about half of that to be
// the lower end throughput. In other words, we expect that you can at least show
// about 12.5kb of content per 500ms. Not counting starting latency for the first
// paint.
// 500 * 1024 / 8 * .8 * 0.5 / 2
var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

function defaultErrorHandler(error) {
  console['error'](error); // Don't transform to our wrapper

  return null;
}

function noop$1() {}

function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
  var pingedTasks = [];
  var abortSet = new Set();
  var request = {
    destination: null,
    responseState: responseState,
    progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
    status: OPEN,
    fatalError: null,
    nextSegmentId: 0,
    allPendingTasks: 0,
    pendingRootTasks: 0,
    completedRootSegment: null,
    abortableTasks: abortSet,
    pingedTasks: pingedTasks,
    clientRenderedBoundaries: [],
    completedBoundaries: [],
    partialBoundaries: [],
    onError: onError === undefined ? defaultErrorHandler : onError,
    onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
    onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
    onShellError: onShellError === undefined ? noop$1 : onShellError,
    onFatalError: onFatalError === undefined ? noop$1 : onFatalError
  }; // This segment represents the root fallback.

  var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
  false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

  rootSegment.parentFlushed = true;
  var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
  pingedTasks.push(rootTask);
  return request;
}

function pingTask(request, task) {
  var pingedTasks = request.pingedTasks;
  pingedTasks.push(task);

  if (pingedTasks.length === 1) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
}

function createSuspenseBoundary(request, fallbackAbortableTasks) {
  return {
    id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
    rootSegmentID: -1,
    parentFlushed: false,
    pendingTasks: 0,
    forceClientRender: false,
    completedSegments: [],
    byteSize: 0,
    fallbackAbortableTasks: fallbackAbortableTasks,
    errorDigest: null
  };
}

function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
  request.allPendingTasks++;

  if (blockedBoundary === null) {
    request.pendingRootTasks++;
  } else {
    blockedBoundary.pendingTasks++;
  }

  var task = {
    node: node,
    ping: function () {
      return pingTask(request, task);
    },
    blockedBoundary: blockedBoundary,
    blockedSegment: blockedSegment,
    abortSet: abortSet,
    legacyContext: legacyContext,
    context: context,
    treeContext: treeContext
  };

  {
    task.componentStack = null;
  }

  abortSet.add(task);
  return task;
}

function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
  return {
    status: PENDING,
    id: -1,
    // lazily assigned later
    index: index,
    parentFlushed: false,
    chunks: [],
    children: [],
    formatContext: formatContext,
    boundary: boundary,
    lastPushedText: lastPushedText,
    textEmbedded: textEmbedded
  };
} // DEV-only global reference to the currently executing task


var currentTaskInDEV = null;

function getCurrentStackInDEV() {
  {
    if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
      return '';
    }

    return getStackByComponentStackNode(currentTaskInDEV.componentStack);
  }
}

function pushBuiltInComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 0,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushFunctionComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 1,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushClassComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 2,
      parent: task.componentStack,
      type: type
    };
  }
}

function popComponentStackInDEV(task) {
  {
    if (task.componentStack === null) {
      error('Unexpectedly popped too many stack frames. This is a bug in React.');
    } else {
      task.componentStack = task.componentStack.parent;
    }
  }
} // stash the component stack of an unwinding error until it is processed


var lastBoundaryErrorComponentStackDev = null;

function captureBoundaryErrorDetailsDev(boundary, error) {
  {
    var errorMessage;

    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error && typeof error.message === 'string') {
      errorMessage = error.message;
    } else {
      // eslint-disable-next-line react-internal/safe-string-coercion
      errorMessage = String(error);
    }

    var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
    lastBoundaryErrorComponentStackDev = null;
    boundary.errorMessage = errorMessage;
    boundary.errorComponentStack = errorComponentStack;
  }
}

function logRecoverableError(request, error) {
  // If this callback errors, we intentionally let that error bubble up to become a fatal error
  // so that someone fixes the error reporting instead of hiding it.
  var errorDigest = request.onError(error);

  if (errorDigest != null && typeof errorDigest !== 'string') {
    // eslint-disable-next-line react-internal/prod-error-codes
    throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
  }

  return errorDigest;
}

function fatalError(request, error) {
  // This is called outside error handling code such as if the root errors outside
  // a suspense boundary or if the root suspense boundary's fallback errors.
  // It's also called if React itself or its host configs errors.
  var onShellError = request.onShellError;
  onShellError(error);
  var onFatalError = request.onFatalError;
  onFatalError(error);

  if (request.destination !== null) {
    request.status = CLOSED;
    closeWithError(request.destination, error);
  } else {
    request.status = CLOSING;
    request.fatalError = error;
  }
}

function renderSuspenseBoundary(request, task, props) {
  pushBuiltInComponentStackInDEV(task, 'Suspense');
  var parentBoundary = task.blockedBoundary;
  var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
  // the fallback so that we can later replace that segment with the content.
  // This also lets us split out the main content even if it doesn't suspend,
  // in case it ends up generating a large subtree of content.

  var fallback = props.fallback;
  var content = props.children;
  var fallbackAbortSet = new Set();
  var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
  var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

  var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false);
  parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

  parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

  var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
  // no parent segment so there's nothing to wait on.

  contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
  // I suspect that there might be some efficiency benefits from not creating the suspended task
  // and instead just using the stack if possible.
  // TODO: Call this directly instead of messing with saving and restoring contexts.
  // We can reuse the current context and task to render the content immediately without
  // context switching. We just need to temporarily switch which boundary and which segment
  // we're writing to. If something suspends, it'll spawn new suspended task with that context.

  task.blockedBoundary = newBoundary;
  task.blockedSegment = contentRootSegment;

  try {
    // We use the safe form because we don't handle suspending here. Only error handling.
    renderNode(request, task, content);
    pushSegmentFinale(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
    contentRootSegment.status = COMPLETED;
    queueCompletedSegment(newBoundary, contentRootSegment);

    if (newBoundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      // Therefore we won't need the fallback. We early return so that we don't have to create
      // the fallback.
      popComponentStackInDEV(task);
      return;
    }
  } catch (error) {
    contentRootSegment.status = ERRORED;
    newBoundary.forceClientRender = true;
    newBoundary.errorDigest = logRecoverableError(request, error);

    {
      captureBoundaryErrorDetailsDev(newBoundary, error);
    } // We don't need to decrement any task numbers because we didn't spawn any new task.
    // We don't need to schedule any task because we know the parent has written yet.
    // We do need to fallthrough to create the fallback though.

  } finally {
    task.blockedBoundary = parentBoundary;
    task.blockedSegment = parentSegment;
  } // We create suspended task for the fallback because we don't want to actually work
  // on it yet in case we finish the main content, so we queue for later.


  var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

  {
    suspendedFallbackTask.componentStack = task.componentStack;
  } // TODO: This should be queued at a separate lower priority queue so that we only work
  // on preparing fallbacks if we don't have any more main content to task on.


  request.pingedTasks.push(suspendedFallbackTask);
  popComponentStackInDEV(task);
}

function renderHostElement(request, task, type, props) {
  pushBuiltInComponentStackInDEV(task, type);
  var segment = task.blockedSegment;
  var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
  segment.lastPushedText = false;
  var prevContext = segment.formatContext;
  segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
  // need to pop back up and finish this subtree of HTML.

  renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
  // the correct context. Therefore this is not in a finally.

  segment.formatContext = prevContext;
  pushEndInstance(segment.chunks, type);
  segment.lastPushedText = false;
  popComponentStackInDEV(task);
}

function shouldConstruct$1(Component) {
  return Component.prototype && Component.prototype.isReactComponent;
}

function renderWithHooks(request, task, Component, props, secondArg) {
  var componentIdentity = {};
  prepareToUseHooks(task, componentIdentity);
  var result = Component(props, secondArg);
  return finishHooks(Component, props, result, secondArg);
}

function finishClassComponent(request, task, instance, Component, props) {
  var nextChildren = instance.render();

  {
    if (instance.props !== props) {
      if (!didWarnAboutReassigningProps) {
        error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
      }

      didWarnAboutReassigningProps = true;
    }
  }

  {
    var childContextTypes = Component.childContextTypes;

    if (childContextTypes !== null && childContextTypes !== undefined) {
      var previousContext = task.legacyContext;
      var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
      task.legacyContext = mergedContext;
      renderNodeDestructive(request, task, nextChildren);
      task.legacyContext = previousContext;
      return;
    }
  }

  renderNodeDestructive(request, task, nextChildren);
}

function renderClassComponent(request, task, Component, props) {
  pushClassComponentStackInDEV(task, Component);
  var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
  var instance = constructClassInstance(Component, props, maskedContext);
  mountClassInstance(instance, Component, props, maskedContext);
  finishClassComponent(request, task, instance, Component, props);
  popComponentStackInDEV(task);
}

var didWarnAboutBadClass = {};
var didWarnAboutModulePatternComponent = {};
var didWarnAboutContextTypeOnFunctionComponent = {};
var didWarnAboutGetDerivedStateOnFunctionComponent = {};
var didWarnAboutReassigningProps = false;
var didWarnAboutDefaultPropsOnFunctionComponent = {};
var didWarnAboutGenerators = false;
var didWarnAboutMaps = false;
var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
// components for some reason.

function renderIndeterminateComponent(request, task, Component, props) {
  var legacyContext;

  {
    legacyContext = getMaskedContext(Component, task.legacyContext);
  }

  pushFunctionComponentStackInDEV(task, Component);

  {
    if (Component.prototype && typeof Component.prototype.render === 'function') {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

        didWarnAboutBadClass[componentName] = true;
      }
    }
  }

  var value = renderWithHooks(request, task, Component, props, legacyContext);
  var hasId = checkDidRenderIdHook();

  {
    // Support for module components is deprecated and is removed behind a flag.
    // Whether or not it would crash later, we want to show a good message in DEV first.
    if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      var _componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

        didWarnAboutModulePatternComponent[_componentName] = true;
      }
    }
  }

  if ( // Run these checks in production only if the flag is off.
  // Eventually we'll delete this branch altogether.
   typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    {
      var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName2]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

        didWarnAboutModulePatternComponent[_componentName2] = true;
      }
    }

    mountClassInstance(value, Component, props, legacyContext);
    finishClassComponent(request, task, value, Component, props);
  } else {

    {
      validateFunctionComponentInDev(Component);
    } // We're now successfully past this task, and we don't have to pop back to
    // the previous task every again, so we can use the destructive recursive form.


    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, value);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, value);
    }
  }

  popComponentStackInDEV(task);
}

function validateFunctionComponentInDev(Component) {
  {
    if (Component) {
      if (Component.childContextTypes) {
        error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
      }
    }

    if ( Component.defaultProps !== undefined) {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
        error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

        didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
      }
    }

    if (typeof Component.getDerivedStateFromProps === 'function') {
      var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
        error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

        didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
      }
    }

    if (typeof Component.contextType === 'object' && Component.contextType !== null) {
      var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
        error('%s: Function components do not support contextType.', _componentName4);

        didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
      }
    }
  }
}

function resolveDefaultProps(Component, baseProps) {
  if (Component && Component.defaultProps) {
    // Resolve default props. Taken from ReactElement
    var props = assign({}, baseProps);
    var defaultProps = Component.defaultProps;

    for (var propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }

    return props;
  }

  return baseProps;
}

function renderForwardRef(request, task, type, props, ref) {
  pushFunctionComponentStackInDEV(task, type.render);
  var children = renderWithHooks(request, task, type.render, props, ref);
  var hasId = checkDidRenderIdHook();

  if (hasId) {
    // This component materialized an id. We treat this as its own level, with
    // a single "child" slot.
    var prevTreeContext = task.treeContext;
    var totalChildren = 1;
    var index = 0;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

    try {
      renderNodeDestructive(request, task, children);
    } finally {
      task.treeContext = prevTreeContext;
    }
  } else {
    renderNodeDestructive(request, task, children);
  }

  popComponentStackInDEV(task);
}

function renderMemo(request, task, type, props, ref) {
  var innerType = type.type;
  var resolvedProps = resolveDefaultProps(innerType, props);
  renderElement(request, task, innerType, resolvedProps, ref);
}

function renderContextConsumer(request, task, context, props) {
  // The logic below for Context differs depending on PROD or DEV mode. In
  // DEV mode, we create a separate object for Context.Consumer that acts
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
  // so we use the old behaviour (Context.Consumer references Context) to
  // reduce size and overhead. The separate object references context via
  // a property called "_context", which also gives us the ability to check
  // in DEV mode if this property exists or not and warn if it does not.
  {
    if (context._context === undefined) {
      // This may be because it's a Context (rather than a Consumer).
      // Or it may be because it's older React where they're the same thing.
      // We only want to warn if we're sure it's a new React.
      if (context !== context.Consumer) {
        if (!hasWarnedAboutUsingContextAsConsumer) {
          hasWarnedAboutUsingContextAsConsumer = true;

          error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
        }
      }
    } else {
      context = context._context;
    }
  }

  var render = props.children;

  {
    if (typeof render !== 'function') {
      error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
    }
  }

  var newValue = readContext(context);
  var newChildren = render(newValue);
  renderNodeDestructive(request, task, newChildren);
}

function renderContextProvider(request, task, type, props) {
  var context = type._context;
  var value = props.value;
  var children = props.children;
  var prevSnapshot;

  {
    prevSnapshot = task.context;
  }

  task.context = pushProvider(context, value);
  renderNodeDestructive(request, task, children);
  task.context = popProvider(context);

  {
    if (prevSnapshot !== task.context) {
      error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
    }
  }
}

function renderLazyComponent(request, task, lazyComponent, props, ref) {
  pushBuiltInComponentStackInDEV(task, 'Lazy');
  var payload = lazyComponent._payload;
  var init = lazyComponent._init;
  var Component = init(payload);
  var resolvedProps = resolveDefaultProps(Component, props);
  renderElement(request, task, Component, resolvedProps, ref);
  popComponentStackInDEV(task);
}

function renderElement(request, task, type, props, ref) {
  if (typeof type === 'function') {
    if (shouldConstruct$1(type)) {
      renderClassComponent(request, task, type, props);
      return;
    } else {
      renderIndeterminateComponent(request, task, type, props);
      return;
    }
  }

  if (typeof type === 'string') {
    renderHostElement(request, task, type, props);
    return;
  }

  switch (type) {
    // TODO: LegacyHidden acts the same as a fragment. This only works
    // because we currently assume that every instance of LegacyHidden is
    // accompanied by a host component wrapper. In the hidden mode, the host
    // component is given a `hidden` attribute, which ensures that the
    // initial HTML is not visible. To support the use of LegacyHidden as a
    // true fragment, without an extra DOM node, we would have to hide the
    // initial HTML in some other way.
    // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
    case REACT_LEGACY_HIDDEN_TYPE:
    case REACT_DEBUG_TRACING_MODE_TYPE:
    case REACT_STRICT_MODE_TYPE:
    case REACT_PROFILER_TYPE:
    case REACT_FRAGMENT_TYPE:
      {
        renderNodeDestructive(request, task, props.children);
        return;
      }

    case REACT_SUSPENSE_LIST_TYPE:
      {
        pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

        renderNodeDestructive(request, task, props.children);
        popComponentStackInDEV(task);
        return;
      }

    case REACT_SCOPE_TYPE:
      {

        throw new Error('ReactDOMServer does not yet support scope components.');
      }
    // eslint-disable-next-line-no-fallthrough

    case REACT_SUSPENSE_TYPE:
      {
        {
          renderSuspenseBoundary(request, task, props);
        }

        return;
      }
  }

  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        {
          renderForwardRef(request, task, type, props, ref);
          return;
        }

      case REACT_MEMO_TYPE:
        {
          renderMemo(request, task, type, props, ref);
          return;
        }

      case REACT_PROVIDER_TYPE:
        {
          renderContextProvider(request, task, type, props);
          return;
        }

      case REACT_CONTEXT_TYPE:
        {
          renderContextConsumer(request, task, type, props);
          return;
        }

      case REACT_LAZY_TYPE:
        {
          renderLazyComponent(request, task, type, props);
          return;
        }
    }
  }

  var info = '';

  {
    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
    }
  }

  throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
}

function validateIterable(iterable, iteratorFn) {
  {
    // We don't support rendering Generators because it's a mutation.
    // See https://github.com/facebook/react/issues/12995
    if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
    iterable[Symbol.toStringTag] === 'Generator') {
      if (!didWarnAboutGenerators) {
        error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
      }

      didWarnAboutGenerators = true;
    } // Warn about using Maps as children


    if (iterable.entries === iteratorFn) {
      if (!didWarnAboutMaps) {
        error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
      }

      didWarnAboutMaps = true;
    }
  }
}

function renderNodeDestructive(request, task, node) {
  {
    // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
    // a component stack at the right place in the tree. We don't do this in renderNode
    // becuase it is not called at every layer of the tree and we may lose frames
    try {
      return renderNodeDestructiveImpl(request, task, node);
    } catch (x) {
      if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
        // This is an error, stash the component stack if it is null.
        lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
      } // rethrow so normal suspense logic can handle thrown value accordingly


      throw x;
    }
  }
} // This function by it self renders a node and consumes the task by mutating it
// to update the current execution state.


function renderNodeDestructiveImpl(request, task, node) {
  // Stash the node we're working on. We'll pick up from this task in case
  // something suspends.
  task.node = node; // Handle object types

  if (typeof node === 'object' && node !== null) {
    switch (node.$$typeof) {
      case REACT_ELEMENT_TYPE:
        {
          var element = node;
          var type = element.type;
          var props = element.props;
          var ref = element.ref;
          renderElement(request, task, type, props, ref);
          return;
        }

      case REACT_PORTAL_TYPE:
        throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
      // eslint-disable-next-line-no-fallthrough

      case REACT_LAZY_TYPE:
        {
          var lazyNode = node;
          var payload = lazyNode._payload;
          var init = lazyNode._init;
          var resolvedNode;

          {
            try {
              resolvedNode = init(payload);
            } catch (x) {
              if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                // vs Component position. We do not want the frame for Errors so we exclusively do this in
                // the wakeable branch
                pushBuiltInComponentStackInDEV(task, 'Lazy');
              }

              throw x;
            }
          }

          renderNodeDestructive(request, task, resolvedNode);
          return;
        }
    }

    if (isArray(node)) {
      renderChildrenArray(request, task, node);
      return;
    }

    var iteratorFn = getIteratorFn(node);

    if (iteratorFn) {
      {
        validateIterable(node, iteratorFn);
      }

      var iterator = iteratorFn.call(node);

      if (iterator) {
        // We need to know how many total children are in this set, so that we
        // can allocate enough id slots to acommodate them. So we must exhaust
        // the iterator before we start recursively rendering the children.
        // TODO: This is not great but I think it's inherent to the id
        // generation algorithm.
        var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

        if (!step.done) {
          var children = [];

          do {
            children.push(step.value);
            step = iterator.next();
          } while (!step.done);

          renderChildrenArray(request, task, children);
          return;
        }

        return;
      }
    }

    var childString = Object.prototype.toString.call(node);
    throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
  }

  if (typeof node === 'string') {
    var segment = task.blockedSegment;
    segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
    return;
  }

  if (typeof node === 'number') {
    var _segment = task.blockedSegment;
    _segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
    return;
  }

  {
    if (typeof node === 'function') {
      error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
    }
  }
}

function renderChildrenArray(request, task, children) {
  var totalChildren = children.length;

  for (var i = 0; i < totalChildren; i++) {
    var prevTreeContext = task.treeContext;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

    try {
      // We need to use the non-destructive form so that we can safely pop back
      // up and render the sibling if something suspends.
      renderNode(request, task, children[i]);
    } finally {
      task.treeContext = prevTreeContext;
    }
  }
}

function spawnNewSuspendedTask(request, task, x) {
  // Something suspended, we'll need to create a new segment and resolve it later.
  var segment = task.blockedSegment;
  var insertionIndex = segment.chunks.length;
  var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
  segment.lastPushedText, // Assume we are text embedded at the trailing edge
  true);
  segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

  segment.lastPushedText = false;
  var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

  {
    if (task.componentStack !== null) {
      // We pop one task off the stack because the node that suspended will be tried again,
      // which will add it back onto the stack.
      newTask.componentStack = task.componentStack.parent;
    }
  }

  var ping = newTask.ping;
  x.then(ping, ping);
} // This is a non-destructive form of rendering a node. If it suspends it spawns
// a new task and restores the context of this task to what it was before.


function renderNode(request, task, node) {
  // TODO: Store segment.children.length here and reset it in case something
  // suspended partially through writing something.
  // Snapshot the current context in case something throws to interrupt the
  // process.
  var previousFormatContext = task.blockedSegment.formatContext;
  var previousLegacyContext = task.legacyContext;
  var previousContext = task.context;
  var previousComponentStack = null;

  {
    previousComponentStack = task.componentStack;
  }

  try {
    return renderNodeDestructive(request, task, node);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.

      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      }

      return;
    } else {
      // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.
      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      } // We assume that we don't need the correct context.
      // Let's terminate the rest of the tree and don't render any siblings.


      throw x;
    }
  }
}

function erroredTask(request, boundary, segment, error) {
  // Report the error to a global handler.
  var errorDigest = logRecoverableError(request, error);

  if (boundary === null) {
    fatalError(request, error);
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;
      boundary.errorDigest = errorDigest;

      {
        captureBoundaryErrorDetailsDev(boundary, error);
      } // Regardless of what happens next, this boundary won't be displayed,
      // so we can flush it, if the parent already flushed.


      if (boundary.parentFlushed) {
        // We don't have a preference where in the queue this goes since it's likely
        // to error on the client anyway. However, intentionally client-rendered
        // boundaries should be flushed earlier so that they can start on the client.
        // We reuse the same queue for errors.
        request.clientRenderedBoundaries.push(boundary);
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function abortTaskSoft(task) {
  // This aborts task without aborting the parent boundary that it blocks.
  // It's used for when we didn't need this task to complete the tree.
  // If task was needed, then it should use abortTask instead.
  var request = this;
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;
  finishedTask(request, boundary, segment);
}

function abortTask(task, request, reason) {
  // This aborts the task and aborts the parent that it blocks, putting it into
  // client rendered mode.
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;

  if (boundary === null) {
    request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
    // the request;

    if (request.status !== CLOSED) {
      request.status = CLOSED;

      if (request.destination !== null) {
        close(request.destination);
      }
    }
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;

      var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

      boundary.errorDigest = request.onError(_error);

      {
        var errorPrefix = 'The server did not finish this Suspense boundary: ';

        if (_error && typeof _error.message === 'string') {
          _error = errorPrefix + _error.message;
        } else {
          // eslint-disable-next-line react-internal/safe-string-coercion
          _error = errorPrefix + String(_error);
        }

        var previousTaskInDev = currentTaskInDEV;
        currentTaskInDEV = task;

        try {
          captureBoundaryErrorDetailsDev(boundary, _error);
        } finally {
          currentTaskInDEV = previousTaskInDev;
        }
      }

      if (boundary.parentFlushed) {
        request.clientRenderedBoundaries.push(boundary);
      }
    } // If this boundary was still pending then we haven't already cancelled its fallbacks.
    // We'll need to abort the fallbacks, which will also error that parent boundary.


    boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
      return abortTask(fallbackTask, request, reason);
    });
    boundary.fallbackAbortableTasks.clear();
    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }
}

function queueCompletedSegment(boundary, segment) {
  if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
    // This is an empty segment. There's nothing to write, so we can instead transfer the ID
    // to the child. That way any existing references point to the child.
    var childSegment = segment.children[0];
    childSegment.id = segment.id;
    childSegment.parentFlushed = true;

    if (childSegment.status === COMPLETED) {
      queueCompletedSegment(boundary, childSegment);
    }
  } else {
    var completedSegments = boundary.completedSegments;
    completedSegments.push(segment);
  }
}

function finishedTask(request, boundary, segment) {
  if (boundary === null) {
    if (segment.parentFlushed) {
      if (request.completedRootSegment !== null) {
        throw new Error('There can only be one root segment. This is a bug in React.');
      }

      request.completedRootSegment = segment;
    }

    request.pendingRootTasks--;

    if (request.pendingRootTasks === 0) {
      // We have completed the shell so the shell can't error anymore.
      request.onShellError = noop$1;
      var onShellReady = request.onShellReady;
      onShellReady();
    }
  } else {
    boundary.pendingTasks--;

    if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      if (segment.parentFlushed) {
        // Our parent segment already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
        }
      }

      if (boundary.parentFlushed) {
        // The segment might be part of a segment that didn't flush yet, but if the boundary's
        // parent flushed, we need to schedule the boundary to be emitted.
        request.completedBoundaries.push(boundary);
      } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
      // This needs to happen after we read the parentFlushed flags because aborting can finish
      // work which can trigger user code, which can start flushing, which can change those flags.


      boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
      boundary.fallbackAbortableTasks.clear();
    } else {
      if (segment.parentFlushed) {
        // Our parent already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
          var completedSegments = boundary.completedSegments;

          if (completedSegments.length === 1) {
            // This is the first time since we last flushed that we completed anything.
            // We can schedule this boundary to emit its partially completed segments early
            // in case the parent has already been flushed.
            if (boundary.parentFlushed) {
              request.partialBoundaries.push(boundary);
            }
          }
        }
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    // This needs to be called at the very end so that we can synchronously write the result
    // in the callback if needed.
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function retryTask(request, task) {
  var segment = task.blockedSegment;

  if (segment.status !== PENDING) {
    // We completed this by other means before we had a chance to retry it.
    return;
  } // We restore the context to what it was when we suspended.
  // We don't restore it after we leave because it's likely that we'll end up
  // needing a very similar context soon again.


  switchContext(task.context);
  var prevTaskInDEV = null;

  {
    prevTaskInDEV = currentTaskInDEV;
    currentTaskInDEV = task;
  }

  try {
    // We call the destructive form that mutates this task. That way if something
    // suspends again, we can reuse the same task instead of spawning a new one.
    renderNodeDestructive(request, task, task.node);
    pushSegmentFinale(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
    task.abortSet.delete(task);
    segment.status = COMPLETED;
    finishedTask(request, task.blockedBoundary, segment);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      // Something suspended again, let's pick it back up later.
      var ping = task.ping;
      x.then(ping, ping);
    } else {
      task.abortSet.delete(task);
      segment.status = ERRORED;
      erroredTask(request, task.blockedBoundary, segment, x);
    }
  } finally {
    {
      currentTaskInDEV = prevTaskInDEV;
    }
  }
}

function performWork(request) {
  if (request.status === CLOSED) {
    return;
  }

  var prevContext = getActiveContext();
  var prevDispatcher = ReactCurrentDispatcher$1.current;
  ReactCurrentDispatcher$1.current = Dispatcher;
  var prevGetCurrentStackImpl;

  {
    prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
    ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
  }

  var prevResponseState = currentResponseState;
  setCurrentResponseState(request.responseState);

  try {
    var pingedTasks = request.pingedTasks;
    var i;

    for (i = 0; i < pingedTasks.length; i++) {
      var task = pingedTasks[i];
      retryTask(request, task);
    }

    pingedTasks.splice(0, i);

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  } finally {
    setCurrentResponseState(prevResponseState);
    ReactCurrentDispatcher$1.current = prevDispatcher;

    {
      ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
    }

    if (prevDispatcher === Dispatcher) {
      // This means that we were in a reentrant work loop. This could happen
      // in a renderer that supports synchronous work like renderToString,
      // when it's called from within another renderer.
      // Normally we don't bother switching the contexts to their root/default
      // values when leaving because we'll likely need the same or similar
      // context again. However, when we're inside a synchronous loop like this
      // we'll to restore the context to what it was before returning.
      switchContext(prevContext);
    }
  }
}

function flushSubtree(request, destination, segment) {
  segment.parentFlushed = true;

  switch (segment.status) {
    case PENDING:
      {
        // We're emitting a placeholder for this segment to be filled in later.
        // Therefore we'll need to assign it an ID - to refer to it by.
        var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

        segment.lastPushedText = false;
        segment.textEmbedded = false;
        return writePlaceholder(destination, request.responseState, segmentID);
      }

    case COMPLETED:
      {
        segment.status = FLUSHED;
        var r = true;
        var chunks = segment.chunks;
        var chunkIdx = 0;
        var children = segment.children;

        for (var childIdx = 0; childIdx < children.length; childIdx++) {
          var nextChild = children[childIdx]; // Write all the chunks up until the next child.

          for (; chunkIdx < nextChild.index; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          r = flushSegment(request, destination, nextChild);
        } // Finally just write all the remaining chunks


        for (; chunkIdx < chunks.length - 1; chunkIdx++) {
          writeChunk(destination, chunks[chunkIdx]);
        }

        if (chunkIdx < chunks.length) {
          r = writeChunkAndReturn(destination, chunks[chunkIdx]);
        }

        return r;
      }

    default:
      {
        throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
      }
  }
}

function flushSegment(request, destination, segment) {
  var boundary = segment.boundary;

  if (boundary === null) {
    // Not a suspense boundary.
    return flushSubtree(request, destination, segment);
  }

  boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
  // emit the content or the fallback now.

  if (boundary.forceClientRender) {
    // Emit a client rendered suspense boundary wrapper.
    // We never queue the inner boundary so we'll never emit its content or partial segments.
    writeStartClientRenderedSuspenseBoundary(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndClientRenderedSuspenseBoundary(destination, request.responseState);
  } else if (boundary.pendingTasks > 0) {
    // This boundary is still loading. Emit a pending suspense boundary wrapper.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;

    if (boundary.completedSegments.length > 0) {
      // If this is at least partially complete, we can queue it to be partially emitted early.
      request.partialBoundaries.push(boundary);
    } /// This is the first time we should have referenced this ID.


    var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
    writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else if (boundary.byteSize > request.progressiveChunkSize) {
    // This boundary is large and will be emitted separately so that we can progressively show
    // other content. We add it to the queue during the flush because we have to ensure that
    // the parent flushes first so that there's something to inject it into.
    // We also have to make sure that it's emitted into the queue in a deterministic slot.
    // I.e. we can't insert it here when it completes.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;
    request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

    writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else {
    // We can inline this boundary's content as a complete boundary.
    writeStartCompletedSuspenseBoundary(destination, request.responseState);
    var completedSegments = boundary.completedSegments;

    if (completedSegments.length !== 1) {
      throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
    }

    var contentSegment = completedSegments[0];
    flushSegment(request, destination, contentSegment);
    return writeEndCompletedSuspenseBoundary(destination, request.responseState);
  }
}

function flushClientRenderedBoundary(request, destination, boundary) {
  return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
}

function flushSegmentContainer(request, destination, segment) {
  writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
  flushSegment(request, destination, segment);
  return writeEndSegment(destination, segment.formatContext);
}

function flushCompletedBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];
    flushPartiallyCompletedSegment(request, destination, boundary, segment);
  }

  completedSegments.length = 0;
  return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
}

function flushPartialBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];

    if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
      i++;
      completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
      // might want to write later.

      return false;
    }
  }

  completedSegments.splice(0, i);
  return true;
}

function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
  if (segment.status === FLUSHED) {
    // We've already flushed this inline.
    return true;
  }

  var segmentID = segment.id;

  if (segmentID === -1) {
    // This segment wasn't previously referred to. This happens at the root of
    // a boundary. We make kind of a leap here and assume this is the root.
    var rootSegmentID = segment.id = boundary.rootSegmentID;

    if (rootSegmentID === -1) {
      throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
    }

    return flushSegmentContainer(request, destination, segment);
  } else {
    flushSegmentContainer(request, destination, segment);
    return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
  }
}

function flushCompletedQueues(request, destination) {
  beginWriting();

  try {
    // The structure of this is to go through each queue one by one and write
    // until the sink tells us to stop. When we should stop, we still finish writing
    // that item fully and then yield. At that point we remove the already completed
    // items up until the point we completed them.
    // TODO: Emit preloading.
    // TODO: It's kind of unfortunate to keep checking this array after we've already
    // emitted the root.
    var completedRootSegment = request.completedRootSegment;

    if (completedRootSegment !== null && request.pendingRootTasks === 0) {
      flushSegment(request, destination, completedRootSegment);
      request.completedRootSegment = null;
      writeCompletedRoot(destination, request.responseState);
    } // We emit client rendering instructions for already emitted boundaries first.
    // This is so that we can signal to the client to start client rendering them as
    // soon as possible.


    var clientRenderedBoundaries = request.clientRenderedBoundaries;
    var i;

    for (i = 0; i < clientRenderedBoundaries.length; i++) {
      var boundary = clientRenderedBoundaries[i];

      if (!flushClientRenderedBoundary(request, destination, boundary)) {
        request.destination = null;
        i++;
        clientRenderedBoundaries.splice(0, i);
        return;
      }
    }

    clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
    // that are completely done since we can actually show them, than it is to emit
    // any individual segments from a partially complete boundary.

    var completedBoundaries = request.completedBoundaries;

    for (i = 0; i < completedBoundaries.length; i++) {
      var _boundary = completedBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary)) {
        request.destination = null;
        i++;
        completedBoundaries.splice(0, i);
        return;
      }
    }

    completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
    // we continue with lower priorities.

    completeWriting(destination);
    beginWriting(destination); // TODO: Here we'll emit data used by hydration.
    // Next we emit any segments of any boundaries that are partially complete
    // but not deeply complete.

    var partialBoundaries = request.partialBoundaries;

    for (i = 0; i < partialBoundaries.length; i++) {
      var _boundary2 = partialBoundaries[i];

      if (!flushPartialBoundary(request, destination, _boundary2)) {
        request.destination = null;
        i++;
        partialBoundaries.splice(0, i);
        return;
      }
    }

    partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
    // boundaries added to it in case they were too larged to be inlined.
    // New ones might be added in this loop.

    var largeBoundaries = request.completedBoundaries;

    for (i = 0; i < largeBoundaries.length; i++) {
      var _boundary3 = largeBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary3)) {
        request.destination = null;
        i++;
        largeBoundaries.splice(0, i);
        return;
      }
    }

    largeBoundaries.splice(0, i);
  } finally {
    completeWriting(destination);

    if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
    // either they have pending task or they're complete.
    ) {
        {
          if (request.abortableTasks.size !== 0) {
            error('There was still abortable task at the root when we closed. This is a bug in React.');
          }
        } // We're done.


        close(destination);
      }
  }
}

function startWork(request) {
  scheduleWork(function () {
    return performWork(request);
  });
}
function startFlowing(request, destination) {
  if (request.status === CLOSING) {
    request.status = CLOSED;
    closeWithError(destination, request.fatalError);
    return;
  }

  if (request.status === CLOSED) {
    return;
  }

  if (request.destination !== null) {
    // We're already flowing.
    return;
  }

  request.destination = destination;

  try {
    flushCompletedQueues(request, destination);
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

function abort(request, reason) {
  try {
    var abortableTasks = request.abortableTasks;
    abortableTasks.forEach(function (task) {
      return abortTask(task, request, reason);
    });
    abortableTasks.clear();

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
}

function renderToReadableStream(children, options) {
  return new Promise(function (resolve, reject) {
    var onFatalError;
    var onAllReady;
    var allReady = new Promise(function (res, rej) {
      onAllReady = res;
      onFatalError = rej;
    });

    function onShellReady() {
      var stream = new ReadableStream({
        type: 'bytes',
        pull: function (controller) {
          startFlowing(request, controller);
        },
        cancel: function (reason) {
          abort(request);
        }
      }, // $FlowFixMe size() methods are not allowed on byte streams.
      {
        highWaterMark: 0
      }); // TODO: Move to sub-classing ReadableStream.

      stream.allReady = allReady;
      resolve(stream);
    }

    function onShellError(error) {
      // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`.
      // However, `allReady` will be rejected by `onFatalError` as well.
      // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`.
      allReady.catch(function () {});
      reject(error);
    }

    var request = createRequest(children, createResponseState(options ? options.identifierPrefix : undefined, options ? options.nonce : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError);

    if (options && options.signal) {
      var signal = options.signal;

      var listener = function () {
        abort(request, signal.reason);
        signal.removeEventListener('abort', listener);
      };

      signal.addEventListener('abort', listener);
    }

    startWork(request);
  });
}

exports.renderToReadableStream = renderToReadableStream;
exports.version = ReactVersion;
  })();
}
/**
 * @license React
 * react-dom-server.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var aa=require("react");function k(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var l=null,n=0;
function p(a,b){if(0!==b.length)if(512<b.length)0<n&&(a.enqueue(new Uint8Array(l.buffer,0,n)),l=new Uint8Array(512),n=0),a.enqueue(b);else{var c=l.length-n;c<b.length&&(0===c?a.enqueue(l):(l.set(b.subarray(0,c),n),a.enqueue(l),b=b.subarray(c)),l=new Uint8Array(512),n=0);l.set(b,n);n+=b.length}}function t(a,b){p(a,b);return!0}function ba(a){l&&0<n&&(a.enqueue(new Uint8Array(l.buffer,0,n)),l=null,n=0)}var ca=new TextEncoder;function u(a){return ca.encode(a)}function w(a){return ca.encode(a)}
function da(a,b){"function"===typeof a.error?a.error(b):a.close()}var x=Object.prototype.hasOwnProperty,ea=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,fa={},ha={};
function ia(a){if(x.call(ha,a))return!0;if(x.call(fa,a))return!1;if(ea.test(a))return ha[a]=!0;fa[a]=!0;return!1}function y(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}var z={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new y(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new y(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new y(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new y(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new y(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){z[a]=new y(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){z[a]=new y(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){z[a]=new y(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){z[a]=new y(a,5,!1,a.toLowerCase(),null,!1,!1)});var ja=/[\-:]([a-z])/g;function ka(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ja,
ka);z[b]=new y(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ja,ka);z[b]=new y(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ja,ka);z[b]=new y(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new y(a,1,!1,a.toLowerCase(),null,!1,!1)});
z.xlinkHref=new y("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new y(a,1,!1,a.toLowerCase(),null,!0,!0)});
var B={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,
fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},la=["Webkit","ms","Moz","O"];Object.keys(B).forEach(function(a){la.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);B[b]=B[a]})});var oa=/["'&<>]/;
function C(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=oa.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}
var pa=/([A-Z])/g,qa=/^ms-/,ra=Array.isArray,sa=w("<script>"),ta=w("\x3c/script>"),ua=w('<script src="'),va=w('<script type="module" src="'),wa=w('" async="">\x3c/script>'),xa=/(<\/|<)(s)(cript)/gi;function ya(a,b,c,d){return""+b+("s"===c?"\\u0073":"\\u0053")+d}
function za(a,b,c,d,f){a=void 0===a?"":a;b=void 0===b?sa:w('<script nonce="'+C(b)+'">');var e=[];void 0!==c&&e.push(b,u((""+c).replace(xa,ya)),ta);if(void 0!==d)for(c=0;c<d.length;c++)e.push(ua,u(C(d[c])),wa);if(void 0!==f)for(d=0;d<f.length;d++)e.push(va,u(C(f[d])),wa);return{bootstrapChunks:e,startInlineScript:b,placeholderPrefix:w(a+"P:"),segmentPrefix:w(a+"S:"),boundaryPrefix:a+"B:",idPrefix:a,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}
function D(a,b){return{insertionMode:a,selectedValue:b}}function Aa(a){return D("http://www.w3.org/2000/svg"===a?2:"http://www.w3.org/1998/Math/MathML"===a?3:0,null)}
function Ba(a,b,c){switch(b){case "select":return D(1,null!=c.value?c.value:c.defaultValue);case "svg":return D(2,null);case "math":return D(3,null);case "foreignObject":return D(1,null);case "table":return D(4,null);case "thead":case "tbody":case "tfoot":return D(5,null);case "colgroup":return D(7,null);case "tr":return D(6,null)}return 4<=a.insertionMode||0===a.insertionMode?D(1,null):a}var Ca=w("\x3c!-- --\x3e");function Da(a,b,c,d){if(""===b)return d;d&&a.push(Ca);a.push(u(C(b)));return!0}
var Ea=new Map,Fa=w(' style="'),Ga=w(":"),Ha=w(";");
function Ia(a,b,c){if("object"!==typeof c)throw Error(k(62));b=!0;for(var d in c)if(x.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=u(C(d));f=u(C((""+f).trim()))}else{e=d;var g=Ea.get(e);void 0!==g?e=g:(g=w(C(e.replace(pa,"-$1").toLowerCase().replace(qa,"-ms-"))),Ea.set(e,g),e=g);f="number"===typeof f?0===f||x.call(B,d)?u(""+f):u(f+"px"):u(C((""+f).trim()))}b?(b=!1,a.push(Fa,e,Ga,f)):a.push(Ha,e,Ga,f)}}b||a.push(E)}
var H=w(" "),I=w('="'),E=w('"'),Ja=w('=""');
function J(a,b,c,d){switch(c){case "style":Ia(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=z.hasOwnProperty(c)?z[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=u(b.attributeName);switch(b.type){case 3:d&&a.push(H,c,Ja);break;case 4:!0===d?a.push(H,c,Ja):!1!==
d&&a.push(H,c,I,u(C(d)),E);break;case 5:isNaN(d)||a.push(H,c,I,u(C(d)),E);break;case 6:!isNaN(d)&&1<=d&&a.push(H,c,I,u(C(d)),E);break;default:b.sanitizeURL&&(d=""+d),a.push(H,c,I,u(C(d)),E)}}else if(ia(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(H,u(c),I,u(C(d)),E)}}var K=w(">"),Ka=w("/>");
function L(a,b,c){if(null!=b){if(null!=c)throw Error(k(60));if("object"!==typeof b||!("__html"in b))throw Error(k(61));b=b.__html;null!==b&&void 0!==b&&a.push(u(""+b))}}function La(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}var Ma=w(' selected=""');
function Na(a,b,c,d){a.push(M(c));var f=c=null,e;for(e in b)if(x.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:J(a,d,e,g)}}a.push(K);L(a,f,c);return"string"===typeof c?(a.push(u(C(c))),null):c}var Oa=w("\n"),Pa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Qa=new Map;function M(a){var b=Qa.get(a);if(void 0===b){if(!Pa.test(a))throw Error(k(65,a));b=w("<"+a);Qa.set(a,b)}return b}var Ra=w("<!DOCTYPE html>");
function Sa(a,b,c,d,f){switch(b){case "select":a.push(M("select"));var e=null,g=null;for(r in c)if(x.call(c,r)){var h=c[r];if(null!=h)switch(r){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:J(a,d,r,h)}}a.push(K);L(a,g,e);return e;case "option":g=f.selectedValue;a.push(M("option"));var m=h=null,q=null;var r=null;for(e in c)if(x.call(c,e)){var v=c[e];if(null!=v)switch(e){case "children":h=v;break;case "selected":q=v;break;case "dangerouslySetInnerHTML":r=
v;break;case "value":m=v;default:J(a,d,e,v)}}if(null!=g)if(c=null!==m?""+m:La(h),ra(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(Ma);break}}else""+g===c&&a.push(Ma);else q&&a.push(Ma);a.push(K);L(a,r,h);return h;case "textarea":a.push(M("textarea"));r=g=e=null;for(h in c)if(x.call(c,h)&&(m=c[h],null!=m))switch(h){case "children":r=m;break;case "value":e=m;break;case "defaultValue":g=m;break;case "dangerouslySetInnerHTML":throw Error(k(91));default:J(a,d,h,m)}null===e&&null!==g&&(e=g);a.push(K);
if(null!=r){if(null!=e)throw Error(k(92));if(ra(r)&&1<r.length)throw Error(k(93));e=""+r}"string"===typeof e&&"\n"===e[0]&&a.push(Oa);null!==e&&a.push(u(C(""+e)));return null;case "input":a.push(M("input"));m=r=h=e=null;for(g in c)if(x.call(c,g)&&(q=c[g],null!=q))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error(k(399,"input"));case "defaultChecked":m=q;break;case "defaultValue":h=q;break;case "checked":r=q;break;case "value":e=q;break;default:J(a,d,g,q)}null!==r?J(a,d,"checked",
r):null!==m&&J(a,d,"checked",m);null!==e?J(a,d,"value",e):null!==h&&J(a,d,"value",h);a.push(Ka);return null;case "menuitem":a.push(M("menuitem"));for(var A in c)if(x.call(c,A)&&(e=c[A],null!=e))switch(A){case "children":case "dangerouslySetInnerHTML":throw Error(k(400));default:J(a,d,A,e)}a.push(K);return null;case "title":a.push(M("title"));e=null;for(v in c)if(x.call(c,v)&&(g=c[v],null!=g))switch(v){case "children":e=g;break;case "dangerouslySetInnerHTML":throw Error(k(434));default:J(a,d,v,g)}a.push(K);
return e;case "listing":case "pre":a.push(M(b));g=e=null;for(m in c)if(x.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:J(a,d,m,h)}a.push(K);if(null!=g){if(null!=e)throw Error(k(60));if("object"!==typeof g||!("__html"in g))throw Error(k(61));c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push(Oa,u(c)):a.push(u(""+c)))}"string"===typeof e&&"\n"===e[0]&&a.push(Oa);return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(M(b));
for(var F in c)if(x.call(c,F)&&(e=c[F],null!=e))switch(F){case "children":case "dangerouslySetInnerHTML":throw Error(k(399,b));default:J(a,d,F,e)}a.push(Ka);return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return Na(a,c,b,d);case "html":return 0===f.insertionMode&&a.push(Ra),Na(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return Na(a,c,b,d);a.push(M(b));
g=e=null;for(q in c)if(x.call(c,q)&&(h=c[q],null!=h))switch(q){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "style":Ia(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ia(q)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(H,u(q),I,u(C(h)),E)}a.push(K);L(a,g,e);return e}}
var Ta=w("</"),Ua=w(">"),Va=w('<template id="'),Wa=w('"></template>'),Xa=w("\x3c!--$--\x3e"),Ya=w('\x3c!--$?--\x3e<template id="'),Za=w('"></template>'),$a=w("\x3c!--$!--\x3e"),ab=w("\x3c!--/$--\x3e"),bb=w("<template"),cb=w('"'),db=w(' data-dgst="');w(' data-msg="');w(' data-stck="');var eb=w("></template>");function fb(a,b,c){p(a,Ya);if(null===c)throw Error(k(395));p(a,c);return t(a,Za)}
var gb=w('<div hidden id="'),hb=w('">'),ib=w("</div>"),jb=w('<svg aria-hidden="true" style="display:none" id="'),kb=w('">'),lb=w("</svg>"),mb=w('<math aria-hidden="true" style="display:none" id="'),nb=w('">'),ob=w("</math>"),pb=w('<table hidden id="'),qb=w('">'),rb=w("</table>"),sb=w('<table hidden><tbody id="'),tb=w('">'),ub=w("</tbody></table>"),vb=w('<table hidden><tr id="'),wb=w('">'),xb=w("</tr></table>"),yb=w('<table hidden><colgroup id="'),zb=w('">'),Ab=w("</colgroup></table>");
function Bb(a,b,c,d){switch(c.insertionMode){case 0:case 1:return p(a,gb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,hb);case 2:return p(a,jb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,kb);case 3:return p(a,mb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,nb);case 4:return p(a,pb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,qb);case 5:return p(a,sb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,tb);case 6:return p(a,vb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,wb);case 7:return p(a,
yb),p(a,b.segmentPrefix),p(a,u(d.toString(16))),t(a,zb);default:throw Error(k(397));}}function Cb(a,b){switch(b.insertionMode){case 0:case 1:return t(a,ib);case 2:return t(a,lb);case 3:return t(a,ob);case 4:return t(a,rb);case 5:return t(a,ub);case 6:return t(a,xb);case 7:return t(a,Ab);default:throw Error(k(397));}}
var Db=w('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),Eb=w('$RS("'),Gb=w('","'),Hb=w('")\x3c/script>'),Ib=w('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),
Jb=w('$RC("'),Kb=w('","'),Lb=w('")\x3c/script>'),Mb=w('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),Nb=w('$RX("'),Ob=w('"'),Pb=w(")\x3c/script>"),Qb=w(","),Rb=/[<\u2028\u2029]/g;
function Sb(a){return JSON.stringify(a).replace(Rb,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}
var N=Object.assign,Tb=Symbol.for("react.element"),Ub=Symbol.for("react.portal"),Vb=Symbol.for("react.fragment"),Wb=Symbol.for("react.strict_mode"),Xb=Symbol.for("react.profiler"),Yb=Symbol.for("react.provider"),Zb=Symbol.for("react.context"),$b=Symbol.for("react.forward_ref"),ac=Symbol.for("react.suspense"),bc=Symbol.for("react.suspense_list"),cc=Symbol.for("react.memo"),dc=Symbol.for("react.lazy"),ec=Symbol.for("react.scope"),fc=Symbol.for("react.debug_trace_mode"),gc=Symbol.for("react.legacy_hidden"),
hc=Symbol.for("react.default_value"),ic=Symbol.iterator;
function jc(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Vb:return"Fragment";case Ub:return"Portal";case Xb:return"Profiler";case Wb:return"StrictMode";case ac:return"Suspense";case bc:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Zb:return(a.displayName||"Context")+".Consumer";case Yb:return(a._context.displayName||"Context")+".Provider";case $b:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case cc:return b=a.displayName||null,null!==b?b:jc(a.type)||"Memo";case dc:b=a._payload;a=a._init;try{return jc(a(b))}catch(c){}}return null}var kc={};function lc(a,b){a=a.contextTypes;if(!a)return kc;var c={},d;for(d in a)c[d]=b[d];return c}var O=null;
function P(a,b){if(a!==b){a.context._currentValue=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error(k(401));}else{if(null===c)throw Error(k(401));P(a,c)}b.context._currentValue=b.value}}function mc(a){a.context._currentValue=a.parentValue;a=a.parent;null!==a&&mc(a)}function nc(a){var b=a.parent;null!==b&&nc(b);a.context._currentValue=a.value}
function oc(a,b){a.context._currentValue=a.parentValue;a=a.parent;if(null===a)throw Error(k(402));a.depth===b.depth?P(a,b):oc(a,b)}function pc(a,b){var c=b.parent;if(null===c)throw Error(k(402));a.depth===c.depth?P(a,c):pc(a,c);b.context._currentValue=b.value}function Q(a){var b=O;b!==a&&(null===b?nc(a):null===a?mc(b):b.depth===a.depth?P(b,a):b.depth>a.depth?oc(b,a):pc(b,a),O=a)}
var qc={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}};
function rc(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=qc;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:N({},f,g),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=
a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&qc.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=N({},e,h)):N(e,h))}a.state=e}else e.queue=null}
var sc={id:1,overflow:""};function tc(a,b,c){var d=a.id;a=a.overflow;var f=32-uc(d)-1;d&=~(1<<f);c+=1;var e=32-uc(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-uc(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}var uc=Math.clz32?Math.clz32:vc,wc=Math.log,xc=Math.LN2;function vc(a){a>>>=0;return 0===a?32:31-(wc(a)/xc|0)|0}function yc(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}
var zc="function"===typeof Object.is?Object.is:yc,R=null,Ac=null,Bc=null,S=null,T=!1,Cc=!1,U=0,V=null,Dc=0;function W(){if(null===R)throw Error(k(321));return R}function Ec(){if(0<Dc)throw Error(k(312));return{memoizedState:null,queue:null,next:null}}function Fc(){null===S?null===Bc?(T=!1,Bc=S=Ec()):(T=!0,S=Bc):null===S.next?(T=!1,S=S.next=Ec()):(T=!0,S=S.next);return S}function Gc(){Ac=R=null;Cc=!1;Bc=null;Dc=0;S=V=null}function Hc(a,b){return"function"===typeof b?b(a):b}
function Ic(a,b,c){R=W();S=Fc();if(T){var d=S.queue;b=d.dispatch;if(null!==V&&(c=V.get(d),void 0!==c)){V.delete(d);d=S.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);S.memoizedState=d;return[d,b]}return[S.memoizedState,b]}a=a===Hc?"function"===typeof b?b():b:void 0!==c?c(b):b;S.memoizedState=a;a=S.queue={last:null,dispatch:null};a=a.dispatch=Jc.bind(null,R,a);return[S.memoizedState,a]}
function Kc(a,b){R=W();S=Fc();b=void 0===b?null:b;if(null!==S){var c=S.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!zc(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();S.memoizedState=[a,b];return a}function Jc(a,b,c){if(25<=Dc)throw Error(k(301));if(a===R)if(Cc=!0,a={action:c,next:null},null===V&&(V=new Map),c=V.get(b),void 0===c)V.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}
function Lc(){throw Error(k(394));}function Mc(){}
var Oc={readContext:function(a){return a._currentValue},useContext:function(a){W();return a._currentValue},useMemo:Kc,useReducer:Ic,useRef:function(a){R=W();S=Fc();var b=S.memoizedState;return null===b?(a={current:a},S.memoizedState=a):b},useState:function(a){return Ic(Hc,a)},useInsertionEffect:Mc,useLayoutEffect:function(){},useCallback:function(a,b){return Kc(function(){return a},b)},useImperativeHandle:Mc,useEffect:Mc,useDebugValue:Mc,useDeferredValue:function(a){W();return a},useTransition:function(){W();
return[!1,Lc]},useId:function(){var a=Ac.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-uc(a)-1)).toString(32)+b;var c=Nc;if(null===c)throw Error(k(404));b=U++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b){W();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error(k(407));return c()}},Nc=null,Pc=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function Qc(a){console.error(a);return null}
function X(){}
function Rc(a,b,c,d,f,e,g,h,m){var q=[],r=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:r,pingedTasks:q,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?Qc:f,onAllReady:void 0===e?X:e,onShellReady:void 0===g?X:g,onShellError:void 0===h?X:h,onFatalError:void 0===m?X:m};c=Sc(b,0,null,c,!1,!1);c.parentFlushed=
!0;a=Tc(b,a,null,c,r,kc,null,sc);q.push(a);return b}function Tc(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var m={node:b,ping:function(){var b=a.pingedTasks;b.push(m);1===b.length&&Uc(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(m);return m}function Sc(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}
function Y(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function Vc(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,da(a.destination,b)):(a.status=1,a.fatalError=b)}
function Wc(a,b,c,d,f){R={};Ac=b;U=0;for(a=c(d,f);Cc;)Cc=!1,U=0,Dc+=1,S=null,a=c(d,f);Gc();return a}function Xc(a,b,c,d){var f=c.render(),e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error(k(108,jc(d)||"Unknown",h));d=N({},g,c)}b.legacyContext=d;Z(a,b,f);b.legacyContext=g}else Z(a,b,f)}
function Yc(a,b){if(a&&a.defaultProps){b=N({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}
function Zc(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=lc(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue:f);rc(e,c,d,f);Xc(a,b,e,c)}else{e=lc(c,b.legacyContext);f=Wc(a,b,c,d,e);var g=0!==U;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)rc(f,c,d,e),Xc(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=tc(d,1,0);try{Z(a,b,f)}finally{b.treeContext=d}}else Z(a,b,f)}else if("string"===
typeof c){f=b.blockedSegment;e=Sa(f.chunks,c,d,a.responseState,f.formatContext);f.lastPushedText=!1;g=f.formatContext;f.formatContext=Ba(g,c,d);$c(a,b,e);f.formatContext=g;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push(Ta,u(c),Ua)}f.lastPushedText=!1}else{switch(c){case gc:case fc:case Wb:case Xb:case Vb:Z(a,b,d.children);return;
case bc:Z(a,b,d.children);return;case ec:throw Error(k(343));case ac:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null},m=Sc(a,f.chunks.length,h,f.formatContext,!1,!1);f.children.push(m);f.lastPushedText=!1;var q=Sc(a,0,null,f.formatContext,!1,!1);q.parentFlushed=!0;b.blockedBoundary=h;b.blockedSegment=q;try{if($c(a,
b,d),q.lastPushedText&&q.textEmbedded&&q.chunks.push(Ca),q.status=1,ad(h,q),0===h.pendingTasks)break a}catch(r){q.status=4,h.forceClientRender=!0,h.errorDigest=Y(a,r)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=Tc(a,e,c,m,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case $b:d=Wc(a,b,c.render,d,f);if(0!==U){c=b.treeContext;b.treeContext=tc(c,1,0);try{Z(a,b,d)}finally{b.treeContext=c}}else Z(a,b,d);return;case cc:c=
c.type;d=Yc(c,d);Zc(a,b,c,d,f);return;case Yb:f=d.children;c=c._context;d=d.value;e=c._currentValue;c._currentValue=d;g=O;O=d={parent:g,depth:null===g?0:g.depth+1,context:c,parentValue:e,value:d};b.context=d;Z(a,b,f);a=O;if(null===a)throw Error(k(403));d=a.parentValue;a.context._currentValue=d===hc?a.context._defaultValue:d;a=O=a.parent;b.context=a;return;case Zb:d=d.children;d=d(c._currentValue);Z(a,b,d);return;case dc:f=c._init;c=f(c._payload);d=Yc(c,d);Zc(a,b,c,d,void 0);return}throw Error(k(130,
null==c?c:typeof c,""));}}
function Z(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Tb:Zc(a,b,c.type,c.props,c.ref);return;case Ub:throw Error(k(257));case dc:var d=c._init;c=d(c._payload);Z(a,b,c);return}if(ra(c)){bd(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=ic&&c[ic]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=[];do f.push(c.value),c=d.next();while(!c.done);bd(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error(k(31,"[object Object]"===
a?"object with keys {"+Object.keys(c).join(", ")+"}":a));}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=Da(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=Da(b.blockedSegment.chunks,""+c,a.responseState,d.lastPushedText))}function bd(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=tc(e,d,f);try{$c(a,b,c[f])}finally{b.treeContext=e}}}
function $c(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return Z(a,b,c)}catch(m){if(Gc(),"object"===typeof m&&null!==m&&"function"===typeof m.then){c=m;var g=b.blockedSegment,h=Sc(a,g.chunks.length,null,g.formatContext,g.lastPushedText,!0);g.children.push(h);g.lastPushedText=!1;a=Tc(a,b.node,b.blockedBoundary,h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;Q(e)}else throw b.blockedSegment.formatContext=
d,b.legacyContext=f,b.context=e,Q(e),m;}}function cd(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;dd(this,b,a)}
function ed(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.close())):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,a=void 0===c?Error(k(432)):c,d.errorDigest=b.onError(a),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return ed(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,0===b.allPendingTasks&&(d=b.onAllReady,d()))}
function ad(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&ad(a,c)}else a.completedSegments.push(b)}
function dd(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error(k(389));a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=X,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&ad(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(cd,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&1===c.status&&(ad(b,c),1===b.completedSegments.length&&
b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}
function Uc(a){if(2!==a.status){var b=O,c=Pc.current;Pc.current=Oc;var d=Nc;Nc=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,m=g.blockedSegment;if(0===m.status){Q(g.context);try{Z(h,g,g.node),m.lastPushedText&&m.textEmbedded&&m.chunks.push(Ca),g.abortSet.delete(g),m.status=1,dd(h,g.blockedBoundary,m)}catch(G){if(Gc(),"object"===typeof G&&null!==G&&"function"===typeof G.then){var q=g.ping;G.then(q,q)}else{g.abortSet.delete(g);m.status=4;var r=g.blockedBoundary,
v=G,A=Y(h,v);null===r?Vc(h,v):(r.pendingTasks--,r.forceClientRender||(r.forceClientRender=!0,r.errorDigest=A,r.parentFlushed&&h.clientRenderedBoundaries.push(r)));h.allPendingTasks--;if(0===h.allPendingTasks){var F=h.onAllReady;F()}}}finally{}}}f.splice(0,e);null!==a.destination&&fd(a,a.destination)}catch(G){Y(a,G),Vc(a,G)}finally{Nc=d,Pc.current=c,c===Oc&&Q(b)}}}
function gd(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;p(b,Va);p(b,a.placeholderPrefix);a=u(d.toString(16));p(b,a);return t(b,Wa);case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)p(b,d[e]);f=hd(a,b,f)}for(;e<d.length-1;e++)p(b,d[e]);e<d.length&&(f=t(b,d[e]));return f;default:throw Error(k(390));}}
function hd(a,b,c){var d=c.boundary;if(null===d)return gd(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)d=d.errorDigest,t(b,$a),p(b,bb),d&&(p(b,db),p(b,u(C(d))),p(b,cb)),t(b,eb),gd(a,b,c);else if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;var e=f.nextSuspenseID++;f=w(f.boundaryPrefix+e.toString(16));d=d.id=f;fb(b,a.responseState,d);gd(a,b,c)}else if(d.byteSize>a.progressiveChunkSize)d.rootSegmentID=a.nextSegmentId++,
a.completedBoundaries.push(d),fb(b,a.responseState,d.id),gd(a,b,c);else{t(b,Xa);c=d.completedSegments;if(1!==c.length)throw Error(k(391));hd(a,b,c[0])}return t(b,ab)}function id(a,b,c){Bb(b,a.responseState,c.formatContext,c.id);hd(a,b,c);return Cb(b,c.formatContext)}
function jd(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)kd(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;p(b,a.startInlineScript);a.sentCompleteBoundaryFunction?p(b,Jb):(a.sentCompleteBoundaryFunction=!0,p(b,Ib));if(null===d)throw Error(k(395));c=u(c.toString(16));p(b,d);p(b,Kb);p(b,a.segmentPrefix);p(b,c);return t(b,Lb)}
function kd(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error(k(392));return id(a,b,d)}id(a,b,d);a=a.responseState;p(b,a.startInlineScript);a.sentCompleteSegmentFunction?p(b,Eb):(a.sentCompleteSegmentFunction=!0,p(b,Db));p(b,a.segmentPrefix);f=u(f.toString(16));p(b,f);p(b,Gb);p(b,a.placeholderPrefix);p(b,f);return t(b,Hb)}
function fd(a,b){l=new Uint8Array(512);n=0;try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){hd(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)p(b,d[c]);c<d.length&&t(b,d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var h=a.responseState,m=g.id,q=g.errorDigest,r=g.errorMessage,v=g.errorComponentStack;p(d,h.startInlineScript);h.sentClientRenderFunction?p(d,Nb):(h.sentClientRenderFunction=!0,p(d,
Mb));if(null===m)throw Error(k(395));p(d,m);p(d,Ob);if(q||r||v)p(d,Qb),p(d,u(Sb(q||"")));if(r||v)p(d,Qb),p(d,u(Sb(r||"")));v&&(p(d,Qb),p(d,u(Sb(v))));if(!t(d,Pb)){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e);var A=a.completedBoundaries;for(e=0;e<A.length;e++)if(!jd(a,b,A[e])){a.destination=null;e++;A.splice(0,e);return}A.splice(0,e);ba(b);l=new Uint8Array(512);n=0;var F=a.partialBoundaries;for(e=0;e<F.length;e++){var G=F[e];a:{f=a;g=b;var ma=G.completedSegments;for(h=0;h<ma.length;h++)if(!kd(f,
g,G,ma[h])){h++;ma.splice(0,h);var Fb=!1;break a}ma.splice(0,h);Fb=!0}if(!Fb){a.destination=null;e++;F.splice(0,e);return}}F.splice(0,e);var na=a.completedBoundaries;for(e=0;e<na.length;e++)if(!jd(a,b,na[e])){a.destination=null;e++;na.splice(0,e);return}na.splice(0,e)}finally{ba(b),0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&b.close()}}
function ld(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return ed(c,a,b)});c.clear();null!==a.destination&&fd(a,a.destination)}catch(d){Y(a,d),Vc(a,d)}}
exports.renderToReadableStream=function(a,b){return new Promise(function(c,d){var f,e,g=new Promise(function(a,b){e=a;f=b}),h=Rc(a,za(b?b.identifierPrefix:void 0,b?b.nonce:void 0,b?b.bootstrapScriptContent:void 0,b?b.bootstrapScripts:void 0,b?b.bootstrapModules:void 0),Aa(b?b.namespaceURI:void 0),b?b.progressiveChunkSize:void 0,b?b.onError:void 0,e,function(){var a=new ReadableStream({type:"bytes",pull:function(a){if(1===h.status)h.status=2,da(a,h.fatalError);else if(2!==h.status&&null===h.destination){h.destination=
a;try{fd(h,a)}catch(A){Y(h,A),Vc(h,A)}}},cancel:function(){ld(h)}},{highWaterMark:0});a.allReady=g;c(a)},function(a){g.catch(function(){});d(a)},f);if(b&&b.signal){var m=b.signal,q=function(){ld(h,m.reason);m.removeEventListener("abort",q)};m.addEventListener("abort",q)}Uc(h)})};exports.version="18.3.1";
/**
 * @license React
 * react-dom-server.node.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');
var util = require('util');

var ReactVersion = '18.3.1';

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

function scheduleWork(callback) {
  setImmediate(callback);
}
function flushBuffered(destination) {
  // If we don't have any more data to send right now.
  // Flush whatever is in the buffer to the wire.
  if (typeof destination.flush === 'function') {
    // By convention the Zlib streams provide a flush function for this purpose.
    // For Express, compression middleware adds this method.
    destination.flush();
  }
}
var VIEW_SIZE = 2048;
var currentView = null;
var writtenBytes = 0;
var destinationHasCapacity = true;
function beginWriting(destination) {
  currentView = new Uint8Array(VIEW_SIZE);
  writtenBytes = 0;
  destinationHasCapacity = true;
}

function writeStringChunk(destination, stringChunk) {
  if (stringChunk.length === 0) {
    return;
  } // maximum possible view needed to encode entire string


  if (stringChunk.length * 3 > VIEW_SIZE) {
    if (writtenBytes > 0) {
      writeToDestination(destination, currentView.subarray(0, writtenBytes));
      currentView = new Uint8Array(VIEW_SIZE);
      writtenBytes = 0;
    }

    writeToDestination(destination, textEncoder.encode(stringChunk));
    return;
  }

  var target = currentView;

  if (writtenBytes > 0) {
    target = currentView.subarray(writtenBytes);
  }

  var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target),
      read = _textEncoder$encodeIn.read,
      written = _textEncoder$encodeIn.written;

  writtenBytes += written;

  if (read < stringChunk.length) {
    writeToDestination(destination, currentView);
    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written;
  }

  if (writtenBytes === VIEW_SIZE) {
    writeToDestination(destination, currentView);
    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = 0;
  }
}

function writeViewChunk(destination, chunk) {
  if (chunk.byteLength === 0) {
    return;
  }

  if (chunk.byteLength > VIEW_SIZE) {
    // this chunk may overflow a single view which implies it was not
    // one that is cached by the streaming renderer. We will enqueu
    // it directly and expect it is not re-used
    if (writtenBytes > 0) {
      writeToDestination(destination, currentView.subarray(0, writtenBytes));
      currentView = new Uint8Array(VIEW_SIZE);
      writtenBytes = 0;
    }

    writeToDestination(destination, chunk);
    return;
  }

  var bytesToWrite = chunk;
  var allowableBytes = currentView.length - writtenBytes;

  if (allowableBytes < bytesToWrite.byteLength) {
    // this chunk would overflow the current view. We enqueue a full view
    // and start a new view with the remaining chunk
    if (allowableBytes === 0) {
      // the current view is already full, send it
      writeToDestination(destination, currentView);
    } else {
      // fill up the current view and apply the remaining chunk bytes
      // to a new view.
      currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes);
      writtenBytes += allowableBytes;
      writeToDestination(destination, currentView);
      bytesToWrite = bytesToWrite.subarray(allowableBytes);
    }

    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = 0;
  }

  currentView.set(bytesToWrite, writtenBytes);
  writtenBytes += bytesToWrite.byteLength;

  if (writtenBytes === VIEW_SIZE) {
    writeToDestination(destination, currentView);
    currentView = new Uint8Array(VIEW_SIZE);
    writtenBytes = 0;
  }
}

function writeChunk(destination, chunk) {
  if (typeof chunk === 'string') {
    writeStringChunk(destination, chunk);
  } else {
    writeViewChunk(destination, chunk);
  }
}

function writeToDestination(destination, view) {
  var currentHasCapacity = destination.write(view);
  destinationHasCapacity = destinationHasCapacity && currentHasCapacity;
}

function writeChunkAndReturn(destination, chunk) {
  writeChunk(destination, chunk);
  return destinationHasCapacity;
}
function completeWriting(destination) {
  if (currentView && writtenBytes > 0) {
    destination.write(currentView.subarray(0, writtenBytes));
  }

  currentView = null;
  writtenBytes = 0;
  destinationHasCapacity = true;
}
function close(destination) {
  destination.end();
}
var textEncoder = new util.TextEncoder();
function stringToChunk(content) {
  return content;
}
function stringToPrecomputedChunk(content) {
  return textEncoder.encode(content);
}
function closeWithError(destination, error) {
  // $FlowFixMe: This is an Error object or the destination accepts other types.
  destination.destroy(error);
}

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}

function checkAttributeStringCoercion(value, attributeName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkCSSPropertyStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkHtmlStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.

var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.

var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.

var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.

var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.

var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.

var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */

var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }

  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }

  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }

  illegalAttributeNameCache[attributeName] = true;

  {
    error('Invalid attribute name: `%s`', attributeName);
  }

  return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }

  switch (typeof value) {
    case 'function': // $FlowIssue symbol is perfectly valid here

    case 'symbol':
      // eslint-disable-line
      return true;

    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }

        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }

    default:
      return false;
  }
}
function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
  this.sanitizeURL = sanitizeURL;
  this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.


var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

reservedProps.forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.

[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).

['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.

['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML boolean attributes.

['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.

['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.

['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be positive numbers.

['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be numbers.

['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
});
var CAMELIZE = /[\-\:]([a-z])/g;

var capitalize = function (token) {
  return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.


['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // String SVG attributes with the xlink namespace.

['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  false);
}); // String SVG attributes with the xml namespace.

['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.

['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.

var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  true, // sanitizeURL
  true);
});

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  aspectRatio: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */

function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */


var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.

Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

var hasReadOnlyValue = {
  button: true,
  checkbox: true,
  image: true,
  hidden: true,
  radio: true,
  reset: true,
  submit: true
};
function checkControlledValueProps(tagName, props) {
  {
    if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
      error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }

    if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
      error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  }
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }

  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this list too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;

    default:
      return true;
  }
}

var ariaProperties = {
  'aria-current': 0,
  // state
  'aria-description': 0,
  'aria-details': 0,
  'aria-disabled': 0,
  // state
  'aria-hidden': 0,
  // state
  'aria-invalid': 0,
  // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

function validateProperty(tagName, name) {
  {
    if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
      return true;
    }

    if (rARIACamel.test(name)) {
      var ariaName = 'aria-' + name.slice(4).toLowerCase();
      var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (correctName == null) {
        error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

        warnedProperties[name] = true;
        return true;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== correctName) {
        error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

        warnedProperties[name] = true;
        return true;
      }
    }

    if (rARIA.test(name)) {
      var lowerCasedName = name.toLowerCase();
      var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (standardName == null) {
        warnedProperties[name] = true;
        return false;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== standardName) {
        error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties[name] = true;
        return true;
      }
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  {
    var invalidProps = [];

    for (var key in props) {
      var isValid = validateProperty(type, key);

      if (!isValid) {
        invalidProps.push(key);
      }
    }

    var unknownPropString = invalidProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (invalidProps.length === 1) {
      error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    } else if (invalidProps.length > 1) {
      error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    }
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;
function validateProperties$1(type, props) {
  {
    if (type !== 'input' && type !== 'textarea' && type !== 'select') {
      return;
    }

    if (props != null && props.value === null && !didWarnValueNull) {
      didWarnValueNull = true;

      if (type === 'select' && props.multiple) {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
      } else {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
      }
    }
  }
}

// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  disablepictureinpicture: 'disablePictureInPicture',
  disableremoteplayback: 'disableRemotePlayback',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  enterkeyhint: 'enterKeyHint',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  imagesizes: 'imageSizes',
  imagesrcset: 'imageSrcSet',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',
  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, eventRegistry) {
    if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();

    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

      warnedProperties$1[name] = true;
      return true;
    } // We can't rely on the event system being injected on the server.


    if (eventRegistry != null) {
      var registrationNameDependencies = eventRegistry.registrationNameDependencies,
          possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

      if (registrationNameDependencies.hasOwnProperty(name)) {
        return true;
      }

      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

      if (registrationName != null) {
        error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (EVENT_NAME_REGEX.test(name)) {
        error('Unknown event handler property `%s`. It will be ignored.', name);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Let the ARIA attribute hook validate ARIA attributes


    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];

      if (standardName !== name) {
        error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
      } else {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Now that we've validated casing, do not validate
    // data types for reserved props


    if (isReserved) {
      return true;
    } // Warn when a known attribute is a bad type


    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    } // Warn when passing the strings 'false' or 'true' into a boolean prop


    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
      error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

      warnedProperties$1[name] = true;
      return true;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, eventRegistry) {
  {
    var unknownProps = [];

    for (var key in props) {
      var isValid = validateProperty$1(type, key, props[key], eventRegistry);

      if (!isValid) {
        unknownProps.push(key);
      }
    }

    var unknownPropString = unknownProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (unknownProps.length === 1) {
      error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    } else if (unknownProps.length > 1) {
      error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    }
  }
};

function validateProperties$2(type, props, eventRegistry) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnUnknownProperties(type, props, eventRegistry);
}

var warnValidStyle = function () {};

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

  var badStyleValueWithSemicolonPattern = /;\s*$/;
  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var camelize = function (string) {
    return string.replace(hyphenPattern, function (_, character) {
      return character.toUpperCase();
    });
  };

  var warnHyphenatedStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
    // is converted to lowercase `ms`.
    camelize(name.replace(msPattern, 'ms-')));
  };

  var warnBadVendoredStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
  };

  var warnStyleValueWithSemicolon = function (name, value) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;

    error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
  };

  var warnStyleValueIsNaN = function (name, value) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;

    error('`NaN` is an invalid value for the `%s` css style property.', name);
  };

  var warnStyleValueIsInfinity = function (name, value) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;

    error('`Infinity` is an invalid value for the `%s` css style property.', name);
  };

  warnValidStyle = function (name, value) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

// code copied and modified from escape-html
var matchHtmlRegExp = /["'&<>]/;
/**
 * Escapes special characters and HTML entities in a given html string.
 *
 * @param  {string} string HTML string to escape for later insertion
 * @return {string}
 * @public
 */

function escapeHtml(string) {
  {
    checkHtmlStringCoercion(string);
  }

  var str = '' + string;
  var match = matchHtmlRegExp.exec(str);

  if (!match) {
    return str;
  }

  var escape;
  var html = '';
  var index;
  var lastIndex = 0;

  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        // "
        escape = '&quot;';
        break;

      case 38:
        // &
        escape = '&amp;';
        break;

      case 39:
        // '
        escape = '&#x27;'; // modified from escape-html; used to be '&#39'

        break;

      case 60:
        // <
        escape = '&lt;';
        break;

      case 62:
        // >
        escape = '&gt;';
        break;

      default:
        continue;
    }

    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }

    lastIndex = index + 1;
    html += escape;
  }

  return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
} // end code copied and modified from escape-html

/**
 * Escapes text to prevent scripting attacks.
 *
 * @param {*} text Text value to escape.
 * @return {string} An escaped string.
 */


function escapeTextForBrowser(text) {
  if (typeof text === 'boolean' || typeof text === 'number') {
    // this shortcircuit helps perf for types that we know will never have
    // special characters, especially given that this function is used often
    // for numeric dom ids.
    return '' + text;
  }

  return escapeHtml(text);
}

var uppercasePattern = /([A-Z])/g;
var msPattern$1 = /^ms-/;
/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */

function hyphenateStyleName(name) {
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
}

// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space

/* eslint-disable max-len */

var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;

function sanitizeURL(url) {
  {
    if (!didWarn && isJavaScriptProtocol.test(url)) {
      didWarn = true;

      error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
    }
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var startInlineScript = stringToPrecomputedChunk('<script>');
var endInlineScript = stringToPrecomputedChunk('</script>');
var startScriptSrc = stringToPrecomputedChunk('<script src="');
var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
/**
 * This escaping function is designed to work with bootstrapScriptContent only.
 * because we know we are escaping the entire script. We can avoid for instance
 * escaping html comment string sequences that are valid javascript as well because
 * if there are no sebsequent <script sequences the html parser will never enter
 * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
 *
 * While untrusted script content should be made safe before using this api it will
 * ensure that the script cannot be early terminated or never terminated state
 */

function escapeBootstrapScriptContent(scriptText) {
  {
    checkHtmlStringCoercion(scriptText);
  }

  return ('' + scriptText).replace(scriptRegex, scriptReplacer);
}

var scriptRegex = /(<\/|<)(s)(cript)/gi;

var scriptReplacer = function (match, prefix, s, suffix) {
  return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
}; // Allows us to keep track of what we've already written so we can refer back to it.


function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
  var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
  var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
  var bootstrapChunks = [];

  if (bootstrapScriptContent !== undefined) {
    bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeBootstrapScriptContent(bootstrapScriptContent)), endInlineScript);
  }

  if (bootstrapScripts !== undefined) {
    for (var i = 0; i < bootstrapScripts.length; i++) {
      bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
    }
  }

  if (bootstrapModules !== undefined) {
    for (var _i = 0; _i < bootstrapModules.length; _i++) {
      bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
    }
  }

  return {
    bootstrapChunks: bootstrapChunks,
    startInlineScript: inlineScriptWithNonce,
    placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
    segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
    boundaryPrefix: idPrefix + 'B:',
    idPrefix: idPrefix,
    nextSuspenseID: 0,
    sentCompleteSegmentFunction: false,
    sentCompleteBoundaryFunction: false,
    sentClientRenderFunction: false
  };
} // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
// modes. We only include the variants as they matter for the sake of our purposes.
// We don't actually provide the namespace therefore we use constants instead of the string.

var ROOT_HTML_MODE = 0; // Used for the root most element tag.

var HTML_MODE = 1;
var SVG_MODE = 2;
var MATHML_MODE = 3;
var HTML_TABLE_MODE = 4;
var HTML_TABLE_BODY_MODE = 5;
var HTML_TABLE_ROW_MODE = 6;
var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
// still makes sense

function createFormatContext(insertionMode, selectedValue) {
  return {
    insertionMode: insertionMode,
    selectedValue: selectedValue
  };
}

function createRootFormatContext(namespaceURI) {
  var insertionMode = namespaceURI === 'http://www.w3.org/2000/svg' ? SVG_MODE : namespaceURI === 'http://www.w3.org/1998/Math/MathML' ? MATHML_MODE : ROOT_HTML_MODE;
  return createFormatContext(insertionMode, null);
}
function getChildFormatContext(parentContext, type, props) {
  switch (type) {
    case 'select':
      return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);

    case 'svg':
      return createFormatContext(SVG_MODE, null);

    case 'math':
      return createFormatContext(MATHML_MODE, null);

    case 'foreignObject':
      return createFormatContext(HTML_MODE, null);
    // Table parents are special in that their children can only be created at all if they're
    // wrapped in a table parent. So we need to encode that we're entering this mode.

    case 'table':
      return createFormatContext(HTML_TABLE_MODE, null);

    case 'thead':
    case 'tbody':
    case 'tfoot':
      return createFormatContext(HTML_TABLE_BODY_MODE, null);

    case 'colgroup':
      return createFormatContext(HTML_COLGROUP_MODE, null);

    case 'tr':
      return createFormatContext(HTML_TABLE_ROW_MODE, null);
  }

  if (parentContext.insertionMode >= HTML_TABLE_MODE) {
    // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
    // entered plain HTML again.
    return createFormatContext(HTML_MODE, null);
  }

  if (parentContext.insertionMode === ROOT_HTML_MODE) {
    // We've emitted the root and is now in plain HTML mode.
    return createFormatContext(HTML_MODE, null);
  }

  return parentContext;
}
var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
function assignSuspenseBoundaryID(responseState) {
  var generatedID = responseState.nextSuspenseID++;
  return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
}
function makeId(responseState, treeId, localId) {
  var idPrefix = responseState.idPrefix;
  var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
  // that represents the position of this useId hook among all the useId
  // hooks for this fiber.

  if (localId > 0) {
    id += 'H' + localId.toString(32);
  }

  return id + ':';
}

function encodeHTMLTextNode(text) {
  return escapeTextForBrowser(text);
}

var textSeparator = stringToPrecomputedChunk('<!-- -->');
function pushTextInstance(target, text, responseState, textEmbedded) {
  if (text === '') {
    // Empty text doesn't have a DOM node representation and the hydration is aware of this.
    return textEmbedded;
  }

  if (textEmbedded) {
    target.push(textSeparator);
  }

  target.push(stringToChunk(encodeHTMLTextNode(text)));
  return true;
} // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
// emit a text separator when we don't know for sure it is safe to omit

function pushSegmentFinale(target, responseState, lastPushedText, textEmbedded) {
  if (lastPushedText && textEmbedded) {
    target.push(textSeparator);
  }
}
var styleNameCache = new Map();

function processStyleName(styleName) {
  var chunk = styleNameCache.get(styleName);

  if (chunk !== undefined) {
    return chunk;
  }

  var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
  styleNameCache.set(styleName, result);
  return result;
}

var styleAttributeStart = stringToPrecomputedChunk(' style="');
var styleAssign = stringToPrecomputedChunk(':');
var styleSeparator = stringToPrecomputedChunk(';');

function pushStyle(target, responseState, style) {
  if (typeof style !== 'object') {
    throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
  }

  var isFirst = true;

  for (var styleName in style) {
    if (!hasOwnProperty.call(style, styleName)) {
      continue;
    } // If you provide unsafe user data here they can inject arbitrary CSS
    // which may be problematic (I couldn't repro this):
    // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
    // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
    // This is not an XSS hole but instead a potential CSS injection issue
    // which has lead to a greater discussion about how we're going to
    // trust URLs moving forward. See #2115901


    var styleValue = style[styleName];

    if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
      // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
      continue;
    }

    var nameChunk = void 0;
    var valueChunk = void 0;
    var isCustomProperty = styleName.indexOf('--') === 0;

    if (isCustomProperty) {
      nameChunk = stringToChunk(escapeTextForBrowser(styleName));

      {
        checkCSSPropertyStringCoercion(styleValue, styleName);
      }

      valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
    } else {
      {
        warnValidStyle$1(styleName, styleValue);
      }

      nameChunk = processStyleName(styleName);

      if (typeof styleValue === 'number') {
        if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
          valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
        } else {
          valueChunk = stringToChunk('' + styleValue);
        }
      } else {
        {
          checkCSSPropertyStringCoercion(styleValue, styleName);
        }

        valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
      }
    }

    if (isFirst) {
      isFirst = false; // If it's first, we don't need any separators prefixed.

      target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
    } else {
      target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
    }
  }

  if (!isFirst) {
    target.push(attributeEnd);
  }
}

var attributeSeparator = stringToPrecomputedChunk(' ');
var attributeAssign = stringToPrecomputedChunk('="');
var attributeEnd = stringToPrecomputedChunk('"');
var attributeEmptyString = stringToPrecomputedChunk('=""');

function pushAttribute(target, responseState, name, value) {
  switch (name) {
    case 'style':
      {
        pushStyle(target, responseState, value);
        return;
      }

    case 'defaultValue':
    case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.

    case 'innerHTML': // Must use dangerouslySetInnerHTML instead.

    case 'suppressContentEditableWarning':
    case 'suppressHydrationWarning':
      // Ignored. These are built-in to React on the client.
      return;
  }

  if ( // shouldIgnoreAttribute
  // We have already filtered out null/undefined and reserved words.
  name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return;
  }

  var propertyInfo = getPropertyInfo(name);

  if (propertyInfo !== null) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          if (!propertyInfo.acceptsBooleans) {
            return;
          }
        }
    }

    var attributeName = propertyInfo.attributeName;
    var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.

    switch (propertyInfo.type) {
      case BOOLEAN:
        if (value) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        }

        return;

      case OVERLOADED_BOOLEAN:
        if (value === true) {
          target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
        } else if (value === false) ; else {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        return;

      case NUMERIC:
        if (!isNaN(value)) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      case POSITIVE_NUMERIC:
        if (!isNaN(value) && value >= 1) {
          target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
        }

        break;

      default:
        if (propertyInfo.sanitizeURL) {
          {
            checkAttributeStringCoercion(value, attributeName);
          }

          value = '' + value;
          sanitizeURL(value);
        }

        target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
    }
  } else if (isAttributeNameSafe(name)) {
    // shouldRemoveAttribute
    switch (typeof value) {
      case 'function': // $FlowIssue symbol is perfectly valid here

      case 'symbol':
        // eslint-disable-line
        return;

      case 'boolean':
        {
          var prefix = name.toLowerCase().slice(0, 5);

          if (prefix !== 'data-' && prefix !== 'aria-') {
            return;
          }
        }
    }

    target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
  }
}

var endOfStartTag = stringToPrecomputedChunk('>');
var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');

function pushInnerHTML(target, innerHTML, children) {
  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      {
        checkHtmlStringCoercion(html);
      }

      target.push(stringToChunk('' + html));
    }
  }
} // TODO: Move these to ResponseState so that we warn for every request.
// It would help debugging in stateful servers (e.g. service worker).


var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnInvalidOptionInnerHTML = false;
var didWarnSelectedSetOnOption = false;

function checkSelectProp(props, propName) {
  {
    var value = props[propName];

    if (value != null) {
      var array = isArray(value);

      if (props.multiple && !array) {
        error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
      } else if (!props.multiple && array) {
        error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
      }
    }
  }
}

function pushStartSelect(target, props, responseState) {
  {
    checkControlledValueProps('select', props);
    checkSelectProp(props, 'value');
    checkSelectProp(props, 'defaultValue');

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
      error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultSelectValue = true;
    }
  }

  target.push(startChunkForTag('select'));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          // TODO: This doesn't really make sense for select since it can't use the controlled
          // value in the innerHTML.
          innerHTML = propValue;
          break;

        case 'defaultValue':
        case 'value':
          // These are set on the Context instead and applied to the nested options.
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function flattenOptionChildren(children) {
  var content = ''; // Flatten children and warn if they aren't strings or numbers;
  // invalid types are ignored.

  React.Children.forEach(children, function (child) {
    if (child == null) {
      return;
    }

    content += child;

    {
      if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
        didWarnInvalidOptionChildren = true;

        error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
      }
    }
  });
  return content;
}

var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');

function pushStartOption(target, props, responseState, formatContext) {
  var selectedValue = formatContext.selectedValue;
  target.push(startChunkForTag('option'));
  var children = null;
  var value = null;
  var selected = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'selected':
          // ignore
          selected = propValue;

          {
            // TODO: Remove support for `selected` in <option>.
            if (!didWarnSelectedSetOnOption) {
              error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

              didWarnSelectedSetOnOption = true;
            }
          }

          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;
        // eslint-disable-next-line-no-fallthrough

        case 'value':
          value = propValue;
        // We intentionally fallthrough to also set the attribute on the node.
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (selectedValue != null) {
    var stringValue;

    if (value !== null) {
      {
        checkAttributeStringCoercion(value, 'value');
      }

      stringValue = '' + value;
    } else {
      {
        if (innerHTML !== null) {
          if (!didWarnInvalidOptionInnerHTML) {
            didWarnInvalidOptionInnerHTML = true;

            error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
          }
        }
      }

      stringValue = flattenOptionChildren(children);
    }

    if (isArray(selectedValue)) {
      // multiple
      for (var i = 0; i < selectedValue.length; i++) {
        {
          checkAttributeStringCoercion(selectedValue[i], 'value');
        }

        var v = '' + selectedValue[i];

        if (v === stringValue) {
          target.push(selectedMarkerAttribute);
          break;
        }
      }
    } else {
      {
        checkAttributeStringCoercion(selectedValue, 'select.value');
      }

      if ('' + selectedValue === stringValue) {
        target.push(selectedMarkerAttribute);
      }
    }
  } else if (selected) {
    target.push(selectedMarkerAttribute);
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

function pushInput(target, props, responseState) {
  {
    checkControlledValueProps('input', props);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
      error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultChecked = true;
    }

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
      error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type);

      didWarnDefaultInputValue = true;
    }
  }

  target.push(startChunkForTag('input'));
  var value = null;
  var defaultValue = null;
  var checked = null;
  var defaultChecked = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        case 'defaultChecked':
          defaultChecked = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'checked':
          checked = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (checked !== null) {
    pushAttribute(target, responseState, 'checked', checked);
  } else if (defaultChecked !== null) {
    pushAttribute(target, responseState, 'checked', defaultChecked);
  }

  if (value !== null) {
    pushAttribute(target, responseState, 'value', value);
  } else if (defaultValue !== null) {
    pushAttribute(target, responseState, 'value', defaultValue);
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartTextArea(target, props, responseState) {
  {
    checkControlledValueProps('textarea', props);

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
      error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnDefaultTextareaValue = true;
    }
  }

  target.push(startChunkForTag('textarea'));
  var value = null;
  var defaultValue = null;
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'value':
          value = propValue;
          break;

        case 'defaultValue':
          defaultValue = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  if (value === null && defaultValue !== null) {
    value = defaultValue;
  }

  target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.

  if (children != null) {
    {
      error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
    }

    if (value != null) {
      throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
    }

    if (isArray(children)) {
      if (children.length > 1) {
        throw new Error('<textarea> can only have at most one child.');
      } // TODO: remove the coercion and the DEV check below because it will
      // always be overwritten by the coercion several lines below it. #22309


      {
        checkHtmlStringCoercion(children[0]);
      }

      value = '' + children[0];
    }

    {
      checkHtmlStringCoercion(children);
    }

    value = '' + children;
  }

  if (typeof value === 'string' && value[0] === '\n') {
    // text/html ignores the first character in these tags if it's a newline
    // Prefer to break application/xml over text/html (for now) by adding
    // a newline specifically to get eaten by the parser. (Alternately for
    // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
    // \r is normalized out by HTMLTextAreaElement#value.)
    // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
    // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
    // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
    // See: Parsing of "textarea" "listing" and "pre" elements
    //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
    target.push(leadingNewline);
  } // ToString and push directly instead of recurse over children.
  // We don't really support complex children in the value anyway.
  // This also currently avoids a trailing comment node which breaks textarea.


  if (value !== null) {
    {
      checkAttributeStringCoercion(value, 'value');
    }

    target.push(stringToChunk(encodeHTMLTextNode('' + value)));
  }

  return null;
}

function pushSelfClosing(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTagSelfClosing);
  return null;
}

function pushStartMenuItem(target, props, responseState) {
  target.push(startChunkForTag('menuitem'));

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
        case 'dangerouslySetInnerHTML':
          throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  return null;
}

function pushStartTitle(target, props, responseState) {
  target.push(startChunkForTag('title'));
  var children = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          throw new Error('`dangerouslySetInnerHTML` does not make sense on <title>.');
        // eslint-disable-next-line-no-fallthrough

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);

  {
    var child = Array.isArray(children) && children.length < 2 ? children[0] || null : children;

    if (Array.isArray(children) && children.length > 1) {
      error('A title element received an array with more than 1 element as children. ' + 'In browsers title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && child.$$typeof != null) {
      error('A title element received a React element for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    } else if (child != null && typeof child !== 'string' && typeof child !== 'number') {
      error('A title element received a value that was not a string or number for children. ' + 'In the browser title Elements can only have Text Nodes as children. If ' + 'the children being rendered output more than a single text node in aggregate the browser ' + 'will display markup and comments as text in the title and hydration will likely fail and ' + 'fall back to client rendering');
    }
  }

  return children;
}

function pushStartGenericElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);

  if (typeof children === 'string') {
    // Special case children as a string to avoid the unnecessary comment.
    // TODO: Remove this special case after the general optimization is in place.
    target.push(stringToChunk(encodeHTMLTextNode(children)));
    return null;
  }

  return children;
}

function pushStartCustomElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        case 'style':
          pushStyle(target, responseState, propValue);
          break;

        case 'suppressContentEditableWarning':
        case 'suppressHydrationWarning':
          // Ignored. These are built-in to React on the client.
          break;

        default:
          if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
            target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
          }

          break;
      }
    }
  }

  target.push(endOfStartTag);
  pushInnerHTML(target, innerHTML, children);
  return children;
}

var leadingNewline = stringToPrecomputedChunk('\n');

function pushStartPreformattedElement(target, props, tag, responseState) {
  target.push(startChunkForTag(tag));
  var children = null;
  var innerHTML = null;

  for (var propKey in props) {
    if (hasOwnProperty.call(props, propKey)) {
      var propValue = props[propKey];

      if (propValue == null) {
        continue;
      }

      switch (propKey) {
        case 'children':
          children = propValue;
          break;

        case 'dangerouslySetInnerHTML':
          innerHTML = propValue;
          break;

        default:
          pushAttribute(target, responseState, propKey, propValue);
          break;
      }
    }
  }

  target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
  // Prefer to break application/xml over text/html (for now) by adding
  // a newline specifically to get eaten by the parser. (Alternately for
  // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
  // \r is normalized out by HTMLTextAreaElement#value.)
  // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
  // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
  // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
  // See: Parsing of "textarea" "listing" and "pre" elements
  //  from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
  // TODO: This doesn't deal with the case where the child is an array
  // or component that returns a string.

  if (innerHTML != null) {
    if (children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }

    var html = innerHTML.__html;

    if (html !== null && html !== undefined) {
      if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
        target.push(leadingNewline, stringToChunk(html));
      } else {
        {
          checkHtmlStringCoercion(html);
        }

        target.push(stringToChunk('' + html));
      }
    }
  }

  if (typeof children === 'string' && children[0] === '\n') {
    target.push(leadingNewline);
  }

  return children;
} // We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name


var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset

var validatedTagCache = new Map();

function startChunkForTag(tag) {
  var tagStartChunk = validatedTagCache.get(tag);

  if (tagStartChunk === undefined) {
    if (!VALID_TAG_REGEX.test(tag)) {
      throw new Error("Invalid tag: " + tag);
    }

    tagStartChunk = stringToPrecomputedChunk('<' + tag);
    validatedTagCache.set(tag, tagStartChunk);
  }

  return tagStartChunk;
}

var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
function pushStartInstance(target, type, props, responseState, formatContext) {
  {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, null);

    if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
      error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
    }

    if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
      if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
        error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
      }
    }
  }

  switch (type) {
    // Special tags
    case 'select':
      return pushStartSelect(target, props, responseState);

    case 'option':
      return pushStartOption(target, props, responseState, formatContext);

    case 'textarea':
      return pushStartTextArea(target, props, responseState);

    case 'input':
      return pushInput(target, props, responseState);

    case 'menuitem':
      return pushStartMenuItem(target, props, responseState);

    case 'title':
      return pushStartTitle(target, props, responseState);
    // Newline eating tags

    case 'listing':
    case 'pre':
      {
        return pushStartPreformattedElement(target, props, type, responseState);
      }
    // Omitted close tags

    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        return pushSelfClosing(target, props, type, responseState);
      }
    // These are reserved SVG and MathML elements, that are never custom elements.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts

    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      {
        return pushStartGenericElement(target, props, type, responseState);
      }

    case 'html':
      {
        if (formatContext.insertionMode === ROOT_HTML_MODE) {
          // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
          // then we also emit the DOCTYPE as part of the root content as a convenience for
          // rendering the whole document.
          target.push(DOCTYPE);
        }

        return pushStartGenericElement(target, props, type, responseState);
      }

    default:
      {
        if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
          // Generic element
          return pushStartGenericElement(target, props, type, responseState);
        } else {
          // Custom element
          return pushStartCustomElement(target, props, type, responseState);
        }
      }
  }
}
var endTag1 = stringToPrecomputedChunk('</');
var endTag2 = stringToPrecomputedChunk('>');
function pushEndInstance(target, type, props) {
  switch (type) {
    // Omitted close tags
    // TODO: Instead of repeating this switch we could try to pass a flag from above.
    // That would require returning a tuple. Which might be ok if it gets inlined.
    case 'area':
    case 'base':
    case 'br':
    case 'col':
    case 'embed':
    case 'hr':
    case 'img':
    case 'input':
    case 'keygen':
    case 'link':
    case 'meta':
    case 'param':
    case 'source':
    case 'track':
    case 'wbr':
      {
        // No close tag needed.
        break;
      }

    default:
      {
        target.push(endTag1, stringToChunk(type), endTag2);
      }
  }
}
function writeCompletedRoot(destination, responseState) {
  var bootstrapChunks = responseState.bootstrapChunks;
  var i = 0;

  for (; i < bootstrapChunks.length - 1; i++) {
    writeChunk(destination, bootstrapChunks[i]);
  }

  if (i < bootstrapChunks.length) {
    return writeChunkAndReturn(destination, bootstrapChunks[i]);
  }

  return true;
} // Structural Nodes
// A placeholder is a node inside a hidden partial tree that can be filled in later, but before
// display. It's never visible to users. We use the template tag because it can be used in every
// type of parent. <script> tags also work in every other tag except <colgroup>.

var placeholder1 = stringToPrecomputedChunk('<template id="');
var placeholder2 = stringToPrecomputedChunk('"></template>');
function writePlaceholder(destination, responseState, id) {
  writeChunk(destination, placeholder1);
  writeChunk(destination, responseState.placeholderPrefix);
  var formattedID = stringToChunk(id.toString(16));
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, placeholder2);
} // Suspense boundaries are encoded as comments.

var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
function writeStartCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
}
function writeStartPendingSuspenseBoundary(destination, responseState, id) {
  writeChunk(destination, startPendingSuspenseBoundary1);

  if (id === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, id);
  return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
}
function writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMesssage, errorComponentStack) {
  var result;
  result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
  writeChunk(destination, clientRenderedSuspenseBoundaryError1);

  if (errorDigest) {
    writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
    writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
    writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
  }

  {
    if (errorMesssage) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMesssage)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }

    if (errorComponentStack) {
      writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
      writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
      writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
    }
  }

  result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
  return result;
}
function writeEndCompletedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndPendingSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
  return writeChunkAndReturn(destination, endSuspenseBoundary);
}
var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
var startSegmentHTML2 = stringToPrecomputedChunk('">');
var endSegmentHTML = stringToPrecomputedChunk('</div>');
var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
var startSegmentSVG2 = stringToPrecomputedChunk('">');
var endSegmentSVG = stringToPrecomputedChunk('</svg>');
var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
var startSegmentMathML2 = stringToPrecomputedChunk('">');
var endSegmentMathML = stringToPrecomputedChunk('</math>');
var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
var startSegmentTable2 = stringToPrecomputedChunk('">');
var endSegmentTable = stringToPrecomputedChunk('</table>');
var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
var startSegmentTableBody2 = stringToPrecomputedChunk('">');
var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
var startSegmentTableRow2 = stringToPrecomputedChunk('">');
var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
var startSegmentColGroup2 = stringToPrecomputedChunk('">');
var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
function writeStartSegment(destination, responseState, formatContext, id) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        writeChunk(destination, startSegmentHTML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentHTML2);
      }

    case SVG_MODE:
      {
        writeChunk(destination, startSegmentSVG);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentSVG2);
      }

    case MATHML_MODE:
      {
        writeChunk(destination, startSegmentMathML);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentMathML2);
      }

    case HTML_TABLE_MODE:
      {
        writeChunk(destination, startSegmentTable);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTable2);
      }
    // TODO: For the rest of these, there will be extra wrapper nodes that never
    // get deleted from the document. We need to delete the table too as part
    // of the injected scripts. They are invisible though so it's not too terrible
    // and it's kind of an edge case to suspend in a table. Totally supported though.

    case HTML_TABLE_BODY_MODE:
      {
        writeChunk(destination, startSegmentTableBody);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableBody2);
      }

    case HTML_TABLE_ROW_MODE:
      {
        writeChunk(destination, startSegmentTableRow);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentTableRow2);
      }

    case HTML_COLGROUP_MODE:
      {
        writeChunk(destination, startSegmentColGroup);
        writeChunk(destination, responseState.segmentPrefix);
        writeChunk(destination, stringToChunk(id.toString(16)));
        return writeChunkAndReturn(destination, startSegmentColGroup2);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
}
function writeEndSegment(destination, formatContext) {
  switch (formatContext.insertionMode) {
    case ROOT_HTML_MODE:
    case HTML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentHTML);
      }

    case SVG_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentSVG);
      }

    case MATHML_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentMathML);
      }

    case HTML_TABLE_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTable);
      }

    case HTML_TABLE_BODY_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableBody);
      }

    case HTML_TABLE_ROW_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentTableRow);
      }

    case HTML_COLGROUP_MODE:
      {
        return writeChunkAndReturn(destination, endSegmentColGroup);
      }

    default:
      {
        throw new Error('Unknown insertion mode. This is a bug in React.');
      }
  }
} // Instruction Set
// The following code is the source scripts that we then minify and inline below,
// with renamed function names that we hope don't collide:
// const COMMENT_NODE = 8;
// const SUSPENSE_START_DATA = '$';
// const SUSPENSE_END_DATA = '/$';
// const SUSPENSE_PENDING_START_DATA = '$?';
// const SUSPENSE_FALLBACK_START_DATA = '$!';
//
// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//   // Tag it to be client rendered.
//   suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
//   // assign error metadata to first sibling
//   let dataset = suspenseIdNode.dataset;
//   if (errorDigest) dataset.dgst = errorDigest;
//   if (errorMsg) dataset.msg = errorMsg;
//   if (errorComponentStack) dataset.stck = errorComponentStack;
//   // Tell React to retry it if the parent already hydrated.
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeBoundary(suspenseBoundaryID, contentID) {
//   // Find the fallback's first element.
//   const suspenseIdNode = document.getElementById(suspenseBoundaryID);
//   const contentNode = document.getElementById(contentID);
//   // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
//   // This might also help by not causing recalcing each time we move a child from here to the target.
//   contentNode.parentNode.removeChild(contentNode);
//   if (!suspenseIdNode) {
//     // The user must have already navigated away from this tree.
//     // E.g. because the parent was hydrated. That's fine there's nothing to do
//     // but we have to make sure that we already deleted the container node.
//     return;
//   }
//   // Find the boundary around the fallback. This is always the previous node.
//   const suspenseNode = suspenseIdNode.previousSibling;
//
//   // Clear all the existing children. This is complicated because
//   // there can be embedded Suspense boundaries in the fallback.
//   // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
//   // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
//   // They never hydrate anyway. However, currently we support incrementally loading the fallback.
//   const parentInstance = suspenseNode.parentNode;
//   let node = suspenseNode.nextSibling;
//   let depth = 0;
//   do {
//     if (node && node.nodeType === COMMENT_NODE) {
//       const data = node.data;
//       if (data === SUSPENSE_END_DATA) {
//         if (depth === 0) {
//           break;
//         } else {
//           depth--;
//         }
//       } else if (
//         data === SUSPENSE_START_DATA ||
//         data === SUSPENSE_PENDING_START_DATA ||
//         data === SUSPENSE_FALLBACK_START_DATA
//       ) {
//         depth++;
//       }
//     }
//
//     const nextNode = node.nextSibling;
//     parentInstance.removeChild(node);
//     node = nextNode;
//   } while (node);
//
//   const endOfBoundary = node;
//
//   // Insert all the children from the contentNode between the start and end of suspense boundary.
//   while (contentNode.firstChild) {
//     parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
//   }
//   suspenseNode.data = SUSPENSE_START_DATA;
//   if (suspenseNode._reactRetry) {
//     suspenseNode._reactRetry();
//   }
// }
//
// function completeSegment(containerID, placeholderID) {
//   const segmentContainer = document.getElementById(containerID);
//   const placeholderNode = document.getElementById(placeholderID);
//   // We always expect both nodes to exist here because, while we might
//   // have navigated away from the main tree, we still expect the detached
//   // tree to exist.
//   segmentContainer.parentNode.removeChild(segmentContainer);
//   while (segmentContainer.firstChild) {
//     placeholderNode.parentNode.insertBefore(
//       segmentContainer.firstChild,
//       placeholderNode,
//     );
//   }
//   placeholderNode.parentNode.removeChild(placeholderNode);
// }

var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
var clientRenderFunction = 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
var completeSegmentScript2 = stringToPrecomputedChunk('","');
var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteSegmentFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteSegmentFunction = true;
    writeChunk(destination, completeSegmentScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeSegmentScript1Partial);
  }

  writeChunk(destination, responseState.segmentPrefix);
  var formattedID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, formattedID);
  writeChunk(destination, completeSegmentScript2);
  writeChunk(destination, responseState.placeholderPrefix);
  writeChunk(destination, formattedID);
  return writeChunkAndReturn(destination, completeSegmentScript3);
}
var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
var completeBoundaryScript2 = stringToPrecomputedChunk('","');
var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentCompleteBoundaryFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentCompleteBoundaryFunction = true;
    writeChunk(destination, completeBoundaryScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, completeBoundaryScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  var formattedContentID = stringToChunk(contentSegmentID.toString(16));
  writeChunk(destination, boundaryID);
  writeChunk(destination, completeBoundaryScript2);
  writeChunk(destination, responseState.segmentPrefix);
  writeChunk(destination, formattedContentID);
  return writeChunkAndReturn(destination, completeBoundaryScript3);
}
var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
var clientRenderScript1A = stringToPrecomputedChunk('"');
var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {
  writeChunk(destination, responseState.startInlineScript);

  if (!responseState.sentClientRenderFunction) {
    // The first time we write this, we'll need to include the full implementation.
    responseState.sentClientRenderFunction = true;
    writeChunk(destination, clientRenderScript1Full);
  } else {
    // Future calls can just reuse the same function.
    writeChunk(destination, clientRenderScript1Partial);
  }

  if (boundaryID === null) {
    throw new Error('An ID must have been assigned before we can complete the boundary.');
  }

  writeChunk(destination, boundaryID);
  writeChunk(destination, clientRenderScript1A);

  if (errorDigest || errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
  }

  if (errorMessage || errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
  }

  if (errorComponentStack) {
    writeChunk(destination, clientRenderErrorScriptArgInterstitial);
    writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
  }

  return writeChunkAndReturn(destination, clientRenderScript2);
}
var regexForJSStringsInScripts = /[<\u2028\u2029]/g;

function escapeJSStringsForInstructionScripts(input) {
  var escaped = JSON.stringify(input);
  return escaped.replace(regexForJSStringsInScripts, function (match) {
    switch (match) {
      // santizing breaking out of strings and script tags
      case '<':
        return "\\u003c";

      case "\u2028":
        return "\\u2028";

      case "\u2029":
        return "\\u2029";

      default:
        {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
        }
    }
  });
}

var assign = Object.assign;

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}

function describeClassComponentFrame(ctor, source, ownerFn) {
  {
    return describeNativeComponentFrame(ctor, true);
  }
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var warnedAboutMissingGetChildContext;

{
  warnedAboutMissingGetChildContext = {};
}

var emptyContextObject = {};

{
  Object.freeze(emptyContextObject);
}

function getMaskedContext(type, unmaskedContext) {
  {
    var contextTypes = type.contextTypes;

    if (!contextTypes) {
      return emptyContextObject;
    }

    var context = {};

    for (var key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(contextTypes, context, 'context', name);
    }

    return context;
  }
}
function processChildContext(instance, type, parentContext, childContextTypes) {
  {
    // TODO (bvaughn) Replace this behavior with an invariant() in the future.
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.
    if (typeof instance.getChildContext !== 'function') {
      {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!warnedAboutMissingGetChildContext[componentName]) {
          warnedAboutMissingGetChildContext[componentName] = true;

          error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
        }
      }

      return parentContext;
    }

    var childContext = instance.getChildContext();

    for (var contextKey in childContext) {
      if (!(contextKey in childContextTypes)) {
        throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
      }
    }

    {
      var name = getComponentNameFromType(type) || 'Unknown';
      checkPropTypes(childContextTypes, childContext, 'child context', name);
    }

    return assign({}, parentContext, childContext);
  }
}

var rendererSigil;

{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
} // Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.


var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are currently in.

var currentActiveSnapshot = null;

function popNode(prev) {
  {
    prev.context._currentValue = prev.parentValue;
  }
}

function pushNode(next) {
  {
    next.context._currentValue = next.value;
  }
}

function popToNearestCommonAncestor(prev, next) {
  if (prev === next) ; else {
    popNode(prev);
    var parentPrev = prev.parent;
    var parentNext = next.parent;

    if (parentPrev === null) {
      if (parentNext !== null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }
    } else {
      if (parentNext === null) {
        throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
      }

      popToNearestCommonAncestor(parentPrev, parentNext);
    } // On the way back, we push the new ones that weren't common.


    pushNode(next);
  }
}

function popAllPrevious(prev) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev !== null) {
    popAllPrevious(parentPrev);
  }
}

function pushAllNext(next) {
  var parentNext = next.parent;

  if (parentNext !== null) {
    pushAllNext(parentNext);
  }

  pushNode(next);
}

function popPreviousToCommonLevel(prev, next) {
  popNode(prev);
  var parentPrev = prev.parent;

  if (parentPrev === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (parentPrev.depth === next.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(parentPrev, next);
  } else {
    // We must still be deeper.
    popPreviousToCommonLevel(parentPrev, next);
  }
}

function popNextToCommonLevel(prev, next) {
  var parentNext = next.parent;

  if (parentNext === null) {
    throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  }

  if (prev.depth === parentNext.depth) {
    // We found the same level. Now we just need to find a shared ancestor.
    popToNearestCommonAncestor(prev, parentNext);
  } else {
    // We must still be deeper.
    popNextToCommonLevel(prev, parentNext);
  }

  pushNode(next);
} // Perform context switching to the new snapshot.
// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
// updating all the context's current values. That way reads, always just read the current value.
// At the cost of updating contexts even if they're never read by this subtree.


function switchContext(newSnapshot) {
  // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
  // We also need to update any new contexts that are now on the stack with the deepest value.
  // The easiest way to update new contexts is to just reapply them in reverse order from the
  // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
  // for that. Therefore this algorithm is recursive.
  // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
  // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
  // 3) Then we reapply new contexts on the way back up the stack.
  var prev = currentActiveSnapshot;
  var next = newSnapshot;

  if (prev !== next) {
    if (prev === null) {
      // $FlowFixMe: This has to be non-null since it's not equal to prev.
      pushAllNext(next);
    } else if (next === null) {
      popAllPrevious(prev);
    } else if (prev.depth === next.depth) {
      popToNearestCommonAncestor(prev, next);
    } else if (prev.depth > next.depth) {
      popPreviousToCommonLevel(prev, next);
    } else {
      popNextToCommonLevel(prev, next);
    }

    currentActiveSnapshot = next;
  }
}
function pushProvider(context, nextValue) {
  var prevValue;

  {
    prevValue = context._currentValue;
    context._currentValue = nextValue;

    {
      if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer = rendererSigil;
    }
  }

  var prevNode = currentActiveSnapshot;
  var newNode = {
    parent: prevNode,
    depth: prevNode === null ? 0 : prevNode.depth + 1,
    context: context,
    parentValue: prevValue,
    value: nextValue
  };
  currentActiveSnapshot = newNode;
  return newNode;
}
function popProvider(context) {
  var prevSnapshot = currentActiveSnapshot;

  if (prevSnapshot === null) {
    throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
  }

  {
    if (prevSnapshot.context !== context) {
      error('The parent context is not the expected context. This is probably a bug in React.');
    }
  }

  {
    var value = prevSnapshot.parentValue;

    if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
      prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
    } else {
      prevSnapshot.context._currentValue = value;
    }

    {
      if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer = rendererSigil;
    }
  }

  return currentActiveSnapshot = prevSnapshot.parent;
}
function getActiveContext() {
  return currentActiveSnapshot;
}
function readContext(context) {
  var value =  context._currentValue ;
  return value;
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}
function set(key, value) {
  key._reactInternals = value;
}

var didWarnAboutNoopUpdateForComponent = {};
var didWarnAboutDeprecatedWillMount = {};
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;

{
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutDirectlyAssigningPropsToState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();
  didWarnAboutContextTypeAndContextTypes = new Set();
  didWarnAboutInvalidateContextType = new Set();
  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }

    var key = callerName + '_' + callback;

    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);

      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (type, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentNameFromType(type) || 'Component';

      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);

        error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  };
}

function warnNoop(publicInstance, callerName) {
  {
    var _constructor = publicInstance.constructor;
    var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
    var warningKey = componentName + '.' + callerName;

    if (didWarnAboutNoopUpdateForComponent[warningKey]) {
      return;
    }

    error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);

    didWarnAboutNoopUpdateForComponent[warningKey] = true;
  }
}

var classComponentUpdater = {
  isMounted: function (inst) {
    return false;
  },
  enqueueSetState: function (inst, payload, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'setState');
    } else {
      internals.queue.push(payload);

      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var internals = get(inst);
    internals.replace = true;
    internals.queue = [payload];

    {
      if (callback !== undefined && callback !== null) {
        warnOnInvalidCallback(callback, 'setState');
      }
    }
  },
  enqueueForceUpdate: function (inst, callback) {
    var internals = get(inst);

    if (internals.queue === null) {
      warnNoop(inst, 'forceUpdate');
    } else {
      {
        if (callback !== undefined && callback !== null) {
          warnOnInvalidCallback(callback, 'setState');
        }
      }
    }
  }
};

function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    warnOnUndefinedDerivedState(ctor, partialState);
  } // Merge the partial state and the previous state.


  var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
  return newState;
}

function constructClassInstance(ctor, props, maskedLegacyContext) {
  var context = emptyContextObject;
  var contextType = ctor.contextType;

  {
    if ('contextType' in ctor) {
      var isValid = // Allow null for conditional declaration
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
        didWarnAboutInvalidateContextType.add(ctor);
        var addendum = '';

        if (contextType === undefined) {
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
        } else if (typeof contextType !== 'object') {
          addendum = ' However, it is set to a ' + typeof contextType + '.';
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
          addendum = ' Did you accidentally pass the Context.Provider instead?';
        } else if (contextType._context !== undefined) {
          // <Context.Consumer>
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
        } else {
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
        }

        error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
      }
    }
  }

  if (typeof contextType === 'object' && contextType !== null) {
    context = readContext(contextType);
  } else {
    context = maskedLegacyContext;
  }

  var instance = new ctor(props, context);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);

        error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
      }
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.


    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;

      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }

      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentNameFromType(ctor) || 'Component';

        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

          error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
        }
      }
    }
  }

  return instance;
}

function checkClassInstance(instance, ctor, newProps) {
  {
    var name = getComponentNameFromType(ctor) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
        error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
      error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
    }

    if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
    }

    if (instance.propTypes) {
      error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
    }

    if (instance.contextType) {
      error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
    }

    {
      if (instance.contextTypes) {
        error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
      }

      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
        didWarnAboutContextTypeAndContextTypes.add(ctor);

        error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
      }
    }

    if (typeof instance.componentShouldUpdate === 'function') {
      error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
    }

    if (typeof instance.componentDidUnmount === 'function') {
      error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
    }

    if (typeof instance.componentDidReceiveProps === 'function') {
      error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
    }

    if (typeof instance.componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
    }

    if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
    }

    var hasMutatedProps = instance.props !== newProps;

    if (instance.props !== undefined && hasMutatedProps) {
      error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
    }

    if (instance.defaultProps) {
      error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

      error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
    }

    if (typeof instance.getDerivedStateFromProps === 'function') {
      error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof instance.getDerivedStateFromError === 'function') {
      error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
      error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
    }

    var _state = instance.state;

    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      error('%s.state: must be set to an object or null', name);
    }

    if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
      error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
    }
  }
}

function callComponentWillMount(type, instance) {
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    {
      if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!didWarnAboutDeprecatedWillMount[componentName]) {
          warn( // keep this warning in sync with ReactStrictModeWarning.js
          'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);

          didWarnAboutDeprecatedWillMount[componentName] = true;
        }
      }
    }

    instance.componentWillMount();
  }

  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  if (oldState !== instance.state) {
    {
      error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
  if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
    var oldQueue = internalInstance.queue;
    var oldReplace = internalInstance.replace;
    internalInstance.queue = null;
    internalInstance.replace = false;

    if (oldReplace && oldQueue.length === 1) {
      inst.state = oldQueue[0];
    } else {
      var nextState = oldReplace ? oldQueue[0] : inst.state;
      var dontMutate = true;

      for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
        var partial = oldQueue[i];
        var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;

        if (partialState != null) {
          if (dontMutate) {
            dontMutate = false;
            nextState = assign({}, nextState, partialState);
          } else {
            assign(nextState, partialState);
          }
        }
      }

      inst.state = nextState;
    }
  } else {
    internalInstance.queue = null;
  }
} // Invokes the mount life-cycles on a previously never rendered instance.


function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
  {
    checkClassInstance(instance, ctor, newProps);
  }

  var initialState = instance.state !== undefined ? instance.state : null;
  instance.updater = classComponentUpdater;
  instance.props = newProps;
  instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
  // The internal instance will be used to manage updates that happen during this mount.

  var internalInstance = {
    queue: [],
    replace: false
  };
  set(instance, internalInstance);
  var contextType = ctor.contextType;

  if (typeof contextType === 'object' && contextType !== null) {
    instance.context = readContext(contextType);
  } else {
    instance.context = maskedLegacyContext;
  }

  {
    if (instance.state === newProps) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);

        error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
      }
    }
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

  if (typeof getDerivedStateFromProps === 'function') {
    instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
  } // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.


  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
    // process them now.

    processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
  }
}

// Ids are base 32 strings whose binary representation corresponds to the
// position of a node in a tree.
// Every time the tree forks into multiple children, we add additional bits to
// the left of the sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      â•°â”€â”¬â”€â•¯       â•°â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â•¯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5. However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
// the zeroth id at a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in the
// sequence. It's treated as a transparent indirection. For example, these two
// trees produce the same ids:
//
// <>                          <>
//   <Indirection>               <A />
//     <A />                     <B />
//   </Indirection>            </>
//   <B />
// </>
//
// However, we cannot skip any node that materializes an id. Otherwise, a parent
// id that does not fork would be indistinguishable from its child id. For
// example, this tree does not fork, but the parent and child must have
// different ids.
//
// <Parent>
//   <Child />
// </Parent>
//
// To handle this scenario, every time we materialize an id, we allocate a
// new level with a single slot. You can think of this as a fork with only one
// prong, or an array of children with length 1.
//
// It's possible for the size of the sequence to exceed 32 bits, the max
// size for bitwise operations. When this happens, we make more room by
// converting the right part of the id to a string and storing it in an overflow
// variable. We use a base 32 string representation, because 32 is the largest
// power of 2 that is supported by toString(). We want the base to be large so
// that the resulting ids are compact, and we want the base to be a power of 2
// because every log2(base) bits corresponds to a single character, i.e. every
// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
// affecting the final result.
var emptyTreeContext = {
  id: 1,
  overflow: ''
};
function getTreeId(context) {
  var overflow = context.overflow;
  var idWithLeadingBit = context.id;
  var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
  return id.toString(32) + overflow;
}
function pushTreeContext(baseContext, totalChildren, index) {
  var baseIdWithLeadingBit = baseContext.id;
  var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
  // of the id; we use it to account for leading 0s.

  var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
  var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
  var slot = index + 1;
  var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
  // consideration the leading 1 we use to mark the end of the sequence.

  if (length > 30) {
    // We overflowed the bitwise-safe range. Fall back to slower algorithm.
    // This branch assumes the length of the base id is greater than 5; it won't
    // work for smaller ids, because you need 5 bits per character.
    //
    // We encode the id in multiple steps: first the base id, then the
    // remaining digits.
    //
    // Each 5 bit sequence corresponds to a single base 32 character. So for
    // example, if the current id is 23 bits long, we can convert 20 of those
    // bits into a string of 4 characters, with 3 bits left over.
    //
    // First calculate how many bits in the base id represent a complete
    // sequence of characters.
    var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

    var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

    var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

    var restOfBaseId = baseId >> numberOfOverflowBits;
    var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
    // we made more room, this time it won't overflow.

    var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
    var restOfNewBits = slot << restOfBaseLength;
    var id = restOfNewBits | restOfBaseId;
    var overflow = newOverflow + baseOverflow;
    return {
      id: 1 << restOfLength | id,
      overflow: overflow
    };
  } else {
    // Normal path
    var newBits = slot << baseLength;

    var _id = newBits | baseId;

    var _overflow = baseOverflow;
    return {
      id: 1 << length | _id,
      overflow: _overflow
    };
  }
}

function getBitLength(number) {
  return 32 - clz32(number);
}

function getLeadingBit(id) {
  return 1 << getBitLength(id) - 1;
} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.


var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

var log = Math.log;
var LN2 = Math.LN2;

function clz32Fallback(x) {
  var asUint = x >>> 0;

  if (asUint === 0) {
    return 32;
  }

  return 31 - (log(asUint) / LN2 | 0) | 0;
}

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  ;
}

var objectIs = typeof Object.is === 'function' ? Object.is : is;

var currentlyRenderingComponent = null;
var currentlyRenderingTask = null;
var firstWorkInProgressHook = null;
var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook

var isReRender = false; // Whether an update was scheduled during the currently executing render pass.

var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component

var localIdCounter = 0; // Lazily created map of render-phase updates

var renderPhaseUpdates = null; // Counter to prevent infinite loops.

var numberOfReRenders = 0;
var RE_RENDER_LIMIT = 25;
var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook

var currentHookNameInDev;

function resolveCurrentlyRenderingComponent() {
  if (currentlyRenderingComponent === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
  }

  {
    if (isInHookUserCodeInDev) {
      error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
    }
  }

  return currentlyRenderingComponent;
}

function areHookInputsEqual(nextDeps, prevDeps) {
  if (prevDeps === null) {
    {
      error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
    }

    return false;
  }

  {
    // Don't bother comparing lengths in prod because these arrays should be
    // passed inline.
    if (nextDeps.length !== prevDeps.length) {
      error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
    }
  }

  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (objectIs(nextDeps[i], prevDeps[i])) {
      continue;
    }

    return false;
  }

  return true;
}

function createHook() {
  if (numberOfReRenders > 0) {
    throw new Error('Rendered more hooks than during the previous render');
  }

  return {
    memoizedState: null,
    queue: null,
    next: null
  };
}

function createWorkInProgressHook() {
  if (workInProgressHook === null) {
    // This is the first hook in the list
    if (firstWorkInProgressHook === null) {
      isReRender = false;
      firstWorkInProgressHook = workInProgressHook = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = firstWorkInProgressHook;
    }
  } else {
    if (workInProgressHook.next === null) {
      isReRender = false; // Append to the end of the list

      workInProgressHook = workInProgressHook.next = createHook();
    } else {
      // There's already a work-in-progress. Reuse it.
      isReRender = true;
      workInProgressHook = workInProgressHook.next;
    }
  }

  return workInProgressHook;
}

function prepareToUseHooks(task, componentIdentity) {
  currentlyRenderingComponent = componentIdentity;
  currentlyRenderingTask = task;

  {
    isInHookUserCodeInDev = false;
  } // The following should have already been reset
  // didScheduleRenderPhaseUpdate = false;
  // localIdCounter = 0;
  // firstWorkInProgressHook = null;
  // numberOfReRenders = 0;
  // renderPhaseUpdates = null;
  // workInProgressHook = null;


  localIdCounter = 0;
}
function finishHooks(Component, props, children, refOrContext) {
  // This must be called after every function component to prevent hooks from
  // being used in classes.
  while (didScheduleRenderPhaseUpdate) {
    // Updates were scheduled during the render phase. They are stored in
    // the `renderPhaseUpdates` map. Call the component again, reusing the
    // work-in-progress hooks and applying the additional updates on top. Keep
    // restarting until no more updates are scheduled.
    didScheduleRenderPhaseUpdate = false;
    localIdCounter = 0;
    numberOfReRenders += 1; // Start over from the beginning of the list

    workInProgressHook = null;
    children = Component(props, refOrContext);
  }

  resetHooksState();
  return children;
}
function checkDidRenderIdHook() {
  // This should be called immediately after every finishHooks call.
  // Conceptually, it's part of the return value of finishHooks; it's only a
  // separate function to avoid using an array tuple.
  var didRenderIdHook = localIdCounter !== 0;
  return didRenderIdHook;
} // Reset the internal hooks state if an error occurs while rendering a component

function resetHooksState() {
  {
    isInHookUserCodeInDev = false;
  }

  currentlyRenderingComponent = null;
  currentlyRenderingTask = null;
  didScheduleRenderPhaseUpdate = false;
  firstWorkInProgressHook = null;
  numberOfReRenders = 0;
  renderPhaseUpdates = null;
  workInProgressHook = null;
}

function readContext$1(context) {
  {
    if (isInHookUserCodeInDev) {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    }
  }

  return readContext(context);
}

function useContext(context) {
  {
    currentHookNameInDev = 'useContext';
  }

  resolveCurrentlyRenderingComponent();
  return readContext(context);
}

function basicStateReducer(state, action) {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

function useState(initialState) {
  {
    currentHookNameInDev = 'useState';
  }

  return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
  initialState);
}
function useReducer(reducer, initialArg, init) {
  {
    if (reducer !== basicStateReducer) {
      currentHookNameInDev = 'useReducer';
    }
  }

  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();

  if (isReRender) {
    // This is a re-render. Apply the new render phase updates to the previous
    // current hook.
    var queue = workInProgressHook.queue;
    var dispatch = queue.dispatch;

    if (renderPhaseUpdates !== null) {
      // Render phase updates are stored in a map of queue -> linked list
      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

      if (firstRenderPhaseUpdate !== undefined) {
        renderPhaseUpdates.delete(queue);
        var newState = workInProgressHook.memoizedState;
        var update = firstRenderPhaseUpdate;

        do {
          // Process this render phase update. We don't have to check the
          // priority because it will always be the same as the current
          // render's.
          var action = update.action;

          {
            isInHookUserCodeInDev = true;
          }

          newState = reducer(newState, action);

          {
            isInHookUserCodeInDev = false;
          }

          update = update.next;
        } while (update !== null);

        workInProgressHook.memoizedState = newState;
        return [newState, dispatch];
      }
    }

    return [workInProgressHook.memoizedState, dispatch];
  } else {
    {
      isInHookUserCodeInDev = true;
    }

    var initialState;

    if (reducer === basicStateReducer) {
      // Special case for `useState`.
      initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
    } else {
      initialState = init !== undefined ? init(initialArg) : initialArg;
    }

    {
      isInHookUserCodeInDev = false;
    }

    workInProgressHook.memoizedState = initialState;

    var _queue = workInProgressHook.queue = {
      last: null,
      dispatch: null
    };

    var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);

    return [workInProgressHook.memoizedState, _dispatch];
  }
}

function useMemo(nextCreate, deps) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;

  if (workInProgressHook !== null) {
    var prevState = workInProgressHook.memoizedState;

    if (prevState !== null) {
      if (nextDeps !== null) {
        var prevDeps = prevState[1];

        if (areHookInputsEqual(nextDeps, prevDeps)) {
          return prevState[0];
        }
      }
    }
  }

  {
    isInHookUserCodeInDev = true;
  }

  var nextValue = nextCreate();

  {
    isInHookUserCodeInDev = false;
  }

  workInProgressHook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function useRef(initialValue) {
  currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
  workInProgressHook = createWorkInProgressHook();
  var previousRef = workInProgressHook.memoizedState;

  if (previousRef === null) {
    var ref = {
      current: initialValue
    };

    {
      Object.seal(ref);
    }

    workInProgressHook.memoizedState = ref;
    return ref;
  } else {
    return previousRef;
  }
}

function useLayoutEffect(create, inputs) {
  {
    currentHookNameInDev = 'useLayoutEffect';

    error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
  }
}

function dispatchAction(componentIdentity, queue, action) {
  if (numberOfReRenders >= RE_RENDER_LIMIT) {
    throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
  }

  if (componentIdentity === currentlyRenderingComponent) {
    // This is a render phase update. Stash it in a lazily-created map of
    // queue -> linked list of updates. After this render pass, we'll restart
    // and apply the stashed updates on top of the work-in-progress hook.
    didScheduleRenderPhaseUpdate = true;
    var update = {
      action: action,
      next: null
    };

    if (renderPhaseUpdates === null) {
      renderPhaseUpdates = new Map();
    }

    var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);

    if (firstRenderPhaseUpdate === undefined) {
      renderPhaseUpdates.set(queue, update);
    } else {
      // Append the update to the end of the list.
      var lastRenderPhaseUpdate = firstRenderPhaseUpdate;

      while (lastRenderPhaseUpdate.next !== null) {
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      }

      lastRenderPhaseUpdate.next = update;
    }
  }
}

function useCallback(callback, deps) {
  return useMemo(function () {
    return callback;
  }, deps);
} // TODO Decide on how to implement this hook for server rendering.
// If a mutation occurs during render, consider triggering a Suspense boundary
// and falling back to client rendering.

function useMutableSource(source, getSnapshot, subscribe) {
  resolveCurrentlyRenderingComponent();
  return getSnapshot(source._source);
}

function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  if (getServerSnapshot === undefined) {
    throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
  }

  return getServerSnapshot();
}

function useDeferredValue(value) {
  resolveCurrentlyRenderingComponent();
  return value;
}

function unsupportedStartTransition() {
  throw new Error('startTransition cannot be called during server rendering.');
}

function useTransition() {
  resolveCurrentlyRenderingComponent();
  return [false, unsupportedStartTransition];
}

function useId() {
  var task = currentlyRenderingTask;
  var treeId = getTreeId(task.treeContext);
  var responseState = currentResponseState;

  if (responseState === null) {
    throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
  }

  var localId = localIdCounter++;
  return makeId(responseState, treeId, localId);
}

function noop() {}

var Dispatcher = {
  readContext: readContext$1,
  useContext: useContext,
  useMemo: useMemo,
  useReducer: useReducer,
  useRef: useRef,
  useState: useState,
  useInsertionEffect: noop,
  useLayoutEffect: useLayoutEffect,
  useCallback: useCallback,
  // useImperativeHandle is not run in the server environment
  useImperativeHandle: noop,
  // Effects are not run in the server environment.
  useEffect: noop,
  // Debugging effect
  useDebugValue: noop,
  useDeferredValue: useDeferredValue,
  useTransition: useTransition,
  useId: useId,
  // Subscriptions are not setup in a server environment.
  useMutableSource: useMutableSource,
  useSyncExternalStore: useSyncExternalStore
};

var currentResponseState = null;
function setCurrentResponseState(responseState) {
  currentResponseState = responseState;
}

function getStackByComponentStackNode(componentStack) {
  try {
    var info = '';
    var node = componentStack;

    do {
      switch (node.tag) {
        case 0:
          info += describeBuiltInComponentFrame(node.type, null, null);
          break;

        case 1:
          info += describeFunctionComponentFrame(node.type, null, null);
          break;

        case 2:
          info += describeClassComponentFrame(node.type, null, null);
          break;
      }

      node = node.parent;
    } while (node);

    return info;
  } catch (x) {
    return '\nError generating stack: ' + x.message + '\n' + x.stack;
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
var PENDING = 0;
var COMPLETED = 1;
var FLUSHED = 2;
var ABORTED = 3;
var ERRORED = 4;
var OPEN = 0;
var CLOSING = 1;
var CLOSED = 2;
// This is a default heuristic for how to split up the HTML content into progressive
// loading. Our goal is to be able to display additional new content about every 500ms.
// Faster than that is unnecessary and should be throttled on the client. It also
// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
// end device but higher end suffer less from the overhead than lower end does from
// not getting small enough pieces. We error on the side of low end.
// We base this on low end 3G speeds which is about 500kbits per second. We assume
// that there can be a reasonable drop off from max bandwidth which leaves you with
// as little as 80%. We can receive half of that each 500ms - at best. In practice,
// a little bandwidth is lost to processing and contention - e.g. CSS and images that
// are downloaded along with the main content. So we estimate about half of that to be
// the lower end throughput. In other words, we expect that you can at least show
// about 12.5kb of content per 500ms. Not counting starting latency for the first
// paint.
// 500 * 1024 / 8 * .8 * 0.5 / 2
var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;

function defaultErrorHandler(error) {
  console['error'](error); // Don't transform to our wrapper

  return null;
}

function noop$1() {}

function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
  var pingedTasks = [];
  var abortSet = new Set();
  var request = {
    destination: null,
    responseState: responseState,
    progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
    status: OPEN,
    fatalError: null,
    nextSegmentId: 0,
    allPendingTasks: 0,
    pendingRootTasks: 0,
    completedRootSegment: null,
    abortableTasks: abortSet,
    pingedTasks: pingedTasks,
    clientRenderedBoundaries: [],
    completedBoundaries: [],
    partialBoundaries: [],
    onError: onError === undefined ? defaultErrorHandler : onError,
    onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
    onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
    onShellError: onShellError === undefined ? noop$1 : onShellError,
    onFatalError: onFatalError === undefined ? noop$1 : onFatalError
  }; // This segment represents the root fallback.

  var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
  false, false); // There is no parent so conceptually, we're unblocked to flush this segment.

  rootSegment.parentFlushed = true;
  var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
  pingedTasks.push(rootTask);
  return request;
}

function pingTask(request, task) {
  var pingedTasks = request.pingedTasks;
  pingedTasks.push(task);

  if (pingedTasks.length === 1) {
    scheduleWork(function () {
      return performWork(request);
    });
  }
}

function createSuspenseBoundary(request, fallbackAbortableTasks) {
  return {
    id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
    rootSegmentID: -1,
    parentFlushed: false,
    pendingTasks: 0,
    forceClientRender: false,
    completedSegments: [],
    byteSize: 0,
    fallbackAbortableTasks: fallbackAbortableTasks,
    errorDigest: null
  };
}

function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
  request.allPendingTasks++;

  if (blockedBoundary === null) {
    request.pendingRootTasks++;
  } else {
    blockedBoundary.pendingTasks++;
  }

  var task = {
    node: node,
    ping: function () {
      return pingTask(request, task);
    },
    blockedBoundary: blockedBoundary,
    blockedSegment: blockedSegment,
    abortSet: abortSet,
    legacyContext: legacyContext,
    context: context,
    treeContext: treeContext
  };

  {
    task.componentStack = null;
  }

  abortSet.add(task);
  return task;
}

function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {
  return {
    status: PENDING,
    id: -1,
    // lazily assigned later
    index: index,
    parentFlushed: false,
    chunks: [],
    children: [],
    formatContext: formatContext,
    boundary: boundary,
    lastPushedText: lastPushedText,
    textEmbedded: textEmbedded
  };
} // DEV-only global reference to the currently executing task


var currentTaskInDEV = null;

function getCurrentStackInDEV() {
  {
    if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
      return '';
    }

    return getStackByComponentStackNode(currentTaskInDEV.componentStack);
  }
}

function pushBuiltInComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 0,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushFunctionComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 1,
      parent: task.componentStack,
      type: type
    };
  }
}

function pushClassComponentStackInDEV(task, type) {
  {
    task.componentStack = {
      tag: 2,
      parent: task.componentStack,
      type: type
    };
  }
}

function popComponentStackInDEV(task) {
  {
    if (task.componentStack === null) {
      error('Unexpectedly popped too many stack frames. This is a bug in React.');
    } else {
      task.componentStack = task.componentStack.parent;
    }
  }
} // stash the component stack of an unwinding error until it is processed


var lastBoundaryErrorComponentStackDev = null;

function captureBoundaryErrorDetailsDev(boundary, error) {
  {
    var errorMessage;

    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error && typeof error.message === 'string') {
      errorMessage = error.message;
    } else {
      // eslint-disable-next-line react-internal/safe-string-coercion
      errorMessage = String(error);
    }

    var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();
    lastBoundaryErrorComponentStackDev = null;
    boundary.errorMessage = errorMessage;
    boundary.errorComponentStack = errorComponentStack;
  }
}

function logRecoverableError(request, error) {
  // If this callback errors, we intentionally let that error bubble up to become a fatal error
  // so that someone fixes the error reporting instead of hiding it.
  var errorDigest = request.onError(error);

  if (errorDigest != null && typeof errorDigest !== 'string') {
    // eslint-disable-next-line react-internal/prod-error-codes
    throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
  }

  return errorDigest;
}

function fatalError(request, error) {
  // This is called outside error handling code such as if the root errors outside
  // a suspense boundary or if the root suspense boundary's fallback errors.
  // It's also called if React itself or its host configs errors.
  var onShellError = request.onShellError;
  onShellError(error);
  var onFatalError = request.onFatalError;
  onFatalError(error);

  if (request.destination !== null) {
    request.status = CLOSED;
    closeWithError(request.destination, error);
  } else {
    request.status = CLOSING;
    request.fatalError = error;
  }
}

function renderSuspenseBoundary(request, task, props) {
  pushBuiltInComponentStackInDEV(task, 'Suspense');
  var parentBoundary = task.blockedBoundary;
  var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
  // the fallback so that we can later replace that segment with the content.
  // This also lets us split out the main content even if it doesn't suspend,
  // in case it ends up generating a large subtree of content.

  var fallback = props.fallback;
  var content = props.children;
  var fallbackAbortSet = new Set();
  var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
  var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.

  var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false);
  parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent

  parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.

  var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
  false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
  // no parent segment so there's nothing to wait on.

  contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
  // I suspect that there might be some efficiency benefits from not creating the suspended task
  // and instead just using the stack if possible.
  // TODO: Call this directly instead of messing with saving and restoring contexts.
  // We can reuse the current context and task to render the content immediately without
  // context switching. We just need to temporarily switch which boundary and which segment
  // we're writing to. If something suspends, it'll spawn new suspended task with that context.

  task.blockedBoundary = newBoundary;
  task.blockedSegment = contentRootSegment;

  try {
    // We use the safe form because we don't handle suspending here. Only error handling.
    renderNode(request, task, content);
    pushSegmentFinale(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
    contentRootSegment.status = COMPLETED;
    queueCompletedSegment(newBoundary, contentRootSegment);

    if (newBoundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      // Therefore we won't need the fallback. We early return so that we don't have to create
      // the fallback.
      popComponentStackInDEV(task);
      return;
    }
  } catch (error) {
    contentRootSegment.status = ERRORED;
    newBoundary.forceClientRender = true;
    newBoundary.errorDigest = logRecoverableError(request, error);

    {
      captureBoundaryErrorDetailsDev(newBoundary, error);
    } // We don't need to decrement any task numbers because we didn't spawn any new task.
    // We don't need to schedule any task because we know the parent has written yet.
    // We do need to fallthrough to create the fallback though.

  } finally {
    task.blockedBoundary = parentBoundary;
    task.blockedSegment = parentSegment;
  } // We create suspended task for the fallback because we don't want to actually work
  // on it yet in case we finish the main content, so we queue for later.


  var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);

  {
    suspendedFallbackTask.componentStack = task.componentStack;
  } // TODO: This should be queued at a separate lower priority queue so that we only work
  // on preparing fallbacks if we don't have any more main content to task on.


  request.pingedTasks.push(suspendedFallbackTask);
  popComponentStackInDEV(task);
}

function renderHostElement(request, task, type, props) {
  pushBuiltInComponentStackInDEV(task, type);
  var segment = task.blockedSegment;
  var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
  segment.lastPushedText = false;
  var prevContext = segment.formatContext;
  segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
  // need to pop back up and finish this subtree of HTML.

  renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
  // the correct context. Therefore this is not in a finally.

  segment.formatContext = prevContext;
  pushEndInstance(segment.chunks, type);
  segment.lastPushedText = false;
  popComponentStackInDEV(task);
}

function shouldConstruct$1(Component) {
  return Component.prototype && Component.prototype.isReactComponent;
}

function renderWithHooks(request, task, Component, props, secondArg) {
  var componentIdentity = {};
  prepareToUseHooks(task, componentIdentity);
  var result = Component(props, secondArg);
  return finishHooks(Component, props, result, secondArg);
}

function finishClassComponent(request, task, instance, Component, props) {
  var nextChildren = instance.render();

  {
    if (instance.props !== props) {
      if (!didWarnAboutReassigningProps) {
        error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
      }

      didWarnAboutReassigningProps = true;
    }
  }

  {
    var childContextTypes = Component.childContextTypes;

    if (childContextTypes !== null && childContextTypes !== undefined) {
      var previousContext = task.legacyContext;
      var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
      task.legacyContext = mergedContext;
      renderNodeDestructive(request, task, nextChildren);
      task.legacyContext = previousContext;
      return;
    }
  }

  renderNodeDestructive(request, task, nextChildren);
}

function renderClassComponent(request, task, Component, props) {
  pushClassComponentStackInDEV(task, Component);
  var maskedContext =  getMaskedContext(Component, task.legacyContext) ;
  var instance = constructClassInstance(Component, props, maskedContext);
  mountClassInstance(instance, Component, props, maskedContext);
  finishClassComponent(request, task, instance, Component, props);
  popComponentStackInDEV(task);
}

var didWarnAboutBadClass = {};
var didWarnAboutModulePatternComponent = {};
var didWarnAboutContextTypeOnFunctionComponent = {};
var didWarnAboutGetDerivedStateOnFunctionComponent = {};
var didWarnAboutReassigningProps = false;
var didWarnAboutDefaultPropsOnFunctionComponent = {};
var didWarnAboutGenerators = false;
var didWarnAboutMaps = false;
var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
// components for some reason.

function renderIndeterminateComponent(request, task, Component, props) {
  var legacyContext;

  {
    legacyContext = getMaskedContext(Component, task.legacyContext);
  }

  pushFunctionComponentStackInDEV(task, Component);

  {
    if (Component.prototype && typeof Component.prototype.render === 'function') {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

        didWarnAboutBadClass[componentName] = true;
      }
    }
  }

  var value = renderWithHooks(request, task, Component, props, legacyContext);
  var hasId = checkDidRenderIdHook();

  {
    // Support for module components is deprecated and is removed behind a flag.
    // Whether or not it would crash later, we want to show a good message in DEV first.
    if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      var _componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

        didWarnAboutModulePatternComponent[_componentName] = true;
      }
    }
  }

  if ( // Run these checks in production only if the flag is off.
  // Eventually we'll delete this branch altogether.
   typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    {
      var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName2]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

        didWarnAboutModulePatternComponent[_componentName2] = true;
      }
    }

    mountClassInstance(value, Component, props, legacyContext);
    finishClassComponent(request, task, value, Component, props);
  } else {

    {
      validateFunctionComponentInDev(Component);
    } // We're now successfully past this task, and we don't have to pop back to
    // the previous task every again, so we can use the destructive recursive form.


    if (hasId) {
      // This component materialized an id. We treat this as its own level, with
      // a single "child" slot.
      var prevTreeContext = task.treeContext;
      var totalChildren = 1;
      var index = 0;
      task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

      try {
        renderNodeDestructive(request, task, value);
      } finally {
        task.treeContext = prevTreeContext;
      }
    } else {
      renderNodeDestructive(request, task, value);
    }
  }

  popComponentStackInDEV(task);
}

function validateFunctionComponentInDev(Component) {
  {
    if (Component) {
      if (Component.childContextTypes) {
        error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
      }
    }

    if ( Component.defaultProps !== undefined) {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
        error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

        didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
      }
    }

    if (typeof Component.getDerivedStateFromProps === 'function') {
      var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
        error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

        didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
      }
    }

    if (typeof Component.contextType === 'object' && Component.contextType !== null) {
      var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
        error('%s: Function components do not support contextType.', _componentName4);

        didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
      }
    }
  }
}

function resolveDefaultProps(Component, baseProps) {
  if (Component && Component.defaultProps) {
    // Resolve default props. Taken from ReactElement
    var props = assign({}, baseProps);
    var defaultProps = Component.defaultProps;

    for (var propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }

    return props;
  }

  return baseProps;
}

function renderForwardRef(request, task, type, props, ref) {
  pushFunctionComponentStackInDEV(task, type.render);
  var children = renderWithHooks(request, task, type.render, props, ref);
  var hasId = checkDidRenderIdHook();

  if (hasId) {
    // This component materialized an id. We treat this as its own level, with
    // a single "child" slot.
    var prevTreeContext = task.treeContext;
    var totalChildren = 1;
    var index = 0;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);

    try {
      renderNodeDestructive(request, task, children);
    } finally {
      task.treeContext = prevTreeContext;
    }
  } else {
    renderNodeDestructive(request, task, children);
  }

  popComponentStackInDEV(task);
}

function renderMemo(request, task, type, props, ref) {
  var innerType = type.type;
  var resolvedProps = resolveDefaultProps(innerType, props);
  renderElement(request, task, innerType, resolvedProps, ref);
}

function renderContextConsumer(request, task, context, props) {
  // The logic below for Context differs depending on PROD or DEV mode. In
  // DEV mode, we create a separate object for Context.Consumer that acts
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
  // so we use the old behaviour (Context.Consumer references Context) to
  // reduce size and overhead. The separate object references context via
  // a property called "_context", which also gives us the ability to check
  // in DEV mode if this property exists or not and warn if it does not.
  {
    if (context._context === undefined) {
      // This may be because it's a Context (rather than a Consumer).
      // Or it may be because it's older React where they're the same thing.
      // We only want to warn if we're sure it's a new React.
      if (context !== context.Consumer) {
        if (!hasWarnedAboutUsingContextAsConsumer) {
          hasWarnedAboutUsingContextAsConsumer = true;

          error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
        }
      }
    } else {
      context = context._context;
    }
  }

  var render = props.children;

  {
    if (typeof render !== 'function') {
      error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
    }
  }

  var newValue = readContext(context);
  var newChildren = render(newValue);
  renderNodeDestructive(request, task, newChildren);
}

function renderContextProvider(request, task, type, props) {
  var context = type._context;
  var value = props.value;
  var children = props.children;
  var prevSnapshot;

  {
    prevSnapshot = task.context;
  }

  task.context = pushProvider(context, value);
  renderNodeDestructive(request, task, children);
  task.context = popProvider(context);

  {
    if (prevSnapshot !== task.context) {
      error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
    }
  }
}

function renderLazyComponent(request, task, lazyComponent, props, ref) {
  pushBuiltInComponentStackInDEV(task, 'Lazy');
  var payload = lazyComponent._payload;
  var init = lazyComponent._init;
  var Component = init(payload);
  var resolvedProps = resolveDefaultProps(Component, props);
  renderElement(request, task, Component, resolvedProps, ref);
  popComponentStackInDEV(task);
}

function renderElement(request, task, type, props, ref) {
  if (typeof type === 'function') {
    if (shouldConstruct$1(type)) {
      renderClassComponent(request, task, type, props);
      return;
    } else {
      renderIndeterminateComponent(request, task, type, props);
      return;
    }
  }

  if (typeof type === 'string') {
    renderHostElement(request, task, type, props);
    return;
  }

  switch (type) {
    // TODO: LegacyHidden acts the same as a fragment. This only works
    // because we currently assume that every instance of LegacyHidden is
    // accompanied by a host component wrapper. In the hidden mode, the host
    // component is given a `hidden` attribute, which ensures that the
    // initial HTML is not visible. To support the use of LegacyHidden as a
    // true fragment, without an extra DOM node, we would have to hide the
    // initial HTML in some other way.
    // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
    case REACT_LEGACY_HIDDEN_TYPE:
    case REACT_DEBUG_TRACING_MODE_TYPE:
    case REACT_STRICT_MODE_TYPE:
    case REACT_PROFILER_TYPE:
    case REACT_FRAGMENT_TYPE:
      {
        renderNodeDestructive(request, task, props.children);
        return;
      }

    case REACT_SUSPENSE_LIST_TYPE:
      {
        pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.

        renderNodeDestructive(request, task, props.children);
        popComponentStackInDEV(task);
        return;
      }

    case REACT_SCOPE_TYPE:
      {

        throw new Error('ReactDOMServer does not yet support scope components.');
      }
    // eslint-disable-next-line-no-fallthrough

    case REACT_SUSPENSE_TYPE:
      {
        {
          renderSuspenseBoundary(request, task, props);
        }

        return;
      }
  }

  if (typeof type === 'object' && type !== null) {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        {
          renderForwardRef(request, task, type, props, ref);
          return;
        }

      case REACT_MEMO_TYPE:
        {
          renderMemo(request, task, type, props, ref);
          return;
        }

      case REACT_PROVIDER_TYPE:
        {
          renderContextProvider(request, task, type, props);
          return;
        }

      case REACT_CONTEXT_TYPE:
        {
          renderContextConsumer(request, task, type, props);
          return;
        }

      case REACT_LAZY_TYPE:
        {
          renderLazyComponent(request, task, type, props);
          return;
        }
    }
  }

  var info = '';

  {
    if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
      info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
    }
  }

  throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
}

function validateIterable(iterable, iteratorFn) {
  {
    // We don't support rendering Generators because it's a mutation.
    // See https://github.com/facebook/react/issues/12995
    if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
    iterable[Symbol.toStringTag] === 'Generator') {
      if (!didWarnAboutGenerators) {
        error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
      }

      didWarnAboutGenerators = true;
    } // Warn about using Maps as children


    if (iterable.entries === iteratorFn) {
      if (!didWarnAboutMaps) {
        error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
      }

      didWarnAboutMaps = true;
    }
  }
}

function renderNodeDestructive(request, task, node) {
  {
    // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture
    // a component stack at the right place in the tree. We don't do this in renderNode
    // becuase it is not called at every layer of the tree and we may lose frames
    try {
      return renderNodeDestructiveImpl(request, task, node);
    } catch (x) {
      if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {
        // This is an error, stash the component stack if it is null.
        lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();
      } // rethrow so normal suspense logic can handle thrown value accordingly


      throw x;
    }
  }
} // This function by it self renders a node and consumes the task by mutating it
// to update the current execution state.


function renderNodeDestructiveImpl(request, task, node) {
  // Stash the node we're working on. We'll pick up from this task in case
  // something suspends.
  task.node = node; // Handle object types

  if (typeof node === 'object' && node !== null) {
    switch (node.$$typeof) {
      case REACT_ELEMENT_TYPE:
        {
          var element = node;
          var type = element.type;
          var props = element.props;
          var ref = element.ref;
          renderElement(request, task, type, props, ref);
          return;
        }

      case REACT_PORTAL_TYPE:
        throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
      // eslint-disable-next-line-no-fallthrough

      case REACT_LAZY_TYPE:
        {
          var lazyNode = node;
          var payload = lazyNode._payload;
          var init = lazyNode._init;
          var resolvedNode;

          {
            try {
              resolvedNode = init(payload);
            } catch (x) {
              if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
                // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be
                // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position
                // vs Component position. We do not want the frame for Errors so we exclusively do this in
                // the wakeable branch
                pushBuiltInComponentStackInDEV(task, 'Lazy');
              }

              throw x;
            }
          }

          renderNodeDestructive(request, task, resolvedNode);
          return;
        }
    }

    if (isArray(node)) {
      renderChildrenArray(request, task, node);
      return;
    }

    var iteratorFn = getIteratorFn(node);

    if (iteratorFn) {
      {
        validateIterable(node, iteratorFn);
      }

      var iterator = iteratorFn.call(node);

      if (iterator) {
        // We need to know how many total children are in this set, so that we
        // can allocate enough id slots to acommodate them. So we must exhaust
        // the iterator before we start recursively rendering the children.
        // TODO: This is not great but I think it's inherent to the id
        // generation algorithm.
        var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.

        if (!step.done) {
          var children = [];

          do {
            children.push(step.value);
            step = iterator.next();
          } while (!step.done);

          renderChildrenArray(request, task, children);
          return;
        }

        return;
      }
    }

    var childString = Object.prototype.toString.call(node);
    throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
  }

  if (typeof node === 'string') {
    var segment = task.blockedSegment;
    segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);
    return;
  }

  if (typeof node === 'number') {
    var _segment = task.blockedSegment;
    _segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);
    return;
  }

  {
    if (typeof node === 'function') {
      error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
    }
  }
}

function renderChildrenArray(request, task, children) {
  var totalChildren = children.length;

  for (var i = 0; i < totalChildren; i++) {
    var prevTreeContext = task.treeContext;
    task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);

    try {
      // We need to use the non-destructive form so that we can safely pop back
      // up and render the sibling if something suspends.
      renderNode(request, task, children[i]);
    } finally {
      task.treeContext = prevTreeContext;
    }
  }
}

function spawnNewSuspendedTask(request, task, x) {
  // Something suspended, we'll need to create a new segment and resolve it later.
  var segment = task.blockedSegment;
  var insertionIndex = segment.chunks.length;
  var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed
  segment.lastPushedText, // Assume we are text embedded at the trailing edge
  true);
  segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it

  segment.lastPushedText = false;
  var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);

  {
    if (task.componentStack !== null) {
      // We pop one task off the stack because the node that suspended will be tried again,
      // which will add it back onto the stack.
      newTask.componentStack = task.componentStack.parent;
    }
  }

  var ping = newTask.ping;
  x.then(ping, ping);
} // This is a non-destructive form of rendering a node. If it suspends it spawns
// a new task and restores the context of this task to what it was before.


function renderNode(request, task, node) {
  // TODO: Store segment.children.length here and reset it in case something
  // suspended partially through writing something.
  // Snapshot the current context in case something throws to interrupt the
  // process.
  var previousFormatContext = task.blockedSegment.formatContext;
  var previousLegacyContext = task.legacyContext;
  var previousContext = task.context;
  var previousComponentStack = null;

  {
    previousComponentStack = task.componentStack;
  }

  try {
    return renderNodeDestructive(request, task, node);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.

      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      }

      return;
    } else {
      // Restore the context. We assume that this will be restored by the inner
      // functions in case nothing throws so we don't use "finally" here.
      task.blockedSegment.formatContext = previousFormatContext;
      task.legacyContext = previousLegacyContext;
      task.context = previousContext; // Restore all active ReactContexts to what they were before.

      switchContext(previousContext);

      {
        task.componentStack = previousComponentStack;
      } // We assume that we don't need the correct context.
      // Let's terminate the rest of the tree and don't render any siblings.


      throw x;
    }
  }
}

function erroredTask(request, boundary, segment, error) {
  // Report the error to a global handler.
  var errorDigest = logRecoverableError(request, error);

  if (boundary === null) {
    fatalError(request, error);
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;
      boundary.errorDigest = errorDigest;

      {
        captureBoundaryErrorDetailsDev(boundary, error);
      } // Regardless of what happens next, this boundary won't be displayed,
      // so we can flush it, if the parent already flushed.


      if (boundary.parentFlushed) {
        // We don't have a preference where in the queue this goes since it's likely
        // to error on the client anyway. However, intentionally client-rendered
        // boundaries should be flushed earlier so that they can start on the client.
        // We reuse the same queue for errors.
        request.clientRenderedBoundaries.push(boundary);
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function abortTaskSoft(task) {
  // This aborts task without aborting the parent boundary that it blocks.
  // It's used for when we didn't need this task to complete the tree.
  // If task was needed, then it should use abortTask instead.
  var request = this;
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;
  finishedTask(request, boundary, segment);
}

function abortTask(task, request, reason) {
  // This aborts the task and aborts the parent that it blocks, putting it into
  // client rendered mode.
  var boundary = task.blockedBoundary;
  var segment = task.blockedSegment;
  segment.status = ABORTED;

  if (boundary === null) {
    request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
    // the request;

    if (request.status !== CLOSED) {
      request.status = CLOSED;

      if (request.destination !== null) {
        close(request.destination);
      }
    }
  } else {
    boundary.pendingTasks--;

    if (!boundary.forceClientRender) {
      boundary.forceClientRender = true;

      var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;

      boundary.errorDigest = request.onError(_error);

      {
        var errorPrefix = 'The server did not finish this Suspense boundary: ';

        if (_error && typeof _error.message === 'string') {
          _error = errorPrefix + _error.message;
        } else {
          // eslint-disable-next-line react-internal/safe-string-coercion
          _error = errorPrefix + String(_error);
        }

        var previousTaskInDev = currentTaskInDEV;
        currentTaskInDEV = task;

        try {
          captureBoundaryErrorDetailsDev(boundary, _error);
        } finally {
          currentTaskInDEV = previousTaskInDev;
        }
      }

      if (boundary.parentFlushed) {
        request.clientRenderedBoundaries.push(boundary);
      }
    } // If this boundary was still pending then we haven't already cancelled its fallbacks.
    // We'll need to abort the fallbacks, which will also error that parent boundary.


    boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
      return abortTask(fallbackTask, request, reason);
    });
    boundary.fallbackAbortableTasks.clear();
    request.allPendingTasks--;

    if (request.allPendingTasks === 0) {
      var onAllReady = request.onAllReady;
      onAllReady();
    }
  }
}

function queueCompletedSegment(boundary, segment) {
  if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
    // This is an empty segment. There's nothing to write, so we can instead transfer the ID
    // to the child. That way any existing references point to the child.
    var childSegment = segment.children[0];
    childSegment.id = segment.id;
    childSegment.parentFlushed = true;

    if (childSegment.status === COMPLETED) {
      queueCompletedSegment(boundary, childSegment);
    }
  } else {
    var completedSegments = boundary.completedSegments;
    completedSegments.push(segment);
  }
}

function finishedTask(request, boundary, segment) {
  if (boundary === null) {
    if (segment.parentFlushed) {
      if (request.completedRootSegment !== null) {
        throw new Error('There can only be one root segment. This is a bug in React.');
      }

      request.completedRootSegment = segment;
    }

    request.pendingRootTasks--;

    if (request.pendingRootTasks === 0) {
      // We have completed the shell so the shell can't error anymore.
      request.onShellError = noop$1;
      var onShellReady = request.onShellReady;
      onShellReady();
    }
  } else {
    boundary.pendingTasks--;

    if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
      // This must have been the last segment we were waiting on. This boundary is now complete.
      if (segment.parentFlushed) {
        // Our parent segment already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
        }
      }

      if (boundary.parentFlushed) {
        // The segment might be part of a segment that didn't flush yet, but if the boundary's
        // parent flushed, we need to schedule the boundary to be emitted.
        request.completedBoundaries.push(boundary);
      } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
      // This needs to happen after we read the parentFlushed flags because aborting can finish
      // work which can trigger user code, which can start flushing, which can change those flags.


      boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
      boundary.fallbackAbortableTasks.clear();
    } else {
      if (segment.parentFlushed) {
        // Our parent already flushed, so we need to schedule this segment to be emitted.
        // If it is a segment that was aborted, we'll write other content instead so we don't need
        // to emit it.
        if (segment.status === COMPLETED) {
          queueCompletedSegment(boundary, segment);
          var completedSegments = boundary.completedSegments;

          if (completedSegments.length === 1) {
            // This is the first time since we last flushed that we completed anything.
            // We can schedule this boundary to emit its partially completed segments early
            // in case the parent has already been flushed.
            if (boundary.parentFlushed) {
              request.partialBoundaries.push(boundary);
            }
          }
        }
      }
    }
  }

  request.allPendingTasks--;

  if (request.allPendingTasks === 0) {
    // This needs to be called at the very end so that we can synchronously write the result
    // in the callback if needed.
    var onAllReady = request.onAllReady;
    onAllReady();
  }
}

function retryTask(request, task) {
  var segment = task.blockedSegment;

  if (segment.status !== PENDING) {
    // We completed this by other means before we had a chance to retry it.
    return;
  } // We restore the context to what it was when we suspended.
  // We don't restore it after we leave because it's likely that we'll end up
  // needing a very similar context soon again.


  switchContext(task.context);
  var prevTaskInDEV = null;

  {
    prevTaskInDEV = currentTaskInDEV;
    currentTaskInDEV = task;
  }

  try {
    // We call the destructive form that mutates this task. That way if something
    // suspends again, we can reuse the same task instead of spawning a new one.
    renderNodeDestructive(request, task, task.node);
    pushSegmentFinale(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);
    task.abortSet.delete(task);
    segment.status = COMPLETED;
    finishedTask(request, task.blockedBoundary, segment);
  } catch (x) {
    resetHooksState();

    if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
      // Something suspended again, let's pick it back up later.
      var ping = task.ping;
      x.then(ping, ping);
    } else {
      task.abortSet.delete(task);
      segment.status = ERRORED;
      erroredTask(request, task.blockedBoundary, segment, x);
    }
  } finally {
    {
      currentTaskInDEV = prevTaskInDEV;
    }
  }
}

function performWork(request) {
  if (request.status === CLOSED) {
    return;
  }

  var prevContext = getActiveContext();
  var prevDispatcher = ReactCurrentDispatcher$1.current;
  ReactCurrentDispatcher$1.current = Dispatcher;
  var prevGetCurrentStackImpl;

  {
    prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
    ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
  }

  var prevResponseState = currentResponseState;
  setCurrentResponseState(request.responseState);

  try {
    var pingedTasks = request.pingedTasks;
    var i;

    for (i = 0; i < pingedTasks.length; i++) {
      var task = pingedTasks[i];
      retryTask(request, task);
    }

    pingedTasks.splice(0, i);

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  } finally {
    setCurrentResponseState(prevResponseState);
    ReactCurrentDispatcher$1.current = prevDispatcher;

    {
      ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
    }

    if (prevDispatcher === Dispatcher) {
      // This means that we were in a reentrant work loop. This could happen
      // in a renderer that supports synchronous work like renderToString,
      // when it's called from within another renderer.
      // Normally we don't bother switching the contexts to their root/default
      // values when leaving because we'll likely need the same or similar
      // context again. However, when we're inside a synchronous loop like this
      // we'll to restore the context to what it was before returning.
      switchContext(prevContext);
    }
  }
}

function flushSubtree(request, destination, segment) {
  segment.parentFlushed = true;

  switch (segment.status) {
    case PENDING:
      {
        // We're emitting a placeholder for this segment to be filled in later.
        // Therefore we'll need to assign it an ID - to refer to it by.
        var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately

        segment.lastPushedText = false;
        segment.textEmbedded = false;
        return writePlaceholder(destination, request.responseState, segmentID);
      }

    case COMPLETED:
      {
        segment.status = FLUSHED;
        var r = true;
        var chunks = segment.chunks;
        var chunkIdx = 0;
        var children = segment.children;

        for (var childIdx = 0; childIdx < children.length; childIdx++) {
          var nextChild = children[childIdx]; // Write all the chunks up until the next child.

          for (; chunkIdx < nextChild.index; chunkIdx++) {
            writeChunk(destination, chunks[chunkIdx]);
          }

          r = flushSegment(request, destination, nextChild);
        } // Finally just write all the remaining chunks


        for (; chunkIdx < chunks.length - 1; chunkIdx++) {
          writeChunk(destination, chunks[chunkIdx]);
        }

        if (chunkIdx < chunks.length) {
          r = writeChunkAndReturn(destination, chunks[chunkIdx]);
        }

        return r;
      }

    default:
      {
        throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
      }
  }
}

function flushSegment(request, destination, segment) {
  var boundary = segment.boundary;

  if (boundary === null) {
    // Not a suspense boundary.
    return flushSubtree(request, destination, segment);
  }

  boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
  // emit the content or the fallback now.

  if (boundary.forceClientRender) {
    // Emit a client rendered suspense boundary wrapper.
    // We never queue the inner boundary so we'll never emit its content or partial segments.
    writeStartClientRenderedSuspenseBoundary(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndClientRenderedSuspenseBoundary(destination, request.responseState);
  } else if (boundary.pendingTasks > 0) {
    // This boundary is still loading. Emit a pending suspense boundary wrapper.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;

    if (boundary.completedSegments.length > 0) {
      // If this is at least partially complete, we can queue it to be partially emitted early.
      request.partialBoundaries.push(boundary);
    } /// This is the first time we should have referenced this ID.


    var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
    writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else if (boundary.byteSize > request.progressiveChunkSize) {
    // This boundary is large and will be emitted separately so that we can progressively show
    // other content. We add it to the queue during the flush because we have to ensure that
    // the parent flushes first so that there's something to inject it into.
    // We also have to make sure that it's emitted into the queue in a deterministic slot.
    // I.e. we can't insert it here when it completes.
    // Assign an ID to refer to the future content by.
    boundary.rootSegmentID = request.nextSegmentId++;
    request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.

    writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.

    flushSubtree(request, destination, segment);
    return writeEndPendingSuspenseBoundary(destination, request.responseState);
  } else {
    // We can inline this boundary's content as a complete boundary.
    writeStartCompletedSuspenseBoundary(destination, request.responseState);
    var completedSegments = boundary.completedSegments;

    if (completedSegments.length !== 1) {
      throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
    }

    var contentSegment = completedSegments[0];
    flushSegment(request, destination, contentSegment);
    return writeEndCompletedSuspenseBoundary(destination, request.responseState);
  }
}

function flushClientRenderedBoundary(request, destination, boundary) {
  return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);
}

function flushSegmentContainer(request, destination, segment) {
  writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
  flushSegment(request, destination, segment);
  return writeEndSegment(destination, segment.formatContext);
}

function flushCompletedBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];
    flushPartiallyCompletedSegment(request, destination, boundary, segment);
  }

  completedSegments.length = 0;
  return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
}

function flushPartialBoundary(request, destination, boundary) {
  var completedSegments = boundary.completedSegments;
  var i = 0;

  for (; i < completedSegments.length; i++) {
    var segment = completedSegments[i];

    if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
      i++;
      completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
      // might want to write later.

      return false;
    }
  }

  completedSegments.splice(0, i);
  return true;
}

function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
  if (segment.status === FLUSHED) {
    // We've already flushed this inline.
    return true;
  }

  var segmentID = segment.id;

  if (segmentID === -1) {
    // This segment wasn't previously referred to. This happens at the root of
    // a boundary. We make kind of a leap here and assume this is the root.
    var rootSegmentID = segment.id = boundary.rootSegmentID;

    if (rootSegmentID === -1) {
      throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
    }

    return flushSegmentContainer(request, destination, segment);
  } else {
    flushSegmentContainer(request, destination, segment);
    return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
  }
}

function flushCompletedQueues(request, destination) {
  beginWriting();

  try {
    // The structure of this is to go through each queue one by one and write
    // until the sink tells us to stop. When we should stop, we still finish writing
    // that item fully and then yield. At that point we remove the already completed
    // items up until the point we completed them.
    // TODO: Emit preloading.
    // TODO: It's kind of unfortunate to keep checking this array after we've already
    // emitted the root.
    var completedRootSegment = request.completedRootSegment;

    if (completedRootSegment !== null && request.pendingRootTasks === 0) {
      flushSegment(request, destination, completedRootSegment);
      request.completedRootSegment = null;
      writeCompletedRoot(destination, request.responseState);
    } // We emit client rendering instructions for already emitted boundaries first.
    // This is so that we can signal to the client to start client rendering them as
    // soon as possible.


    var clientRenderedBoundaries = request.clientRenderedBoundaries;
    var i;

    for (i = 0; i < clientRenderedBoundaries.length; i++) {
      var boundary = clientRenderedBoundaries[i];

      if (!flushClientRenderedBoundary(request, destination, boundary)) {
        request.destination = null;
        i++;
        clientRenderedBoundaries.splice(0, i);
        return;
      }
    }

    clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
    // that are completely done since we can actually show them, than it is to emit
    // any individual segments from a partially complete boundary.

    var completedBoundaries = request.completedBoundaries;

    for (i = 0; i < completedBoundaries.length; i++) {
      var _boundary = completedBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary)) {
        request.destination = null;
        i++;
        completedBoundaries.splice(0, i);
        return;
      }
    }

    completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
    // we continue with lower priorities.

    completeWriting(destination);
    beginWriting(destination); // TODO: Here we'll emit data used by hydration.
    // Next we emit any segments of any boundaries that are partially complete
    // but not deeply complete.

    var partialBoundaries = request.partialBoundaries;

    for (i = 0; i < partialBoundaries.length; i++) {
      var _boundary2 = partialBoundaries[i];

      if (!flushPartialBoundary(request, destination, _boundary2)) {
        request.destination = null;
        i++;
        partialBoundaries.splice(0, i);
        return;
      }
    }

    partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
    // boundaries added to it in case they were too larged to be inlined.
    // New ones might be added in this loop.

    var largeBoundaries = request.completedBoundaries;

    for (i = 0; i < largeBoundaries.length; i++) {
      var _boundary3 = largeBoundaries[i];

      if (!flushCompletedBoundary(request, destination, _boundary3)) {
        request.destination = null;
        i++;
        largeBoundaries.splice(0, i);
        return;
      }
    }

    largeBoundaries.splice(0, i);
  } finally {
    completeWriting(destination);
    flushBuffered(destination);

    if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
    // either they have pending task or they're complete.
    ) {
        {
          if (request.abortableTasks.size !== 0) {
            error('There was still abortable task at the root when we closed. This is a bug in React.');
          }
        } // We're done.


        close(destination);
      }
  }
}

function startWork(request) {
  scheduleWork(function () {
    return performWork(request);
  });
}
function startFlowing(request, destination) {
  if (request.status === CLOSING) {
    request.status = CLOSED;
    closeWithError(destination, request.fatalError);
    return;
  }

  if (request.status === CLOSED) {
    return;
  }

  if (request.destination !== null) {
    // We're already flowing.
    return;
  }

  request.destination = destination;

  try {
    flushCompletedQueues(request, destination);
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.

function abort(request, reason) {
  try {
    var abortableTasks = request.abortableTasks;
    abortableTasks.forEach(function (task) {
      return abortTask(task, request, reason);
    });
    abortableTasks.clear();

    if (request.destination !== null) {
      flushCompletedQueues(request, request.destination);
    }
  } catch (error) {
    logRecoverableError(request, error);
    fatalError(request, error);
  }
}

function createDrainHandler(destination, request) {
  return function () {
    return startFlowing(request, destination);
  };
}

function createAbortHandler(request, reason) {
  return function () {
    return abort(request, reason);
  };
}

function createRequestImpl(children, options) {
  return createRequest(children, createResponseState(options ? options.identifierPrefix : undefined, options ? options.nonce : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, options ? options.onAllReady : undefined, options ? options.onShellReady : undefined, options ? options.onShellError : undefined, undefined);
}

function renderToPipeableStream(children, options) {
  var request = createRequestImpl(children, options);
  var hasStartedFlowing = false;
  startWork(request);
  return {
    pipe: function (destination) {
      if (hasStartedFlowing) {
        throw new Error('React currently only supports piping to one writable stream.');
      }

      hasStartedFlowing = true;
      startFlowing(request, destination);
      destination.on('drain', createDrainHandler(destination, request));
      destination.on('error', createAbortHandler(request, // eslint-disable-next-line react-internal/prod-error-codes
      new Error('The destination stream errored while writing data.')));
      destination.on('close', createAbortHandler(request, // eslint-disable-next-line react-internal/prod-error-codes
      new Error('The destination stream closed early.')));
      return destination;
    },
    abort: function (reason) {
      abort(request, reason);
    }
  };
}

exports.renderToPipeableStream = renderToPipeableStream;
exports.version = ReactVersion;
  })();
}
/**
 * @license React
 * react-dom-server.node.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var aa=require("util"),ba=require("react"),k=null,l=0,q=!0;
function r(a,b){if("string"===typeof b){if(0!==b.length)if(2048<3*b.length)0<l&&(t(a,k.subarray(0,l)),k=new Uint8Array(2048),l=0),t(a,u.encode(b));else{var c=k;0<l&&(c=k.subarray(l));c=u.encodeInto(b,c);var d=c.read;l+=c.written;d<b.length&&(t(a,k),k=new Uint8Array(2048),l=u.encodeInto(b.slice(d),k).written);2048===l&&(t(a,k),k=new Uint8Array(2048),l=0)}}else 0!==b.byteLength&&(2048<b.byteLength?(0<l&&(t(a,k.subarray(0,l)),k=new Uint8Array(2048),l=0),t(a,b)):(c=k.length-l,c<b.byteLength&&(0===c?t(a,
k):(k.set(b.subarray(0,c),l),l+=c,t(a,k),b=b.subarray(c)),k=new Uint8Array(2048),l=0),k.set(b,l),l+=b.byteLength,2048===l&&(t(a,k),k=new Uint8Array(2048),l=0)))}function t(a,b){a=a.write(b);q=q&&a}function w(a,b){r(a,b);return q}function ca(a){k&&0<l&&a.write(k.subarray(0,l));k=null;l=0;q=!0}var u=new aa.TextEncoder;function x(a){return u.encode(a)}
var y=Object.prototype.hasOwnProperty,da=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ea={},fa={};
function ha(a){if(y.call(fa,a))return!0;if(y.call(ea,a))return!1;if(da.test(a))return fa[a]=!0;ea[a]=!0;return!1}function z(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}var A={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){A[a]=new z(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];A[b]=new z(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){A[a]=new z(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){A[a]=new z(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){A[a]=new z(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){A[a]=new z(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){A[a]=new z(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){A[a]=new z(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){A[a]=new z(a,5,!1,a.toLowerCase(),null,!1,!1)});var ia=/[\-:]([a-z])/g;function ja(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ia,
ja);A[b]=new z(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ia,ja);A[b]=new z(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ia,ja);A[b]=new z(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){A[a]=new z(a,1,!1,a.toLowerCase(),null,!1,!1)});
A.xlinkHref=new z("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){A[a]=new z(a,1,!1,a.toLowerCase(),null,!0,!0)});
var B={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,
fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ka=["Webkit","ms","Moz","O"];Object.keys(B).forEach(function(a){ka.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);B[b]=B[a]})});var la=/["'&<>]/;
function F(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=la.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a}
var ma=/([A-Z])/g,pa=/^ms-/,qa=Array.isArray,ra=x("<script>"),sa=x("\x3c/script>"),ta=x('<script src="'),ua=x('<script type="module" src="'),va=x('" async="">\x3c/script>'),wa=/(<\/|<)(s)(cript)/gi;function xa(a,b,c,d){return""+b+("s"===c?"\\u0073":"\\u0053")+d}function G(a,b){return{insertionMode:a,selectedValue:b}}
function ya(a,b,c){switch(b){case "select":return G(1,null!=c.value?c.value:c.defaultValue);case "svg":return G(2,null);case "math":return G(3,null);case "foreignObject":return G(1,null);case "table":return G(4,null);case "thead":case "tbody":case "tfoot":return G(5,null);case "colgroup":return G(7,null);case "tr":return G(6,null)}return 4<=a.insertionMode||0===a.insertionMode?G(1,null):a}var za=x("\x3c!-- --\x3e");function Aa(a,b,c,d){if(""===b)return d;d&&a.push(za);a.push(F(b));return!0}
var Ba=new Map,Ca=x(' style="'),Da=x(":"),Ea=x(";");
function Fa(a,b,c){if("object"!==typeof c)throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");b=!0;for(var d in c)if(y.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=F(d);f=F((""+f).trim())}else{e=d;var g=Ba.get(e);void 0!==g?e=g:(g=x(F(e.replace(ma,"-$1").toLowerCase().replace(pa,"-ms-"))),Ba.set(e,g),e=g);f="number"===typeof f?0===f||y.call(B,
d)?""+f:f+"px":F((""+f).trim())}b?(b=!1,a.push(Ca,e,Da,f)):a.push(Ea,e,Da,f)}}b||a.push(H)}var I=x(" "),J=x('="'),H=x('"'),Ga=x('=""');
function K(a,b,c,d){switch(c){case "style":Fa(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=A.hasOwnProperty(c)?A[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=b.attributeName;switch(b.type){case 3:d&&a.push(I,c,Ga);break;case 4:!0===d?a.push(I,c,Ga):!1!==
d&&a.push(I,c,J,F(d),H);break;case 5:isNaN(d)||a.push(I,c,J,F(d),H);break;case 6:!isNaN(d)&&1<=d&&a.push(I,c,J,F(d),H);break;default:b.sanitizeURL&&(d=""+d),a.push(I,c,J,F(d),H)}}else if(ha(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(I,c,J,F(d),H)}}var L=x(">"),Ha=x("/>");
function M(a,b,c){if(null!=b){if(null!=c)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!==typeof b||!("__html"in b))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");b=b.__html;null!==b&&void 0!==b&&a.push(""+b)}}function Ia(a){var b="";ba.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}var Ja=x(' selected=""');
function Ka(a,b,c,d){a.push(N(c));var f=c=null,e;for(e in b)if(y.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:K(a,d,e,g)}}a.push(L);M(a,f,c);return"string"===typeof c?(a.push(F(c)),null):c}var La=x("\n"),Ma=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Na=new Map;function N(a){var b=Na.get(a);if(void 0===b){if(!Ma.test(a))throw Error("Invalid tag: "+a);b=x("<"+a);Na.set(a,b)}return b}var Oa=x("<!DOCTYPE html>");
function Pa(a,b,c,d,f){switch(b){case "select":a.push(N("select"));var e=null,g=null;for(p in c)if(y.call(c,p)){var h=c[p];if(null!=h)switch(p){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:K(a,d,p,h)}}a.push(L);M(a,g,e);return e;case "option":g=f.selectedValue;a.push(N("option"));var m=h=null,n=null;var p=null;for(e in c)if(y.call(c,e)){var v=c[e];if(null!=v)switch(e){case "children":h=v;break;case "selected":n=v;break;case "dangerouslySetInnerHTML":p=
v;break;case "value":m=v;default:K(a,d,e,v)}}if(null!=g)if(c=null!==m?""+m:Ia(h),qa(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(Ja);break}}else""+g===c&&a.push(Ja);else n&&a.push(Ja);a.push(L);M(a,p,h);return h;case "textarea":a.push(N("textarea"));p=g=e=null;for(h in c)if(y.call(c,h)&&(m=c[h],null!=m))switch(h){case "children":p=m;break;case "value":e=m;break;case "defaultValue":g=m;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
default:K(a,d,h,m)}null===e&&null!==g&&(e=g);a.push(L);if(null!=p){if(null!=e)throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");if(qa(p)&&1<p.length)throw Error("<textarea> can only have at most one child.");e=""+p}"string"===typeof e&&"\n"===e[0]&&a.push(La);null!==e&&a.push(F(""+e));return null;case "input":a.push(N("input"));m=p=h=e=null;for(g in c)if(y.call(c,g)&&(n=c[g],null!=n))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error("input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");
case "defaultChecked":m=n;break;case "defaultValue":h=n;break;case "checked":p=n;break;case "value":e=n;break;default:K(a,d,g,n)}null!==p?K(a,d,"checked",p):null!==m&&K(a,d,"checked",m);null!==e?K(a,d,"value",e):null!==h&&K(a,d,"value",h);a.push(Ha);return null;case "menuitem":a.push(N("menuitem"));for(var C in c)if(y.call(c,C)&&(e=c[C],null!=e))switch(C){case "children":case "dangerouslySetInnerHTML":throw Error("menuitems cannot have `children` nor `dangerouslySetInnerHTML`.");default:K(a,d,C,e)}a.push(L);
return null;case "title":a.push(N("title"));e=null;for(v in c)if(y.call(c,v)&&(g=c[v],null!=g))switch(v){case "children":e=g;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <title>.");default:K(a,d,v,g)}a.push(L);return e;case "listing":case "pre":a.push(N(b));g=e=null;for(m in c)if(y.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:K(a,d,m,h)}a.push(L);if(null!=g){if(null!=e)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
if("object"!==typeof g||!("__html"in g))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push(La,c):a.push(""+c))}"string"===typeof e&&"\n"===e[0]&&a.push(La);return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(N(b));
for(var D in c)if(y.call(c,D)&&(e=c[D],null!=e))switch(D){case "children":case "dangerouslySetInnerHTML":throw Error(b+" is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:K(a,d,D,e)}a.push(Ha);return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return Ka(a,c,b,d);case "html":return 0===f.insertionMode&&a.push(Oa),Ka(a,c,
b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return Ka(a,c,b,d);a.push(N(b));g=e=null;for(n in c)if(y.call(c,n)&&(h=c[n],null!=h))switch(n){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "style":Fa(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ha(n)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(I,n,J,F(h),H)}a.push(L);M(a,g,e);return e}}
var Qa=x("</"),Ra=x(">"),Sa=x('<template id="'),Ta=x('"></template>'),Ua=x("\x3c!--$--\x3e"),Va=x('\x3c!--$?--\x3e<template id="'),Wa=x('"></template>'),Xa=x("\x3c!--$!--\x3e"),Ya=x("\x3c!--/$--\x3e"),Za=x("<template"),$a=x('"'),ab=x(' data-dgst="');x(' data-msg="');x(' data-stck="');var bb=x("></template>");function cb(a,b,c){r(a,Va);if(null===c)throw Error("An ID must have been assigned before we can complete the boundary.");r(a,c);return w(a,Wa)}
var db=x('<div hidden id="'),eb=x('">'),fb=x("</div>"),gb=x('<svg aria-hidden="true" style="display:none" id="'),hb=x('">'),ib=x("</svg>"),jb=x('<math aria-hidden="true" style="display:none" id="'),kb=x('">'),lb=x("</math>"),mb=x('<table hidden id="'),nb=x('">'),ob=x("</table>"),pb=x('<table hidden><tbody id="'),qb=x('">'),rb=x("</tbody></table>"),sb=x('<table hidden><tr id="'),tb=x('">'),ub=x("</tr></table>"),vb=x('<table hidden><colgroup id="'),wb=x('">'),xb=x("</colgroup></table>");
function yb(a,b,c,d){switch(c.insertionMode){case 0:case 1:return r(a,db),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,eb);case 2:return r(a,gb),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,hb);case 3:return r(a,jb),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,kb);case 4:return r(a,mb),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,nb);case 5:return r(a,pb),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,qb);case 6:return r(a,sb),r(a,b.segmentPrefix),r(a,d.toString(16)),w(a,tb);case 7:return r(a,vb),r(a,
b.segmentPrefix),r(a,d.toString(16)),w(a,wb);default:throw Error("Unknown insertion mode. This is a bug in React.");}}function zb(a,b){switch(b.insertionMode){case 0:case 1:return w(a,fb);case 2:return w(a,ib);case 3:return w(a,lb);case 4:return w(a,ob);case 5:return w(a,rb);case 6:return w(a,ub);case 7:return w(a,xb);default:throw Error("Unknown insertion mode. This is a bug in React.");}}
var Ab=x('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),Bb=x('$RS("'),Cb=x('","'),Db=x('")\x3c/script>'),Fb=x('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),
Gb=x('$RC("'),Hb=x('","'),Ib=x('")\x3c/script>'),Jb=x('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),Kb=x('$RX("'),Lb=x('"'),Mb=x(")\x3c/script>"),Nb=x(","),Ob=/[<\u2028\u2029]/g;
function Pb(a){return JSON.stringify(a).replace(Ob,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}
var O=Object.assign,Qb=Symbol.for("react.element"),Rb=Symbol.for("react.portal"),Sb=Symbol.for("react.fragment"),Tb=Symbol.for("react.strict_mode"),Ub=Symbol.for("react.profiler"),Vb=Symbol.for("react.provider"),Wb=Symbol.for("react.context"),Xb=Symbol.for("react.forward_ref"),Yb=Symbol.for("react.suspense"),Zb=Symbol.for("react.suspense_list"),$b=Symbol.for("react.memo"),ac=Symbol.for("react.lazy"),bc=Symbol.for("react.scope"),cc=Symbol.for("react.debug_trace_mode"),dc=Symbol.for("react.legacy_hidden"),
ec=Symbol.for("react.default_value"),fc=Symbol.iterator;
function gc(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Sb:return"Fragment";case Rb:return"Portal";case Ub:return"Profiler";case Tb:return"StrictMode";case Yb:return"Suspense";case Zb:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Wb:return(a.displayName||"Context")+".Consumer";case Vb:return(a._context.displayName||"Context")+".Provider";case Xb:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case $b:return b=a.displayName||null,null!==b?b:gc(a.type)||"Memo";case ac:b=a._payload;a=a._init;try{return gc(a(b))}catch(c){}}return null}var hc={};function ic(a,b){a=a.contextTypes;if(!a)return hc;var c={},d;for(d in a)c[d]=b[d];return c}var P=null;
function Q(a,b){if(a!==b){a.context._currentValue=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");}else{if(null===c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");Q(a,c)}b.context._currentValue=b.value}}function jc(a){a.context._currentValue=a.parentValue;a=a.parent;null!==a&&jc(a)}
function kc(a){var b=a.parent;null!==b&&kc(b);a.context._currentValue=a.value}function lc(a,b){a.context._currentValue=a.parentValue;a=a.parent;if(null===a)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===b.depth?Q(a,b):lc(a,b)}
function mc(a,b){var c=b.parent;if(null===c)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===c.depth?Q(a,c):mc(a,c);b.context._currentValue=b.value}function nc(a){var b=P;b!==a&&(null===b?kc(a):null===a?jc(b):b.depth===a.depth?Q(b,a):b.depth>a.depth?lc(b,a):mc(b,a),P=a)}
var oc={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}};
function pc(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=oc;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:O({},f,g),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b=
a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&oc.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=O({},e,h)):O(e,h))}a.state=e}else e.queue=null}
var qc={id:1,overflow:""};function rc(a,b,c){var d=a.id;a=a.overflow;var f=32-sc(d)-1;d&=~(1<<f);c+=1;var e=32-sc(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-sc(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}var sc=Math.clz32?Math.clz32:tc,uc=Math.log,vc=Math.LN2;function tc(a){a>>>=0;return 0===a?32:31-(uc(a)/vc|0)|0}function wc(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}
var xc="function"===typeof Object.is?Object.is:wc,R=null,yc=null,zc=null,S=null,T=!1,Ac=!1,U=0,V=null,Bc=0;
function W(){if(null===R)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");return R}
function Cc(){if(0<Bc)throw Error("Rendered more hooks than during the previous render");return{memoizedState:null,queue:null,next:null}}function Dc(){null===S?null===zc?(T=!1,zc=S=Cc()):(T=!0,S=zc):null===S.next?(T=!1,S=S.next=Cc()):(T=!0,S=S.next);return S}function Ec(){yc=R=null;Ac=!1;zc=null;Bc=0;S=V=null}function Fc(a,b){return"function"===typeof b?b(a):b}
function Gc(a,b,c){R=W();S=Dc();if(T){var d=S.queue;b=d.dispatch;if(null!==V&&(c=V.get(d),void 0!==c)){V.delete(d);d=S.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);S.memoizedState=d;return[d,b]}return[S.memoizedState,b]}a=a===Fc?"function"===typeof b?b():b:void 0!==c?c(b):b;S.memoizedState=a;a=S.queue={last:null,dispatch:null};a=a.dispatch=Hc.bind(null,R,a);return[S.memoizedState,a]}
function Ic(a,b){R=W();S=Dc();b=void 0===b?null:b;if(null!==S){var c=S.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!xc(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();S.memoizedState=[a,b];return a}
function Hc(a,b,c){if(25<=Bc)throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");if(a===R)if(Ac=!0,a={action:c,next:null},null===V&&(V=new Map),c=V.get(b),void 0===c)V.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function Jc(){throw Error("startTransition cannot be called during server rendering.");}function Kc(){}
var Mc={readContext:function(a){return a._currentValue},useContext:function(a){W();return a._currentValue},useMemo:Ic,useReducer:Gc,useRef:function(a){R=W();S=Dc();var b=S.memoizedState;return null===b?(a={current:a},S.memoizedState=a):b},useState:function(a){return Gc(Fc,a)},useInsertionEffect:Kc,useLayoutEffect:function(){},useCallback:function(a,b){return Ic(function(){return a},b)},useImperativeHandle:Kc,useEffect:Kc,useDebugValue:Kc,useDeferredValue:function(a){W();return a},useTransition:function(){W();
return[!1,Jc]},useId:function(){var a=yc.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-sc(a)-1)).toString(32)+b;var c=Lc;if(null===c)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");b=U++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b){W();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
return c()}},Lc=null,Nc=ba.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function Oc(a){console.error(a);return null}function X(){}function Pc(a,b){var c=a.pingedTasks;c.push(b);1===c.length&&setImmediate(function(){return Qc(a)})}
function Rc(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var m={node:b,ping:function(){return Pc(a,m)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(m);return m}function Sc(a,b,c,d,f,e){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:f,textEmbedded:e}}
function Y(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function Tc(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,a.destination.destroy(b)):(a.status=1,a.fatalError=b)}
function Uc(a,b,c,d,f){R={};yc=b;U=0;for(a=c(d,f);Ac;)Ac=!1,U=0,Bc+=1,S=null,a=c(d,f);Ec();return a}function Vc(a,b,c,d){var f=c.render(),e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error((gc(d)||"Unknown")+'.getChildContext(): key "'+h+'" is not defined in childContextTypes.');d=O({},g,c)}b.legacyContext=d;Z(a,b,f);b.legacyContext=g}else Z(a,b,f)}
function Wc(a,b){if(a&&a.defaultProps){b=O({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}
function Xc(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=ic(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue:f);pc(e,c,d,f);Vc(a,b,e,c)}else{e=ic(c,b.legacyContext);f=Uc(a,b,c,d,e);var g=0!==U;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)pc(f,c,d,e),Vc(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=rc(d,1,0);try{Z(a,b,f)}finally{b.treeContext=d}}else Z(a,b,f)}else if("string"===
typeof c){f=b.blockedSegment;e=Pa(f.chunks,c,d,a.responseState,f.formatContext);f.lastPushedText=!1;g=f.formatContext;f.formatContext=ya(g,c,d);Yc(a,b,e);f.formatContext=g;switch(c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push(Qa,c,Ra)}f.lastPushedText=!1}else{switch(c){case dc:case cc:case Tb:case Ub:case Sb:Z(a,b,d.children);return;case Zb:Z(a,
b,d.children);return;case bc:throw Error("ReactDOMServer does not yet support scope components.");case Yb:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null},m=Sc(a,f.chunks.length,h,f.formatContext,!1,!1);f.children.push(m);f.lastPushedText=!1;var n=Sc(a,0,null,f.formatContext,!1,!1);n.parentFlushed=!0;b.blockedBoundary=
h;b.blockedSegment=n;try{if(Yc(a,b,d),n.lastPushedText&&n.textEmbedded&&n.chunks.push(za),n.status=1,Zc(h,n),0===h.pendingTasks)break a}catch(p){n.status=4,h.forceClientRender=!0,h.errorDigest=Y(a,p)}finally{b.blockedBoundary=c,b.blockedSegment=f}b=Rc(a,e,c,m,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case Xb:d=Uc(a,b,c.render,d,f);if(0!==U){c=b.treeContext;b.treeContext=rc(c,1,0);try{Z(a,b,d)}finally{b.treeContext=c}}else Z(a,
b,d);return;case $b:c=c.type;d=Wc(c,d);Xc(a,b,c,d,f);return;case Vb:f=d.children;c=c._context;d=d.value;e=c._currentValue;c._currentValue=d;g=P;P=d={parent:g,depth:null===g?0:g.depth+1,context:c,parentValue:e,value:d};b.context=d;Z(a,b,f);a=P;if(null===a)throw Error("Tried to pop a Context at the root of the app. This is a bug in React.");d=a.parentValue;a.context._currentValue=d===ec?a.context._defaultValue:d;a=P=a.parent;b.context=a;return;case Wb:d=d.children;d=d(c._currentValue);Z(a,b,d);return;
case ac:f=c._init;c=f(c._payload);d=Wc(c,d);Xc(a,b,c,d,void 0);return}throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+((null==c?c:typeof c)+"."));}}
function Z(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Qb:Xc(a,b,c.type,c.props,c.ref);return;case Rb:throw Error("Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.");case ac:var d=c._init;c=d(c._payload);Z(a,b,c);return}if(qa(c)){$c(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=fc&&c[fc]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=
[];do f.push(c.value),c=d.next();while(!c.done);$c(a,b,f)}return}a=Object.prototype.toString.call(c);throw Error("Objects are not valid as a React child (found: "+("[object Object]"===a?"object with keys {"+Object.keys(c).join(", ")+"}":a)+"). If you meant to render a collection of children, use an array instead.");}"string"===typeof c?(d=b.blockedSegment,d.lastPushedText=Aa(b.blockedSegment.chunks,c,a.responseState,d.lastPushedText)):"number"===typeof c&&(d=b.blockedSegment,d.lastPushedText=Aa(b.blockedSegment.chunks,
""+c,a.responseState,d.lastPushedText))}function $c(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=rc(e,d,f);try{Yc(a,b,c[f])}finally{b.treeContext=e}}}
function Yc(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return Z(a,b,c)}catch(m){if(Ec(),"object"===typeof m&&null!==m&&"function"===typeof m.then){c=m;var g=b.blockedSegment,h=Sc(a,g.chunks.length,null,g.formatContext,g.lastPushedText,!0);g.children.push(h);g.lastPushedText=!1;a=Rc(a,b.node,b.blockedBoundary,h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;nc(e)}else throw b.blockedSegment.formatContext=
d,b.legacyContext=f,b.context=e,nc(e),m;}}function ad(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;bd(this,b,a)}
function cd(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,2!==b.status&&(b.status=2,null!==b.destination&&b.destination.end())):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,d.errorDigest=b.onError(void 0===c?Error("The render was aborted by the server without a reason."):c),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return cd(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,
0===b.allPendingTasks&&(a=b.onAllReady,a()))}function Zc(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&Zc(a,c)}else a.completedSegments.push(b)}
function bd(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error("There can only be one root segment. This is a bug in React.");a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=X,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&Zc(b,c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(ad,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&
1===c.status&&(Zc(b,c),1===b.completedSegments.length&&b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())}
function Qc(a){if(2!==a.status){var b=P,c=Nc.current;Nc.current=Mc;var d=Lc;Lc=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,m=g.blockedSegment;if(0===m.status){nc(g.context);try{Z(h,g,g.node),m.lastPushedText&&m.textEmbedded&&m.chunks.push(za),g.abortSet.delete(g),m.status=1,bd(h,g.blockedBoundary,m)}catch(E){if(Ec(),"object"===typeof E&&null!==E&&"function"===typeof E.then){var n=g.ping;E.then(n,n)}else{g.abortSet.delete(g);m.status=4;var p=g.blockedBoundary,
v=E,C=Y(h,v);null===p?Tc(h,v):(p.pendingTasks--,p.forceClientRender||(p.forceClientRender=!0,p.errorDigest=C,p.parentFlushed&&h.clientRenderedBoundaries.push(p)));h.allPendingTasks--;if(0===h.allPendingTasks){var D=h.onAllReady;D()}}}finally{}}}f.splice(0,e);null!==a.destination&&dd(a,a.destination)}catch(E){Y(a,E),Tc(a,E)}finally{Lc=d,Nc.current=c,c===Mc&&nc(b)}}}
function ed(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;r(b,Sa);r(b,a.placeholderPrefix);a=d.toString(16);r(b,a);return w(b,Ta);case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)r(b,d[e]);f=fd(a,b,f)}for(;e<d.length-1;e++)r(b,d[e]);e<d.length&&(f=w(b,d[e]));return f;default:throw Error("Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.");
}}
function fd(a,b,c){var d=c.boundary;if(null===d)return ed(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)d=d.errorDigest,w(b,Xa),r(b,Za),d&&(r(b,ab),r(b,F(d)),r(b,$a)),w(b,bb),ed(a,b,c);else if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;var e=f.nextSuspenseID++;f=x(f.boundaryPrefix+e.toString(16));d=d.id=f;cb(b,a.responseState,d);ed(a,b,c)}else if(d.byteSize>a.progressiveChunkSize)d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),
cb(b,a.responseState,d.id),ed(a,b,c);else{w(b,Ua);c=d.completedSegments;if(1!==c.length)throw Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");fd(a,b,c[0])}return w(b,Ya)}function gd(a,b,c){yb(b,a.responseState,c.formatContext,c.id);fd(a,b,c);return zb(b,c.formatContext)}
function hd(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)id(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;r(b,a.startInlineScript);a.sentCompleteBoundaryFunction?r(b,Gb):(a.sentCompleteBoundaryFunction=!0,r(b,Fb));if(null===d)throw Error("An ID must have been assigned before we can complete the boundary.");c=c.toString(16);r(b,d);r(b,Hb);r(b,a.segmentPrefix);r(b,c);return w(b,Ib)}
function id(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error("A root segment ID must have been assigned by now. This is a bug in React.");return gd(a,b,d)}gd(a,b,d);a=a.responseState;r(b,a.startInlineScript);a.sentCompleteSegmentFunction?r(b,Bb):(a.sentCompleteSegmentFunction=!0,r(b,Ab));r(b,a.segmentPrefix);f=f.toString(16);r(b,f);r(b,Cb);r(b,a.placeholderPrefix);r(b,f);return w(b,Db)}
function dd(a,b){k=new Uint8Array(2048);l=0;q=!0;try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){fd(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length-1;c++)r(b,d[c]);c<d.length&&w(b,d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){var g=f[e];d=b;var h=a.responseState,m=g.id,n=g.errorDigest,p=g.errorMessage,v=g.errorComponentStack;r(d,h.startInlineScript);h.sentClientRenderFunction?r(d,Kb):(h.sentClientRenderFunction=!0,
r(d,Jb));if(null===m)throw Error("An ID must have been assigned before we can complete the boundary.");r(d,m);r(d,Lb);if(n||p||v)r(d,Nb),r(d,Pb(n||""));if(p||v)r(d,Nb),r(d,Pb(p||""));v&&(r(d,Nb),r(d,Pb(v)));if(!w(d,Mb)){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e);var C=a.completedBoundaries;for(e=0;e<C.length;e++)if(!hd(a,b,C[e])){a.destination=null;e++;C.splice(0,e);return}C.splice(0,e);ca(b);k=new Uint8Array(2048);l=0;q=!0;var D=a.partialBoundaries;for(e=0;e<D.length;e++){var E=D[e];
a:{f=a;g=b;var na=E.completedSegments;for(h=0;h<na.length;h++)if(!id(f,g,E,na[h])){h++;na.splice(0,h);var Eb=!1;break a}na.splice(0,h);Eb=!0}if(!Eb){a.destination=null;e++;D.splice(0,e);return}}D.splice(0,e);var oa=a.completedBoundaries;for(e=0;e<oa.length;e++)if(!hd(a,b,oa[e])){a.destination=null;e++;oa.splice(0,e);return}oa.splice(0,e)}finally{ca(b),"function"===typeof b.flush&&b.flush(),0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&
b.end()}}function jd(a){setImmediate(function(){return Qc(a)})}function kd(a,b){if(1===a.status)a.status=2,b.destroy(a.fatalError);else if(2!==a.status&&null===a.destination){a.destination=b;try{dd(a,b)}catch(c){Y(a,c),Tc(a,c)}}}function ld(a,b){try{var c=a.abortableTasks;c.forEach(function(c){return cd(c,a,b)});c.clear();null!==a.destination&&dd(a,a.destination)}catch(d){Y(a,d),Tc(a,d)}}function md(a,b){return function(){return kd(b,a)}}function nd(a,b){return function(){return ld(a,b)}}
function od(a,b){var c=b?b.identifierPrefix:void 0,d=b?b.nonce:void 0,f=b?b.bootstrapScriptContent:void 0,e=b?b.bootstrapScripts:void 0;var g=b?b.bootstrapModules:void 0;c=void 0===c?"":c;d=void 0===d?ra:x('<script nonce="'+F(d)+'">');var h=[];void 0!==f&&h.push(d,(""+f).replace(wa,xa),sa);if(void 0!==e)for(f=0;f<e.length;f++)h.push(ta,F(e[f]),va);if(void 0!==g)for(e=0;e<g.length;e++)h.push(ua,F(g[e]),va);g={bootstrapChunks:h,startInlineScript:d,placeholderPrefix:x(c+"P:"),segmentPrefix:x(c+"S:"),
boundaryPrefix:c+"B:",idPrefix:c,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1};e=b?b.namespaceURI:void 0;e=G("http://www.w3.org/2000/svg"===e?2:"http://www.w3.org/1998/Math/MathML"===e?3:0,null);f=b?b.progressiveChunkSize:void 0;d=b?b.onError:void 0;h=b?b.onAllReady:void 0;var m=b?b.onShellReady:void 0,n=b?b.onShellError:void 0;b=[];c=new Set;g={destination:null,responseState:g,progressiveChunkSize:void 0===f?12800:f,status:0,fatalError:null,
nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:c,pingedTasks:b,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===d?Oc:d,onAllReady:void 0===h?X:h,onShellReady:void 0===m?X:m,onShellError:void 0===n?X:n,onFatalError:X};e=Sc(g,0,null,e,!1,!1);e.parentFlushed=!0;a=Rc(g,a,null,e,c,hc,null,qc);b.push(a);return g}
exports.renderToPipeableStream=function(a,b){var c=od(a,b),d=!1;jd(c);return{pipe:function(a){if(d)throw Error("React currently only supports piping to one writable stream.");d=!0;kd(c,a);a.on("drain",md(a,c));a.on("error",nd(c,Error("The destination stream errored while writing data.")));a.on("close",nd(c,Error("The destination stream closed early.")));return a},abort:function(a){ld(c,a)}}};exports.version="18.3.1";
/**
 * @license React
 * react-dom-test-utils.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var React = require('react');
var ReactDOM = require('react-dom');

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}

var FunctionComponent = 0;
var ClassComponent = 1;

var HostRoot = 3; // Root of a host tree. Could be nested inside another node.

var HostComponent = 5;
var HostText = 6;

// Don't change these two values. They're used by React Dev Tools.
var NoFlags =
/*                      */
0;

var Placement =
/*                    */
2;
var Hydrating =
/*                    */
4096;

var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
function getNearestMountedFiber(fiber) {
  var node = fiber;
  var nearestMounted = fiber;

  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    var nextNode = node;

    do {
      node = nextNode;

      if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
        // This is an insertion or in-progress hydration. The nearest possible
        // mounted fiber is the parent but we need to continue to figure out
        // if that one is still mounted.
        nearestMounted = node.return;
      }

      nextNode = node.return;
    } while (nextNode);
  } else {
    while (node.return) {
      node = node.return;
    }
  }

  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return nearestMounted;
  } // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.


  return null;
}

function assertIsMounted(fiber) {
  if (getNearestMountedFiber(fiber) !== fiber) {
    throw new Error('Unable to find node on an unmounted component.');
  }
}

function findCurrentFiberUsingSlowPath(fiber) {
  var alternate = fiber.alternate;

  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    var nearestMounted = getNearestMountedFiber(fiber);

    if (nearestMounted === null) {
      throw new Error('Unable to find node on an unmounted component.');
    }

    if (nearestMounted !== fiber) {
      return null;
    }

    return fiber;
  } // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.


  var a = fiber;
  var b = alternate;

  while (true) {
    var parentA = a.return;

    if (parentA === null) {
      // We're at the root.
      break;
    }

    var parentB = parentA.alternate;

    if (parentB === null) {
      // There is no alternate. This is an unusual case. Currently, it only
      // happens when a Suspense component is hidden. An extra fragment fiber
      // is inserted in between the Suspense fiber and its children. Skip
      // over this extra fragment fiber and proceed to the next parent.
      var nextParent = parentA.return;

      if (nextParent !== null) {
        a = b = nextParent;
        continue;
      } // If there's no parent, we're at the root.


      break;
    } // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.


    if (parentA.child === parentB.child) {
      var child = parentA.child;

      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }

        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }

        child = child.sibling;
      } // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.


      throw new Error('Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      var didFindChild = false;
      var _child = parentA.child;

      while (_child) {
        if (_child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }

        if (_child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }

        _child = _child.sibling;
      }

      if (!didFindChild) {
        // Search parent B's child set
        _child = parentB.child;

        while (_child) {
          if (_child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }

          if (_child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }

          _child = _child.sibling;
        }

        if (!didFindChild) {
          throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
        }
      }
    }

    if (a.alternate !== b) {
      throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
    }
  } // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.


  if (a.tag !== HostRoot) {
    throw new Error('Unable to find node on an unmounted component.');
  }

  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  } // Otherwise B has to be current branch.


  return alternate;
}

var assign = Object.assign;

/**
 * `charCode` represents the actual "character code" and is safe to use with
 * `String.fromCharCode`. As such, only keys that correspond to printable
 * characters produce a valid `charCode`, the only exception to this is Enter.
 * The Tab-key is considered non-printable and does not have a `charCode`,
 * presumably because it does not produce a tab-character in browsers.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {number} Normalized `charCode` property.
 */
function getEventCharCode(nativeEvent) {
  var charCode;
  var keyCode = nativeEvent.keyCode;

  if ('charCode' in nativeEvent) {
    charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.

    if (charCode === 0 && keyCode === 13) {
      charCode = 13;
    }
  } else {
    // IE8 does not implement `charCode`, but `keyCode` has the correct value.
    charCode = keyCode;
  } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  // report Enter as charCode 10 when ctrl is pressed.


  if (charCode === 10) {
    charCode = 13;
  } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  // Must not discard the (non-)printable Enter-key.


  if (charCode >= 32 || charCode === 13) {
    return charCode;
  }

  return 0;
}

function functionThatReturnsTrue() {
  return true;
}

function functionThatReturnsFalse() {
  return false;
} // This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.


function createSyntheticEvent(Interface) {
  /**
   * Synthetic events are dispatched by event plugins, typically in response to a
   * top-level event delegation handler.
   *
   * These systems should generally use pooling to reduce the frequency of garbage
   * collection. The system should check `isPersistent` to determine whether the
   * event should be released into the pool after being dispatched. Users that
   * need a persisted event should invoke `persist`.
   *
   * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
   * normalizing browser quirks. Subclasses do not necessarily have to implement a
   * DOM interface; custom application-specific events can also subclass this.
   */
  function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
    this._reactName = reactName;
    this._targetInst = targetInst;
    this.type = reactEventType;
    this.nativeEvent = nativeEvent;
    this.target = nativeEventTarget;
    this.currentTarget = null;

    for (var _propName in Interface) {
      if (!Interface.hasOwnProperty(_propName)) {
        continue;
      }

      var normalize = Interface[_propName];

      if (normalize) {
        this[_propName] = normalize(nativeEvent);
      } else {
        this[_propName] = nativeEvent[_propName];
      }
    }

    var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;

    if (defaultPrevented) {
      this.isDefaultPrevented = functionThatReturnsTrue;
    } else {
      this.isDefaultPrevented = functionThatReturnsFalse;
    }

    this.isPropagationStopped = functionThatReturnsFalse;
    return this;
  }

  assign(SyntheticBaseEvent.prototype, {
    preventDefault: function () {
      this.defaultPrevented = true;
      var event = this.nativeEvent;

      if (!event) {
        return;
      }

      if (event.preventDefault) {
        event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
      } else if (typeof event.returnValue !== 'unknown') {
        event.returnValue = false;
      }

      this.isDefaultPrevented = functionThatReturnsTrue;
    },
    stopPropagation: function () {
      var event = this.nativeEvent;

      if (!event) {
        return;
      }

      if (event.stopPropagation) {
        event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
      } else if (typeof event.cancelBubble !== 'unknown') {
        // The ChangeEventPlugin registers a "propertychange" event for
        // IE. This event does not support bubbling or cancelling, and
        // any references to cancelBubble throw "Member not found".  A
        // typeof check of "unknown" circumvents this issue (and is also
        // IE specific).
        event.cancelBubble = true;
      }

      this.isPropagationStopped = functionThatReturnsTrue;
    },

    /**
     * We release all dispatched `SyntheticEvent`s after each event loop, adding
     * them back into the pool. This allows a way to hold onto a reference that
     * won't be added back into the pool.
     */
    persist: function () {// Modern event system doesn't use pooling.
    },

    /**
     * Checks if this event should be released back into the pool.
     *
     * @return {boolean} True if this should not be released, false otherwise.
     */
    isPersistent: functionThatReturnsTrue
  });
  return SyntheticBaseEvent;
}
/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var EventInterface = {
  eventPhase: 0,
  bubbles: 0,
  cancelable: 0,
  timeStamp: function (event) {
    return event.timeStamp || Date.now();
  },
  defaultPrevented: 0,
  isTrusted: 0
};
var SyntheticEvent = createSyntheticEvent(EventInterface);

var UIEventInterface = assign({}, EventInterface, {
  view: 0,
  detail: 0
});

var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
var lastMovementX;
var lastMovementY;
var lastMouseEvent;

function updateMouseMovementPolyfillState(event) {
  if (event !== lastMouseEvent) {
    if (lastMouseEvent && event.type === 'mousemove') {
      lastMovementX = event.screenX - lastMouseEvent.screenX;
      lastMovementY = event.screenY - lastMouseEvent.screenY;
    } else {
      lastMovementX = 0;
      lastMovementY = 0;
    }

    lastMouseEvent = event;
  }
}
/**
 * @interface MouseEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var MouseEventInterface = assign({}, UIEventInterface, {
  screenX: 0,
  screenY: 0,
  clientX: 0,
  clientY: 0,
  pageX: 0,
  pageY: 0,
  ctrlKey: 0,
  shiftKey: 0,
  altKey: 0,
  metaKey: 0,
  getModifierState: getEventModifierState,
  button: 0,
  buttons: 0,
  relatedTarget: function (event) {
    if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
    return event.relatedTarget;
  },
  movementX: function (event) {
    if ('movementX' in event) {
      return event.movementX;
    }

    updateMouseMovementPolyfillState(event);
    return lastMovementX;
  },
  movementY: function (event) {
    if ('movementY' in event) {
      return event.movementY;
    } // Don't need to call updateMouseMovementPolyfillState() here
    // because it's guaranteed to have already run when movementX
    // was copied.


    return lastMovementY;
  }
});

var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
/**
 * @interface DragEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var DragEventInterface = assign({}, MouseEventInterface, {
  dataTransfer: 0
});

var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
/**
 * @interface FocusEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var FocusEventInterface = assign({}, UIEventInterface, {
  relatedTarget: 0
});

var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
 */

var AnimationEventInterface = assign({}, EventInterface, {
  animationName: 0,
  elapsedTime: 0,
  pseudoElement: 0
});

var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/clipboard-apis/
 */

var ClipboardEventInterface = assign({}, EventInterface, {
  clipboardData: function (event) {
    return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  }
});

var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
 */

var CompositionEventInterface = assign({}, EventInterface, {
  data: 0
});

var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
/**
 * Normalization of deprecated HTML5 `key` values
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */

var normalizeKey = {
  Esc: 'Escape',
  Spacebar: ' ',
  Left: 'ArrowLeft',
  Up: 'ArrowUp',
  Right: 'ArrowRight',
  Down: 'ArrowDown',
  Del: 'Delete',
  Win: 'OS',
  Menu: 'ContextMenu',
  Apps: 'ContextMenu',
  Scroll: 'ScrollLock',
  MozPrintableKey: 'Unidentified'
};
/**
 * Translation from legacy `keyCode` to HTML5 `key`
 * Only special keys supported, all others depend on keyboard layout or browser
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */

var translateToKey = {
  '8': 'Backspace',
  '9': 'Tab',
  '12': 'Clear',
  '13': 'Enter',
  '16': 'Shift',
  '17': 'Control',
  '18': 'Alt',
  '19': 'Pause',
  '20': 'CapsLock',
  '27': 'Escape',
  '32': ' ',
  '33': 'PageUp',
  '34': 'PageDown',
  '35': 'End',
  '36': 'Home',
  '37': 'ArrowLeft',
  '38': 'ArrowUp',
  '39': 'ArrowRight',
  '40': 'ArrowDown',
  '45': 'Insert',
  '46': 'Delete',
  '112': 'F1',
  '113': 'F2',
  '114': 'F3',
  '115': 'F4',
  '116': 'F5',
  '117': 'F6',
  '118': 'F7',
  '119': 'F8',
  '120': 'F9',
  '121': 'F10',
  '122': 'F11',
  '123': 'F12',
  '144': 'NumLock',
  '145': 'ScrollLock',
  '224': 'Meta'
};
/**
 * @param {object} nativeEvent Native browser event.
 * @return {string} Normalized `key` property.
 */

function getEventKey(nativeEvent) {
  if (nativeEvent.key) {
    // Normalize inconsistent values reported by browsers due to
    // implementations of a working draft specification.
    // FireFox implements `key` but returns `MozPrintableKey` for all
    // printable characters (normalized to `Unidentified`), ignore it.
    var key = normalizeKey[nativeEvent.key] || nativeEvent.key;

    if (key !== 'Unidentified') {
      return key;
    }
  } // Browser does not implement `key`, polyfill as much of it as we can.


  if (nativeEvent.type === 'keypress') {
    var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
    // thus be captured by `keypress`, no other non-printable key should.

    return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  }

  if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
    // While user keyboard layout determines the actual meaning of each
    // `keyCode` value, almost all function keys have a universal value.
    return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  }

  return '';
}
/**
 * Translation from modifier key to the associated property in the event.
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
 */


var modifierKeyToProp = {
  Alt: 'altKey',
  Control: 'ctrlKey',
  Meta: 'metaKey',
  Shift: 'shiftKey'
}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.

function modifierStateGetter(keyArg) {
  var syntheticEvent = this;
  var nativeEvent = syntheticEvent.nativeEvent;

  if (nativeEvent.getModifierState) {
    return nativeEvent.getModifierState(keyArg);
  }

  var keyProp = modifierKeyToProp[keyArg];
  return keyProp ? !!nativeEvent[keyProp] : false;
}

function getEventModifierState(nativeEvent) {
  return modifierStateGetter;
}
/**
 * @interface KeyboardEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var KeyboardEventInterface = assign({}, UIEventInterface, {
  key: getEventKey,
  code: 0,
  location: 0,
  ctrlKey: 0,
  shiftKey: 0,
  altKey: 0,
  metaKey: 0,
  repeat: 0,
  locale: 0,
  getModifierState: getEventModifierState,
  // Legacy Interface
  charCode: function (event) {
    // `charCode` is the result of a KeyPress event and represents the value of
    // the actual printable character.
    // KeyPress is deprecated, but its replacement is not yet final and not
    // implemented in any major browser. Only KeyPress has charCode.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }

    return 0;
  },
  keyCode: function (event) {
    // `keyCode` is the result of a KeyDown/Up event and represents the value of
    // physical keyboard key.
    // The actual meaning of the value depends on the users' keyboard layout
    // which cannot be detected. Assuming that it is a US keyboard layout
    // provides a surprisingly accurate mapping for US and European users.
    // Due to this, it is left to the user to implement at this time.
    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }

    return 0;
  },
  which: function (event) {
    // `which` is an alias for either `keyCode` or `charCode` depending on the
    // type of the event.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }

    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }

    return 0;
  }
});

var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
/**
 * @interface PointerEvent
 * @see http://www.w3.org/TR/pointerevents/
 */

var PointerEventInterface = assign({}, MouseEventInterface, {
  pointerId: 0,
  width: 0,
  height: 0,
  pressure: 0,
  tangentialPressure: 0,
  tiltX: 0,
  tiltY: 0,
  twist: 0,
  pointerType: 0,
  isPrimary: 0
});

var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
/**
 * @interface TouchEvent
 * @see http://www.w3.org/TR/touch-events/
 */

var TouchEventInterface = assign({}, UIEventInterface, {
  touches: 0,
  targetTouches: 0,
  changedTouches: 0,
  altKey: 0,
  metaKey: 0,
  ctrlKey: 0,
  shiftKey: 0,
  getModifierState: getEventModifierState
});

var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
 */

var TransitionEventInterface = assign({}, EventInterface, {
  propertyName: 0,
  elapsedTime: 0,
  pseudoElement: 0
});

var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
/**
 * @interface WheelEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var WheelEventInterface = assign({}, MouseEventInterface, {
  deltaX: function (event) {
    return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
    'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  },
  deltaY: function (event) {
    return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
    'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
    'wheelDelta' in event ? -event.wheelDelta : 0;
  },
  deltaZ: 0,
  // Browsers without "deltaMode" is reporting in raw wheel delta where one
  // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  deltaMode: 0
});

var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);

/**
 * HTML nodeType values that represent the type of the node
 */
var ELEMENT_NODE = 1;

function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
  var funcArgs = Array.prototype.slice.call(arguments, 3);

  try {
    func.apply(context, funcArgs);
  } catch (error) {
    this.onError(error);
  }
}

var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;

{
  // In DEV mode, we swap out invokeGuardedCallback for a special version
  // that plays more nicely with the browser's DevTools. The idea is to preserve
  // "Pause on exceptions" behavior. Because React wraps all user-provided
  // functions in invokeGuardedCallback, and the production version of
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  // like caught exceptions, and the DevTools won't pause unless the developer
  // takes the extra step of enabling pause on caught exceptions. This is
  // unintuitive, though, because even though React has caught the error, from
  // the developer's perspective, the error is uncaught.
  //
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  // DOM node, and call the user-provided callback from inside an event handler
  // for that fake event. If the callback throws, the error is "captured" using
  // a global event handler. But because the error happens in a different
  // event loop context, it does not interrupt the normal program flow.
  // Effectively, this gives us try-catch behavior without actually using
  // try-catch. Neat!
  // Check that the browser supports the APIs we need to implement our special
  // DEV version of invokeGuardedCallback
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
    var fakeNode = document.createElement('react');

    invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
      // If document doesn't exist we know for sure we will crash in this method
      // when we call document.createEvent(). However this can cause confusing
      // errors: https://github.com/facebook/create-react-app/issues/3482
      // So we preemptively throw with a better message instead.
      if (typeof document === 'undefined' || document === null) {
        throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
      }

      var evt = document.createEvent('Event');
      var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
      // set this to true at the beginning, then set it to false right after
      // calling the function. If the function errors, `didError` will never be
      // set to false. This strategy works even if the browser is flaky and
      // fails to call our global error handler, because it doesn't rely on
      // the error event at all.

      var didError = true; // Keeps track of the value of window.event so that we can reset it
      // during the callback to let user code access window.event in the
      // browsers that support it.

      var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
      // dispatching: https://github.com/facebook/react/issues/13688

      var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');

      function restoreAfterDispatch() {
        // We immediately remove the callback from event listeners so that
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
        // nested call would trigger the fake event handlers of any call higher
        // in the stack.
        fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
        // window.event assignment in both IE <= 10 as they throw an error
        // "Member not found" in strict mode, and in Firefox which does not
        // support window.event.

        if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
          window.event = windowEvent;
        }
      } // Create an event handler for our fake event. We will synchronously
      // dispatch our fake event using `dispatchEvent`. Inside the handler, we
      // call the user-provided callback.


      var funcArgs = Array.prototype.slice.call(arguments, 3);

      function callCallback() {
        didCall = true;
        restoreAfterDispatch();
        func.apply(context, funcArgs);
        didError = false;
      } // Create a global error event handler. We use this to capture the value
      // that was thrown. It's possible that this error handler will fire more
      // than once; for example, if non-React code also calls `dispatchEvent`
      // and a handler for that event throws. We should be resilient to most of
      // those cases. Even if our error event handler fires more than once, the
      // last error event is always used. If the callback actually does error,
      // we know that the last error event is the correct one, because it's not
      // possible for anything else to have happened in between our callback
      // erroring and the code that follows the `dispatchEvent` call below. If
      // the callback doesn't error, but the error event was fired, we know to
      // ignore it because `didError` will be false, as described above.


      var error; // Use this to track whether the error event is ever called.

      var didSetError = false;
      var isCrossOriginError = false;

      function handleWindowError(event) {
        error = event.error;
        didSetError = true;

        if (error === null && event.colno === 0 && event.lineno === 0) {
          isCrossOriginError = true;
        }

        if (event.defaultPrevented) {
          // Some other error handler has prevented default.
          // Browsers silence the error report if this happens.
          // We'll remember this to later decide whether to log it or not.
          if (error != null && typeof error === 'object') {
            try {
              error._suppressLogging = true;
            } catch (inner) {// Ignore.
            }
          }
        }
      } // Create a fake event type.


      var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers

      window.addEventListener('error', handleWindowError);
      fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
      // errors, it will trigger our global error handler.

      evt.initEvent(evtType, false, false);
      fakeNode.dispatchEvent(evt);

      if (windowEventDescriptor) {
        Object.defineProperty(window, 'event', windowEventDescriptor);
      }

      if (didCall && didError) {
        if (!didSetError) {
          // The callback errored, but the error event never fired.
          // eslint-disable-next-line react-internal/prod-error-codes
          error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
        } else if (isCrossOriginError) {
          // eslint-disable-next-line react-internal/prod-error-codes
          error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
        }

        this.onError(error);
      } // Remove our event listeners


      window.removeEventListener('error', handleWindowError);

      if (!didCall) {
        // Something went really wrong, and our event was not dispatched.
        // https://github.com/facebook/react/issues/16734
        // https://github.com/facebook/react/issues/16585
        // Fall back to the production implementation.
        restoreAfterDispatch();
        return invokeGuardedCallbackProd.apply(this, arguments);
      }
    };
  }
}

var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;

var hasError = false;
var caughtError = null; // Used by event system to capture/rethrow the first error.

var hasRethrowError = false;
var rethrowError = null;
var reporter = {
  onError: function (error) {
    hasError = true;
    caughtError = error;
  }
};
/**
 * Call a function while guarding against errors that happens within it.
 * Returns an error if it throws, otherwise null.
 *
 * In production, this is implemented using a try-catch. The reason we don't
 * use a try-catch directly is so that we can swap out a different
 * implementation in DEV mode.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */

function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  hasError = false;
  caughtError = null;
  invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}
/**
 * Same as invokeGuardedCallback, but instead of returning an error, it stores
 * it in a global so it can be rethrown by `rethrowCaughtError` later.
 * TODO: See if caughtError and rethrowError can be unified.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */

function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
  invokeGuardedCallback.apply(this, arguments);

  if (hasError) {
    var error = clearCaughtError();

    if (!hasRethrowError) {
      hasRethrowError = true;
      rethrowError = error;
    }
  }
}
/**
 * During execution of guarded functions we will capture the first error which
 * we will rethrow to be handled by the top level error handler.
 */

function rethrowCaughtError() {
  if (hasRethrowError) {
    var error = rethrowError;
    hasRethrowError = false;
    rethrowError = null;
    throw error;
  }
}
function clearCaughtError() {
  if (hasError) {
    var error = caughtError;
    hasError = false;
    caughtError = null;
    return error;
  } else {
    throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var SecretInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var EventInternals = SecretInternals.Events;
var getInstanceFromNode = EventInternals[0];
var getNodeFromInstance = EventInternals[1];
var getFiberCurrentPropsFromNode = EventInternals[2];
var enqueueStateRestore = EventInternals[3];
var restoreStateIfNeeded = EventInternals[4];
var reactAct = React.unstable_act;

function Event(suffix) {}

var hasWarnedAboutDeprecatedMockComponent = false;
/**
 * @class ReactTestUtils
 */

function findAllInRenderedFiberTreeInternal(fiber, test) {
  if (!fiber) {
    return [];
  }

  var currentParent = findCurrentFiberUsingSlowPath(fiber);

  if (!currentParent) {
    return [];
  }

  var node = currentParent;
  var ret = [];

  while (true) {
    if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
      var publicInst = node.stateNode;

      if (test(publicInst)) {
        ret.push(publicInst);
      }
    }

    if (node.child) {
      node.child.return = node;
      node = node.child;
      continue;
    }

    if (node === currentParent) {
      return ret;
    }

    while (!node.sibling) {
      if (!node.return || node.return === currentParent) {
        return ret;
      }

      node = node.return;
    }

    node.sibling.return = node.return;
    node = node.sibling;
  }
}

function validateClassInstance(inst, methodName) {
  if (!inst) {
    // This is probably too relaxed but it's existing behavior.
    return;
  }

  if (get(inst)) {
    // This is a public instance indeed.
    return;
  }

  var received;
  var stringified = String(inst);

  if (isArray(inst)) {
    received = 'an array';
  } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
    received = 'a DOM node';
  } else if (stringified === '[object Object]') {
    received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  } else {
    received = stringified;
  }

  throw new Error(methodName + "(...): the first argument must be a React class instance. " + ("Instead received: " + received + "."));
}
/**
 * Utilities for making it easy to test React components.
 *
 * See https://reactjs.org/docs/test-utils.html
 *
 * Todo: Support the entire DOM.scry query syntax. For now, these simple
 * utilities will suffice for testing purposes.
 * @lends ReactTestUtils
 */


var didWarnAboutReactTestUtilsDeprecation = false;

function renderIntoDocument(element) {
  {
    if (!didWarnAboutReactTestUtilsDeprecation) {
      didWarnAboutReactTestUtilsDeprecation = true;

      error('ReactDOMTestUtils is deprecated and will be removed in a future ' + 'major release, because it exposes internal implementation details ' + 'that are highly likely to change between releases. Upgrade to a ' + 'modern testing library, such as @testing-library/react. See ' + 'https://react.dev/warnings/react-dom-test-utils for more info.');
    }
  }

  var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  // DOM, and doing so creates a mess that we rely on test isolation to
  // clean up, so we're going to stop honoring the name of this method
  // (and probably rename it eventually) if no problems arise.
  // document.documentElement.appendChild(div);

  return ReactDOM.render(element, div);
}

function isElement(element) {
  return React.isValidElement(element);
}

function isElementOfType(inst, convenienceConstructor) {
  return React.isValidElement(inst) && inst.type === convenienceConstructor;
}

function isDOMComponent(inst) {
  return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
}

function isDOMComponentElement(inst) {
  return !!(inst && React.isValidElement(inst) && !!inst.tagName);
}

function isCompositeComponent(inst) {
  if (isDOMComponent(inst)) {
    // Accessing inst.setState warns; just return false as that'll be what
    // this returns when we have DOM nodes as refs directly
    return false;
  }

  return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
}

function isCompositeComponentWithType(inst, type) {
  if (!isCompositeComponent(inst)) {
    return false;
  }

  var internalInstance = get(inst);
  var constructor = internalInstance.type;
  return constructor === type;
}

function findAllInRenderedTree(inst, test) {
  validateClassInstance(inst, 'findAllInRenderedTree');

  if (!inst) {
    return [];
  }

  var internalInstance = get(inst);
  return findAllInRenderedFiberTreeInternal(internalInstance, test);
}
/**
 * Finds all instances of components in the rendered tree that are DOM
 * components with the class name matching `className`.
 * @return {array} an array of all the matches.
 */


function scryRenderedDOMComponentsWithClass(root, classNames) {
  validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  return findAllInRenderedTree(root, function (inst) {
    if (isDOMComponent(inst)) {
      var className = inst.className;

      if (typeof className !== 'string') {
        // SVG, probably.
        className = inst.getAttribute('class') || '';
      }

      var classList = className.split(/\s+/);

      if (!isArray(classNames)) {
        if (classNames === undefined) {
          throw new Error('TestUtils.scryRenderedDOMComponentsWithClass expects a ' + 'className as a second argument.');
        }

        classNames = classNames.split(/\s+/);
      }

      return classNames.every(function (name) {
        return classList.indexOf(name) !== -1;
      });
    }

    return false;
  });
}
/**
 * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
 * and returns that one result, or throws exception if there is any other
 * number of matches besides one.
 * @return {!ReactDOMComponent} The one match.
 */


function findRenderedDOMComponentWithClass(root, className) {
  validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  var all = scryRenderedDOMComponentsWithClass(root, className);

  if (all.length !== 1) {
    throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  }

  return all[0];
}
/**
 * Finds all instances of components in the rendered tree that are DOM
 * components with the tag name matching `tagName`.
 * @return {array} an array of all the matches.
 */


function scryRenderedDOMComponentsWithTag(root, tagName) {
  validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  return findAllInRenderedTree(root, function (inst) {
    return isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  });
}
/**
 * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
 * and returns that one result, or throws exception if there is any other
 * number of matches besides one.
 * @return {!ReactDOMComponent} The one match.
 */


function findRenderedDOMComponentWithTag(root, tagName) {
  validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  var all = scryRenderedDOMComponentsWithTag(root, tagName);

  if (all.length !== 1) {
    throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  }

  return all[0];
}
/**
 * Finds all instances of components with type equal to `componentType`.
 * @return {array} an array of all the matches.
 */


function scryRenderedComponentsWithType(root, componentType) {
  validateClassInstance(root, 'scryRenderedComponentsWithType');
  return findAllInRenderedTree(root, function (inst) {
    return isCompositeComponentWithType(inst, componentType);
  });
}
/**
 * Same as `scryRenderedComponentsWithType` but expects there to be one result
 * and returns that one result, or throws exception if there is any other
 * number of matches besides one.
 * @return {!ReactComponent} The one match.
 */


function findRenderedComponentWithType(root, componentType) {
  validateClassInstance(root, 'findRenderedComponentWithType');
  var all = scryRenderedComponentsWithType(root, componentType);

  if (all.length !== 1) {
    throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  }

  return all[0];
}
/**
 * Pass a mocked component module to this method to augment it with
 * useful methods that allow it to be used as a dummy React component.
 * Instead of rendering as usual, the component will become a simple
 * <div> containing any provided children.
 *
 * @param {object} module the mock function object exported from a
 *                        module that defines the component to be mocked
 * @param {?string} mockTagName optional dummy root tag name to return
 *                              from render method (overrides
 *                              module.mockTagName if provided)
 * @return {object} the ReactTestUtils object (for chaining)
 */


function mockComponent(module, mockTagName) {
  {
    if (!hasWarnedAboutDeprecatedMockComponent) {
      hasWarnedAboutDeprecatedMockComponent = true;

      warn('ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.');
    }
  }

  mockTagName = mockTagName || module.mockTagName || 'div';
  module.prototype.render.mockImplementation(function () {
    return React.createElement(mockTagName, null, this.props.children);
  });
  return this;
}

function nativeTouchData(x, y) {
  return {
    touches: [{
      pageX: x,
      pageY: y
    }]
  };
} // Start of inline: the below functions were inlined from
// EventPropagator.js, as they deviated from ReactDOM's newer
// implementations.

/**
 * Dispatch the event to the listener.
 * @param {SyntheticEvent} event SyntheticEvent to handle
 * @param {function} listener Application-level callback
 * @param {*} inst Internal component instance
 */


function executeDispatch(event, listener, inst) {
  var type = event.type || 'unknown-event';
  event.currentTarget = getNodeFromInstance(inst);
  invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  event.currentTarget = null;
}
/**
 * Standard/simple iteration through an event's collected dispatches.
 */


function executeDispatchesInOrder(event) {
  var dispatchListeners = event._dispatchListeners;
  var dispatchInstances = event._dispatchInstances;

  if (isArray(dispatchListeners)) {
    for (var i = 0; i < dispatchListeners.length; i++) {
      if (event.isPropagationStopped()) {
        break;
      } // Listeners and Instances are two parallel arrays that are always in sync.


      executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
    }
  } else if (dispatchListeners) {
    executeDispatch(event, dispatchListeners, dispatchInstances);
  }

  event._dispatchListeners = null;
  event._dispatchInstances = null;
}
/**
 * Dispatches an event and releases it back into the pool, unless persistent.
 *
 * @param {?object} event Synthetic event to be dispatched.
 * @private
 */


var executeDispatchesAndRelease = function (event) {
  if (event) {
    executeDispatchesInOrder(event);

    if (!event.isPersistent()) {
      event.constructor.release(event);
    }
  }
};

function isInteractive(tag) {
  return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}

function getParent(inst) {
  do {
    inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
    // That is depending on if we want nested subtrees (layers) to bubble
    // events to their parent. We could also go through parentNode on the
    // host node but that wouldn't work for React Native and doesn't let us
    // do the portal feature.
  } while (inst && inst.tag !== HostComponent);

  if (inst) {
    return inst;
  }

  return null;
}
/**
 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
 */


function traverseTwoPhase(inst, fn, arg) {
  var path = [];

  while (inst) {
    path.push(inst);
    inst = getParent(inst);
  }

  var i;

  for (i = path.length; i-- > 0;) {
    fn(path[i], 'captured', arg);
  }

  for (i = 0; i < path.length; i++) {
    fn(path[i], 'bubbled', arg);
  }
}

function shouldPreventMouseEvent(name, type, props) {
  switch (name) {
    case 'onClick':
    case 'onClickCapture':
    case 'onDoubleClick':
    case 'onDoubleClickCapture':
    case 'onMouseDown':
    case 'onMouseDownCapture':
    case 'onMouseMove':
    case 'onMouseMoveCapture':
    case 'onMouseUp':
    case 'onMouseUpCapture':
    case 'onMouseEnter':
      return !!(props.disabled && isInteractive(type));

    default:
      return false;
  }
}
/**
 * @param {object} inst The instance, which is the source of events.
 * @param {string} registrationName Name of listener (e.g. `onClick`).
 * @return {?function} The stored callback.
 */


function getListener(inst, registrationName) {
  // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
  // live here; needs to be moved to a better place soon
  var stateNode = inst.stateNode;

  if (!stateNode) {
    // Work in progress (ex: onload events in incremental mode).
    return null;
  }

  var props = getFiberCurrentPropsFromNode(stateNode);

  if (!props) {
    // Work in progress.
    return null;
  }

  var listener = props[registrationName];

  if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
    return null;
  }

  if (listener && typeof listener !== 'function') {
    throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
  }

  return listener;
}

function listenerAtPhase(inst, event, propagationPhase) {
  var registrationName = event._reactName;

  if (propagationPhase === 'captured') {
    registrationName += 'Capture';
  }

  return getListener(inst, registrationName);
}

function accumulateDispatches(inst, ignoredDirection, event) {
  if (inst && event && event._reactName) {
    var registrationName = event._reactName;
    var listener = getListener(inst, registrationName);

    if (listener) {
      if (event._dispatchListeners == null) {
        event._dispatchListeners = [];
      }

      if (event._dispatchInstances == null) {
        event._dispatchInstances = [];
      }

      event._dispatchListeners.push(listener);

      event._dispatchInstances.push(inst);
    }
  }
}

function accumulateDirectionalDispatches(inst, phase, event) {
  {
    if (!inst) {
      error('Dispatching inst must not be null');
    }
  }

  var listener = listenerAtPhase(inst, event, phase);

  if (listener) {
    if (event._dispatchListeners == null) {
      event._dispatchListeners = [];
    }

    if (event._dispatchInstances == null) {
      event._dispatchInstances = [];
    }

    event._dispatchListeners.push(listener);

    event._dispatchInstances.push(inst);
  }
}

function accumulateDirectDispatchesSingle(event) {
  if (event && event._reactName) {
    accumulateDispatches(event._targetInst, null, event);
  }
}

function accumulateTwoPhaseDispatchesSingle(event) {
  if (event && event._reactName) {
    traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
  }
} // End of inline


var Simulate = {};
var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
/**
 * Exports:
 *
 * - `Simulate.click(Element)`
 * - `Simulate.mouseMove(Element)`
 * - `Simulate.change(Element)`
 * - ... (All keys from event plugin `eventTypes` objects)
 */

function makeSimulator(eventType) {
  return function (domNode, eventData) {
    if (React.isValidElement(domNode)) {
      throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a React element. Pass the DOM node you wish to simulate the event on instead. ' + 'Note that TestUtils.Simulate will not work if you are using shallow rendering.');
    }

    if (isCompositeComponent(domNode)) {
      throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a component instance. Pass the DOM node you wish to simulate the event on instead.');
    }

    var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
    var fakeNativeEvent = new Event();
    fakeNativeEvent.target = domNode;
    fakeNativeEvent.type = eventType.toLowerCase();
    var targetInst = getInstanceFromNode(domNode);
    var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
    // sure it's marked and won't warn when setting additional properties.

    event.persist();
    assign(event, eventData);

    if (directDispatchEventTypes.has(eventType)) {
      accumulateDirectDispatchesSingle(event);
    } else {
      accumulateTwoPhaseDispatchesSingle(event);
    }

    ReactDOM.unstable_batchedUpdates(function () {
      // Normally extractEvent enqueues a state restore, but we'll just always
      // do that since we're by-passing it here.
      enqueueStateRestore(domNode);
      executeDispatchesAndRelease(event);
      rethrowCaughtError();
    });
    restoreStateIfNeeded();
  };
} // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.


var simulatedEventTypes = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'auxClick', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'pointerCancel', 'pointerDown', 'pointerUp', 'rateChange', 'reset', 'resize', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'mouseMove', 'mouseOut', 'mouseOver', 'pointerMove', 'pointerOut', 'pointerOver', 'scroll', 'toggle', 'touchMove', 'wheel', 'abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'playing', 'progress', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'transitionEnd', 'waiting', 'mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave', 'change', 'select', 'beforeInput', 'compositionEnd', 'compositionStart', 'compositionUpdate'];

function buildSimulators() {
  simulatedEventTypes.forEach(function (eventType) {
    Simulate[eventType] = makeSimulator(eventType);
  });
}

buildSimulators();
var didWarnAboutUsingAct = false;
var act =  function actWithWarning(callback) {
  {
    if (!didWarnAboutUsingAct) {
      didWarnAboutUsingAct = true;

      error('`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. ' + 'Import `act` from `react` instead of `react-dom/test-utils`. ' + 'See https://react.dev/warnings/react-dom-test-utils for more info.');
    }
  }

  return reactAct(callback);
} ;

exports.Simulate = Simulate;
exports.act = act;
exports.findAllInRenderedTree = findAllInRenderedTree;
exports.findRenderedComponentWithType = findRenderedComponentWithType;
exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
exports.isCompositeComponent = isCompositeComponent;
exports.isCompositeComponentWithType = isCompositeComponentWithType;
exports.isDOMComponent = isDOMComponent;
exports.isDOMComponentElement = isDOMComponentElement;
exports.isElement = isElement;
exports.isElementOfType = isElementOfType;
exports.mockComponent = mockComponent;
exports.nativeTouchData = nativeTouchData;
exports.renderIntoDocument = renderIntoDocument;
exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
exports.traverseTwoPhase = traverseTwoPhase;
  })();
}
/**
 * @license React
 * react-dom-test-utils.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var k=require("react"),l=require("react-dom");function m(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function n(a){if(m(a)!==a)throw Error("Unable to find node on an unmounted component.");}
function p(a){var b=a.alternate;if(!b){b=m(a);if(null===b)throw Error("Unable to find node on an unmounted component.");return b!==a?null:a}for(var c=a,d=b;;){var f=c.return;if(null===f)break;var g=f.alternate;if(null===g){d=f.return;if(null!==d){c=d;continue}break}if(f.child===g.child){for(g=f.child;g;){if(g===c)return n(f),a;if(g===d)return n(f),b;g=g.sibling}throw Error("Unable to find node on an unmounted component.");}if(c.return!==d.return)c=f,d=g;else{for(var e=!1,h=f.child;h;){if(h===c){e=
!0;c=f;d=g;break}if(h===d){e=!0;d=f;c=g;break}h=h.sibling}if(!e){for(h=g.child;h;){if(h===c){e=!0;c=g;d=f;break}if(h===d){e=!0;d=g;c=f;break}h=h.sibling}if(!e)throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");}}if(c.alternate!==d)throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");}if(3!==c.tag)throw Error("Unable to find node on an unmounted component.");
return c.stateNode.current===c?a:b}var q=Object.assign;function r(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function t(){return!0}function u(){return!1}
function v(a){function b(c,b,f,g,e){this._reactName=c;this._targetInst=f;this.type=b;this.nativeEvent=g;this.target=e;this.currentTarget=null;for(var d in a)a.hasOwnProperty(d)&&(c=a[d],this[d]=c?c(g):g[d]);this.isDefaultPrevented=(null!=g.defaultPrevented?g.defaultPrevented:!1===g.returnValue)?t:u;this.isPropagationStopped=u;return this}q(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&
(a.returnValue=!1),this.isDefaultPrevented=t)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=t)},persist:function(){},isPersistent:t});return b}var w={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},x=v(w),y=q({},w,{view:0,detail:0});v(y);
var z,A,B,D=q({},y,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:C,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in a)return a.movementX;a!==B&&(B&&"mousemove"===a.type?(z=a.screenX-B.screenX,A=a.screenY-B.screenY):A=z=0,B=a);return z},movementY:function(a){return"movementY"in a?a.movementY:A}});
v(D);var E=q({},D,{dataTransfer:0});v(E);var F=q({},y,{relatedTarget:0});v(F);var aa=q({},w,{animationName:0,elapsedTime:0,pseudoElement:0});v(aa);var ba=q({},w,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}});v(ba);var ca=q({},w,{data:0});v(ca);
var da={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ea={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",
116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fa={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ha(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=fa[a])?!!b[a]:!1}function C(){return ha}
var ia=q({},y,{key:function(a){if(a.key){var b=da[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=r(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?ea[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:C,charCode:function(a){return"keypress"===a.type?r(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
a.type?r(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}});v(ia);var ja=q({},D,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0});v(ja);var ka=q({},y,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:C});v(ka);var la=q({},w,{propertyName:0,elapsedTime:0,pseudoElement:0});v(la);
var ma=q({},D,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0});v(ma);function na(a,b,c,d,f,g,e,h,N){var G=Array.prototype.slice.call(arguments,3);try{b.apply(c,G)}catch(oa){this.onError(oa)}}var H=!1,I=null,J=!1,K=null,pa={onError:function(a){H=!0;I=a}};function qa(a,b,c,d,f,g,e,h,N){H=!1;I=null;na.apply(pa,arguments)}
function ra(a,b,c,d,f,g,e,h,N){qa.apply(this,arguments);if(H){if(H){var G=I;H=!1;I=null}else throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");J||(J=!0,K=G)}}var L=Array.isArray,M=l.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,sa=M[0],ta=M[1],ua=M[2],va=M[3],wa=M[4],xa=k.unstable_act;function ya(){}
function za(a,b){if(!a)return[];a=p(a);if(!a)return[];for(var c=a,d=[];;){if(5===c.tag||6===c.tag||1===c.tag||0===c.tag){var f=c.stateNode;b(f)&&d.push(f)}if(c.child)c.child.return=c,c=c.child;else{if(c===a)return d;for(;!c.sibling;){if(!c.return||c.return===a)return d;c=c.return}c.sibling.return=c.return;c=c.sibling}}}
function O(a,b){if(a&&!a._reactInternals){var c=String(a);a=L(a)?"an array":a&&1===a.nodeType&&a.tagName?"a DOM node":"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c;throw Error(b+"(...): the first argument must be a React class instance. Instead received: "+(a+"."));}}function P(a){return!(!a||1!==a.nodeType||!a.tagName)}function Q(a){return P(a)?!1:null!=a&&"function"===typeof a.render&&"function"===typeof a.setState}
function R(a,b){return Q(a)?a._reactInternals.type===b:!1}function S(a,b){O(a,"findAllInRenderedTree");return a?za(a._reactInternals,b):[]}
function T(a,b){O(a,"scryRenderedDOMComponentsWithClass");return S(a,function(a){if(P(a)){var c=a.className;"string"!==typeof c&&(c=a.getAttribute("class")||"");var f=c.split(/\s+/);if(!L(b)){if(void 0===b)throw Error("TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.");b=b.split(/\s+/)}return b.every(function(a){return-1!==f.indexOf(a)})}return!1})}
function U(a,b){O(a,"scryRenderedDOMComponentsWithTag");return S(a,function(a){return P(a)&&a.tagName.toUpperCase()===b.toUpperCase()})}function V(a,b){O(a,"scryRenderedComponentsWithType");return S(a,function(a){return R(a,b)})}function W(a,b,c){var d=a.type||"unknown-event";a.currentTarget=ta(c);ra(d,b,void 0,a);a.currentTarget=null}
function X(a,b,c){for(var d=[];a;){d.push(a);do a=a.return;while(a&&5!==a.tag);a=a?a:null}for(a=d.length;0<a--;)b(d[a],"captured",c);for(a=0;a<d.length;a++)b(d[a],"bubbled",c)}
function Y(a,b){var c=a.stateNode;if(!c)return null;var d=ua(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error("Expected `"+
b+"` listener to be a function, instead got a value of `"+typeof c+"` type.");return c}function Aa(a,b,c){a&&c&&c._reactName&&(b=Y(a,c._reactName))&&(null==c._dispatchListeners&&(c._dispatchListeners=[]),null==c._dispatchInstances&&(c._dispatchInstances=[]),c._dispatchListeners.push(b),c._dispatchInstances.push(a))}
function Ba(a,b,c){var d=c._reactName;"captured"===b&&(d+="Capture");if(b=Y(a,d))null==c._dispatchListeners&&(c._dispatchListeners=[]),null==c._dispatchInstances&&(c._dispatchInstances=[]),c._dispatchListeners.push(b),c._dispatchInstances.push(a)}var Z={},Ca=new Set(["mouseEnter","mouseLeave","pointerEnter","pointerLeave"]);
function Da(a){return function(b,c){if(k.isValidElement(b))throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering.");if(Q(b))throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead.");var d="on"+a[0].toUpperCase()+
a.slice(1),f=new ya;f.target=b;f.type=a.toLowerCase();var g=sa(b),e=new x(d,f.type,g,f,b);e.persist();q(e,c);Ca.has(a)?e&&e._reactName&&Aa(e._targetInst,null,e):e&&e._reactName&&X(e._targetInst,Ba,e);l.unstable_batchedUpdates(function(){va(b);if(e){var a=e._dispatchListeners,c=e._dispatchInstances;if(L(a))for(var d=0;d<a.length&&!e.isPropagationStopped();d++)W(e,a[d],c[d]);else a&&W(e,a,c);e._dispatchListeners=null;e._dispatchInstances=null;e.isPersistent()||e.constructor.release(e)}if(J)throw a=
K,J=!1,K=null,a;});wa()}}
"blur cancel click close contextMenu copy cut auxClick doubleClick dragEnd dragStart drop focus input invalid keyDown keyPress keyUp mouseDown mouseUp paste pause play pointerCancel pointerDown pointerUp rateChange reset resize seeked submit touchCancel touchEnd touchStart volumeChange drag dragEnter dragExit dragLeave dragOver mouseMove mouseOut mouseOver pointerMove pointerOut pointerOver scroll toggle touchMove wheel abort animationEnd animationIteration animationStart canPlay canPlayThrough durationChange emptied encrypted ended error gotPointerCapture load loadedData loadedMetadata loadStart lostPointerCapture playing progress seeking stalled suspend timeUpdate transitionEnd waiting mouseEnter mouseLeave pointerEnter pointerLeave change select beforeInput compositionEnd compositionStart compositionUpdate".split(" ").forEach(function(a){Z[a]=Da(a)});
exports.Simulate=Z;exports.act=xa;exports.findAllInRenderedTree=S;exports.findRenderedComponentWithType=function(a,b){O(a,"findRenderedComponentWithType");a=V(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for componentType:"+b);return a[0]};exports.findRenderedDOMComponentWithClass=function(a,b){O(a,"findRenderedDOMComponentWithClass");a=T(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for class:"+b);return a[0]};
exports.findRenderedDOMComponentWithTag=function(a,b){O(a,"findRenderedDOMComponentWithTag");a=U(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for tag:"+b);return a[0]};exports.isCompositeComponent=Q;exports.isCompositeComponentWithType=R;exports.isDOMComponent=P;exports.isDOMComponentElement=function(a){return!!(a&&k.isValidElement(a)&&a.tagName)};exports.isElement=function(a){return k.isValidElement(a)};
exports.isElementOfType=function(a,b){return k.isValidElement(a)&&a.type===b};exports.mockComponent=function(a,b){b=b||a.mockTagName||"div";a.prototype.render.mockImplementation(function(){return k.createElement(b,null,this.props.children)});return this};exports.nativeTouchData=function(a,b){return{touches:[{pageX:a,pageY:b}]}};exports.renderIntoDocument=function(a){var b=document.createElement("div");return l.render(a,b)};exports.scryRenderedComponentsWithType=V;
exports.scryRenderedDOMComponentsWithClass=T;exports.scryRenderedDOMComponentsWithTag=U;exports.traverseTwoPhase=X;
/**
 * @license React
 * react-dom.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {

          'use strict';

/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
}
          var React = require('react');
var Scheduler = require('scheduler');

var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

var suppressWarning = false;
function setSuppressWarning(newSuppressWarning) {
  {
    suppressWarning = newSuppressWarning;
  }
} // In DEV, calls to console.warn and console.error get replaced
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.

function warn(format) {
  {
    if (!suppressWarning) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      printWarning('warn', format, args);
    }
  }
}
function error(format) {
  {
    if (!suppressWarning) {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      printWarning('error', format, args);
    }
  }
}

function printWarning(level, format, args) {
  // When changing this logic, you might want to also
  // update consoleWithStackDev.www.js as well.
  {
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    var stack = ReactDebugCurrentFrame.getStackAddendum();

    if (stack !== '') {
      format += '%s';
      args = args.concat([stack]);
    } // eslint-disable-next-line react-internal/safe-string-coercion


    var argsWithFormat = args.map(function (item) {
      return String(item);
    }); // Careful: RN currently depends on this prefix

    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
    // breaks IE9: https://github.com/facebook/react/issues/13610
    // eslint-disable-next-line react-internal/no-production-logging

    Function.prototype.apply.call(console[level], console, argsWithFormat);
  }
}

var FunctionComponent = 0;
var ClassComponent = 1;
var IndeterminateComponent = 2; // Before we know whether it is function or class

var HostRoot = 3; // Root of a host tree. Could be nested inside another node.

var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.

var HostComponent = 5;
var HostText = 6;
var Fragment = 7;
var Mode = 8;
var ContextConsumer = 9;
var ContextProvider = 10;
var ForwardRef = 11;
var Profiler = 12;
var SuspenseComponent = 13;
var MemoComponent = 14;
var SimpleMemoComponent = 15;
var LazyComponent = 16;
var IncompleteClassComponent = 17;
var DehydratedFragment = 18;
var SuspenseListComponent = 19;
var ScopeComponent = 21;
var OffscreenComponent = 22;
var LegacyHiddenComponent = 23;
var CacheComponent = 24;
var TracingMarkerComponent = 25;

// -----------------------------------------------------------------------------

var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing
// the react-reconciler package.

var enableNewReconciler = false; // Support legacy Primer support on internal FB www

var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics.

var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber

var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz
// React DOM Chopping Block
//
// Similar to main Chopping Block but only flags related to React DOM. These are
// grouped because we will likely batch all of them into a single major release.
// -----------------------------------------------------------------------------
// Disable support for comment nodes as React DOM containers. Already disabled
// in open source, but www codebase still relies on it. Need to remove.

var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection.
// and client rendering, mostly to allow JSX attributes to apply to the custom
// element's object properties instead of only HTML attributes.
// https://github.com/facebook/react/issues/11347

var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements
var warnAboutStringRefs = true; // -----------------------------------------------------------------------------
// Debugging and DevTools
// -----------------------------------------------------------------------------
// Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
// for an experimental timeline tool.

var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState

var enableProfilerTimer = true; // Record durations for commit and passive effects phases.

var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update".

var allNativeEvents = new Set();
/**
 * Mapping from registration name to event name
 */


var registrationNameDependencies = {};
/**
 * Mapping from lowercase registration names to the properly cased version,
 * used to warn in the case of missing event handlers. Available
 * only in true.
 * @type {Object}
 */

var possibleRegistrationNames =  {} ; // Trust the developer to only use possibleRegistrationNames in true

function registerTwoPhaseEvent(registrationName, dependencies) {
  registerDirectEvent(registrationName, dependencies);
  registerDirectEvent(registrationName + 'Capture', dependencies);
}
function registerDirectEvent(registrationName, dependencies) {
  {
    if (registrationNameDependencies[registrationName]) {
      error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);
    }
  }

  registrationNameDependencies[registrationName] = dependencies;

  {
    var lowerCasedName = registrationName.toLowerCase();
    possibleRegistrationNames[lowerCasedName] = registrationName;

    if (registrationName === 'onDoubleClick') {
      possibleRegistrationNames.ondblclick = registrationName;
    }
  }

  for (var i = 0; i < dependencies.length; i++) {
    allNativeEvents.add(dependencies[i]);
  }
}

var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');

var hasOwnProperty = Object.prototype.hasOwnProperty;

/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
  {
    // toStringTag is needed for namespaced types like Temporal.Instant
    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
    return type;
  }
} // $FlowFixMe only called in DEV, so void return is not possible.


function willCoercionThrow(value) {
  {
    try {
      testStringCoercion(value);
      return false;
    } catch (e) {
      return true;
    }
  }
}

function testStringCoercion(value) {
  // If you ended up here by following an exception call stack, here's what's
  // happened: you supplied an object or symbol value to React (as a prop, key,
  // DOM attribute, CSS property, string ref, etc.) and when React tried to
  // coerce it to a string using `'' + value`, an exception was thrown.
  //
  // The most common types that will cause this exception are `Symbol` instances
  // and Temporal objects like `Temporal.Instant`. But any object that has a
  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
  // exception. (Library authors do this to prevent users from using built-in
  // numeric operators like `+` or comparison operators like `>=` because custom
  // methods are needed to perform accurate arithmetic or comparison.)
  //
  // To fix the problem, coerce this object or symbol value to a string before
  // passing it to React. The most reliable way is usually `String(value)`.
  //
  // To find which value is throwing, check the browser or debugger console.
  // Before this exception was thrown, there should be `console.error` output
  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
  // problem and how that type was used: key, atrribute, input value prop, etc.
  // In most cases, this console output also shows the component and its
  // ancestor components where the exception happened.
  //
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}

function checkAttributeStringCoercion(value, attributeName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkKeyStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkPropStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkCSSPropertyStringCoercion(value, propName) {
  {
    if (willCoercionThrow(value)) {
      error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkHtmlStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}
function checkFormFieldValueStringCoercion(value) {
  {
    if (willCoercionThrow(value)) {
      error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));

      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
    }
  }
}

// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.

var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.

var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.

var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.

var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.

var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.

var POSITIVE_NUMERIC = 6;

/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */

var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
    return true;
  }

  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
    return false;
  }

  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
    validatedAttributeNameCache[attributeName] = true;
    return true;
  }

  illegalAttributeNameCache[attributeName] = true;

  {
    error('Invalid attribute name: `%s`', attributeName);
  }

  return false;
}
function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null) {
    return propertyInfo.type === RESERVED;
  }

  if (isCustomComponentTag) {
    return false;
  }

  if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return true;
  }

  return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
    return false;
  }

  switch (typeof value) {
    case 'function': // $FlowIssue symbol is perfectly valid here

    case 'symbol':
      // eslint-disable-line
      return true;

    case 'boolean':
      {
        if (isCustomComponentTag) {
          return false;
        }

        if (propertyInfo !== null) {
          return !propertyInfo.acceptsBooleans;
        } else {
          var prefix = name.toLowerCase().slice(0, 5);
          return prefix !== 'data-' && prefix !== 'aria-';
        }
      }

    default:
      return false;
  }
}
function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
  if (value === null || typeof value === 'undefined') {
    return true;
  }

  if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
    return true;
  }

  if (isCustomComponentTag) {

    return false;
  }

  if (propertyInfo !== null) {

    switch (propertyInfo.type) {
      case BOOLEAN:
        return !value;

      case OVERLOADED_BOOLEAN:
        return value === false;

      case NUMERIC:
        return isNaN(value);

      case POSITIVE_NUMERIC:
        return isNaN(value) || value < 1;
    }
  }

  return false;
}
function getPropertyInfo(name) {
  return properties.hasOwnProperty(name) ? properties[name] : null;
}

function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  this.attributeName = attributeName;
  this.attributeNamespace = attributeNamespace;
  this.mustUseProperty = mustUseProperty;
  this.propertyName = name;
  this.type = type;
  this.sanitizeURL = sanitizeURL;
  this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.


var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];

reservedProps.forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.

[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  var name = _ref[0],
      attributeName = _ref[1];
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).

['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.

['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML boolean attributes.

['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.

['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.

['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be positive numbers.

['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  name, // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These are HTML attributes that must be numbers.

['rowSpan', 'start'].forEach(function (name) {
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  name.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
});
var CAMELIZE = /[\-\:]([a-z])/g;

var capitalize = function (token) {
  return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.


['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // String SVG attributes with the xlink namespace.

['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  false);
}); // String SVG attributes with the xml namespace.

['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
  var name = attributeName.replace(CAMELIZE, capitalize);
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.

['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  false, // sanitizeURL
  false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.

var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  attributeName.toLowerCase(), // attributeName
  null, // attributeNamespace
  true, // sanitizeURL
  true);
});

// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space

/* eslint-disable max-len */

var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;

function sanitizeURL(url) {
  {
    if (!didWarn && isJavaScriptProtocol.test(url)) {
      didWarn = true;

      error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
    }
  }
}

/**
 * Get the value for a property on a node. Only used in DEV for SSR validation.
 * The "expected" argument is used as a hint of what the expected value is.
 * Some properties have multiple equivalent values.
 */
function getValueForProperty(node, name, expected, propertyInfo) {
  {
    if (propertyInfo.mustUseProperty) {
      var propertyName = propertyInfo.propertyName;
      return node[propertyName];
    } else {
      // This check protects multiple uses of `expected`, which is why the
      // react-internal/safe-string-coercion rule is disabled in several spots
      // below.
      {
        checkAttributeStringCoercion(expected, name);
      }

      if ( propertyInfo.sanitizeURL) {
        // If we haven't fully disabled javascript: URLs, and if
        // the hydration is successful of a javascript: URL, we
        // still want to warn on the client.
        // eslint-disable-next-line react-internal/safe-string-coercion
        sanitizeURL('' + expected);
      }

      var attributeName = propertyInfo.attributeName;
      var stringValue = null;

      if (propertyInfo.type === OVERLOADED_BOOLEAN) {
        if (node.hasAttribute(attributeName)) {
          var value = node.getAttribute(attributeName);

          if (value === '') {
            return true;
          }

          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
            return value;
          } // eslint-disable-next-line react-internal/safe-string-coercion


          if (value === '' + expected) {
            return expected;
          }

          return value;
        }
      } else if (node.hasAttribute(attributeName)) {
        if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
          // We had an attribute but shouldn't have had one, so read it
          // for the error message.
          return node.getAttribute(attributeName);
        }

        if (propertyInfo.type === BOOLEAN) {
          // If this was a boolean, it doesn't matter what the value is
          // the fact that we have it is the same as the expected.
          return expected;
        } // Even if this property uses a namespace we use getAttribute
        // because we assume its namespaced name is the same as our config.
        // To use getAttributeNS we need the local name which we don't have
        // in our config atm.


        stringValue = node.getAttribute(attributeName);
      }

      if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
        return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion
      } else if (stringValue === '' + expected) {
        return expected;
      } else {
        return stringValue;
      }
    }
  }
}
/**
 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
 * The third argument is used as a hint of what the expected value is. Some
 * attributes have multiple equivalent values.
 */

function getValueForAttribute(node, name, expected, isCustomComponentTag) {
  {
    if (!isAttributeNameSafe(name)) {
      return;
    }

    if (!node.hasAttribute(name)) {
      return expected === undefined ? undefined : null;
    }

    var value = node.getAttribute(name);

    {
      checkAttributeStringCoercion(expected, name);
    }

    if (value === '' + expected) {
      return expected;
    }

    return value;
  }
}
/**
 * Sets the value for a property on a node.
 *
 * @param {DOMElement} node
 * @param {string} name
 * @param {*} value
 */

function setValueForProperty(node, name, value, isCustomComponentTag) {
  var propertyInfo = getPropertyInfo(name);

  if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
    return;
  }

  if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
    value = null;
  }


  if (isCustomComponentTag || propertyInfo === null) {
    if (isAttributeNameSafe(name)) {
      var _attributeName = name;

      if (value === null) {
        node.removeAttribute(_attributeName);
      } else {
        {
          checkAttributeStringCoercion(value, name);
        }

        node.setAttribute(_attributeName,  '' + value);
      }
    }

    return;
  }

  var mustUseProperty = propertyInfo.mustUseProperty;

  if (mustUseProperty) {
    var propertyName = propertyInfo.propertyName;

    if (value === null) {
      var type = propertyInfo.type;
      node[propertyName] = type === BOOLEAN ? false : '';
    } else {
      // Contrary to `setAttribute`, object properties are properly
      // `toString`ed by IE8/9.
      node[propertyName] = value;
    }

    return;
  } // The rest are treated as attributes with special cases.


  var attributeName = propertyInfo.attributeName,
      attributeNamespace = propertyInfo.attributeNamespace;

  if (value === null) {
    node.removeAttribute(attributeName);
  } else {
    var _type = propertyInfo.type;
    var attributeValue;

    if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
      // If attribute type is boolean, we know for sure it won't be an execution sink
      // and we won't require Trusted Type here.
      attributeValue = '';
    } else {
      // `setAttribute` with objects becomes only `[object]` in IE8/9,
      // ('' + value) makes it output the correct toString()-value.
      {
        {
          checkAttributeStringCoercion(value, attributeName);
        }

        attributeValue = '' + value;
      }

      if (propertyInfo.sanitizeURL) {
        sanitizeURL(attributeValue.toString());
      }
    }

    if (attributeNamespace) {
      node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
    } else {
      node.setAttribute(attributeName, attributeValue);
    }
  }
}

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_CACHE_TYPE = Symbol.for('react.cache');
var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
    return null;
  }

  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

  if (typeof maybeIterator === 'function') {
    return maybeIterator;
  }

  return null;
}

var assign = Object.assign;

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;

function disabledLog() {}

disabledLog.__reactDisabledLog = true;
function disableLogs() {
  {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

      var props = {
        configurable: true,
        enumerable: true,
        value: disabledLog,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        info: props,
        log: props,
        warn: props,
        error: props,
        group: props,
        groupCollapsed: props,
        groupEnd: props
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    disabledDepth++;
  }
}
function reenableLogs() {
  {
    disabledDepth--;

    if (disabledDepth === 0) {
      /* eslint-disable react-internal/no-production-logging */
      var props = {
        configurable: true,
        enumerable: true,
        writable: true
      }; // $FlowFixMe Flow thinks console is immutable.

      Object.defineProperties(console, {
        log: assign({}, props, {
          value: prevLog
        }),
        info: assign({}, props, {
          value: prevInfo
        }),
        warn: assign({}, props, {
          value: prevWarn
        }),
        error: assign({}, props, {
          value: prevError
        }),
        group: assign({}, props, {
          value: prevGroup
        }),
        groupCollapsed: assign({}, props, {
          value: prevGroupCollapsed
        }),
        groupEnd: assign({}, props, {
          value: prevGroupEnd
        })
      });
      /* eslint-enable react-internal/no-production-logging */
    }

    if (disabledDepth < 0) {
      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
    }
  }
}

var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
  {
    if (prefix === undefined) {
      // Extract the VM specific prefix used by each line.
      try {
        throw Error();
      } catch (x) {
        var match = x.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || '';
      }
    } // We use the prefix to ensure our stacks line up with native stack frames.


    return '\n' + prefix + name;
  }
}
var reentry = false;
var componentFrameCache;

{
  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
  componentFrameCache = new PossiblyWeakMap();
}

function describeNativeComponentFrame(fn, construct) {
  // If something asked for a stack inside a fake render, it should get ignored.
  if ( !fn || reentry) {
    return '';
  }

  {
    var frame = componentFrameCache.get(fn);

    if (frame !== undefined) {
      return frame;
    }
  }

  var control;
  reentry = true;
  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

  Error.prepareStackTrace = undefined;
  var previousDispatcher;

  {
    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
    // for warnings.

    ReactCurrentDispatcher.current = null;
    disableLogs();
  }

  try {
    // This should throw.
    if (construct) {
      // Something should be setting the props in the constructor.
      var Fake = function () {
        throw Error();
      }; // $FlowFixMe


      Object.defineProperty(Fake.prototype, 'props', {
        set: function () {
          // We use a throwing setter instead of frozen or non-writable props
          // because that won't throw in a non-strict mode function.
          throw Error();
        }
      });

      if (typeof Reflect === 'object' && Reflect.construct) {
        // We construct a different control for this case to include any extra
        // frames added by the construct call.
        try {
          Reflect.construct(Fake, []);
        } catch (x) {
          control = x;
        }

        Reflect.construct(fn, [], Fake);
      } else {
        try {
          Fake.call();
        } catch (x) {
          control = x;
        }

        fn.call(Fake.prototype);
      }
    } else {
      try {
        throw Error();
      } catch (x) {
        control = x;
      }

      fn();
    }
  } catch (sample) {
    // This is inlined manually because closure doesn't do it for us.
    if (sample && control && typeof sample.stack === 'string') {
      // This extracts the first frame from the sample that isn't also in the control.
      // Skipping one frame that we assume is the frame that calls the two.
      var sampleLines = sample.stack.split('\n');
      var controlLines = control.stack.split('\n');
      var s = sampleLines.length - 1;
      var c = controlLines.length - 1;

      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
        // We expect at least one stack frame to be shared.
        // Typically this will be the root most one. However, stack frames may be
        // cut off due to maximum stack limits. In this case, one maybe cut off
        // earlier than the other. We assume that the sample is longer or the same
        // and there for cut off earlier. So we should find the root most frame in
        // the sample somewhere in the control.
        c--;
      }

      for (; s >= 1 && c >= 0; s--, c--) {
        // Next we find the first one that isn't the same which should be the
        // frame that called our sample function and the control.
        if (sampleLines[s] !== controlLines[c]) {
          // In V8, the first line is describing the message but other VMs don't.
          // If we're about to return the first line, and the control is also on the same
          // line, that's a pretty good indicator that our sample threw at same line as
          // the control. I.e. before we entered the sample frame. So we ignore this result.
          // This can happen if you passed a class to function component, or non-function.
          if (s !== 1 || c !== 1) {
            do {
              s--;
              c--; // We may still have similar intermediate frames from the construct call.
              // The next one that isn't the same should be our match though.

              if (c < 0 || sampleLines[s] !== controlLines[c]) {
                // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                // but we have a user-provided "displayName"
                // splice it in to make the stack more readable.


                if (fn.displayName && _frame.includes('<anonymous>')) {
                  _frame = _frame.replace('<anonymous>', fn.displayName);
                }

                {
                  if (typeof fn === 'function') {
                    componentFrameCache.set(fn, _frame);
                  }
                } // Return the line we found.


                return _frame;
              }
            } while (s >= 1 && c >= 0);
          }

          break;
        }
      }
    }
  } finally {
    reentry = false;

    {
      ReactCurrentDispatcher.current = previousDispatcher;
      reenableLogs();
    }

    Error.prepareStackTrace = previousPrepareStackTrace;
  } // Fallback to just using the name if we couldn't make it throw.


  var name = fn ? fn.displayName || fn.name : '';
  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';

  {
    if (typeof fn === 'function') {
      componentFrameCache.set(fn, syntheticFrame);
    }
  }

  return syntheticFrame;
}

function describeClassComponentFrame(ctor, source, ownerFn) {
  {
    return describeNativeComponentFrame(ctor, true);
  }
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
  {
    return describeNativeComponentFrame(fn, false);
  }
}

function shouldConstruct(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {

  if (type == null) {
    return '';
  }

  if (typeof type === 'function') {
    {
      return describeNativeComponentFrame(type, shouldConstruct(type));
    }
  }

  if (typeof type === 'string') {
    return describeBuiltInComponentFrame(type);
  }

  switch (type) {
    case REACT_SUSPENSE_TYPE:
      return describeBuiltInComponentFrame('Suspense');

    case REACT_SUSPENSE_LIST_TYPE:
      return describeBuiltInComponentFrame('SuspenseList');
  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_FORWARD_REF_TYPE:
        return describeFunctionComponentFrame(type.render);

      case REACT_MEMO_TYPE:
        // Memo may contain any component type so we recursively resolve it.
        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            // Lazy may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
          } catch (x) {}
        }
    }
  }

  return '';
}

function describeFiber(fiber) {
  var owner =  fiber._debugOwner ? fiber._debugOwner.type : null ;
  var source =  fiber._debugSource ;

  switch (fiber.tag) {
    case HostComponent:
      return describeBuiltInComponentFrame(fiber.type);

    case LazyComponent:
      return describeBuiltInComponentFrame('Lazy');

    case SuspenseComponent:
      return describeBuiltInComponentFrame('Suspense');

    case SuspenseListComponent:
      return describeBuiltInComponentFrame('SuspenseList');

    case FunctionComponent:
    case IndeterminateComponent:
    case SimpleMemoComponent:
      return describeFunctionComponentFrame(fiber.type);

    case ForwardRef:
      return describeFunctionComponentFrame(fiber.type.render);

    case ClassComponent:
      return describeClassComponentFrame(fiber.type);

    default:
      return '';
  }
}

function getStackByFiberInDevAndProd(workInProgress) {
  try {
    var info = '';
    var node = workInProgress;

    do {
      info += describeFiber(node);
      node = node.return;
    } while (node);

    return info;
  } catch (x) {
    return '\nError generating stack: ' + x.message + '\n' + x.stack;
  }
}

function getWrappedName(outerType, innerType, wrapperName) {
  var displayName = outerType.displayName;

  if (displayName) {
    return displayName;
  }

  var functionName = innerType.displayName || innerType.name || '';
  return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber


function getContextName(type) {
  return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.


function getComponentNameFromType(type) {
  if (type == null) {
    // Host root, text node or just invalid type.
    return null;
  }

  {
    if (typeof type.tag === 'number') {
      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
    }
  }

  if (typeof type === 'function') {
    return type.displayName || type.name || null;
  }

  if (typeof type === 'string') {
    return type;
  }

  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return 'Fragment';

    case REACT_PORTAL_TYPE:
      return 'Portal';

    case REACT_PROFILER_TYPE:
      return 'Profiler';

    case REACT_STRICT_MODE_TYPE:
      return 'StrictMode';

    case REACT_SUSPENSE_TYPE:
      return 'Suspense';

    case REACT_SUSPENSE_LIST_TYPE:
      return 'SuspenseList';

  }

  if (typeof type === 'object') {
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        var context = type;
        return getContextName(context) + '.Consumer';

      case REACT_PROVIDER_TYPE:
        var provider = type;
        return getContextName(provider._context) + '.Provider';

      case REACT_FORWARD_REF_TYPE:
        return getWrappedName(type, type.render, 'ForwardRef');

      case REACT_MEMO_TYPE:
        var outerName = type.displayName || null;

        if (outerName !== null) {
          return outerName;
        }

        return getComponentNameFromType(type.type) || 'Memo';

      case REACT_LAZY_TYPE:
        {
          var lazyComponent = type;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;

          try {
            return getComponentNameFromType(init(payload));
          } catch (x) {
            return null;
          }
        }

      // eslint-disable-next-line no-fallthrough
    }
  }

  return null;
}

function getWrappedName$1(outerType, innerType, wrapperName) {
  var functionName = innerType.displayName || innerType.name || '';
  return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
} // Keep in sync with shared/getComponentNameFromType


function getContextName$1(type) {
  return type.displayName || 'Context';
}

function getComponentNameFromFiber(fiber) {
  var tag = fiber.tag,
      type = fiber.type;

  switch (tag) {
    case CacheComponent:
      return 'Cache';

    case ContextConsumer:
      var context = type;
      return getContextName$1(context) + '.Consumer';

    case ContextProvider:
      var provider = type;
      return getContextName$1(provider._context) + '.Provider';

    case DehydratedFragment:
      return 'DehydratedFragment';

    case ForwardRef:
      return getWrappedName$1(type, type.render, 'ForwardRef');

    case Fragment:
      return 'Fragment';

    case HostComponent:
      // Host component type is the display name (e.g. "div", "View")
      return type;

    case HostPortal:
      return 'Portal';

    case HostRoot:
      return 'Root';

    case HostText:
      return 'Text';

    case LazyComponent:
      // Name comes from the type in this case; we don't have a tag.
      return getComponentNameFromType(type);

    case Mode:
      if (type === REACT_STRICT_MODE_TYPE) {
        // Don't be less specific than shared/getComponentNameFromType
        return 'StrictMode';
      }

      return 'Mode';

    case OffscreenComponent:
      return 'Offscreen';

    case Profiler:
      return 'Profiler';

    case ScopeComponent:
      return 'Scope';

    case SuspenseComponent:
      return 'Suspense';

    case SuspenseListComponent:
      return 'SuspenseList';

    case TracingMarkerComponent:
      return 'TracingMarker';
    // The display name for this tags come from the user-provided type:

    case ClassComponent:
    case FunctionComponent:
    case IncompleteClassComponent:
    case IndeterminateComponent:
    case MemoComponent:
    case SimpleMemoComponent:
      if (typeof type === 'function') {
        return type.displayName || type.name || null;
      }

      if (typeof type === 'string') {
        return type;
      }

      break;

  }

  return null;
}

var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var current = null;
var isRendering = false;
function getCurrentFiberOwnerNameInDevOrNull() {
  {
    if (current === null) {
      return null;
    }

    var owner = current._debugOwner;

    if (owner !== null && typeof owner !== 'undefined') {
      return getComponentNameFromFiber(owner);
    }
  }

  return null;
}

function getCurrentFiberStackInDev() {
  {
    if (current === null) {
      return '';
    } // Safe because if current fiber exists, we are reconciling,
    // and it is guaranteed to be the work-in-progress version.


    return getStackByFiberInDevAndProd(current);
  }
}

function resetCurrentFiber() {
  {
    ReactDebugCurrentFrame.getCurrentStack = null;
    current = null;
    isRendering = false;
  }
}
function setCurrentFiber(fiber) {
  {
    ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
    current = fiber;
    isRendering = false;
  }
}
function getCurrentFiber() {
  {
    return current;
  }
}
function setIsRendering(rendering) {
  {
    isRendering = rendering;
  }
}

// Flow does not allow string concatenation of most non-string types. To work
// around this limitation, we use an opaque type that can only be obtained by
// passing the value through getToStringValue first.
function toString(value) {
  // The coercion safety check is performed in getToStringValue().
  // eslint-disable-next-line react-internal/safe-string-coercion
  return '' + value;
}
function getToStringValue(value) {
  switch (typeof value) {
    case 'boolean':
    case 'number':
    case 'string':
    case 'undefined':
      return value;

    case 'object':
      {
        checkFormFieldValueStringCoercion(value);
      }

      return value;

    default:
      // function, symbol are assigned as empty strings
      return '';
  }
}

var hasReadOnlyValue = {
  button: true,
  checkbox: true,
  image: true,
  hidden: true,
  radio: true,
  reset: true,
  submit: true
};
function checkControlledValueProps(tagName, props) {
  {
    if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
      error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }

    if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
      error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
    }
  }
}

function isCheckable(elem) {
  var type = elem.type;
  var nodeName = elem.nodeName;
  return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
}

function getTracker(node) {
  return node._valueTracker;
}

function detachTracker(node) {
  node._valueTracker = null;
}

function getValueFromNode(node) {
  var value = '';

  if (!node) {
    return value;
  }

  if (isCheckable(node)) {
    value = node.checked ? 'true' : 'false';
  } else {
    value = node.value;
  }

  return value;
}

function trackValueOnNode(node) {
  var valueField = isCheckable(node) ? 'checked' : 'value';
  var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);

  {
    checkFormFieldValueStringCoercion(node[valueField]);
  }

  var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
  // and don't track value will cause over reporting of changes,
  // but it's better then a hard failure
  // (needed for certain tests that spyOn input values and Safari)

  if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
    return;
  }

  var get = descriptor.get,
      set = descriptor.set;
  Object.defineProperty(node, valueField, {
    configurable: true,
    get: function () {
      return get.call(this);
    },
    set: function (value) {
      {
        checkFormFieldValueStringCoercion(value);
      }

      currentValue = '' + value;
      set.call(this, value);
    }
  }); // We could've passed this the first time
  // but it triggers a bug in IE11 and Edge 14/15.
  // Calling defineProperty() again should be equivalent.
  // https://github.com/facebook/react/issues/11768

  Object.defineProperty(node, valueField, {
    enumerable: descriptor.enumerable
  });
  var tracker = {
    getValue: function () {
      return currentValue;
    },
    setValue: function (value) {
      {
        checkFormFieldValueStringCoercion(value);
      }

      currentValue = '' + value;
    },
    stopTracking: function () {
      detachTracker(node);
      delete node[valueField];
    }
  };
  return tracker;
}

function track(node) {
  if (getTracker(node)) {
    return;
  } // TODO: Once it's just Fiber we can move this to node._wrapperState


  node._valueTracker = trackValueOnNode(node);
}
function updateValueIfChanged(node) {
  if (!node) {
    return false;
  }

  var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
  // that trying again will succeed

  if (!tracker) {
    return true;
  }

  var lastValue = tracker.getValue();
  var nextValue = getValueFromNode(node);

  if (nextValue !== lastValue) {
    tracker.setValue(nextValue);
    return true;
  }

  return false;
}

function getActiveElement(doc) {
  doc = doc || (typeof document !== 'undefined' ? document : undefined);

  if (typeof doc === 'undefined') {
    return null;
  }

  try {
    return doc.activeElement || doc.body;
  } catch (e) {
    return doc.body;
  }
}

var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;

function isControlled(props) {
  var usesChecked = props.type === 'checkbox' || props.type === 'radio';
  return usesChecked ? props.checked != null : props.value != null;
}
/**
 * Implements an <input> host component that allows setting these optional
 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
 *
 * If `checked` or `value` are not supplied (or null/undefined), user actions
 * that affect the checked state or value will trigger updates to the element.
 *
 * If they are supplied (and not null/undefined), the rendered element will not
 * trigger updates to the element. Instead, the props must change in order for
 * the rendered element to be updated.
 *
 * The rendered element will be initialized as unchecked (or `defaultChecked`)
 * with an empty value (or `defaultValue`).
 *
 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
 */


function getHostProps(element, props) {
  var node = element;
  var checked = props.checked;
  var hostProps = assign({}, props, {
    defaultChecked: undefined,
    defaultValue: undefined,
    value: undefined,
    checked: checked != null ? checked : node._wrapperState.initialChecked
  });
  return hostProps;
}
function initWrapperState(element, props) {
  {
    checkControlledValueProps('input', props);

    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
      error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);

      didWarnCheckedDefaultChecked = true;
    }

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
      error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);

      didWarnValueDefaultValue = true;
    }
  }

  var node = element;
  var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
  node._wrapperState = {
    initialChecked: props.checked != null ? props.checked : props.defaultChecked,
    initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
    controlled: isControlled(props)
  };
}
function updateChecked(element, props) {
  var node = element;
  var checked = props.checked;

  if (checked != null) {
    setValueForProperty(node, 'checked', checked, false);
  }
}
function updateWrapper(element, props) {
  var node = element;

  {
    var controlled = isControlled(props);

    if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
      error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');

      didWarnUncontrolledToControlled = true;
    }

    if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
      error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');

      didWarnControlledToUncontrolled = true;
    }
  }

  updateChecked(element, props);
  var value = getToStringValue(props.value);
  var type = props.type;

  if (value != null) {
    if (type === 'number') {
      if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
      // eslint-disable-next-line
      node.value != value) {
        node.value = toString(value);
      }
    } else if (node.value !== toString(value)) {
      node.value = toString(value);
    }
  } else if (type === 'submit' || type === 'reset') {
    // Submit/reset inputs need the attribute removed completely to avoid
    // blank-text buttons.
    node.removeAttribute('value');
    return;
  }

  {
    // When syncing the value attribute, the value comes from a cascade of
    // properties:
    //  1. The value React property
    //  2. The defaultValue React property
    //  3. Otherwise there should be no change
    if (props.hasOwnProperty('value')) {
      setDefaultValue(node, props.type, value);
    } else if (props.hasOwnProperty('defaultValue')) {
      setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
    }
  }

  {
    // When syncing the checked attribute, it only changes when it needs
    // to be removed, such as transitioning from a checkbox into a text input
    if (props.checked == null && props.defaultChecked != null) {
      node.defaultChecked = !!props.defaultChecked;
    }
  }
}
function postMountWrapper(element, props, isHydrating) {
  var node = element; // Do not assign value if it is already set. This prevents user text input
  // from being lost during SSR hydration.

  if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
    var type = props.type;
    var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
    // default value provided by the browser. See: #12872

    if (isButton && (props.value === undefined || props.value === null)) {
      return;
    }

    var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
    // from being lost during SSR hydration.

    if (!isHydrating) {
      {
        // When syncing the value attribute, the value property should use
        // the wrapperState._initialValue property. This uses:
        //
        //   1. The value React property when present
        //   2. The defaultValue React property when present
        //   3. An empty string
        if (initialValue !== node.value) {
          node.value = initialValue;
        }
      }
    }

    {
      // Otherwise, the value attribute is synchronized to the property,
      // so we assign defaultValue to the same thing as the value property
      // assignment step above.
      node.defaultValue = initialValue;
    }
  } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
  // this is needed to work around a chrome bug where setting defaultChecked
  // will sometimes influence the value of checked (even after detachment).
  // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
  // We need to temporarily unset name to avoid disrupting radio button groups.


  var name = node.name;

  if (name !== '') {
    node.name = '';
  }

  {
    // When syncing the checked attribute, both the checked property and
    // attribute are assigned at the same time using defaultChecked. This uses:
    //
    //   1. The checked React property when present
    //   2. The defaultChecked React property when present
    //   3. Otherwise, false
    node.defaultChecked = !node.defaultChecked;
    node.defaultChecked = !!node._wrapperState.initialChecked;
  }

  if (name !== '') {
    node.name = name;
  }
}
function restoreControlledState(element, props) {
  var node = element;
  updateWrapper(node, props);
  updateNamedCousins(node, props);
}

function updateNamedCousins(rootNode, props) {
  var name = props.name;

  if (props.type === 'radio' && name != null) {
    var queryRoot = rootNode;

    while (queryRoot.parentNode) {
      queryRoot = queryRoot.parentNode;
    } // If `rootNode.form` was non-null, then we could try `form.elements`,
    // but that sometimes behaves strangely in IE8. We could also try using
    // `form.getElementsByName`, but that will only return direct children
    // and won't include inputs that use the HTML5 `form=` attribute. Since
    // the input might not even be in a form. It might not even be in the
    // document. Let's just use the local `querySelectorAll` to ensure we don't
    // miss anything.


    {
      checkAttributeStringCoercion(name, 'name');
    }

    var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');

    for (var i = 0; i < group.length; i++) {
      var otherNode = group[i];

      if (otherNode === rootNode || otherNode.form !== rootNode.form) {
        continue;
      } // This will throw if radio buttons rendered by different copies of React
      // and the same name are rendered into the same form (same as #1939).
      // That's probably okay; we don't support it just as we don't support
      // mixing React radio buttons with non-React ones.


      var otherProps = getFiberCurrentPropsFromNode(otherNode);

      if (!otherProps) {
        throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.');
      } // We need update the tracked value on the named cousin since the value
      // was changed but the input saw no event or value set


      updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
      // was previously checked to update will cause it to be come re-checked
      // as appropriate.

      updateWrapper(otherNode, otherProps);
    }
  }
} // In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253


function setDefaultValue(node, type, value) {
  if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
  type !== 'number' || getActiveElement(node.ownerDocument) !== node) {
    if (value == null) {
      node.defaultValue = toString(node._wrapperState.initialValue);
    } else if (node.defaultValue !== toString(value)) {
      node.defaultValue = toString(value);
    }
  }
}

var didWarnSelectedSetOnOption = false;
var didWarnInvalidChild = false;
var didWarnInvalidInnerHTML = false;
/**
 * Implements an <option> host component that warns when `selected` is set.
 */

function validateProps(element, props) {
  {
    // If a value is not provided, then the children must be simple.
    if (props.value == null) {
      if (typeof props.children === 'object' && props.children !== null) {
        React.Children.forEach(props.children, function (child) {
          if (child == null) {
            return;
          }

          if (typeof child === 'string' || typeof child === 'number') {
            return;
          }

          if (!didWarnInvalidChild) {
            didWarnInvalidChild = true;

            error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
          }
        });
      } else if (props.dangerouslySetInnerHTML != null) {
        if (!didWarnInvalidInnerHTML) {
          didWarnInvalidInnerHTML = true;

          error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
        }
      }
    } // TODO: Remove support for `selected` in <option>.


    if (props.selected != null && !didWarnSelectedSetOnOption) {
      error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');

      didWarnSelectedSetOnOption = true;
    }
  }
}
function postMountWrapper$1(element, props) {
  // value="" should make a value attribute (#6219)
  if (props.value != null) {
    element.setAttribute('value', toString(getToStringValue(props.value)));
  }
}

var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

function isArray(a) {
  return isArrayImpl(a);
}

var didWarnValueDefaultValue$1;

{
  didWarnValueDefaultValue$1 = false;
}

function getDeclarationErrorAddendum() {
  var ownerName = getCurrentFiberOwnerNameInDevOrNull();

  if (ownerName) {
    return '\n\nCheck the render method of `' + ownerName + '`.';
  }

  return '';
}

var valuePropNames = ['value', 'defaultValue'];
/**
 * Validation function for `value` and `defaultValue`.
 */

function checkSelectPropTypes(props) {
  {
    checkControlledValueProps('select', props);

    for (var i = 0; i < valuePropNames.length; i++) {
      var propName = valuePropNames[i];

      if (props[propName] == null) {
        continue;
      }

      var propNameIsArray = isArray(props[propName]);

      if (props.multiple && !propNameIsArray) {
        error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
      } else if (!props.multiple && propNameIsArray) {
        error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
      }
    }
  }
}

function updateOptions(node, multiple, propValue, setDefaultSelected) {
  var options = node.options;

  if (multiple) {
    var selectedValues = propValue;
    var selectedValue = {};

    for (var i = 0; i < selectedValues.length; i++) {
      // Prefix to avoid chaos with special keys.
      selectedValue['$' + selectedValues[i]] = true;
    }

    for (var _i = 0; _i < options.length; _i++) {
      var selected = selectedValue.hasOwnProperty('$' + options[_i].value);

      if (options[_i].selected !== selected) {
        options[_i].selected = selected;
      }

      if (selected && setDefaultSelected) {
        options[_i].defaultSelected = true;
      }
    }
  } else {
    // Do not set `select.value` as exact behavior isn't consistent across all
    // browsers for all cases.
    var _selectedValue = toString(getToStringValue(propValue));

    var defaultSelected = null;

    for (var _i2 = 0; _i2 < options.length; _i2++) {
      if (options[_i2].value === _selectedValue) {
        options[_i2].selected = true;

        if (setDefaultSelected) {
          options[_i2].defaultSelected = true;
        }

        return;
      }

      if (defaultSelected === null && !options[_i2].disabled) {
        defaultSelected = options[_i2];
      }
    }

    if (defaultSelected !== null) {
      defaultSelected.selected = true;
    }
  }
}
/**
 * Implements a <select> host component that allows optionally setting the
 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
 * stringable. If `multiple` is true, the prop must be an array of stringables.
 *
 * If `value` is not supplied (or null/undefined), user actions that change the
 * selected option will trigger updates to the rendered options.
 *
 * If it is supplied (and not null/undefined), the rendered options will not
 * update in response to user actions. Instead, the `value` prop must change in
 * order for the rendered options to update.
 *
 * If `defaultValue` is provided, any options with the supplied values will be
 * selected.
 */


function getHostProps$1(element, props) {
  return assign({}, props, {
    value: undefined
  });
}
function initWrapperState$1(element, props) {
  var node = element;

  {
    checkSelectPropTypes(props);
  }

  node._wrapperState = {
    wasMultiple: !!props.multiple
  };

  {
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
      error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');

      didWarnValueDefaultValue$1 = true;
    }
  }
}
function postMountWrapper$2(element, props) {
  var node = element;
  node.multiple = !!props.multiple;
  var value = props.value;

  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  } else if (props.defaultValue != null) {
    updateOptions(node, !!props.multiple, props.defaultValue, true);
  }
}
function postUpdateWrapper(element, props) {
  var node = element;
  var wasMultiple = node._wrapperState.wasMultiple;
  node._wrapperState.wasMultiple = !!props.multiple;
  var value = props.value;

  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  } else if (wasMultiple !== !!props.multiple) {
    // For simplicity, reapply `defaultValue` if `multiple` is toggled.
    if (props.defaultValue != null) {
      updateOptions(node, !!props.multiple, props.defaultValue, true);
    } else {
      // Revert the select back to its default unselected state.
      updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
    }
  }
}
function restoreControlledState$1(element, props) {
  var node = element;
  var value = props.value;

  if (value != null) {
    updateOptions(node, !!props.multiple, value, false);
  }
}

var didWarnValDefaultVal = false;

/**
 * Implements a <textarea> host component that allows setting `value`, and
 * `defaultValue`. This differs from the traditional DOM API because value is
 * usually set as PCDATA children.
 *
 * If `value` is not supplied (or null/undefined), user actions that affect the
 * value will trigger updates to the element.
 *
 * If `value` is supplied (and not null/undefined), the rendered element will
 * not trigger updates to the element. Instead, the `value` prop must change in
 * order for the rendered element to be updated.
 *
 * The rendered element will be initialized with an empty value, the prop
 * `defaultValue` if specified, or the children content (deprecated).
 */
function getHostProps$2(element, props) {
  var node = element;

  if (props.dangerouslySetInnerHTML != null) {
    throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
  } // Always set children to the same thing. In IE9, the selection range will
  // get reset if `textContent` is mutated.  We could add a check in setTextContent
  // to only set the value if/when the value differs from the node value (which would
  // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
  // solution. The value can be a boolean or object so that's why it's forced
  // to be a string.


  var hostProps = assign({}, props, {
    value: undefined,
    defaultValue: undefined,
    children: toString(node._wrapperState.initialValue)
  });

  return hostProps;
}
function initWrapperState$2(element, props) {
  var node = element;

  {
    checkControlledValueProps('textarea', props);

    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
      error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');

      didWarnValDefaultVal = true;
    }
  }

  var initialValue = props.value; // Only bother fetching default value if we're going to use it

  if (initialValue == null) {
    var children = props.children,
        defaultValue = props.defaultValue;

    if (children != null) {
      {
        error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
      }

      {
        if (defaultValue != null) {
          throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
        }

        if (isArray(children)) {
          if (children.length > 1) {
            throw new Error('<textarea> can only have at most one child.');
          }

          children = children[0];
        }

        defaultValue = children;
      }
    }

    if (defaultValue == null) {
      defaultValue = '';
    }

    initialValue = defaultValue;
  }

  node._wrapperState = {
    initialValue: getToStringValue(initialValue)
  };
}
function updateWrapper$1(element, props) {
  var node = element;
  var value = getToStringValue(props.value);
  var defaultValue = getToStringValue(props.defaultValue);

  if (value != null) {
    // Cast `value` to a string to ensure the value is set correctly. While
    // browsers typically do this as necessary, jsdom doesn't.
    var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed

    if (newValue !== node.value) {
      node.value = newValue;
    }

    if (props.defaultValue == null && node.defaultValue !== newValue) {
      node.defaultValue = newValue;
    }
  }

  if (defaultValue != null) {
    node.defaultValue = toString(defaultValue);
  }
}
function postMountWrapper$3(element, props) {
  var node = element; // This is in postMount because we need access to the DOM node, which is not
  // available until after the component has mounted.

  var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
  // initial value. In IE10/IE11 there is a bug where the placeholder attribute
  // will populate textContent as well.
  // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/

  if (textContent === node._wrapperState.initialValue) {
    if (textContent !== '' && textContent !== null) {
      node.value = textContent;
    }
  }
}
function restoreControlledState$2(element, props) {
  // DOM component is still mounted; update
  updateWrapper$1(element, props);
}

var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace.

function getIntrinsicNamespace(type) {
  switch (type) {
    case 'svg':
      return SVG_NAMESPACE;

    case 'math':
      return MATH_NAMESPACE;

    default:
      return HTML_NAMESPACE;
  }
}
function getChildNamespace(parentNamespace, type) {
  if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
    // No (or default) parent namespace: potential entry point.
    return getIntrinsicNamespace(type);
  }

  if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
    // We're leaving SVG.
    return HTML_NAMESPACE;
  } // By default, pass namespace below.


  return parentNamespace;
}

/* globals MSApp */

/**
 * Create a function which has 'unsafe' privileges (required by windows8 apps)
 */
var createMicrosoftUnsafeLocalFunction = function (func) {
  if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
    return function (arg0, arg1, arg2, arg3) {
      MSApp.execUnsafeLocalFunction(function () {
        return func(arg0, arg1, arg2, arg3);
      });
    };
  } else {
    return func;
  }
};

var reusableSVGContainer;
/**
 * Set the innerHTML property of a node
 *
 * @param {DOMElement} node
 * @param {string} html
 * @internal
 */

var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
  if (node.namespaceURI === SVG_NAMESPACE) {

    if (!('innerHTML' in node)) {
      // IE does not have innerHTML for SVG nodes, so instead we inject the
      // new markup in a temp node and then move the child nodes across into
      // the target node
      reusableSVGContainer = reusableSVGContainer || document.createElement('div');
      reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
      var svgNode = reusableSVGContainer.firstChild;

      while (node.firstChild) {
        node.removeChild(node.firstChild);
      }

      while (svgNode.firstChild) {
        node.appendChild(svgNode.firstChild);
      }

      return;
    }
  }

  node.innerHTML = html;
});

/**
 * HTML nodeType values that represent the type of the node
 */
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_NODE = 9;
var DOCUMENT_FRAGMENT_NODE = 11;

/**
 * Set the textContent property of a node. For text updates, it's faster
 * to set the `nodeValue` of the Text node directly instead of using
 * `.textContent` which will remove the existing node and create a new one.
 *
 * @param {DOMElement} node
 * @param {string} text
 * @internal
 */

var setTextContent = function (node, text) {
  if (text) {
    var firstChild = node.firstChild;

    if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
      firstChild.nodeValue = text;
      return;
    }
  }

  node.textContent = text;
};

// List derived from Gecko source code:
// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
var shorthandToLonghand = {
  animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
  background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
  backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
  border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
  borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
  borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
  borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
  borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
  borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
  borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
  borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
  borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
  borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
  borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
  borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
  borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
  borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
  columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
  columns: ['columnCount', 'columnWidth'],
  flex: ['flexBasis', 'flexGrow', 'flexShrink'],
  flexFlow: ['flexDirection', 'flexWrap'],
  font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
  fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
  gap: ['columnGap', 'rowGap'],
  grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
  gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
  gridColumn: ['gridColumnEnd', 'gridColumnStart'],
  gridColumnGap: ['columnGap'],
  gridGap: ['columnGap', 'rowGap'],
  gridRow: ['gridRowEnd', 'gridRowStart'],
  gridRowGap: ['rowGap'],
  gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
  listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
  margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
  marker: ['markerEnd', 'markerMid', 'markerStart'],
  mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
  maskPosition: ['maskPositionX', 'maskPositionY'],
  outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
  overflow: ['overflowX', 'overflowY'],
  padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
  placeContent: ['alignContent', 'justifyContent'],
  placeItems: ['alignItems', 'justifyItems'],
  placeSelf: ['alignSelf', 'justifySelf'],
  textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
  textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
  transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
  wordWrap: ['overflowWrap']
};

/**
 * CSS properties which accept numbers but are not in units of "px".
 */
var isUnitlessNumber = {
  animationIterationCount: true,
  aspectRatio: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */

function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */


var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.

Object.keys(isUnitlessNumber).forEach(function (prop) {
  prefixes.forEach(function (prefix) {
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  });
});

/**
 * Convert a value into the proper css writable value. The style name `name`
 * should be logical (no hyphens), as specified
 * in `CSSProperty.isUnitlessNumber`.
 *
 * @param {string} name CSS property name such as `topMargin`.
 * @param {*} value CSS property value such as `10px`.
 * @return {string} Normalized style value with dimensions applied.
 */

function dangerousStyleValue(name, value, isCustomProperty) {
  // Note that we've removed escapeTextForBrowser() calls here since the
  // whole string will be escaped when the attribute is injected into
  // the markup. If you provide unsafe user data here they can inject
  // arbitrary CSS which may be problematic (I couldn't repro this):
  // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
  // This is not an XSS hole but instead a potential CSS injection issue
  // which has lead to a greater discussion about how we're going to
  // trust URLs moving forward. See #2115901
  var isEmpty = value == null || typeof value === 'boolean' || value === '';

  if (isEmpty) {
    return '';
  }

  if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
    return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
  }

  {
    checkCSSPropertyStringCoercion(value, name);
  }

  return ('' + value).trim();
}

var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */

function hyphenateStyleName(name) {
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
}

var warnValidStyle = function () {};

{
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
  var msPattern$1 = /^-ms-/;
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

  var badStyleValueWithSemicolonPattern = /;\s*$/;
  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;
  var warnedForInfinityValue = false;

  var camelize = function (string) {
    return string.replace(hyphenPattern, function (_, character) {
      return character.toUpperCase();
    });
  };

  var warnHyphenatedStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
    // is converted to lowercase `ms`.
    camelize(name.replace(msPattern$1, 'ms-')));
  };

  var warnBadVendoredStyleName = function (name) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;

    error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
  };

  var warnStyleValueWithSemicolon = function (name, value) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;

    error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
  };

  var warnStyleValueIsNaN = function (name, value) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;

    error('`NaN` is an invalid value for the `%s` css style property.', name);
  };

  var warnStyleValueIsInfinity = function (name, value) {
    if (warnedForInfinityValue) {
      return;
    }

    warnedForInfinityValue = true;

    error('`Infinity` is an invalid value for the `%s` css style property.', name);
  };

  warnValidStyle = function (name, value) {
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value);
    }

    if (typeof value === 'number') {
      if (isNaN(value)) {
        warnStyleValueIsNaN(name, value);
      } else if (!isFinite(value)) {
        warnStyleValueIsInfinity(name, value);
      }
    }
  };
}

var warnValidStyle$1 = warnValidStyle;

/**
 * Operations for dealing with CSS properties.
 */

/**
 * This creates a string that is expected to be equivalent to the style
 * attribute generated by server-side rendering. It by-passes warnings and
 * security checks so it's not safe to use this value for anything other than
 * comparison. It is only used in DEV for SSR validation.
 */

function createDangerousStringForStyles(styles) {
  {
    var serialized = '';
    var delimiter = '';

    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }

      var styleValue = styles[styleName];

      if (styleValue != null) {
        var isCustomProperty = styleName.indexOf('--') === 0;
        serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
        serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
        delimiter = ';';
      }
    }

    return serialized || null;
  }
}
/**
 * Sets the value for multiple styles on a node.  If a value is specified as
 * '' (empty string), the corresponding style property will be unset.
 *
 * @param {DOMElement} node
 * @param {object} styles
 */

function setValueForStyles(node, styles) {
  var style = node.style;

  for (var styleName in styles) {
    if (!styles.hasOwnProperty(styleName)) {
      continue;
    }

    var isCustomProperty = styleName.indexOf('--') === 0;

    {
      if (!isCustomProperty) {
        warnValidStyle$1(styleName, styles[styleName]);
      }
    }

    var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);

    if (styleName === 'float') {
      styleName = 'cssFloat';
    }

    if (isCustomProperty) {
      style.setProperty(styleName, styleValue);
    } else {
      style[styleName] = styleValue;
    }
  }
}

function isValueEmpty(value) {
  return value == null || typeof value === 'boolean' || value === '';
}
/**
 * Given {color: 'red', overflow: 'hidden'} returns {
 *   color: 'color',
 *   overflowX: 'overflow',
 *   overflowY: 'overflow',
 * }. This can be read as "the overflowY property was set by the overflow
 * shorthand". That is, the values are the property that each was derived from.
 */


function expandShorthandMap(styles) {
  var expanded = {};

  for (var key in styles) {
    var longhands = shorthandToLonghand[key] || [key];

    for (var i = 0; i < longhands.length; i++) {
      expanded[longhands[i]] = key;
    }
  }

  return expanded;
}
/**
 * When mixing shorthand and longhand property names, we warn during updates if
 * we expect an incorrect result to occur. In particular, we warn for:
 *
 * Updating a shorthand property (longhand gets overwritten):
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
 *   becomes .style.font = 'baz'
 * Removing a shorthand property (longhand gets lost too):
 *   {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
 *   becomes .style.font = ''
 * Removing a longhand property (should revert to shorthand; doesn't):
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
 *   becomes .style.fontVariant = ''
 */


function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
  {
    if (!nextStyles) {
      return;
    }

    var expandedUpdates = expandShorthandMap(styleUpdates);
    var expandedStyles = expandShorthandMap(nextStyles);
    var warnedAbout = {};

    for (var key in expandedUpdates) {
      var originalKey = expandedUpdates[key];
      var correctOriginalKey = expandedStyles[key];

      if (correctOriginalKey && originalKey !== correctOriginalKey) {
        var warningKey = originalKey + ',' + correctOriginalKey;

        if (warnedAbout[warningKey]) {
          continue;
        }

        warnedAbout[warningKey] = true;

        error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
      }
    }
  }
}

// For HTML, certain tags should omit their close tag. We keep a list for
// those special-case tags.
var omittedCloseTags = {
  area: true,
  base: true,
  br: true,
  col: true,
  embed: true,
  hr: true,
  img: true,
  input: true,
  keygen: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.

};

// `omittedCloseTags` except that `menuitem` should still have its closing tag.

var voidElementTags = assign({
  menuitem: true
}, omittedCloseTags);

var HTML = '__html';

function assertValidProps(tag, props) {
  if (!props) {
    return;
  } // Note the use of `==` which checks for null or undefined.


  if (voidElementTags[tag]) {
    if (props.children != null || props.dangerouslySetInnerHTML != null) {
      throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
    }
  }

  if (props.dangerouslySetInnerHTML != null) {
    if (props.children != null) {
      throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
    }

    if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) {
      throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
    }
  }

  {
    if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
      error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
    }
  }

  if (props.style != null && typeof props.style !== 'object') {
    throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
  }
}

function isCustomComponent(tagName, props) {
  if (tagName.indexOf('-') === -1) {
    return typeof props.is === 'string';
  }

  switch (tagName) {
    // These are reserved SVG and MathML elements.
    // We don't mind this list too much because we expect it to never grow.
    // The alternative is to track the namespace in a few places which is convoluted.
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
    case 'annotation-xml':
    case 'color-profile':
    case 'font-face':
    case 'font-face-src':
    case 'font-face-uri':
    case 'font-face-format':
    case 'font-face-name':
    case 'missing-glyph':
      return false;

    default:
      return true;
  }
}

// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
  // HTML
  accept: 'accept',
  acceptcharset: 'acceptCharset',
  'accept-charset': 'acceptCharset',
  accesskey: 'accessKey',
  action: 'action',
  allowfullscreen: 'allowFullScreen',
  alt: 'alt',
  as: 'as',
  async: 'async',
  autocapitalize: 'autoCapitalize',
  autocomplete: 'autoComplete',
  autocorrect: 'autoCorrect',
  autofocus: 'autoFocus',
  autoplay: 'autoPlay',
  autosave: 'autoSave',
  capture: 'capture',
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing',
  challenge: 'challenge',
  charset: 'charSet',
  checked: 'checked',
  children: 'children',
  cite: 'cite',
  class: 'className',
  classid: 'classID',
  classname: 'className',
  cols: 'cols',
  colspan: 'colSpan',
  content: 'content',
  contenteditable: 'contentEditable',
  contextmenu: 'contextMenu',
  controls: 'controls',
  controlslist: 'controlsList',
  coords: 'coords',
  crossorigin: 'crossOrigin',
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
  data: 'data',
  datetime: 'dateTime',
  default: 'default',
  defaultchecked: 'defaultChecked',
  defaultvalue: 'defaultValue',
  defer: 'defer',
  dir: 'dir',
  disabled: 'disabled',
  disablepictureinpicture: 'disablePictureInPicture',
  disableremoteplayback: 'disableRemotePlayback',
  download: 'download',
  draggable: 'draggable',
  enctype: 'encType',
  enterkeyhint: 'enterKeyHint',
  for: 'htmlFor',
  form: 'form',
  formmethod: 'formMethod',
  formaction: 'formAction',
  formenctype: 'formEncType',
  formnovalidate: 'formNoValidate',
  formtarget: 'formTarget',
  frameborder: 'frameBorder',
  headers: 'headers',
  height: 'height',
  hidden: 'hidden',
  high: 'high',
  href: 'href',
  hreflang: 'hrefLang',
  htmlfor: 'htmlFor',
  httpequiv: 'httpEquiv',
  'http-equiv': 'httpEquiv',
  icon: 'icon',
  id: 'id',
  imagesizes: 'imageSizes',
  imagesrcset: 'imageSrcSet',
  innerhtml: 'innerHTML',
  inputmode: 'inputMode',
  integrity: 'integrity',
  is: 'is',
  itemid: 'itemID',
  itemprop: 'itemProp',
  itemref: 'itemRef',
  itemscope: 'itemScope',
  itemtype: 'itemType',
  keyparams: 'keyParams',
  keytype: 'keyType',
  kind: 'kind',
  label: 'label',
  lang: 'lang',
  list: 'list',
  loop: 'loop',
  low: 'low',
  manifest: 'manifest',
  marginwidth: 'marginWidth',
  marginheight: 'marginHeight',
  max: 'max',
  maxlength: 'maxLength',
  media: 'media',
  mediagroup: 'mediaGroup',
  method: 'method',
  min: 'min',
  minlength: 'minLength',
  multiple: 'multiple',
  muted: 'muted',
  name: 'name',
  nomodule: 'noModule',
  nonce: 'nonce',
  novalidate: 'noValidate',
  open: 'open',
  optimum: 'optimum',
  pattern: 'pattern',
  placeholder: 'placeholder',
  playsinline: 'playsInline',
  poster: 'poster',
  preload: 'preload',
  profile: 'profile',
  radiogroup: 'radioGroup',
  readonly: 'readOnly',
  referrerpolicy: 'referrerPolicy',
  rel: 'rel',
  required: 'required',
  reversed: 'reversed',
  role: 'role',
  rows: 'rows',
  rowspan: 'rowSpan',
  sandbox: 'sandbox',
  scope: 'scope',
  scoped: 'scoped',
  scrolling: 'scrolling',
  seamless: 'seamless',
  selected: 'selected',
  shape: 'shape',
  size: 'size',
  sizes: 'sizes',
  span: 'span',
  spellcheck: 'spellCheck',
  src: 'src',
  srcdoc: 'srcDoc',
  srclang: 'srcLang',
  srcset: 'srcSet',
  start: 'start',
  step: 'step',
  style: 'style',
  summary: 'summary',
  tabindex: 'tabIndex',
  target: 'target',
  title: 'title',
  type: 'type',
  usemap: 'useMap',
  value: 'value',
  width: 'width',
  wmode: 'wmode',
  wrap: 'wrap',
  // SVG
  about: 'about',
  accentheight: 'accentHeight',
  'accent-height': 'accentHeight',
  accumulate: 'accumulate',
  additive: 'additive',
  alignmentbaseline: 'alignmentBaseline',
  'alignment-baseline': 'alignmentBaseline',
  allowreorder: 'allowReorder',
  alphabetic: 'alphabetic',
  amplitude: 'amplitude',
  arabicform: 'arabicForm',
  'arabic-form': 'arabicForm',
  ascent: 'ascent',
  attributename: 'attributeName',
  attributetype: 'attributeType',
  autoreverse: 'autoReverse',
  azimuth: 'azimuth',
  basefrequency: 'baseFrequency',
  baselineshift: 'baselineShift',
  'baseline-shift': 'baselineShift',
  baseprofile: 'baseProfile',
  bbox: 'bbox',
  begin: 'begin',
  bias: 'bias',
  by: 'by',
  calcmode: 'calcMode',
  capheight: 'capHeight',
  'cap-height': 'capHeight',
  clip: 'clip',
  clippath: 'clipPath',
  'clip-path': 'clipPath',
  clippathunits: 'clipPathUnits',
  cliprule: 'clipRule',
  'clip-rule': 'clipRule',
  color: 'color',
  colorinterpolation: 'colorInterpolation',
  'color-interpolation': 'colorInterpolation',
  colorinterpolationfilters: 'colorInterpolationFilters',
  'color-interpolation-filters': 'colorInterpolationFilters',
  colorprofile: 'colorProfile',
  'color-profile': 'colorProfile',
  colorrendering: 'colorRendering',
  'color-rendering': 'colorRendering',
  contentscripttype: 'contentScriptType',
  contentstyletype: 'contentStyleType',
  cursor: 'cursor',
  cx: 'cx',
  cy: 'cy',
  d: 'd',
  datatype: 'datatype',
  decelerate: 'decelerate',
  descent: 'descent',
  diffuseconstant: 'diffuseConstant',
  direction: 'direction',
  display: 'display',
  divisor: 'divisor',
  dominantbaseline: 'dominantBaseline',
  'dominant-baseline': 'dominantBaseline',
  dur: 'dur',
  dx: 'dx',
  dy: 'dy',
  edgemode: 'edgeMode',
  elevation: 'elevation',
  enablebackground: 'enableBackground',
  'enable-background': 'enableBackground',
  end: 'end',
  exponent: 'exponent',
  externalresourcesrequired: 'externalResourcesRequired',
  fill: 'fill',
  fillopacity: 'fillOpacity',
  'fill-opacity': 'fillOpacity',
  fillrule: 'fillRule',
  'fill-rule': 'fillRule',
  filter: 'filter',
  filterres: 'filterRes',
  filterunits: 'filterUnits',
  floodopacity: 'floodOpacity',
  'flood-opacity': 'floodOpacity',
  floodcolor: 'floodColor',
  'flood-color': 'floodColor',
  focusable: 'focusable',
  fontfamily: 'fontFamily',
  'font-family': 'fontFamily',
  fontsize: 'fontSize',
  'font-size': 'fontSize',
  fontsizeadjust: 'fontSizeAdjust',
  'font-size-adjust': 'fontSizeAdjust',
  fontstretch: 'fontStretch',
  'font-stretch': 'fontStretch',
  fontstyle: 'fontStyle',
  'font-style': 'fontStyle',
  fontvariant: 'fontVariant',
  'font-variant': 'fontVariant',
  fontweight: 'fontWeight',
  'font-weight': 'fontWeight',
  format: 'format',
  from: 'from',
  fx: 'fx',
  fy: 'fy',
  g1: 'g1',
  g2: 'g2',
  glyphname: 'glyphName',
  'glyph-name': 'glyphName',
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
  glyphorientationvertical: 'glyphOrientationVertical',
  'glyph-orientation-vertical': 'glyphOrientationVertical',
  glyphref: 'glyphRef',
  gradienttransform: 'gradientTransform',
  gradientunits: 'gradientUnits',
  hanging: 'hanging',
  horizadvx: 'horizAdvX',
  'horiz-adv-x': 'horizAdvX',
  horizoriginx: 'horizOriginX',
  'horiz-origin-x': 'horizOriginX',
  ideographic: 'ideographic',
  imagerendering: 'imageRendering',
  'image-rendering': 'imageRendering',
  in2: 'in2',
  in: 'in',
  inlist: 'inlist',
  intercept: 'intercept',
  k1: 'k1',
  k2: 'k2',
  k3: 'k3',
  k4: 'k4',
  k: 'k',
  kernelmatrix: 'kernelMatrix',
  kernelunitlength: 'kernelUnitLength',
  kerning: 'kerning',
  keypoints: 'keyPoints',
  keysplines: 'keySplines',
  keytimes: 'keyTimes',
  lengthadjust: 'lengthAdjust',
  letterspacing: 'letterSpacing',
  'letter-spacing': 'letterSpacing',
  lightingcolor: 'lightingColor',
  'lighting-color': 'lightingColor',
  limitingconeangle: 'limitingConeAngle',
  local: 'local',
  markerend: 'markerEnd',
  'marker-end': 'markerEnd',
  markerheight: 'markerHeight',
  markermid: 'markerMid',
  'marker-mid': 'markerMid',
  markerstart: 'markerStart',
  'marker-start': 'markerStart',
  markerunits: 'markerUnits',
  markerwidth: 'markerWidth',
  mask: 'mask',
  maskcontentunits: 'maskContentUnits',
  maskunits: 'maskUnits',
  mathematical: 'mathematical',
  mode: 'mode',
  numoctaves: 'numOctaves',
  offset: 'offset',
  opacity: 'opacity',
  operator: 'operator',
  order: 'order',
  orient: 'orient',
  orientation: 'orientation',
  origin: 'origin',
  overflow: 'overflow',
  overlineposition: 'overlinePosition',
  'overline-position': 'overlinePosition',
  overlinethickness: 'overlineThickness',
  'overline-thickness': 'overlineThickness',
  paintorder: 'paintOrder',
  'paint-order': 'paintOrder',
  panose1: 'panose1',
  'panose-1': 'panose1',
  pathlength: 'pathLength',
  patterncontentunits: 'patternContentUnits',
  patterntransform: 'patternTransform',
  patternunits: 'patternUnits',
  pointerevents: 'pointerEvents',
  'pointer-events': 'pointerEvents',
  points: 'points',
  pointsatx: 'pointsAtX',
  pointsaty: 'pointsAtY',
  pointsatz: 'pointsAtZ',
  prefix: 'prefix',
  preservealpha: 'preserveAlpha',
  preserveaspectratio: 'preserveAspectRatio',
  primitiveunits: 'primitiveUnits',
  property: 'property',
  r: 'r',
  radius: 'radius',
  refx: 'refX',
  refy: 'refY',
  renderingintent: 'renderingIntent',
  'rendering-intent': 'renderingIntent',
  repeatcount: 'repeatCount',
  repeatdur: 'repeatDur',
  requiredextensions: 'requiredExtensions',
  requiredfeatures: 'requiredFeatures',
  resource: 'resource',
  restart: 'restart',
  result: 'result',
  results: 'results',
  rotate: 'rotate',
  rx: 'rx',
  ry: 'ry',
  scale: 'scale',
  security: 'security',
  seed: 'seed',
  shaperendering: 'shapeRendering',
  'shape-rendering': 'shapeRendering',
  slope: 'slope',
  spacing: 'spacing',
  specularconstant: 'specularConstant',
  specularexponent: 'specularExponent',
  speed: 'speed',
  spreadmethod: 'spreadMethod',
  startoffset: 'startOffset',
  stddeviation: 'stdDeviation',
  stemh: 'stemh',
  stemv: 'stemv',
  stitchtiles: 'stitchTiles',
  stopcolor: 'stopColor',
  'stop-color': 'stopColor',
  stopopacity: 'stopOpacity',
  'stop-opacity': 'stopOpacity',
  strikethroughposition: 'strikethroughPosition',
  'strikethrough-position': 'strikethroughPosition',
  strikethroughthickness: 'strikethroughThickness',
  'strikethrough-thickness': 'strikethroughThickness',
  string: 'string',
  stroke: 'stroke',
  strokedasharray: 'strokeDasharray',
  'stroke-dasharray': 'strokeDasharray',
  strokedashoffset: 'strokeDashoffset',
  'stroke-dashoffset': 'strokeDashoffset',
  strokelinecap: 'strokeLinecap',
  'stroke-linecap': 'strokeLinecap',
  strokelinejoin: 'strokeLinejoin',
  'stroke-linejoin': 'strokeLinejoin',
  strokemiterlimit: 'strokeMiterlimit',
  'stroke-miterlimit': 'strokeMiterlimit',
  strokewidth: 'strokeWidth',
  'stroke-width': 'strokeWidth',
  strokeopacity: 'strokeOpacity',
  'stroke-opacity': 'strokeOpacity',
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
  suppresshydrationwarning: 'suppressHydrationWarning',
  surfacescale: 'surfaceScale',
  systemlanguage: 'systemLanguage',
  tablevalues: 'tableValues',
  targetx: 'targetX',
  targety: 'targetY',
  textanchor: 'textAnchor',
  'text-anchor': 'textAnchor',
  textdecoration: 'textDecoration',
  'text-decoration': 'textDecoration',
  textlength: 'textLength',
  textrendering: 'textRendering',
  'text-rendering': 'textRendering',
  to: 'to',
  transform: 'transform',
  typeof: 'typeof',
  u1: 'u1',
  u2: 'u2',
  underlineposition: 'underlinePosition',
  'underline-position': 'underlinePosition',
  underlinethickness: 'underlineThickness',
  'underline-thickness': 'underlineThickness',
  unicode: 'unicode',
  unicodebidi: 'unicodeBidi',
  'unicode-bidi': 'unicodeBidi',
  unicoderange: 'unicodeRange',
  'unicode-range': 'unicodeRange',
  unitsperem: 'unitsPerEm',
  'units-per-em': 'unitsPerEm',
  unselectable: 'unselectable',
  valphabetic: 'vAlphabetic',
  'v-alphabetic': 'vAlphabetic',
  values: 'values',
  vectoreffect: 'vectorEffect',
  'vector-effect': 'vectorEffect',
  version: 'version',
  vertadvy: 'vertAdvY',
  'vert-adv-y': 'vertAdvY',
  vertoriginx: 'vertOriginX',
  'vert-origin-x': 'vertOriginX',
  vertoriginy: 'vertOriginY',
  'vert-origin-y': 'vertOriginY',
  vhanging: 'vHanging',
  'v-hanging': 'vHanging',
  videographic: 'vIdeographic',
  'v-ideographic': 'vIdeographic',
  viewbox: 'viewBox',
  viewtarget: 'viewTarget',
  visibility: 'visibility',
  vmathematical: 'vMathematical',
  'v-mathematical': 'vMathematical',
  vocab: 'vocab',
  widths: 'widths',
  wordspacing: 'wordSpacing',
  'word-spacing': 'wordSpacing',
  writingmode: 'writingMode',
  'writing-mode': 'writingMode',
  x1: 'x1',
  x2: 'x2',
  x: 'x',
  xchannelselector: 'xChannelSelector',
  xheight: 'xHeight',
  'x-height': 'xHeight',
  xlinkactuate: 'xlinkActuate',
  'xlink:actuate': 'xlinkActuate',
  xlinkarcrole: 'xlinkArcrole',
  'xlink:arcrole': 'xlinkArcrole',
  xlinkhref: 'xlinkHref',
  'xlink:href': 'xlinkHref',
  xlinkrole: 'xlinkRole',
  'xlink:role': 'xlinkRole',
  xlinkshow: 'xlinkShow',
  'xlink:show': 'xlinkShow',
  xlinktitle: 'xlinkTitle',
  'xlink:title': 'xlinkTitle',
  xlinktype: 'xlinkType',
  'xlink:type': 'xlinkType',
  xmlbase: 'xmlBase',
  'xml:base': 'xmlBase',
  xmllang: 'xmlLang',
  'xml:lang': 'xmlLang',
  xmlns: 'xmlns',
  'xml:space': 'xmlSpace',
  xmlnsxlink: 'xmlnsXlink',
  'xmlns:xlink': 'xmlnsXlink',
  xmlspace: 'xmlSpace',
  y1: 'y1',
  y2: 'y2',
  y: 'y',
  ychannelselector: 'yChannelSelector',
  z: 'z',
  zoomandpan: 'zoomAndPan'
};

var ariaProperties = {
  'aria-current': 0,
  // state
  'aria-description': 0,
  'aria-details': 0,
  'aria-disabled': 0,
  // state
  'aria-hidden': 0,
  // state
  'aria-invalid': 0,
  // state
  'aria-keyshortcuts': 0,
  'aria-label': 0,
  'aria-roledescription': 0,
  // Widget Attributes
  'aria-autocomplete': 0,
  'aria-checked': 0,
  'aria-expanded': 0,
  'aria-haspopup': 0,
  'aria-level': 0,
  'aria-modal': 0,
  'aria-multiline': 0,
  'aria-multiselectable': 0,
  'aria-orientation': 0,
  'aria-placeholder': 0,
  'aria-pressed': 0,
  'aria-readonly': 0,
  'aria-required': 0,
  'aria-selected': 0,
  'aria-sort': 0,
  'aria-valuemax': 0,
  'aria-valuemin': 0,
  'aria-valuenow': 0,
  'aria-valuetext': 0,
  // Live Region Attributes
  'aria-atomic': 0,
  'aria-busy': 0,
  'aria-live': 0,
  'aria-relevant': 0,
  // Drag-and-Drop Attributes
  'aria-dropeffect': 0,
  'aria-grabbed': 0,
  // Relationship Attributes
  'aria-activedescendant': 0,
  'aria-colcount': 0,
  'aria-colindex': 0,
  'aria-colspan': 0,
  'aria-controls': 0,
  'aria-describedby': 0,
  'aria-errormessage': 0,
  'aria-flowto': 0,
  'aria-labelledby': 0,
  'aria-owns': 0,
  'aria-posinset': 0,
  'aria-rowcount': 0,
  'aria-rowindex': 0,
  'aria-rowspan': 0,
  'aria-setsize': 0
};

var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

function validateProperty(tagName, name) {
  {
    if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
      return true;
    }

    if (rARIACamel.test(name)) {
      var ariaName = 'aria-' + name.slice(4).toLowerCase();
      var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (correctName == null) {
        error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);

        warnedProperties[name] = true;
        return true;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== correctName) {
        error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);

        warnedProperties[name] = true;
        return true;
      }
    }

    if (rARIA.test(name)) {
      var lowerCasedName = name.toLowerCase();
      var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
      // DOM properties, then it is an invalid aria-* attribute.

      if (standardName == null) {
        warnedProperties[name] = true;
        return false;
      } // aria-* attributes should be lowercase; suggest the lowercase version.


      if (name !== standardName) {
        error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties[name] = true;
        return true;
      }
    }
  }

  return true;
}

function warnInvalidARIAProps(type, props) {
  {
    var invalidProps = [];

    for (var key in props) {
      var isValid = validateProperty(type, key);

      if (!isValid) {
        invalidProps.push(key);
      }
    }

    var unknownPropString = invalidProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (invalidProps.length === 1) {
      error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    } else if (invalidProps.length > 1) {
      error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
    }
  }
}

function validateProperties(type, props) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnInvalidARIAProps(type, props);
}

var didWarnValueNull = false;
function validateProperties$1(type, props) {
  {
    if (type !== 'input' && type !== 'textarea' && type !== 'select') {
      return;
    }

    if (props != null && props.value === null && !didWarnValueNull) {
      didWarnValueNull = true;

      if (type === 'select' && props.multiple) {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
      } else {
        error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
      }
    }
  }
}

var validateProperty$1 = function () {};

{
  var warnedProperties$1 = {};
  var EVENT_NAME_REGEX = /^on./;
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

  validateProperty$1 = function (tagName, name, value, eventRegistry) {
    if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
      return true;
    }

    var lowerCasedName = name.toLowerCase();

    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
      error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');

      warnedProperties$1[name] = true;
      return true;
    } // We can't rely on the event system being injected on the server.


    if (eventRegistry != null) {
      var registrationNameDependencies = eventRegistry.registrationNameDependencies,
          possibleRegistrationNames = eventRegistry.possibleRegistrationNames;

      if (registrationNameDependencies.hasOwnProperty(name)) {
        return true;
      }

      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

      if (registrationName != null) {
        error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);

        warnedProperties$1[name] = true;
        return true;
      }

      if (EVENT_NAME_REGEX.test(name)) {
        error('Unknown event handler property `%s`. It will be ignored.', name);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (EVENT_NAME_REGEX.test(name)) {
      // If no event plugins have been injected, we are in a server environment.
      // So we can't tell if the event name is correct for sure, but we can filter
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
        error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Let the ARIA attribute hook validate ARIA attributes


    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
      return true;
    }

    if (lowerCasedName === 'innerhtml') {
      error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'aria') {
      error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');

      warnedProperties$1[name] = true;
      return true;
    }

    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
      error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'number' && isNaN(value)) {
      error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);

      warnedProperties$1[name] = true;
      return true;
    }

    var propertyInfo = getPropertyInfo(name);
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      var standardName = possibleStandardNames[lowerCasedName];

      if (standardName !== name) {
        error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);

        warnedProperties$1[name] = true;
        return true;
      }
    } else if (!isReserved && name !== lowerCasedName) {
      // Unknown attributes should have lowercase casing since that's how they
      // will be cased anyway with server rendering.
      error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);

      warnedProperties$1[name] = true;
      return true;
    }

    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      if (value) {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
      } else {
        error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
      }

      warnedProperties$1[name] = true;
      return true;
    } // Now that we've validated casing, do not validate
    // data types for reserved props


    if (isReserved) {
      return true;
    } // Warn when a known attribute is a bad type


    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
      warnedProperties$1[name] = true;
      return false;
    } // Warn when passing the strings 'false' or 'true' into a boolean prop


    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
      error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);

      warnedProperties$1[name] = true;
      return true;
    }

    return true;
  };
}

var warnUnknownProperties = function (type, props, eventRegistry) {
  {
    var unknownProps = [];

    for (var key in props) {
      var isValid = validateProperty$1(type, key, props[key], eventRegistry);

      if (!isValid) {
        unknownProps.push(key);
      }
    }

    var unknownPropString = unknownProps.map(function (prop) {
      return '`' + prop + '`';
    }).join(', ');

    if (unknownProps.length === 1) {
      error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    } else if (unknownProps.length > 1) {
      error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
    }
  }
};

function validateProperties$2(type, props, eventRegistry) {
  if (isCustomComponent(type, props)) {
    return;
  }

  warnUnknownProperties(type, props, eventRegistry);
}

var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
var IS_NON_DELEGATED = 1 << 1;
var IS_CAPTURE_PHASE = 1 << 2;
// set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
// we call willDeferLaterForLegacyFBSupport, thus not bailing out
// will result in endless cycles like an infinite loop.
// We also don't want to defer during event replaying.

var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;

// This exists to avoid circular dependency between ReactDOMEventReplaying
// and DOMPluginEventSystem.
var currentReplayingEvent = null;
function setReplayingEvent(event) {
  {
    if (currentReplayingEvent !== null) {
      error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
    }
  }

  currentReplayingEvent = event;
}
function resetReplayingEvent() {
  {
    if (currentReplayingEvent === null) {
      error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
    }
  }

  currentReplayingEvent = null;
}
function isReplayingEvent(event) {
  return event === currentReplayingEvent;
}

/**
 * Gets the target node from a native browser event by accounting for
 * inconsistencies in browser DOM APIs.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {DOMEventTarget} Target node.
 */

function getEventTarget(nativeEvent) {
  // Fallback to nativeEvent.srcElement for IE9
  // https://github.com/facebook/react/issues/12506
  var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963

  if (target.correspondingUseElement) {
    target = target.correspondingUseElement;
  } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
  // @see http://www.quirksmode.org/js/events_properties.html


  return target.nodeType === TEXT_NODE ? target.parentNode : target;
}

var restoreImpl = null;
var restoreTarget = null;
var restoreQueue = null;

function restoreStateOfTarget(target) {
  // We perform this translation at the end of the event loop so that we
  // always receive the correct fiber here
  var internalInstance = getInstanceFromNode(target);

  if (!internalInstance) {
    // Unmounted
    return;
  }

  if (typeof restoreImpl !== 'function') {
    throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.');
  }

  var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.

  if (stateNode) {
    var _props = getFiberCurrentPropsFromNode(stateNode);

    restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
  }
}

function setRestoreImplementation(impl) {
  restoreImpl = impl;
}
function enqueueStateRestore(target) {
  if (restoreTarget) {
    if (restoreQueue) {
      restoreQueue.push(target);
    } else {
      restoreQueue = [target];
    }
  } else {
    restoreTarget = target;
  }
}
function needsStateRestore() {
  return restoreTarget !== null || restoreQueue !== null;
}
function restoreStateIfNeeded() {
  if (!restoreTarget) {
    return;
  }

  var target = restoreTarget;
  var queuedTargets = restoreQueue;
  restoreTarget = null;
  restoreQueue = null;
  restoreStateOfTarget(target);

  if (queuedTargets) {
    for (var i = 0; i < queuedTargets.length; i++) {
      restoreStateOfTarget(queuedTargets[i]);
    }
  }
}

// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.
// Defaults

var batchedUpdatesImpl = function (fn, bookkeeping) {
  return fn(bookkeeping);
};

var flushSyncImpl = function () {};

var isInsideEventHandler = false;

function finishEventHandler() {
  // Here we wait until all updates have propagated, which is important
  // when using controlled components within layers:
  // https://github.com/facebook/react/issues/1698
  // Then we restore state of any controlled component.
  var controlledComponentsHavePendingUpdates = needsStateRestore();

  if (controlledComponentsHavePendingUpdates) {
    // If a controlled event was fired, we may need to restore the state of
    // the DOM node back to the controlled value. This is necessary when React
    // bails out of the update without touching the DOM.
    // TODO: Restore state in the microtask, after the discrete updates flush,
    // instead of early flushing them here.
    flushSyncImpl();
    restoreStateIfNeeded();
  }
}

function batchedUpdates(fn, a, b) {
  if (isInsideEventHandler) {
    // If we are currently inside another batch, we need to wait until it
    // fully completes before restoring state.
    return fn(a, b);
  }

  isInsideEventHandler = true;

  try {
    return batchedUpdatesImpl(fn, a, b);
  } finally {
    isInsideEventHandler = false;
    finishEventHandler();
  }
} // TODO: Replace with flushSync
function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
  batchedUpdatesImpl = _batchedUpdatesImpl;
  flushSyncImpl = _flushSyncImpl;
}

function isInteractive(tag) {
  return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}

function shouldPreventMouseEvent(name, type, props) {
  switch (name) {
    case 'onClick':
    case 'onClickCapture':
    case 'onDoubleClick':
    case 'onDoubleClickCapture':
    case 'onMouseDown':
    case 'onMouseDownCapture':
    case 'onMouseMove':
    case 'onMouseMoveCapture':
    case 'onMouseUp':
    case 'onMouseUpCapture':
    case 'onMouseEnter':
      return !!(props.disabled && isInteractive(type));

    default:
      return false;
  }
}
/**
 * @param {object} inst The instance, which is the source of events.
 * @param {string} registrationName Name of listener (e.g. `onClick`).
 * @return {?function} The stored callback.
 */


function getListener(inst, registrationName) {
  var stateNode = inst.stateNode;

  if (stateNode === null) {
    // Work in progress (ex: onload events in incremental mode).
    return null;
  }

  var props = getFiberCurrentPropsFromNode(stateNode);

  if (props === null) {
    // Work in progress.
    return null;
  }

  var listener = props[registrationName];

  if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
    return null;
  }

  if (listener && typeof listener !== 'function') {
    throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
  }

  return listener;
}

var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support

if (canUseDOM) {
  try {
    var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value

    Object.defineProperty(options, 'passive', {
      get: function () {
        passiveBrowserEventsSupported = true;
      }
    });
    window.addEventListener('test', options, options);
    window.removeEventListener('test', options, options);
  } catch (e) {
    passiveBrowserEventsSupported = false;
  }
}

function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
  var funcArgs = Array.prototype.slice.call(arguments, 3);

  try {
    func.apply(context, funcArgs);
  } catch (error) {
    this.onError(error);
  }
}

var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;

{
  // In DEV mode, we swap out invokeGuardedCallback for a special version
  // that plays more nicely with the browser's DevTools. The idea is to preserve
  // "Pause on exceptions" behavior. Because React wraps all user-provided
  // functions in invokeGuardedCallback, and the production version of
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  // like caught exceptions, and the DevTools won't pause unless the developer
  // takes the extra step of enabling pause on caught exceptions. This is
  // unintuitive, though, because even though React has caught the error, from
  // the developer's perspective, the error is uncaught.
  //
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  // DOM node, and call the user-provided callback from inside an event handler
  // for that fake event. If the callback throws, the error is "captured" using
  // a global event handler. But because the error happens in a different
  // event loop context, it does not interrupt the normal program flow.
  // Effectively, this gives us try-catch behavior without actually using
  // try-catch. Neat!
  // Check that the browser supports the APIs we need to implement our special
  // DEV version of invokeGuardedCallback
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
    var fakeNode = document.createElement('react');

    invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
      // If document doesn't exist we know for sure we will crash in this method
      // when we call document.createEvent(). However this can cause confusing
      // errors: https://github.com/facebook/create-react-app/issues/3482
      // So we preemptively throw with a better message instead.
      if (typeof document === 'undefined' || document === null) {
        throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
      }

      var evt = document.createEvent('Event');
      var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
      // set this to true at the beginning, then set it to false right after
      // calling the function. If the function errors, `didError` will never be
      // set to false. This strategy works even if the browser is flaky and
      // fails to call our global error handler, because it doesn't rely on
      // the error event at all.

      var didError = true; // Keeps track of the value of window.event so that we can reset it
      // during the callback to let user code access window.event in the
      // browsers that support it.

      var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
      // dispatching: https://github.com/facebook/react/issues/13688

      var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');

      function restoreAfterDispatch() {
        // We immediately remove the callback from event listeners so that
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
        // nested call would trigger the fake event handlers of any call higher
        // in the stack.
        fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
        // window.event assignment in both IE <= 10 as they throw an error
        // "Member not found" in strict mode, and in Firefox which does not
        // support window.event.

        if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
          window.event = windowEvent;
        }
      } // Create an event handler for our fake event. We will synchronously
      // dispatch our fake event using `dispatchEvent`. Inside the handler, we
      // call the user-provided callback.


      var funcArgs = Array.prototype.slice.call(arguments, 3);

      function callCallback() {
        didCall = true;
        restoreAfterDispatch();
        func.apply(context, funcArgs);
        didError = false;
      } // Create a global error event handler. We use this to capture the value
      // that was thrown. It's possible that this error handler will fire more
      // than once; for example, if non-React code also calls `dispatchEvent`
      // and a handler for that event throws. We should be resilient to most of
      // those cases. Even if our error event handler fires more than once, the
      // last error event is always used. If the callback actually does error,
      // we know that the last error event is the correct one, because it's not
      // possible for anything else to have happened in between our callback
      // erroring and the code that follows the `dispatchEvent` call below. If
      // the callback doesn't error, but the error event was fired, we know to
      // ignore it because `didError` will be false, as described above.


      var error; // Use this to track whether the error event is ever called.

      var didSetError = false;
      var isCrossOriginError = false;

      function handleWindowError(event) {
        error = event.error;
        didSetError = true;

        if (error === null && event.colno === 0 && event.lineno === 0) {
          isCrossOriginError = true;
        }

        if (event.defaultPrevented) {
          // Some other error handler has prevented default.
          // Browsers silence the error report if this happens.
          // We'll remember this to later decide whether to log it or not.
          if (error != null && typeof error === 'object') {
            try {
              error._suppressLogging = true;
            } catch (inner) {// Ignore.
            }
          }
        }
      } // Create a fake event type.


      var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers

      window.addEventListener('error', handleWindowError);
      fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
      // errors, it will trigger our global error handler.

      evt.initEvent(evtType, false, false);
      fakeNode.dispatchEvent(evt);

      if (windowEventDescriptor) {
        Object.defineProperty(window, 'event', windowEventDescriptor);
      }

      if (didCall && didError) {
        if (!didSetError) {
          // The callback errored, but the error event never fired.
          // eslint-disable-next-line react-internal/prod-error-codes
          error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
        } else if (isCrossOriginError) {
          // eslint-disable-next-line react-internal/prod-error-codes
          error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
        }

        this.onError(error);
      } // Remove our event listeners


      window.removeEventListener('error', handleWindowError);

      if (!didCall) {
        // Something went really wrong, and our event was not dispatched.
        // https://github.com/facebook/react/issues/16734
        // https://github.com/facebook/react/issues/16585
        // Fall back to the production implementation.
        restoreAfterDispatch();
        return invokeGuardedCallbackProd.apply(this, arguments);
      }
    };
  }
}

var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;

var hasError = false;
var caughtError = null; // Used by event system to capture/rethrow the first error.

var hasRethrowError = false;
var rethrowError = null;
var reporter = {
  onError: function (error) {
    hasError = true;
    caughtError = error;
  }
};
/**
 * Call a function while guarding against errors that happens within it.
 * Returns an error if it throws, otherwise null.
 *
 * In production, this is implemented using a try-catch. The reason we don't
 * use a try-catch directly is so that we can swap out a different
 * implementation in DEV mode.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */

function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  hasError = false;
  caughtError = null;
  invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}
/**
 * Same as invokeGuardedCallback, but instead of returning an error, it stores
 * it in a global so it can be rethrown by `rethrowCaughtError` later.
 * TODO: See if caughtError and rethrowError can be unified.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */

function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
  invokeGuardedCallback.apply(this, arguments);

  if (hasError) {
    var error = clearCaughtError();

    if (!hasRethrowError) {
      hasRethrowError = true;
      rethrowError = error;
    }
  }
}
/**
 * During execution of guarded functions we will capture the first error which
 * we will rethrow to be handled by the top level error handler.
 */

function rethrowCaughtError() {
  if (hasRethrowError) {
    var error = rethrowError;
    hasRethrowError = false;
    rethrowError = null;
    throw error;
  }
}
function hasCaughtError() {
  return hasError;
}
function clearCaughtError() {
  if (hasError) {
    var error = caughtError;
    hasError = false;
    caughtError = null;
    return error;
  } else {
    throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
  }
}

/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */
function get(key) {
  return key._reactInternals;
}
function has(key) {
  return key._reactInternals !== undefined;
}
function set(key, value) {
  key._reactInternals = value;
}

// Don't change these two values. They're used by React Dev Tools.
var NoFlags =
/*                      */
0;
var PerformedWork =
/*                */
1; // You can change the rest (and add more).

var Placement =
/*                    */
2;
var Update =
/*                       */
4;
var ChildDeletion =
/*                */
16;
var ContentReset =
/*                 */
32;
var Callback =
/*                     */
64;
var DidCapture =
/*                   */
128;
var ForceClientRender =
/*            */
256;
var Ref =
/*                          */
512;
var Snapshot =
/*                     */
1024;
var Passive =
/*                      */
2048;
var Hydrating =
/*                    */
4096;
var Visibility =
/*                   */
8192;
var StoreConsistency =
/*             */
16384;
var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit)

var HostEffectMask =
/*               */
32767; // These are not really side effects, but we still reuse this field.

var Incomplete =
/*                   */
32768;
var ShouldCapture =
/*                */
65536;
var ForceUpdateForLegacySuspense =
/* */
131072;
var Forked =
/*                       */
1048576; // Static tags describe aspects of a fiber that are not specific to a render,
// e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
// This enables us to defer more work in the unmount case,
// since we can defer traversing the tree during layout to look for Passive effects,
// and instead rely on the static flag as a signal that there may be cleanup work.

var RefStatic =
/*                    */
2097152;
var LayoutStatic =
/*                 */
4194304;
var PassiveStatic =
/*                */
8388608; // These flags allow us to traverse to fibers that have effects on mount
// without traversing the entire tree after every commit for
// double invoking

var MountLayoutDev =
/*               */
16777216;
var MountPassiveDev =
/*              */
33554432; // Groups of flags that are used in the commit phase to skip over trees that
// don't contain effects, by checking subtreeFlags.

var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility
// flag logic (see #20043)
Update | Snapshot | ( 0);
var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask

var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones.
// This allows certain concepts to persist without recalculating them,
// e.g. whether a subtree contains passive effects or portals.

var StaticMask = LayoutStatic | PassiveStatic | RefStatic;

var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
function getNearestMountedFiber(fiber) {
  var node = fiber;
  var nearestMounted = fiber;

  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    var nextNode = node;

    do {
      node = nextNode;

      if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
        // This is an insertion or in-progress hydration. The nearest possible
        // mounted fiber is the parent but we need to continue to figure out
        // if that one is still mounted.
        nearestMounted = node.return;
      }

      nextNode = node.return;
    } while (nextNode);
  } else {
    while (node.return) {
      node = node.return;
    }
  }

  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return nearestMounted;
  } // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.


  return null;
}
function getSuspenseInstanceFromFiber(fiber) {
  if (fiber.tag === SuspenseComponent) {
    var suspenseState = fiber.memoizedState;

    if (suspenseState === null) {
      var current = fiber.alternate;

      if (current !== null) {
        suspenseState = current.memoizedState;
      }
    }

    if (suspenseState !== null) {
      return suspenseState.dehydrated;
    }
  }

  return null;
}
function getContainerFromFiber(fiber) {
  return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
}
function isFiberMounted(fiber) {
  return getNearestMountedFiber(fiber) === fiber;
}
function isMounted(component) {
  {
    var owner = ReactCurrentOwner.current;

    if (owner !== null && owner.tag === ClassComponent) {
      var ownerFiber = owner;
      var instance = ownerFiber.stateNode;

      if (!instance._warnedAboutRefsInRender) {
        error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component');
      }

      instance._warnedAboutRefsInRender = true;
    }
  }

  var fiber = get(component);

  if (!fiber) {
    return false;
  }

  return getNearestMountedFiber(fiber) === fiber;
}

function assertIsMounted(fiber) {
  if (getNearestMountedFiber(fiber) !== fiber) {
    throw new Error('Unable to find node on an unmounted component.');
  }
}

function findCurrentFiberUsingSlowPath(fiber) {
  var alternate = fiber.alternate;

  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    var nearestMounted = getNearestMountedFiber(fiber);

    if (nearestMounted === null) {
      throw new Error('Unable to find node on an unmounted component.');
    }

    if (nearestMounted !== fiber) {
      return null;
    }

    return fiber;
  } // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.


  var a = fiber;
  var b = alternate;

  while (true) {
    var parentA = a.return;

    if (parentA === null) {
      // We're at the root.
      break;
    }

    var parentB = parentA.alternate;

    if (parentB === null) {
      // There is no alternate. This is an unusual case. Currently, it only
      // happens when a Suspense component is hidden. An extra fragment fiber
      // is inserted in between the Suspense fiber and its children. Skip
      // over this extra fragment fiber and proceed to the next parent.
      var nextParent = parentA.return;

      if (nextParent !== null) {
        a = b = nextParent;
        continue;
      } // If there's no parent, we're at the root.


      break;
    } // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.


    if (parentA.child === parentB.child) {
      var child = parentA.child;

      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }

        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }

        child = child.sibling;
      } // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.


      throw new Error('Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      var didFindChild = false;
      var _child = parentA.child;

      while (_child) {
        if (_child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }

        if (_child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }

        _child = _child.sibling;
      }

      if (!didFindChild) {
        // Search parent B's child set
        _child = parentB.child;

        while (_child) {
          if (_child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }

          if (_child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }

          _child = _child.sibling;
        }

        if (!didFindChild) {
          throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
        }
      }
    }

    if (a.alternate !== b) {
      throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
    }
  } // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.


  if (a.tag !== HostRoot) {
    throw new Error('Unable to find node on an unmounted component.');
  }

  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  } // Otherwise B has to be current branch.


  return alternate;
}
function findCurrentHostFiber(parent) {
  var currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
}

function findCurrentHostFiberImpl(node) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (node.tag === HostComponent || node.tag === HostText) {
    return node;
  }

  var child = node.child;

  while (child !== null) {
    var match = findCurrentHostFiberImpl(child);

    if (match !== null) {
      return match;
    }

    child = child.sibling;
  }

  return null;
}

function findCurrentHostFiberWithNoPortals(parent) {
  var currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
}

function findCurrentHostFiberWithNoPortalsImpl(node) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (node.tag === HostComponent || node.tag === HostText) {
    return node;
  }

  var child = node.child;

  while (child !== null) {
    if (child.tag !== HostPortal) {
      var match = findCurrentHostFiberWithNoPortalsImpl(child);

      if (match !== null) {
        return match;
      }
    }

    child = child.sibling;
  }

  return null;
}

// This module only exists as an ESM wrapper around the external CommonJS
var scheduleCallback = Scheduler.unstable_scheduleCallback;
var cancelCallback = Scheduler.unstable_cancelCallback;
var shouldYield = Scheduler.unstable_shouldYield;
var requestPaint = Scheduler.unstable_requestPaint;
var now = Scheduler.unstable_now;
var getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel;
var ImmediatePriority = Scheduler.unstable_ImmediatePriority;
var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
var NormalPriority = Scheduler.unstable_NormalPriority;
var LowPriority = Scheduler.unstable_LowPriority;
var IdlePriority = Scheduler.unstable_IdlePriority;
// this doesn't actually exist on the scheduler, but it *does*
// on scheduler/unstable_mock, which we'll need for internal testing
var unstable_yieldValue = Scheduler.unstable_yieldValue;
var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue;

var rendererID = null;
var injectedHook = null;
var injectedProfilingHooks = null;
var hasLoggedError = false;
var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
function injectInternals(internals) {
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
    // No DevTools
    return false;
  }

  var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;

  if (hook.isDisabled) {
    // This isn't a real property on the hook, but it can be set to opt out
    // of DevTools integration and associated warnings and logs.
    // https://github.com/facebook/react/issues/3877
    return true;
  }

  if (!hook.supportsFiber) {
    {
      error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools');
    } // DevTools exists, even though it doesn't support Fiber.


    return true;
  }

  try {
    if (enableSchedulingProfiler) {
      // Conditionally inject these hooks only if Timeline profiler is supported by this build.
      // This gives DevTools a way to feature detect that isn't tied to version number
      // (since profiling and timeline are controlled by different feature flags).
      internals = assign({}, internals, {
        getLaneLabelMap: getLaneLabelMap,
        injectProfilingHooks: injectProfilingHooks
      });
    }

    rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.

    injectedHook = hook;
  } catch (err) {
    // Catch all errors because it is unsafe to throw during initialization.
    {
      error('React instrumentation encountered an error: %s.', err);
    }
  }

  if (hook.checkDCE) {
    // This is the real DevTools.
    return true;
  } else {
    // This is likely a hook installed by Fast Refresh runtime.
    return false;
  }
}
function onScheduleRoot(root, children) {
  {
    if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
      try {
        injectedHook.onScheduleFiberRoot(rendererID, root, children);
      } catch (err) {
        if ( !hasLoggedError) {
          hasLoggedError = true;

          error('React instrumentation encountered an error: %s', err);
        }
      }
    }
  }
}
function onCommitRoot(root, eventPriority) {
  if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
    try {
      var didError = (root.current.flags & DidCapture) === DidCapture;

      if (enableProfilerTimer) {
        var schedulerPriority;

        switch (eventPriority) {
          case DiscreteEventPriority:
            schedulerPriority = ImmediatePriority;
            break;

          case ContinuousEventPriority:
            schedulerPriority = UserBlockingPriority;
            break;

          case DefaultEventPriority:
            schedulerPriority = NormalPriority;
            break;

          case IdleEventPriority:
            schedulerPriority = IdlePriority;
            break;

          default:
            schedulerPriority = NormalPriority;
            break;
        }

        injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError);
      } else {
        injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
      }
    } catch (err) {
      {
        if (!hasLoggedError) {
          hasLoggedError = true;

          error('React instrumentation encountered an error: %s', err);
        }
      }
    }
  }
}
function onPostCommitRoot(root) {
  if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') {
    try {
      injectedHook.onPostCommitFiberRoot(rendererID, root);
    } catch (err) {
      {
        if (!hasLoggedError) {
          hasLoggedError = true;

          error('React instrumentation encountered an error: %s', err);
        }
      }
    }
  }
}
function onCommitUnmount(fiber) {
  if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
    try {
      injectedHook.onCommitFiberUnmount(rendererID, fiber);
    } catch (err) {
      {
        if (!hasLoggedError) {
          hasLoggedError = true;

          error('React instrumentation encountered an error: %s', err);
        }
      }
    }
  }
}
function setIsStrictModeForDevtools(newIsStrictMode) {
  {
    if (typeof unstable_yieldValue === 'function') {
      // We're in a test because Scheduler.unstable_yieldValue only exists
      // in SchedulerMock. To reduce the noise in strict mode tests,
      // suppress warnings and disable scheduler yielding during the double render
      unstable_setDisableYieldValue(newIsStrictMode);
      setSuppressWarning(newIsStrictMode);
    }

    if (injectedHook && typeof injectedHook.setStrictMode === 'function') {
      try {
        injectedHook.setStrictMode(rendererID, newIsStrictMode);
      } catch (err) {
        {
          if (!hasLoggedError) {
            hasLoggedError = true;

            error('React instrumentation encountered an error: %s', err);
          }
        }
      }
    }
  }
} // Profiler API hooks

function injectProfilingHooks(profilingHooks) {
  injectedProfilingHooks = profilingHooks;
}

function getLaneLabelMap() {
  {
    var map = new Map();
    var lane = 1;

    for (var index = 0; index < TotalLanes; index++) {
      var label = getLabelForLane(lane);
      map.set(lane, label);
      lane *= 2;
    }

    return map;
  }
}

function markCommitStarted(lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') {
      injectedProfilingHooks.markCommitStarted(lanes);
    }
  }
}
function markCommitStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') {
      injectedProfilingHooks.markCommitStopped();
    }
  }
}
function markComponentRenderStarted(fiber) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') {
      injectedProfilingHooks.markComponentRenderStarted(fiber);
    }
  }
}
function markComponentRenderStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') {
      injectedProfilingHooks.markComponentRenderStopped();
    }
  }
}
function markComponentPassiveEffectMountStarted(fiber) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') {
      injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
    }
  }
}
function markComponentPassiveEffectMountStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') {
      injectedProfilingHooks.markComponentPassiveEffectMountStopped();
    }
  }
}
function markComponentPassiveEffectUnmountStarted(fiber) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') {
      injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
    }
  }
}
function markComponentPassiveEffectUnmountStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') {
      injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
    }
  }
}
function markComponentLayoutEffectMountStarted(fiber) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') {
      injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
    }
  }
}
function markComponentLayoutEffectMountStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') {
      injectedProfilingHooks.markComponentLayoutEffectMountStopped();
    }
  }
}
function markComponentLayoutEffectUnmountStarted(fiber) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') {
      injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
    }
  }
}
function markComponentLayoutEffectUnmountStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') {
      injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
    }
  }
}
function markComponentErrored(fiber, thrownValue, lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') {
      injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
    }
  }
}
function markComponentSuspended(fiber, wakeable, lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') {
      injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
    }
  }
}
function markLayoutEffectsStarted(lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') {
      injectedProfilingHooks.markLayoutEffectsStarted(lanes);
    }
  }
}
function markLayoutEffectsStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') {
      injectedProfilingHooks.markLayoutEffectsStopped();
    }
  }
}
function markPassiveEffectsStarted(lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') {
      injectedProfilingHooks.markPassiveEffectsStarted(lanes);
    }
  }
}
function markPassiveEffectsStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') {
      injectedProfilingHooks.markPassiveEffectsStopped();
    }
  }
}
function markRenderStarted(lanes) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') {
      injectedProfilingHooks.markRenderStarted(lanes);
    }
  }
}
function markRenderYielded() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') {
      injectedProfilingHooks.markRenderYielded();
    }
  }
}
function markRenderStopped() {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') {
      injectedProfilingHooks.markRenderStopped();
    }
  }
}
function markRenderScheduled(lane) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') {
      injectedProfilingHooks.markRenderScheduled(lane);
    }
  }
}
function markForceUpdateScheduled(fiber, lane) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') {
      injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
    }
  }
}
function markStateUpdateScheduled(fiber, lane) {
  {
    if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') {
      injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
    }
  }
}

var NoMode =
/*                         */
0; // TODO: Remove ConcurrentMode by reading from the root tag instead

var ConcurrentMode =
/*                 */
1;
var ProfileMode =
/*                    */
2;
var StrictLegacyMode =
/*               */
8;
var StrictEffectsMode =
/*              */
16;

// TODO: This is pretty well supported by browsers. Maybe we can drop it.
var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32

var log = Math.log;
var LN2 = Math.LN2;

function clz32Fallback(x) {
  var asUint = x >>> 0;

  if (asUint === 0) {
    return 32;
  }

  return 31 - (log(asUint) / LN2 | 0) | 0;
}

// If those values are changed that package should be rebuilt and redeployed.

var TotalLanes = 31;
var NoLanes =
/*                        */
0;
var NoLane =
/*                          */
0;
var SyncLane =
/*                        */
1;
var InputContinuousHydrationLane =
/*    */
2;
var InputContinuousLane =
/*             */
4;
var DefaultHydrationLane =
/*            */
8;
var DefaultLane =
/*                     */
16;
var TransitionHydrationLane =
/*                */
32;
var TransitionLanes =
/*                       */
4194240;
var TransitionLane1 =
/*                        */
64;
var TransitionLane2 =
/*                        */
128;
var TransitionLane3 =
/*                        */
256;
var TransitionLane4 =
/*                        */
512;
var TransitionLane5 =
/*                        */
1024;
var TransitionLane6 =
/*                        */
2048;
var TransitionLane7 =
/*                        */
4096;
var TransitionLane8 =
/*                        */
8192;
var TransitionLane9 =
/*                        */
16384;
var TransitionLane10 =
/*                       */
32768;
var TransitionLane11 =
/*                       */
65536;
var TransitionLane12 =
/*                       */
131072;
var TransitionLane13 =
/*                       */
262144;
var TransitionLane14 =
/*                       */
524288;
var TransitionLane15 =
/*                       */
1048576;
var TransitionLane16 =
/*                       */
2097152;
var RetryLanes =
/*                            */
130023424;
var RetryLane1 =
/*                             */
4194304;
var RetryLane2 =
/*                             */
8388608;
var RetryLane3 =
/*                             */
16777216;
var RetryLane4 =
/*                             */
33554432;
var RetryLane5 =
/*                             */
67108864;
var SomeRetryLane = RetryLane1;
var SelectiveHydrationLane =
/*          */
134217728;
var NonIdleLanes =
/*                          */
268435455;
var IdleHydrationLane =
/*               */
268435456;
var IdleLane =
/*                        */
536870912;
var OffscreenLane =
/*                   */
1073741824; // This function is used for the experimental timeline (react-devtools-timeline)
// It should be kept in sync with the Lanes values above.

function getLabelForLane(lane) {
  {
    if (lane & SyncLane) {
      return 'Sync';
    }

    if (lane & InputContinuousHydrationLane) {
      return 'InputContinuousHydration';
    }

    if (lane & InputContinuousLane) {
      return 'InputContinuous';
    }

    if (lane & DefaultHydrationLane) {
      return 'DefaultHydration';
    }

    if (lane & DefaultLane) {
      return 'Default';
    }

    if (lane & TransitionHydrationLane) {
      return 'TransitionHydration';
    }

    if (lane & TransitionLanes) {
      return 'Transition';
    }

    if (lane & RetryLanes) {
      return 'Retry';
    }

    if (lane & SelectiveHydrationLane) {
      return 'SelectiveHydration';
    }

    if (lane & IdleHydrationLane) {
      return 'IdleHydration';
    }

    if (lane & IdleLane) {
      return 'Idle';
    }

    if (lane & OffscreenLane) {
      return 'Offscreen';
    }
  }
}
var NoTimestamp = -1;
var nextTransitionLane = TransitionLane1;
var nextRetryLane = RetryLane1;

function getHighestPriorityLanes(lanes) {
  switch (getHighestPriorityLane(lanes)) {
    case SyncLane:
      return SyncLane;

    case InputContinuousHydrationLane:
      return InputContinuousHydrationLane;

    case InputContinuousLane:
      return InputContinuousLane;

    case DefaultHydrationLane:
      return DefaultHydrationLane;

    case DefaultLane:
      return DefaultLane;

    case TransitionHydrationLane:
      return TransitionHydrationLane;

    case TransitionLane1:
    case TransitionLane2:
    case TransitionLane3:
    case TransitionLane4:
    case TransitionLane5:
    case TransitionLane6:
    case TransitionLane7:
    case TransitionLane8:
    case TransitionLane9:
    case TransitionLane10:
    case TransitionLane11:
    case TransitionLane12:
    case TransitionLane13:
    case TransitionLane14:
    case TransitionLane15:
    case TransitionLane16:
      return lanes & TransitionLanes;

    case RetryLane1:
    case RetryLane2:
    case RetryLane3:
    case RetryLane4:
    case RetryLane5:
      return lanes & RetryLanes;

    case SelectiveHydrationLane:
      return SelectiveHydrationLane;

    case IdleHydrationLane:
      return IdleHydrationLane;

    case IdleLane:
      return IdleLane;

    case OffscreenLane:
      return OffscreenLane;

    default:
      {
        error('Should have found matching lanes. This is a bug in React.');
      } // This shouldn't be reachable, but as a fallback, return the entire bitmask.


      return lanes;
  }
}

function getNextLanes(root, wipLanes) {
  // Early bailout if there's no pending work left.
  var pendingLanes = root.pendingLanes;

  if (pendingLanes === NoLanes) {
    return NoLanes;
  }

  var nextLanes = NoLanes;
  var suspendedLanes = root.suspendedLanes;
  var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished,
  // even if the work is suspended.

  var nonIdlePendingLanes = pendingLanes & NonIdleLanes;

  if (nonIdlePendingLanes !== NoLanes) {
    var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;

    if (nonIdleUnblockedLanes !== NoLanes) {
      nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
    } else {
      var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;

      if (nonIdlePingedLanes !== NoLanes) {
        nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
      }
    }
  } else {
    // The only remaining work is Idle.
    var unblockedLanes = pendingLanes & ~suspendedLanes;

    if (unblockedLanes !== NoLanes) {
      nextLanes = getHighestPriorityLanes(unblockedLanes);
    } else {
      if (pingedLanes !== NoLanes) {
        nextLanes = getHighestPriorityLanes(pingedLanes);
      }
    }
  }

  if (nextLanes === NoLanes) {
    // This should only be reachable if we're suspended
    // TODO: Consider warning in this path if a fallback timer is not scheduled.
    return NoLanes;
  } // If we're already in the middle of a render, switching lanes will interrupt
  // it and we'll lose our progress. We should only do this if the new lanes are
  // higher priority.


  if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
  // bother waiting until the root is complete.
  (wipLanes & suspendedLanes) === NoLanes) {
    var nextLane = getHighestPriorityLane(nextLanes);
    var wipLane = getHighestPriorityLane(wipLanes);

    if ( // Tests whether the next lane is equal or lower priority than the wip
    // one. This works because the bits decrease in priority as you go left.
    nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
    // only difference between default updates and transition updates is that
    // default updates do not support refresh transitions.
    nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) {
      // Keep working on the existing in-progress tree. Do not interrupt.
      return wipLanes;
    }
  }

  if ((nextLanes & InputContinuousLane) !== NoLanes) {
    // When updates are sync by default, we entangle continuous priority updates
    // and default updates, so they render in the same batch. The only reason
    // they use separate lanes is because continuous updates should interrupt
    // transitions, but default updates should not.
    nextLanes |= pendingLanes & DefaultLane;
  } // Check for entangled lanes and add them to the batch.
  //
  // A lane is said to be entangled with another when it's not allowed to render
  // in a batch that does not also include the other lane. Typically we do this
  // when multiple updates have the same source, and we only want to respond to
  // the most recent event from that source.
  //
  // Note that we apply entanglements *after* checking for partial work above.
  // This means that if a lane is entangled during an interleaved event while
  // it's already rendering, we won't interrupt it. This is intentional, since
  // entanglement is usually "best effort": we'll try our best to render the
  // lanes in the same batch, but it's not worth throwing out partially
  // completed work in order to do it.
  // TODO: Reconsider this. The counter-argument is that the partial work
  // represents an intermediate state, which we don't want to show to the user.
  // And by spending extra time finishing it, we're increasing the amount of
  // time it takes to show the final state, which is what they are actually
  // waiting for.
  //
  // For those exceptions where entanglement is semantically important, like
  // useMutableSource, we should ensure that there is no partial work at the
  // time we apply the entanglement.


  var entangledLanes = root.entangledLanes;

  if (entangledLanes !== NoLanes) {
    var entanglements = root.entanglements;
    var lanes = nextLanes & entangledLanes;

    while (lanes > 0) {
      var index = pickArbitraryLaneIndex(lanes);
      var lane = 1 << index;
      nextLanes |= entanglements[index];
      lanes &= ~lane;
    }
  }

  return nextLanes;
}
function getMostRecentEventTime(root, lanes) {
  var eventTimes = root.eventTimes;
  var mostRecentEventTime = NoTimestamp;

  while (lanes > 0) {
    var index = pickArbitraryLaneIndex(lanes);
    var lane = 1 << index;
    var eventTime = eventTimes[index];

    if (eventTime > mostRecentEventTime) {
      mostRecentEventTime = eventTime;
    }

    lanes &= ~lane;
  }

  return mostRecentEventTime;
}

function computeExpirationTime(lane, currentTime) {
  switch (lane) {
    case SyncLane:
    case InputContinuousHydrationLane:
    case InputContinuousLane:
      // User interactions should expire slightly more quickly.
      //
      // NOTE: This is set to the corresponding constant as in Scheduler.js.
      // When we made it larger, a product metric in www regressed, suggesting
      // there's a user interaction that's being starved by a series of
      // synchronous updates. If that theory is correct, the proper solution is
      // to fix the starvation. However, this scenario supports the idea that
      // expiration times are an important safeguard when starvation
      // does happen.
      return currentTime + 250;

    case DefaultHydrationLane:
    case DefaultLane:
    case TransitionHydrationLane:
    case TransitionLane1:
    case TransitionLane2:
    case TransitionLane3:
    case TransitionLane4:
    case TransitionLane5:
    case TransitionLane6:
    case TransitionLane7:
    case TransitionLane8:
    case TransitionLane9:
    case TransitionLane10:
    case TransitionLane11:
    case TransitionLane12:
    case TransitionLane13:
    case TransitionLane14:
    case TransitionLane15:
    case TransitionLane16:
      return currentTime + 5000;

    case RetryLane1:
    case RetryLane2:
    case RetryLane3:
    case RetryLane4:
    case RetryLane5:
      // TODO: Retries should be allowed to expire if they are CPU bound for
      // too long, but when I made this change it caused a spike in browser
      // crashes. There must be some other underlying bug; not super urgent but
      // ideally should figure out why and fix it. Unfortunately we don't have
      // a repro for the crashes, only detected via production metrics.
      return NoTimestamp;

    case SelectiveHydrationLane:
    case IdleHydrationLane:
    case IdleLane:
    case OffscreenLane:
      // Anything idle priority or lower should never expire.
      return NoTimestamp;

    default:
      {
        error('Should have found matching lanes. This is a bug in React.');
      }

      return NoTimestamp;
  }
}

function markStarvedLanesAsExpired(root, currentTime) {
  // TODO: This gets called every time we yield. We can optimize by storing
  // the earliest expiration time on the root. Then use that to quickly bail out
  // of this function.
  var pendingLanes = root.pendingLanes;
  var suspendedLanes = root.suspendedLanes;
  var pingedLanes = root.pingedLanes;
  var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
  // expiration time. If so, we'll assume the update is being starved and mark
  // it as expired to force it to finish.

  var lanes = pendingLanes;

  while (lanes > 0) {
    var index = pickArbitraryLaneIndex(lanes);
    var lane = 1 << index;
    var expirationTime = expirationTimes[index];

    if (expirationTime === NoTimestamp) {
      // Found a pending lane with no expiration time. If it's not suspended, or
      // if it's pinged, assume it's CPU-bound. Compute a new expiration time
      // using the current time.
      if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
        // Assumes timestamps are monotonically increasing.
        expirationTimes[index] = computeExpirationTime(lane, currentTime);
      }
    } else if (expirationTime <= currentTime) {
      // This lane expired
      root.expiredLanes |= lane;
    }

    lanes &= ~lane;
  }
} // This returns the highest priority pending lanes regardless of whether they
// are suspended.

function getHighestPriorityPendingLanes(root) {
  return getHighestPriorityLanes(root.pendingLanes);
}
function getLanesToRetrySynchronouslyOnError(root) {
  var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;

  if (everythingButOffscreen !== NoLanes) {
    return everythingButOffscreen;
  }

  if (everythingButOffscreen & OffscreenLane) {
    return OffscreenLane;
  }

  return NoLanes;
}
function includesSyncLane(lanes) {
  return (lanes & SyncLane) !== NoLanes;
}
function includesNonIdleWork(lanes) {
  return (lanes & NonIdleLanes) !== NoLanes;
}
function includesOnlyRetries(lanes) {
  return (lanes & RetryLanes) === lanes;
}
function includesOnlyNonUrgentLanes(lanes) {
  var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
  return (lanes & UrgentLanes) === NoLanes;
}
function includesOnlyTransitions(lanes) {
  return (lanes & TransitionLanes) === lanes;
}
function includesBlockingLane(root, lanes) {

  var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
  return (lanes & SyncDefaultLanes) !== NoLanes;
}
function includesExpiredLane(root, lanes) {
  // This is a separate check from includesBlockingLane because a lane can
  // expire after a render has already started.
  return (lanes & root.expiredLanes) !== NoLanes;
}
function isTransitionLane(lane) {
  return (lane & TransitionLanes) !== NoLanes;
}
function claimNextTransitionLane() {
  // Cycle through the lanes, assigning each new transition to the next lane.
  // In most cases, this means every transition gets its own lane, until we
  // run out of lanes and cycle back to the beginning.
  var lane = nextTransitionLane;
  nextTransitionLane <<= 1;

  if ((nextTransitionLane & TransitionLanes) === NoLanes) {
    nextTransitionLane = TransitionLane1;
  }

  return lane;
}
function claimNextRetryLane() {
  var lane = nextRetryLane;
  nextRetryLane <<= 1;

  if ((nextRetryLane & RetryLanes) === NoLanes) {
    nextRetryLane = RetryLane1;
  }

  return lane;
}
function getHighestPriorityLane(lanes) {
  return lanes & -lanes;
}
function pickArbitraryLane(lanes) {
  // This wrapper function gets inlined. Only exists so to communicate that it
  // doesn't matter which bit is selected; you can pick any bit without
  // affecting the algorithms where its used. Here I'm using
  // getHighestPriorityLane because it requires the fewest operations.
  return getHighestPriorityLane(lanes);
}

function pickArbitraryLaneIndex(lanes) {
  return 31 - clz32(lanes);
}

function laneToIndex(lane) {
  return pickArbitraryLaneIndex(lane);
}

function includesSomeLane(a, b) {
  return (a & b) !== NoLanes;
}
function isSubsetOfLanes(set, subset) {
  return (set & subset) === subset;
}
function mergeLanes(a, b) {
  return a | b;
}
function removeLanes(set, subset) {
  return set & ~subset;
}
function intersectLanes(a, b) {
  return a & b;
} // Seems redundant, but it changes the type from a single lane (used for
// updates) to a group of lanes (used for flushing work).

function laneToLanes(lane) {
  return lane;
}
function higherPriorityLane(a, b) {
  // This works because the bit ranges decrease in priority as you go left.
  return a !== NoLane && a < b ? a : b;
}
function createLaneMap(initial) {
  // Intentionally pushing one by one.
  // https://v8.dev/blog/elements-kinds#avoid-creating-holes
  var laneMap = [];

  for (var i = 0; i < TotalLanes; i++) {
    laneMap.push(initial);
  }

  return laneMap;
}
function markRootUpdated(root, updateLane, eventTime) {
  root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update
  // could unblock them. Clear the suspended lanes so that we can try rendering
  // them again.
  //
  // TODO: We really only need to unsuspend only lanes that are in the
  // `subtreeLanes` of the updated fiber, or the update lanes of the return
  // path. This would exclude suspended updates in an unrelated sibling tree,
  // since there's no way for this update to unblock it.
  //
  // We don't do this if the incoming update is idle, because we never process
  // idle updates until after all the regular updates have finished; there's no
  // way it could unblock a transition.

  if (updateLane !== IdleLane) {
    root.suspendedLanes = NoLanes;
    root.pingedLanes = NoLanes;
  }

  var eventTimes = root.eventTimes;
  var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
  // recent event, and we assume time is monotonically increasing.

  eventTimes[index] = eventTime;
}
function markRootSuspended(root, suspendedLanes) {
  root.suspendedLanes |= suspendedLanes;
  root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.

  var expirationTimes = root.expirationTimes;
  var lanes = suspendedLanes;

  while (lanes > 0) {
    var index = pickArbitraryLaneIndex(lanes);
    var lane = 1 << index;
    expirationTimes[index] = NoTimestamp;
    lanes &= ~lane;
  }
}
function markRootPinged(root, pingedLanes, eventTime) {
  root.pingedLanes |= root.suspendedLanes & pingedLanes;
}
function markRootFinished(root, remainingLanes) {
  var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
  root.pendingLanes = remainingLanes; // Let's try everything again

  root.suspendedLanes = NoLanes;
  root.pingedLanes = NoLanes;
  root.expiredLanes &= remainingLanes;
  root.mutableReadLanes &= remainingLanes;
  root.entangledLanes &= remainingLanes;
  var entanglements = root.entanglements;
  var eventTimes = root.eventTimes;
  var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work

  var lanes = noLongerPendingLanes;

  while (lanes > 0) {
    var index = pickArbitraryLaneIndex(lanes);
    var lane = 1 << index;
    entanglements[index] = NoLanes;
    eventTimes[index] = NoTimestamp;
    expirationTimes[index] = NoTimestamp;
    lanes &= ~lane;
  }
}
function markRootEntangled(root, entangledLanes) {
  // In addition to entangling each of the given lanes with each other, we also
  // have to consider _transitive_ entanglements. For each lane that is already
  // entangled with *any* of the given lanes, that lane is now transitively
  // entangled with *all* the given lanes.
  //
  // Translated: If C is entangled with A, then entangling A with B also
  // entangles C with B.
  //
  // If this is hard to grasp, it might help to intentionally break this
  // function and look at the tests that fail in ReactTransition-test.js. Try
  // commenting out one of the conditions below.
  var rootEntangledLanes = root.entangledLanes |= entangledLanes;
  var entanglements = root.entanglements;
  var lanes = rootEntangledLanes;

  while (lanes) {
    var index = pickArbitraryLaneIndex(lanes);
    var lane = 1 << index;

    if ( // Is this one of the newly entangled lanes?
    lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
    entanglements[index] & entangledLanes) {
      entanglements[index] |= entangledLanes;
    }

    lanes &= ~lane;
  }
}
function getBumpedLaneForHydration(root, renderLanes) {
  var renderLane = getHighestPriorityLane(renderLanes);
  var lane;

  switch (renderLane) {
    case InputContinuousLane:
      lane = InputContinuousHydrationLane;
      break;

    case DefaultLane:
      lane = DefaultHydrationLane;
      break;

    case TransitionLane1:
    case TransitionLane2:
    case TransitionLane3:
    case TransitionLane4:
    case TransitionLane5:
    case TransitionLane6:
    case TransitionLane7:
    case TransitionLane8:
    case TransitionLane9:
    case TransitionLane10:
    case TransitionLane11:
    case TransitionLane12:
    case TransitionLane13:
    case TransitionLane14:
    case TransitionLane15:
    case TransitionLane16:
    case RetryLane1:
    case RetryLane2:
    case RetryLane3:
    case RetryLane4:
    case RetryLane5:
      lane = TransitionHydrationLane;
      break;

    case IdleLane:
      lane = IdleHydrationLane;
      break;

    default:
      // Everything else is already either a hydration lane, or shouldn't
      // be retried at a hydration lane.
      lane = NoLane;
      break;
  } // Check if the lane we chose is suspended. If so, that indicates that we
  // already attempted and failed to hydrate at that level. Also check if we're
  // already rendering that lane, which is rare but could happen.


  if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) {
    // Give up trying to hydrate and fall back to client render.
    return NoLane;
  }

  return lane;
}
function addFiberToLanesMap(root, fiber, lanes) {

  if (!isDevToolsPresent) {
    return;
  }

  var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;

  while (lanes > 0) {
    var index = laneToIndex(lanes);
    var lane = 1 << index;
    var updaters = pendingUpdatersLaneMap[index];
    updaters.add(fiber);
    lanes &= ~lane;
  }
}
function movePendingFibersToMemoized(root, lanes) {

  if (!isDevToolsPresent) {
    return;
  }

  var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
  var memoizedUpdaters = root.memoizedUpdaters;

  while (lanes > 0) {
    var index = laneToIndex(lanes);
    var lane = 1 << index;
    var updaters = pendingUpdatersLaneMap[index];

    if (updaters.size > 0) {
      updaters.forEach(function (fiber) {
        var alternate = fiber.alternate;

        if (alternate === null || !memoizedUpdaters.has(alternate)) {
          memoizedUpdaters.add(fiber);
        }
      });
      updaters.clear();
    }

    lanes &= ~lane;
  }
}
function getTransitionsForLanes(root, lanes) {
  {
    return null;
  }
}

var DiscreteEventPriority = SyncLane;
var ContinuousEventPriority = InputContinuousLane;
var DefaultEventPriority = DefaultLane;
var IdleEventPriority = IdleLane;
var currentUpdatePriority = NoLane;
function getCurrentUpdatePriority() {
  return currentUpdatePriority;
}
function setCurrentUpdatePriority(newPriority) {
  currentUpdatePriority = newPriority;
}
function runWithPriority(priority, fn) {
  var previousPriority = currentUpdatePriority;

  try {
    currentUpdatePriority = priority;
    return fn();
  } finally {
    currentUpdatePriority = previousPriority;
  }
}
function higherEventPriority(a, b) {
  return a !== 0 && a < b ? a : b;
}
function lowerEventPriority(a, b) {
  return a === 0 || a > b ? a : b;
}
function isHigherEventPriority(a, b) {
  return a !== 0 && a < b;
}
function lanesToEventPriority(lanes) {
  var lane = getHighestPriorityLane(lanes);

  if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
    return DiscreteEventPriority;
  }

  if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
    return ContinuousEventPriority;
  }

  if (includesNonIdleWork(lane)) {
    return DefaultEventPriority;
  }

  return IdleEventPriority;
}

// This is imported by the event replaying implementation in React DOM. It's
// in a separate file to break a circular dependency between the renderer and
// the reconciler.
function isRootDehydrated(root) {
  var currentState = root.current.memoizedState;
  return currentState.isDehydrated;
}

var _attemptSynchronousHydration;

function setAttemptSynchronousHydration(fn) {
  _attemptSynchronousHydration = fn;
}
function attemptSynchronousHydration(fiber) {
  _attemptSynchronousHydration(fiber);
}
var attemptContinuousHydration;
function setAttemptContinuousHydration(fn) {
  attemptContinuousHydration = fn;
}
var attemptHydrationAtCurrentPriority;
function setAttemptHydrationAtCurrentPriority(fn) {
  attemptHydrationAtCurrentPriority = fn;
}
var getCurrentUpdatePriority$1;
function setGetCurrentUpdatePriority(fn) {
  getCurrentUpdatePriority$1 = fn;
}
var attemptHydrationAtPriority;
function setAttemptHydrationAtPriority(fn) {
  attemptHydrationAtPriority = fn;
} // TODO: Upgrade this definition once we're on a newer version of Flow that
// has this definition built-in.

var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.

var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
// if the last target was dehydrated.

var queuedFocus = null;
var queuedDrag = null;
var queuedMouse = null; // For pointer events there can be one latest event per pointerId.

var queuedPointers = new Map();
var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.

var queuedExplicitHydrationTargets = [];
var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase
'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit'];
function isDiscreteEventThatRequiresHydration(eventType) {
  return discreteReplayableEvents.indexOf(eventType) > -1;
}

function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  return {
    blockedOn: blockedOn,
    domEventName: domEventName,
    eventSystemFlags: eventSystemFlags,
    nativeEvent: nativeEvent,
    targetContainers: [targetContainer]
  };
}

function clearIfContinuousEvent(domEventName, nativeEvent) {
  switch (domEventName) {
    case 'focusin':
    case 'focusout':
      queuedFocus = null;
      break;

    case 'dragenter':
    case 'dragleave':
      queuedDrag = null;
      break;

    case 'mouseover':
    case 'mouseout':
      queuedMouse = null;
      break;

    case 'pointerover':
    case 'pointerout':
      {
        var pointerId = nativeEvent.pointerId;
        queuedPointers.delete(pointerId);
        break;
      }

    case 'gotpointercapture':
    case 'lostpointercapture':
      {
        var _pointerId = nativeEvent.pointerId;
        queuedPointerCaptures.delete(_pointerId);
        break;
      }
  }
}

function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
    var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);

    if (blockedOn !== null) {
      var _fiber2 = getInstanceFromNode(blockedOn);

      if (_fiber2 !== null) {
        // Attempt to increase the priority of this target.
        attemptContinuousHydration(_fiber2);
      }
    }

    return queuedEvent;
  } // If we have already queued this exact event, then it's because
  // the different event systems have different DOM event listeners.
  // We can accumulate the flags, and the targetContainers, and
  // store a single event to be replayed.


  existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
  var targetContainers = existingQueuedEvent.targetContainers;

  if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
    targetContainers.push(targetContainer);
  }

  return existingQueuedEvent;
}

function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  // These set relatedTarget to null because the replayed event will be treated as if we
  // moved from outside the window (no target) onto the target once it hydrates.
  // Instead of mutating we could clone the event.
  switch (domEventName) {
    case 'focusin':
      {
        var focusEvent = nativeEvent;
        queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
        return true;
      }

    case 'dragenter':
      {
        var dragEvent = nativeEvent;
        queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
        return true;
      }

    case 'mouseover':
      {
        var mouseEvent = nativeEvent;
        queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
        return true;
      }

    case 'pointerover':
      {
        var pointerEvent = nativeEvent;
        var pointerId = pointerEvent.pointerId;
        queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
        return true;
      }

    case 'gotpointercapture':
      {
        var _pointerEvent = nativeEvent;
        var _pointerId2 = _pointerEvent.pointerId;
        queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
        return true;
      }
  }

  return false;
} // Check if this target is unblocked. Returns true if it's unblocked.

function attemptExplicitHydrationTarget(queuedTarget) {
  // TODO: This function shares a lot of logic with findInstanceBlockingEvent.
  // Try to unify them. It's a bit tricky since it would require two return
  // values.
  var targetInst = getClosestInstanceFromNode(queuedTarget.target);

  if (targetInst !== null) {
    var nearestMounted = getNearestMountedFiber(targetInst);

    if (nearestMounted !== null) {
      var tag = nearestMounted.tag;

      if (tag === SuspenseComponent) {
        var instance = getSuspenseInstanceFromFiber(nearestMounted);

        if (instance !== null) {
          // We're blocked on hydrating this boundary.
          // Increase its priority.
          queuedTarget.blockedOn = instance;
          attemptHydrationAtPriority(queuedTarget.priority, function () {
            attemptHydrationAtCurrentPriority(nearestMounted);
          });
          return;
        }
      } else if (tag === HostRoot) {
        var root = nearestMounted.stateNode;

        if (isRootDehydrated(root)) {
          queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
          // a root other than sync.

          return;
        }
      }
    }
  }

  queuedTarget.blockedOn = null;
}

function queueExplicitHydrationTarget(target) {
  // TODO: This will read the priority if it's dispatched by the React
  // event system but not native events. Should read window.event.type, like
  // we do for updates (getCurrentEventPriority).
  var updatePriority = getCurrentUpdatePriority$1();
  var queuedTarget = {
    blockedOn: null,
    target: target,
    priority: updatePriority
  };
  var i = 0;

  for (; i < queuedExplicitHydrationTargets.length; i++) {
    // Stop once we hit the first target with lower priority than
    if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) {
      break;
    }
  }

  queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);

  if (i === 0) {
    attemptExplicitHydrationTarget(queuedTarget);
  }
}

function attemptReplayContinuousQueuedEvent(queuedEvent) {
  if (queuedEvent.blockedOn !== null) {
    return false;
  }

  var targetContainers = queuedEvent.targetContainers;

  while (targetContainers.length > 0) {
    var targetContainer = targetContainers[0];
    var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);

    if (nextBlockedOn === null) {
      {
        var nativeEvent = queuedEvent.nativeEvent;
        var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
        setReplayingEvent(nativeEventClone);
        nativeEvent.target.dispatchEvent(nativeEventClone);
        resetReplayingEvent();
      }
    } else {
      // We're still blocked. Try again later.
      var _fiber3 = getInstanceFromNode(nextBlockedOn);

      if (_fiber3 !== null) {
        attemptContinuousHydration(_fiber3);
      }

      queuedEvent.blockedOn = nextBlockedOn;
      return false;
    } // This target container was successfully dispatched. Try the next.


    targetContainers.shift();
  }

  return true;
}

function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
  if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
    map.delete(key);
  }
}

function replayUnblockedEvents() {
  hasScheduledReplayAttempt = false;


  if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
    queuedFocus = null;
  }

  if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
    queuedDrag = null;
  }

  if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
    queuedMouse = null;
  }

  queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
  queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}

function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
  if (queuedEvent.blockedOn === unblocked) {
    queuedEvent.blockedOn = null;

    if (!hasScheduledReplayAttempt) {
      hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
      // now unblocked. This first might not actually be unblocked yet.
      // We could check it early to avoid scheduling an unnecessary callback.

      Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
    }
  }
}

function retryIfBlockedOn(unblocked) {
  // Mark anything that was blocked on this as no longer blocked
  // and eligible for a replay.
  if (queuedDiscreteEvents.length > 0) {
    scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
    // worth it because we expect very few discrete events to queue up and once
    // we are actually fully unblocked it will be fast to replay them.

    for (var i = 1; i < queuedDiscreteEvents.length; i++) {
      var queuedEvent = queuedDiscreteEvents[i];

      if (queuedEvent.blockedOn === unblocked) {
        queuedEvent.blockedOn = null;
      }
    }
  }

  if (queuedFocus !== null) {
    scheduleCallbackIfUnblocked(queuedFocus, unblocked);
  }

  if (queuedDrag !== null) {
    scheduleCallbackIfUnblocked(queuedDrag, unblocked);
  }

  if (queuedMouse !== null) {
    scheduleCallbackIfUnblocked(queuedMouse, unblocked);
  }

  var unblock = function (queuedEvent) {
    return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
  };

  queuedPointers.forEach(unblock);
  queuedPointerCaptures.forEach(unblock);

  for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
    var queuedTarget = queuedExplicitHydrationTargets[_i];

    if (queuedTarget.blockedOn === unblocked) {
      queuedTarget.blockedOn = null;
    }
  }

  while (queuedExplicitHydrationTargets.length > 0) {
    var nextExplicitTarget = queuedExplicitHydrationTargets[0];

    if (nextExplicitTarget.blockedOn !== null) {
      // We're still blocked.
      break;
    } else {
      attemptExplicitHydrationTarget(nextExplicitTarget);

      if (nextExplicitTarget.blockedOn === null) {
        // We're unblocked.
        queuedExplicitHydrationTargets.shift();
      }
    }
  }
}

var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these?

var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra.
// We'd like to remove this but it's not clear if this is safe.

function setEnabled(enabled) {
  _enabled = !!enabled;
}
function isEnabled() {
  return _enabled;
}
function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
  var eventPriority = getEventPriority(domEventName);
  var listenerWrapper;

  switch (eventPriority) {
    case DiscreteEventPriority:
      listenerWrapper = dispatchDiscreteEvent;
      break;

    case ContinuousEventPriority:
      listenerWrapper = dispatchContinuousEvent;
      break;

    case DefaultEventPriority:
    default:
      listenerWrapper = dispatchEvent;
      break;
  }

  return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
}

function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
  var previousPriority = getCurrentUpdatePriority();
  var prevTransition = ReactCurrentBatchConfig.transition;
  ReactCurrentBatchConfig.transition = null;

  try {
    setCurrentUpdatePriority(DiscreteEventPriority);
    dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
  } finally {
    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig.transition = prevTransition;
  }
}

function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
  var previousPriority = getCurrentUpdatePriority();
  var prevTransition = ReactCurrentBatchConfig.transition;
  ReactCurrentBatchConfig.transition = null;

  try {
    setCurrentUpdatePriority(ContinuousEventPriority);
    dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
  } finally {
    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig.transition = prevTransition;
  }
}

function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  if (!_enabled) {
    return;
  }

  {
    dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
  }
}

function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);

  if (blockedOn === null) {
    dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
    clearIfContinuousEvent(domEventName, nativeEvent);
    return;
  }

  if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
    nativeEvent.stopPropagation();
    return;
  } // We need to clear only if we didn't queue because
  // queueing is accumulative.


  clearIfContinuousEvent(domEventName, nativeEvent);

  if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
    while (blockedOn !== null) {
      var fiber = getInstanceFromNode(blockedOn);

      if (fiber !== null) {
        attemptSynchronousHydration(fiber);
      }

      var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);

      if (nextBlockedOn === null) {
        dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
      }

      if (nextBlockedOn === blockedOn) {
        break;
      }

      blockedOn = nextBlockedOn;
    }

    if (blockedOn !== null) {
      nativeEvent.stopPropagation();
    }

    return;
  } // This is not replayable so we'll invoke it but without a target,
  // in case the event system needs to trace it.


  dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
}

var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked.
// The return_targetInst field above is conceptually part of the return value.

function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
  // TODO: Warn if _enabled is false.
  return_targetInst = null;
  var nativeEventTarget = getEventTarget(nativeEvent);
  var targetInst = getClosestInstanceFromNode(nativeEventTarget);

  if (targetInst !== null) {
    var nearestMounted = getNearestMountedFiber(targetInst);

    if (nearestMounted === null) {
      // This tree has been unmounted already. Dispatch without a target.
      targetInst = null;
    } else {
      var tag = nearestMounted.tag;

      if (tag === SuspenseComponent) {
        var instance = getSuspenseInstanceFromFiber(nearestMounted);

        if (instance !== null) {
          // Queue the event to be replayed later. Abort dispatching since we
          // don't want this event dispatched twice through the event system.
          // TODO: If this is the first discrete event in the queue. Schedule an increased
          // priority for this boundary.
          return instance;
        } // This shouldn't happen, something went wrong but to avoid blocking
        // the whole system, dispatch the event without a target.
        // TODO: Warn.


        targetInst = null;
      } else if (tag === HostRoot) {
        var root = nearestMounted.stateNode;

        if (isRootDehydrated(root)) {
          // If this happens during a replay something went wrong and it might block
          // the whole system.
          return getContainerFromFiber(nearestMounted);
        }

        targetInst = null;
      } else if (nearestMounted !== targetInst) {
        // If we get an event (ex: img onload) before committing that
        // component's mount, ignore it for now (that is, treat it as if it was an
        // event on a non-React tree). We might also consider queueing events and
        // dispatching them after the mount.
        targetInst = null;
      }
    }
  }

  return_targetInst = targetInst; // We're not blocked on anything.

  return null;
}
function getEventPriority(domEventName) {
  switch (domEventName) {
    // Used by SimpleEventPlugin:
    case 'cancel':
    case 'click':
    case 'close':
    case 'contextmenu':
    case 'copy':
    case 'cut':
    case 'auxclick':
    case 'dblclick':
    case 'dragend':
    case 'dragstart':
    case 'drop':
    case 'focusin':
    case 'focusout':
    case 'input':
    case 'invalid':
    case 'keydown':
    case 'keypress':
    case 'keyup':
    case 'mousedown':
    case 'mouseup':
    case 'paste':
    case 'pause':
    case 'play':
    case 'pointercancel':
    case 'pointerdown':
    case 'pointerup':
    case 'ratechange':
    case 'reset':
    case 'resize':
    case 'seeked':
    case 'submit':
    case 'touchcancel':
    case 'touchend':
    case 'touchstart':
    case 'volumechange': // Used by polyfills:
    // eslint-disable-next-line no-fallthrough

    case 'change':
    case 'selectionchange':
    case 'textInput':
    case 'compositionstart':
    case 'compositionend':
    case 'compositionupdate': // Only enableCreateEventHandleAPI:
    // eslint-disable-next-line no-fallthrough

    case 'beforeblur':
    case 'afterblur': // Not used by React but could be by user code:
    // eslint-disable-next-line no-fallthrough

    case 'beforeinput':
    case 'blur':
    case 'fullscreenchange':
    case 'focus':
    case 'hashchange':
    case 'popstate':
    case 'select':
    case 'selectstart':
      return DiscreteEventPriority;

    case 'drag':
    case 'dragenter':
    case 'dragexit':
    case 'dragleave':
    case 'dragover':
    case 'mousemove':
    case 'mouseout':
    case 'mouseover':
    case 'pointermove':
    case 'pointerout':
    case 'pointerover':
    case 'scroll':
    case 'toggle':
    case 'touchmove':
    case 'wheel': // Not used by React but could be by user code:
    // eslint-disable-next-line no-fallthrough

    case 'mouseenter':
    case 'mouseleave':
    case 'pointerenter':
    case 'pointerleave':
      return ContinuousEventPriority;

    case 'message':
      {
        // We might be in the Scheduler callback.
        // Eventually this mechanism will be replaced by a check
        // of the current priority on the native scheduler.
        var schedulerPriority = getCurrentPriorityLevel();

        switch (schedulerPriority) {
          case ImmediatePriority:
            return DiscreteEventPriority;

          case UserBlockingPriority:
            return ContinuousEventPriority;

          case NormalPriority:
          case LowPriority:
            // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
            return DefaultEventPriority;

          case IdlePriority:
            return IdleEventPriority;

          default:
            return DefaultEventPriority;
        }
      }

    default:
      return DefaultEventPriority;
  }
}

function addEventBubbleListener(target, eventType, listener) {
  target.addEventListener(eventType, listener, false);
  return listener;
}
function addEventCaptureListener(target, eventType, listener) {
  target.addEventListener(eventType, listener, true);
  return listener;
}
function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
  target.addEventListener(eventType, listener, {
    capture: true,
    passive: passive
  });
  return listener;
}
function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
  target.addEventListener(eventType, listener, {
    passive: passive
  });
  return listener;
}

/**
 * These variables store information about text content of a target node,
 * allowing comparison of content before and after a given event.
 *
 * Identify the node where selection currently begins, then observe
 * both its text content and its current position in the DOM. Since the
 * browser may natively replace the target node during composition, we can
 * use its position to find its replacement.
 *
 *
 */
var root = null;
var startText = null;
var fallbackText = null;
function initialize(nativeEventTarget) {
  root = nativeEventTarget;
  startText = getText();
  return true;
}
function reset() {
  root = null;
  startText = null;
  fallbackText = null;
}
function getData() {
  if (fallbackText) {
    return fallbackText;
  }

  var start;
  var startValue = startText;
  var startLength = startValue.length;
  var end;
  var endValue = getText();
  var endLength = endValue.length;

  for (start = 0; start < startLength; start++) {
    if (startValue[start] !== endValue[start]) {
      break;
    }
  }

  var minEnd = startLength - start;

  for (end = 1; end <= minEnd; end++) {
    if (startValue[startLength - end] !== endValue[endLength - end]) {
      break;
    }
  }

  var sliceTail = end > 1 ? 1 - end : undefined;
  fallbackText = endValue.slice(start, sliceTail);
  return fallbackText;
}
function getText() {
  if ('value' in root) {
    return root.value;
  }

  return root.textContent;
}

/**
 * `charCode` represents the actual "character code" and is safe to use with
 * `String.fromCharCode`. As such, only keys that correspond to printable
 * characters produce a valid `charCode`, the only exception to this is Enter.
 * The Tab-key is considered non-printable and does not have a `charCode`,
 * presumably because it does not produce a tab-character in browsers.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {number} Normalized `charCode` property.
 */
function getEventCharCode(nativeEvent) {
  var charCode;
  var keyCode = nativeEvent.keyCode;

  if ('charCode' in nativeEvent) {
    charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.

    if (charCode === 0 && keyCode === 13) {
      charCode = 13;
    }
  } else {
    // IE8 does not implement `charCode`, but `keyCode` has the correct value.
    charCode = keyCode;
  } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  // report Enter as charCode 10 when ctrl is pressed.


  if (charCode === 10) {
    charCode = 13;
  } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  // Must not discard the (non-)printable Enter-key.


  if (charCode >= 32 || charCode === 13) {
    return charCode;
  }

  return 0;
}

function functionThatReturnsTrue() {
  return true;
}

function functionThatReturnsFalse() {
  return false;
} // This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.


function createSyntheticEvent(Interface) {
  /**
   * Synthetic events are dispatched by event plugins, typically in response to a
   * top-level event delegation handler.
   *
   * These systems should generally use pooling to reduce the frequency of garbage
   * collection. The system should check `isPersistent` to determine whether the
   * event should be released into the pool after being dispatched. Users that
   * need a persisted event should invoke `persist`.
   *
   * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
   * normalizing browser quirks. Subclasses do not necessarily have to implement a
   * DOM interface; custom application-specific events can also subclass this.
   */
  function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
    this._reactName = reactName;
    this._targetInst = targetInst;
    this.type = reactEventType;
    this.nativeEvent = nativeEvent;
    this.target = nativeEventTarget;
    this.currentTarget = null;

    for (var _propName in Interface) {
      if (!Interface.hasOwnProperty(_propName)) {
        continue;
      }

      var normalize = Interface[_propName];

      if (normalize) {
        this[_propName] = normalize(nativeEvent);
      } else {
        this[_propName] = nativeEvent[_propName];
      }
    }

    var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;

    if (defaultPrevented) {
      this.isDefaultPrevented = functionThatReturnsTrue;
    } else {
      this.isDefaultPrevented = functionThatReturnsFalse;
    }

    this.isPropagationStopped = functionThatReturnsFalse;
    return this;
  }

  assign(SyntheticBaseEvent.prototype, {
    preventDefault: function () {
      this.defaultPrevented = true;
      var event = this.nativeEvent;

      if (!event) {
        return;
      }

      if (event.preventDefault) {
        event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
      } else if (typeof event.returnValue !== 'unknown') {
        event.returnValue = false;
      }

      this.isDefaultPrevented = functionThatReturnsTrue;
    },
    stopPropagation: function () {
      var event = this.nativeEvent;

      if (!event) {
        return;
      }

      if (event.stopPropagation) {
        event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
      } else if (typeof event.cancelBubble !== 'unknown') {
        // The ChangeEventPlugin registers a "propertychange" event for
        // IE. This event does not support bubbling or cancelling, and
        // any references to cancelBubble throw "Member not found".  A
        // typeof check of "unknown" circumvents this issue (and is also
        // IE specific).
        event.cancelBubble = true;
      }

      this.isPropagationStopped = functionThatReturnsTrue;
    },

    /**
     * We release all dispatched `SyntheticEvent`s after each event loop, adding
     * them back into the pool. This allows a way to hold onto a reference that
     * won't be added back into the pool.
     */
    persist: function () {// Modern event system doesn't use pooling.
    },

    /**
     * Checks if this event should be released back into the pool.
     *
     * @return {boolean} True if this should not be released, false otherwise.
     */
    isPersistent: functionThatReturnsTrue
  });
  return SyntheticBaseEvent;
}
/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var EventInterface = {
  eventPhase: 0,
  bubbles: 0,
  cancelable: 0,
  timeStamp: function (event) {
    return event.timeStamp || Date.now();
  },
  defaultPrevented: 0,
  isTrusted: 0
};
var SyntheticEvent = createSyntheticEvent(EventInterface);

var UIEventInterface = assign({}, EventInterface, {
  view: 0,
  detail: 0
});

var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
var lastMovementX;
var lastMovementY;
var lastMouseEvent;

function updateMouseMovementPolyfillState(event) {
  if (event !== lastMouseEvent) {
    if (lastMouseEvent && event.type === 'mousemove') {
      lastMovementX = event.screenX - lastMouseEvent.screenX;
      lastMovementY = event.screenY - lastMouseEvent.screenY;
    } else {
      lastMovementX = 0;
      lastMovementY = 0;
    }

    lastMouseEvent = event;
  }
}
/**
 * @interface MouseEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var MouseEventInterface = assign({}, UIEventInterface, {
  screenX: 0,
  screenY: 0,
  clientX: 0,
  clientY: 0,
  pageX: 0,
  pageY: 0,
  ctrlKey: 0,
  shiftKey: 0,
  altKey: 0,
  metaKey: 0,
  getModifierState: getEventModifierState,
  button: 0,
  buttons: 0,
  relatedTarget: function (event) {
    if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
    return event.relatedTarget;
  },
  movementX: function (event) {
    if ('movementX' in event) {
      return event.movementX;
    }

    updateMouseMovementPolyfillState(event);
    return lastMovementX;
  },
  movementY: function (event) {
    if ('movementY' in event) {
      return event.movementY;
    } // Don't need to call updateMouseMovementPolyfillState() here
    // because it's guaranteed to have already run when movementX
    // was copied.


    return lastMovementY;
  }
});

var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
/**
 * @interface DragEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var DragEventInterface = assign({}, MouseEventInterface, {
  dataTransfer: 0
});

var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
/**
 * @interface FocusEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var FocusEventInterface = assign({}, UIEventInterface, {
  relatedTarget: 0
});

var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
 */

var AnimationEventInterface = assign({}, EventInterface, {
  animationName: 0,
  elapsedTime: 0,
  pseudoElement: 0
});

var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/clipboard-apis/
 */

var ClipboardEventInterface = assign({}, EventInterface, {
  clipboardData: function (event) {
    return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  }
});

var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
 */

var CompositionEventInterface = assign({}, EventInterface, {
  data: 0
});

var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
 *      /#events-inputevents
 */
// Happens to share the same list for now.

var SyntheticInputEvent = SyntheticCompositionEvent;
/**
 * Normalization of deprecated HTML5 `key` values
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */

var normalizeKey = {
  Esc: 'Escape',
  Spacebar: ' ',
  Left: 'ArrowLeft',
  Up: 'ArrowUp',
  Right: 'ArrowRight',
  Down: 'ArrowDown',
  Del: 'Delete',
  Win: 'OS',
  Menu: 'ContextMenu',
  Apps: 'ContextMenu',
  Scroll: 'ScrollLock',
  MozPrintableKey: 'Unidentified'
};
/**
 * Translation from legacy `keyCode` to HTML5 `key`
 * Only special keys supported, all others depend on keyboard layout or browser
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */

var translateToKey = {
  '8': 'Backspace',
  '9': 'Tab',
  '12': 'Clear',
  '13': 'Enter',
  '16': 'Shift',
  '17': 'Control',
  '18': 'Alt',
  '19': 'Pause',
  '20': 'CapsLock',
  '27': 'Escape',
  '32': ' ',
  '33': 'PageUp',
  '34': 'PageDown',
  '35': 'End',
  '36': 'Home',
  '37': 'ArrowLeft',
  '38': 'ArrowUp',
  '39': 'ArrowRight',
  '40': 'ArrowDown',
  '45': 'Insert',
  '46': 'Delete',
  '112': 'F1',
  '113': 'F2',
  '114': 'F3',
  '115': 'F4',
  '116': 'F5',
  '117': 'F6',
  '118': 'F7',
  '119': 'F8',
  '120': 'F9',
  '121': 'F10',
  '122': 'F11',
  '123': 'F12',
  '144': 'NumLock',
  '145': 'ScrollLock',
  '224': 'Meta'
};
/**
 * @param {object} nativeEvent Native browser event.
 * @return {string} Normalized `key` property.
 */

function getEventKey(nativeEvent) {
  if (nativeEvent.key) {
    // Normalize inconsistent values reported by browsers due to
    // implementations of a working draft specification.
    // FireFox implements `key` but returns `MozPrintableKey` for all
    // printable characters (normalized to `Unidentified`), ignore it.
    var key = normalizeKey[nativeEvent.key] || nativeEvent.key;

    if (key !== 'Unidentified') {
      return key;
    }
  } // Browser does not implement `key`, polyfill as much of it as we can.


  if (nativeEvent.type === 'keypress') {
    var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
    // thus be captured by `keypress`, no other non-printable key should.

    return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  }

  if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
    // While user keyboard layout determines the actual meaning of each
    // `keyCode` value, almost all function keys have a universal value.
    return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  }

  return '';
}
/**
 * Translation from modifier key to the associated property in the event.
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
 */


var modifierKeyToProp = {
  Alt: 'altKey',
  Control: 'ctrlKey',
  Meta: 'metaKey',
  Shift: 'shiftKey'
}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.

function modifierStateGetter(keyArg) {
  var syntheticEvent = this;
  var nativeEvent = syntheticEvent.nativeEvent;

  if (nativeEvent.getModifierState) {
    return nativeEvent.getModifierState(keyArg);
  }

  var keyProp = modifierKeyToProp[keyArg];
  return keyProp ? !!nativeEvent[keyProp] : false;
}

function getEventModifierState(nativeEvent) {
  return modifierStateGetter;
}
/**
 * @interface KeyboardEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */


var KeyboardEventInterface = assign({}, UIEventInterface, {
  key: getEventKey,
  code: 0,
  location: 0,
  ctrlKey: 0,
  shiftKey: 0,
  altKey: 0,
  metaKey: 0,
  repeat: 0,
  locale: 0,
  getModifierState: getEventModifierState,
  // Legacy Interface
  charCode: function (event) {
    // `charCode` is the result of a KeyPress event and represents the value of
    // the actual printable character.
    // KeyPress is deprecated, but its replacement is not yet final and not
    // implemented in any major browser. Only KeyPress has charCode.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }

    return 0;
  },
  keyCode: function (event) {
    // `keyCode` is the result of a KeyDown/Up event and represents the value of
    // physical keyboard key.
    // The actual meaning of the value depends on the users' keyboard layout
    // which cannot be detected. Assuming that it is a US keyboard layout
    // provides a surprisingly accurate mapping for US and European users.
    // Due to this, it is left to the user to implement at this time.
    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }

    return 0;
  },
  which: function (event) {
    // `which` is an alias for either `keyCode` or `charCode` depending on the
    // type of the event.
    if (event.type === 'keypress') {
      return getEventCharCode(event);
    }

    if (event.type === 'keydown' || event.type === 'keyup') {
      return event.keyCode;
    }

    return 0;
  }
});

var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
/**
 * @interface PointerEvent
 * @see http://www.w3.org/TR/pointerevents/
 */

var PointerEventInterface = assign({}, MouseEventInterface, {
  pointerId: 0,
  width: 0,
  height: 0,
  pressure: 0,
  tangentialPressure: 0,
  tiltX: 0,
  tiltY: 0,
  twist: 0,
  pointerType: 0,
  isPrimary: 0
});

var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
/**
 * @interface TouchEvent
 * @see http://www.w3.org/TR/touch-events/
 */

var TouchEventInterface = assign({}, UIEventInterface, {
  touches: 0,
  targetTouches: 0,
  changedTouches: 0,
  altKey: 0,
  metaKey: 0,
  ctrlKey: 0,
  shiftKey: 0,
  getModifierState: getEventModifierState
});

var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
/**
 * @interface Event
 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
 */

var TransitionEventInterface = assign({}, EventInterface, {
  propertyName: 0,
  elapsedTime: 0,
  pseudoElement: 0
});

var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
/**
 * @interface WheelEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */

var WheelEventInterface = assign({}, MouseEventInterface, {
  deltaX: function (event) {
    return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
    'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  },
  deltaY: function (event) {
    return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
    'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
    'wheelDelta' in event ? -event.wheelDelta : 0;
  },
  deltaZ: 0,
  // Browsers without "deltaMode" is reporting in raw wheel delta where one
  // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  deltaMode: 0
});

var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);

var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space

var START_KEYCODE = 229;
var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
var documentMode = null;

if (canUseDOM && 'documentMode' in document) {
  documentMode = document.documentMode;
} // Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.


var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.

var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);

function registerEvents() {
  registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']);
  registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
  registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
  registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
} // Track whether we've ever handled a keypress on the space key.


var hasSpaceKeypress = false;
/**
 * Return whether a native keypress event is assumed to be a command.
 * This is required because Firefox fires `keypress` events for key commands
 * (cut, copy, select-all, etc.) even though no character is inserted.
 */

function isKeypressCommand(nativeEvent) {
  return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
  !(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
 * Translate native top level events into event types.
 */


function getCompositionEventType(domEventName) {
  switch (domEventName) {
    case 'compositionstart':
      return 'onCompositionStart';

    case 'compositionend':
      return 'onCompositionEnd';

    case 'compositionupdate':
      return 'onCompositionUpdate';
  }
}
/**
 * Does our fallback best-guess model think this event signifies that
 * composition has begun?
 */


function isFallbackCompositionStart(domEventName, nativeEvent) {
  return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE;
}
/**
 * Does our fallback mode think that this event is the end of composition?
 */


function isFallbackCompositionEnd(domEventName, nativeEvent) {
  switch (domEventName) {
    case 'keyup':
      // Command keys insert or clear IME input.
      return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;

    case 'keydown':
      // Expect IME keyCode on each keydown. If we get any other
      // code we must have exited earlier.
      return nativeEvent.keyCode !== START_KEYCODE;

    case 'keypress':
    case 'mousedown':
    case 'focusout':
      // Events are not possible without cancelling IME.
      return true;

    default:
      return false;
  }
}
/**
 * Google Input Tools provides composition data via a CustomEvent,
 * with the `data` property populated in the `detail` object. If this
 * is available on the event object, use it. If not, this is a plain
 * composition event and we have nothing special to extract.
 *
 * @param {object} nativeEvent
 * @return {?string}
 */


function getDataFromCustomEvent(nativeEvent) {
  var detail = nativeEvent.detail;

  if (typeof detail === 'object' && 'data' in detail) {
    return detail.data;
  }

  return null;
}
/**
 * Check if a composition event was triggered by Korean IME.
 * Our fallback mode does not work well with IE's Korean IME,
 * so just use native composition events when Korean IME is used.
 * Although CompositionEvent.locale property is deprecated,
 * it is available in IE, where our fallback mode is enabled.
 *
 * @param {object} nativeEvent
 * @return {boolean}
 */


function isUsingKoreanIME(nativeEvent) {
  return nativeEvent.locale === 'ko';
} // Track the current IME composition status, if any.


var isComposing = false;
/**
 * @return {?object} A SyntheticCompositionEvent.
 */

function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
  var eventType;
  var fallbackData;

  if (canUseCompositionEvent) {
    eventType = getCompositionEventType(domEventName);
  } else if (!isComposing) {
    if (isFallbackCompositionStart(domEventName, nativeEvent)) {
      eventType = 'onCompositionStart';
    }
  } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
    eventType = 'onCompositionEnd';
  }

  if (!eventType) {
    return null;
  }

  if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
    // The current composition is stored statically and must not be
    // overwritten while composition continues.
    if (!isComposing && eventType === 'onCompositionStart') {
      isComposing = initialize(nativeEventTarget);
    } else if (eventType === 'onCompositionEnd') {
      if (isComposing) {
        fallbackData = getData();
      }
    }
  }

  var listeners = accumulateTwoPhaseListeners(targetInst, eventType);

  if (listeners.length > 0) {
    var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
    dispatchQueue.push({
      event: event,
      listeners: listeners
    });

    if (fallbackData) {
      // Inject data generated from fallback path into the synthetic event.
      // This matches the property of native CompositionEventInterface.
      event.data = fallbackData;
    } else {
      var customData = getDataFromCustomEvent(nativeEvent);

      if (customData !== null) {
        event.data = customData;
      }
    }
  }
}

function getNativeBeforeInputChars(domEventName, nativeEvent) {
  switch (domEventName) {
    case 'compositionend':
      return getDataFromCustomEvent(nativeEvent);

    case 'keypress':
      /**
       * If native `textInput` events are available, our goal is to make
       * use of them. However, there is a special case: the spacebar key.
       * In Webkit, preventing default on a spacebar `textInput` event
       * cancels character insertion, but it *also* causes the browser
       * to fall back to its default spacebar behavior of scrolling the
       * page.
       *
       * Tracking at:
       * https://code.google.com/p/chromium/issues/detail?id=355103
       *
       * To avoid this issue, use the keypress event as if no `textInput`
       * event is available.
       */
      var which = nativeEvent.which;

      if (which !== SPACEBAR_CODE) {
        return null;
      }

      hasSpaceKeypress = true;
      return SPACEBAR_CHAR;

    case 'textInput':
      // Record the characters to be added to the DOM.
      var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
      // it at the keypress level and bail immediately. Android Chrome
      // doesn't give us keycodes, so we need to ignore it.

      if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
        return null;
      }

      return chars;

    default:
      // For other native event types, do nothing.
      return null;
  }
}
/**
 * For browsers that do not provide the `textInput` event, extract the
 * appropriate string to use for SyntheticInputEvent.
 */


function getFallbackBeforeInputChars(domEventName, nativeEvent) {
  // If we are currently composing (IME) and using a fallback to do so,
  // try to extract the composed characters from the fallback object.
  // If composition event is available, we extract a string only at
  // compositionevent, otherwise extract it at fallback events.
  if (isComposing) {
    if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
      var chars = getData();
      reset();
      isComposing = false;
      return chars;
    }

    return null;
  }

  switch (domEventName) {
    case 'paste':
      // If a paste event occurs after a keypress, throw out the input
      // chars. Paste events should not lead to BeforeInput events.
      return null;

    case 'keypress':
      /**
       * As of v27, Firefox may fire keypress events even when no character
       * will be inserted. A few possibilities:
       *
       * - `which` is `0`. Arrow keys, Esc key, etc.
       *
       * - `which` is the pressed key code, but no char is available.
       *   Ex: 'AltGr + d` in Polish. There is no modified character for
       *   this key combination and no character is inserted into the
       *   document, but FF fires the keypress for char code `100` anyway.
       *   No `input` event will occur.
       *
       * - `which` is the pressed key code, but a command combination is
       *   being used. Ex: `Cmd+C`. No character is inserted, and no
       *   `input` event will occur.
       */
      if (!isKeypressCommand(nativeEvent)) {
        // IE fires the `keypress` event when a user types an emoji via
        // Touch keyboard of Windows.  In such a case, the `char` property
        // holds an emoji character like `\uD83D\uDE0A`.  Because its length
        // is 2, the property `which` does not represent an emoji correctly.
        // In such a case, we directly return the `char` property instead of
        // using `which`.
        if (nativeEvent.char && nativeEvent.char.length > 1) {
          return nativeEvent.char;
        } else if (nativeEvent.which) {
          return String.fromCharCode(nativeEvent.which);
        }
      }

      return null;

    case 'compositionend':
      return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;

    default:
      return null;
  }
}
/**
 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
 * `textInput` or fallback behavior.
 *
 * @return {?object} A SyntheticInputEvent.
 */


function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
  var chars;

  if (canUseTextInputEvent) {
    chars = getNativeBeforeInputChars(domEventName, nativeEvent);
  } else {
    chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
  } // If no characters are being inserted, no BeforeInput event should
  // be fired.


  if (!chars) {
    return null;
  }

  var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput');

  if (listeners.length > 0) {
    var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget);
    dispatchQueue.push({
      event: event,
      listeners: listeners
    });
    event.data = chars;
  }
}
/**
 * Create an `onBeforeInput` event to match
 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
 *
 * This event plugin is based on the native `textInput` event
 * available in Chrome, Safari, Opera, and IE. This event fires after
 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
 *
 * `beforeInput` is spec'd but not implemented in any browsers, and
 * the `input` event does not provide any useful information about what has
 * actually been added, contrary to the spec. Thus, `textInput` is the best
 * available event to identify the characters that have actually been inserted
 * into the target node.
 *
 * This plugin is also responsible for emitting `composition` events, thus
 * allowing us to share composition fallback code for both `beforeInput` and
 * `composition` event types.
 */


function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
  extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
}

/**
 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
 */
var supportedInputTypes = {
  color: true,
  date: true,
  datetime: true,
  'datetime-local': true,
  email: true,
  month: true,
  number: true,
  password: true,
  range: true,
  search: true,
  tel: true,
  text: true,
  time: true,
  url: true,
  week: true
};

function isTextInputElement(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();

  if (nodeName === 'input') {
    return !!supportedInputTypes[elem.type];
  }

  if (nodeName === 'textarea') {
    return true;
  }

  return false;
}

/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */

function isEventSupported(eventNameSuffix) {
  if (!canUseDOM) {
    return false;
  }

  var eventName = 'on' + eventNameSuffix;
  var isSupported = (eventName in document);

  if (!isSupported) {
    var element = document.createElement('div');
    element.setAttribute(eventName, 'return;');
    isSupported = typeof element[eventName] === 'function';
  }

  return isSupported;
}

function registerEvents$1() {
  registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']);
}

function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
  // Flag this event loop as needing state restore.
  enqueueStateRestore(target);
  var listeners = accumulateTwoPhaseListeners(inst, 'onChange');

  if (listeners.length > 0) {
    var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target);
    dispatchQueue.push({
      event: event,
      listeners: listeners
    });
  }
}
/**
 * For IE shims
 */


var activeElement = null;
var activeElementInst = null;
/**
 * SECTION: handle `change` event
 */

function shouldUseChangeEvent(elem) {
  var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
  return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}

function manualDispatchChangeEvent(nativeEvent) {
  var dispatchQueue = [];
  createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
  // other events and have it go through ReactBrowserEventEmitter. Since it
  // doesn't, we manually listen for the events and so we have to enqueue and
  // process the abstract event manually.
  //
  // Batching is necessary here in order to ensure that all event handlers run
  // before the next rerender (including event handlers attached to ancestor
  // elements instead of directly on the input). Without this, controlled
  // components don't work properly in conjunction with event bubbling because
  // the component is rerendered and the value reverted before all the event
  // handlers can run. See https://github.com/facebook/react/issues/708.

  batchedUpdates(runEventInBatch, dispatchQueue);
}

function runEventInBatch(dispatchQueue) {
  processDispatchQueue(dispatchQueue, 0);
}

function getInstIfValueChanged(targetInst) {
  var targetNode = getNodeFromInstance(targetInst);

  if (updateValueIfChanged(targetNode)) {
    return targetInst;
  }
}

function getTargetInstForChangeEvent(domEventName, targetInst) {
  if (domEventName === 'change') {
    return targetInst;
  }
}
/**
 * SECTION: handle `input` event
 */


var isInputEventSupported = false;

if (canUseDOM) {
  // IE9 claims to support the input event but fails to trigger it when
  // deleting text, so we ignore its input events.
  isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
}
/**
 * (For IE <=9) Starts tracking propertychange events on the passed-in element
 * and override the value property so that we can distinguish user events from
 * value changes in JS.
 */


function startWatchingForValueChange(target, targetInst) {
  activeElement = target;
  activeElementInst = targetInst;
  activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
 * (For IE <=9) Removes the event listeners from the currently-tracked element,
 * if any exists.
 */


function stopWatchingForValueChange() {
  if (!activeElement) {
    return;
  }

  activeElement.detachEvent('onpropertychange', handlePropertyChange);
  activeElement = null;
  activeElementInst = null;
}
/**
 * (For IE <=9) Handles a propertychange event, sending a `change` event if
 * the value of the active element has changed.
 */


function handlePropertyChange(nativeEvent) {
  if (nativeEvent.propertyName !== 'value') {
    return;
  }

  if (getInstIfValueChanged(activeElementInst)) {
    manualDispatchChangeEvent(nativeEvent);
  }
}

function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
  if (domEventName === 'focusin') {
    // In IE9, propertychange fires for most input events but is buggy and
    // doesn't fire when text is deleted, but conveniently, selectionchange
    // appears to fire in all of the remaining cases so we catch those and
    // forward the event if the value has changed
    // In either case, we don't want to call the event handler if the value
    // is changed from JS so we redefine a setter for `.value` that updates
    // our activeElementValue variable, allowing us to ignore those changes
    //
    // stopWatching() should be a noop here but we call it just in case we
    // missed a blur event somehow.
    stopWatchingForValueChange();
    startWatchingForValueChange(target, targetInst);
  } else if (domEventName === 'focusout') {
    stopWatchingForValueChange();
  }
} // For IE8 and IE9.


function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
  if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') {
    // On the selectionchange event, the target is just document which isn't
    // helpful for us so just check activeElement instead.
    //
    // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
    // propertychange on the first input event after setting `value` from a
    // script and fires only keydown, keypress, keyup. Catching keyup usually
    // gets it and catching keydown lets us fire an event for the first
    // keystroke if user does a key repeat (it'll be a little delayed: right
    // before the second keystroke). Other input methods (e.g., paste) seem to
    // fire selectionchange normally.
    return getInstIfValueChanged(activeElementInst);
  }
}
/**
 * SECTION: handle `click` event
 */


function shouldUseClickEvent(elem) {
  // Use the `click` event to detect changes to checkbox and radio inputs.
  // This approach works across all browsers, whereas `change` does not fire
  // until `blur` in IE8.
  var nodeName = elem.nodeName;
  return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}

function getTargetInstForClickEvent(domEventName, targetInst) {
  if (domEventName === 'click') {
    return getInstIfValueChanged(targetInst);
  }
}

function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
  if (domEventName === 'input' || domEventName === 'change') {
    return getInstIfValueChanged(targetInst);
  }
}

function handleControlledInputBlur(node) {
  var state = node._wrapperState;

  if (!state || !state.controlled || node.type !== 'number') {
    return;
  }

  {
    // If controlled, assign the value attribute to the current value on blur
    setDefaultValue(node, 'number', node.value);
  }
}
/**
 * This plugin creates an `onChange` event that normalizes change events
 * across form elements. This event fires at a time when it's possible to
 * change the element's value without seeing a flicker.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - select
 */


function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
  var getTargetInstFunc, handleEventFunc;

  if (shouldUseChangeEvent(targetNode)) {
    getTargetInstFunc = getTargetInstForChangeEvent;
  } else if (isTextInputElement(targetNode)) {
    if (isInputEventSupported) {
      getTargetInstFunc = getTargetInstForInputOrChangeEvent;
    } else {
      getTargetInstFunc = getTargetInstForInputEventPolyfill;
      handleEventFunc = handleEventsForInputEventPolyfill;
    }
  } else if (shouldUseClickEvent(targetNode)) {
    getTargetInstFunc = getTargetInstForClickEvent;
  }

  if (getTargetInstFunc) {
    var inst = getTargetInstFunc(domEventName, targetInst);

    if (inst) {
      createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
      return;
    }
  }

  if (handleEventFunc) {
    handleEventFunc(domEventName, targetNode, targetInst);
  } // When blurring, set the value attribute for number inputs


  if (domEventName === 'focusout') {
    handleControlledInputBlur(targetNode);
  }
}

function registerEvents$2() {
  registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']);
  registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']);
  registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']);
  registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']);
}
/**
 * For almost every interaction we care about, there will be both a top-level
 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
 * we do not extract duplicate events. However, moving the mouse into the
 * browser from outside will not fire a `mouseout` event. In this case, we use
 * the `mouseover` top-level event.
 */


function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover';
  var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout';

  if (isOverEvent && !isReplayingEvent(nativeEvent)) {
    // If this is an over event with a target, we might have already dispatched
    // the event in the out event of the other target. If this is replayed,
    // then it's because we couldn't dispatch against this target previously
    // so we have to do it now instead.
    var related = nativeEvent.relatedTarget || nativeEvent.fromElement;

    if (related) {
      // If the related node is managed by React, we can assume that we have
      // already dispatched the corresponding events during its mouseout.
      if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
        return;
      }
    }
  }

  if (!isOutEvent && !isOverEvent) {
    // Must not be a mouse or pointer in or out - ignoring.
    return;
  }

  var win; // TODO: why is this nullable in the types but we read from it?

  if (nativeEventTarget.window === nativeEventTarget) {
    // `nativeEventTarget` is probably a window object.
    win = nativeEventTarget;
  } else {
    // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
    var doc = nativeEventTarget.ownerDocument;

    if (doc) {
      win = doc.defaultView || doc.parentWindow;
    } else {
      win = window;
    }
  }

  var from;
  var to;

  if (isOutEvent) {
    var _related = nativeEvent.relatedTarget || nativeEvent.toElement;

    from = targetInst;
    to = _related ? getClosestInstanceFromNode(_related) : null;

    if (to !== null) {
      var nearestMounted = getNearestMountedFiber(to);

      if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
        to = null;
      }
    }
  } else {
    // Moving to a node from outside the window.
    from = null;
    to = targetInst;
  }

  if (from === to) {
    // Nothing pertains to our managed components.
    return;
  }

  var SyntheticEventCtor = SyntheticMouseEvent;
  var leaveEventType = 'onMouseLeave';
  var enterEventType = 'onMouseEnter';
  var eventTypePrefix = 'mouse';

  if (domEventName === 'pointerout' || domEventName === 'pointerover') {
    SyntheticEventCtor = SyntheticPointerEvent;
    leaveEventType = 'onPointerLeave';
    enterEventType = 'onPointerEnter';
    eventTypePrefix = 'pointer';
  }

  var fromNode = from == null ? win : getNodeFromInstance(from);
  var toNode = to == null ? win : getNodeFromInstance(to);
  var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget);
  leave.target = fromNode;
  leave.relatedTarget = toNode;
  var enter = null; // We should only process this nativeEvent if we are processing
  // the first ancestor. Next time, we will ignore the event.

  var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);

  if (nativeTargetInst === targetInst) {
    var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget);
    enterEvent.target = toNode;
    enterEvent.relatedTarget = fromNode;
    enter = enterEvent;
  }

  accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
}

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  ;
}

var objectIs = typeof Object.is === 'function' ? Object.is : is;

/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */

function shallowEqual(objA, objB) {
  if (objectIs(objA, objB)) {
    return true;
  }

  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }

  var keysA = Object.keys(objA);
  var keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  } // Test for A's keys different from B.


  for (var i = 0; i < keysA.length; i++) {
    var currentKey = keysA[i];

    if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
      return false;
    }
  }

  return true;
}

/**
 * Given any node return the first leaf node without children.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {DOMElement|DOMTextNode}
 */

function getLeafNode(node) {
  while (node && node.firstChild) {
    node = node.firstChild;
  }

  return node;
}
/**
 * Get the next sibling within a container. This will walk up the
 * DOM if a node's siblings have been exhausted.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {?DOMElement|DOMTextNode}
 */


function getSiblingNode(node) {
  while (node) {
    if (node.nextSibling) {
      return node.nextSibling;
    }

    node = node.parentNode;
  }
}
/**
 * Get object describing the nodes which contain characters at offset.
 *
 * @param {DOMElement|DOMTextNode} root
 * @param {number} offset
 * @return {?object}
 */


function getNodeForCharacterOffset(root, offset) {
  var node = getLeafNode(root);
  var nodeStart = 0;
  var nodeEnd = 0;

  while (node) {
    if (node.nodeType === TEXT_NODE) {
      nodeEnd = nodeStart + node.textContent.length;

      if (nodeStart <= offset && nodeEnd >= offset) {
        return {
          node: node,
          offset: offset - nodeStart
        };
      }

      nodeStart = nodeEnd;
    }

    node = getLeafNode(getSiblingNode(node));
  }
}

/**
 * @param {DOMElement} outerNode
 * @return {?object}
 */

function getOffsets(outerNode) {
  var ownerDocument = outerNode.ownerDocument;
  var win = ownerDocument && ownerDocument.defaultView || window;
  var selection = win.getSelection && win.getSelection();

  if (!selection || selection.rangeCount === 0) {
    return null;
  }

  var anchorNode = selection.anchorNode,
      anchorOffset = selection.anchorOffset,
      focusNode = selection.focusNode,
      focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
  // up/down buttons on an <input type="number">. Anonymous divs do not seem to
  // expose properties, triggering a "Permission denied error" if any of its
  // properties are accessed. The only seemingly possible way to avoid erroring
  // is to access a property that typically works for non-anonymous divs and
  // catch any error that may otherwise arise. See
  // https://bugzilla.mozilla.org/show_bug.cgi?id=208427

  try {
    /* eslint-disable no-unused-expressions */
    anchorNode.nodeType;
    focusNode.nodeType;
    /* eslint-enable no-unused-expressions */
  } catch (e) {
    return null;
  }

  return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
}
/**
 * Returns {start, end} where `start` is the character/codepoint index of
 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
 * `end` is the index of (focusNode, focusOffset).
 *
 * Returns null if you pass in garbage input but we should probably just crash.
 *
 * Exported only for testing.
 */

function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
  var length = 0;
  var start = -1;
  var end = -1;
  var indexWithinAnchor = 0;
  var indexWithinFocus = 0;
  var node = outerNode;
  var parentNode = null;

  outer: while (true) {
    var next = null;

    while (true) {
      if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
        start = length + anchorOffset;
      }

      if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
        end = length + focusOffset;
      }

      if (node.nodeType === TEXT_NODE) {
        length += node.nodeValue.length;
      }

      if ((next = node.firstChild) === null) {
        break;
      } // Moving from `node` to its first child `next`.


      parentNode = node;
      node = next;
    }

    while (true) {
      if (node === outerNode) {
        // If `outerNode` has children, this is always the second time visiting
        // it. If it has no children, this is still the first loop, and the only
        // valid selection is anchorNode and focusNode both equal to this node
        // and both offsets 0, in which case we will have handled above.
        break outer;
      }

      if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
        start = length;
      }

      if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
        end = length;
      }

      if ((next = node.nextSibling) !== null) {
        break;
      }

      node = parentNode;
      parentNode = node.parentNode;
    } // Moving from `node` to its next sibling `next`.


    node = next;
  }

  if (start === -1 || end === -1) {
    // This should never happen. (Would happen if the anchor/focus nodes aren't
    // actually inside the passed-in node.)
    return null;
  }

  return {
    start: start,
    end: end
  };
}
/**
 * In modern non-IE browsers, we can support both forward and backward
 * selections.
 *
 * Note: IE10+ supports the Selection object, but it does not support
 * the `extend` method, which means that even in modern IE, it's not possible
 * to programmatically create a backward selection. Thus, for all IE
 * versions, we use the old IE API to create our selections.
 *
 * @param {DOMElement|DOMTextNode} node
 * @param {object} offsets
 */

function setOffsets(node, offsets) {
  var doc = node.ownerDocument || document;
  var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
  // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
  // fails when pasting 100+ items)

  if (!win.getSelection) {
    return;
  }

  var selection = win.getSelection();
  var length = node.textContent.length;
  var start = Math.min(offsets.start, length);
  var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
  // Flip backward selections, so we can set with a single range.

  if (!selection.extend && start > end) {
    var temp = end;
    end = start;
    start = temp;
  }

  var startMarker = getNodeForCharacterOffset(node, start);
  var endMarker = getNodeForCharacterOffset(node, end);

  if (startMarker && endMarker) {
    if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
      return;
    }

    var range = doc.createRange();
    range.setStart(startMarker.node, startMarker.offset);
    selection.removeAllRanges();

    if (start > end) {
      selection.addRange(range);
      selection.extend(endMarker.node, endMarker.offset);
    } else {
      range.setEnd(endMarker.node, endMarker.offset);
      selection.addRange(range);
    }
  }
}

function isTextNode(node) {
  return node && node.nodeType === TEXT_NODE;
}

function containsNode(outerNode, innerNode) {
  if (!outerNode || !innerNode) {
    return false;
  } else if (outerNode === innerNode) {
    return true;
  } else if (isTextNode(outerNode)) {
    return false;
  } else if (isTextNode(innerNode)) {
    return containsNode(outerNode, innerNode.parentNode);
  } else if ('contains' in outerNode) {
    return outerNode.contains(innerNode);
  } else if (outerNode.compareDocumentPosition) {
    return !!(outerNode.compareDocumentPosition(innerNode) & 16);
  } else {
    return false;
  }
}

function isInDocument(node) {
  return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
}

function isSameOriginFrame(iframe) {
  try {
    // Accessing the contentDocument of a HTMLIframeElement can cause the browser
    // to throw, e.g. if it has a cross-origin src attribute.
    // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
    // iframe.contentDocument.defaultView;
    // A safety way is to access one of the cross origin properties: Window or Location
    // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
    // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
    return typeof iframe.contentWindow.location.href === 'string';
  } catch (err) {
    return false;
  }
}

function getActiveElementDeep() {
  var win = window;
  var element = getActiveElement();

  while (element instanceof win.HTMLIFrameElement) {
    if (isSameOriginFrame(element)) {
      win = element.contentWindow;
    } else {
      return element;
    }

    element = getActiveElement(win.document);
  }

  return element;
}
/**
 * @ReactInputSelection: React input selection module. Based on Selection.js,
 * but modified to be suitable for react and has a couple of bug fixes (doesn't
 * assume buttons have range selections allowed).
 * Input selection module for React.
 */

/**
 * @hasSelectionCapabilities: we get the element types that support selection
 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
 * and `selectionEnd` rows.
 */


function hasSelectionCapabilities(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
  return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
}
function getSelectionInformation() {
  var focusedElem = getActiveElementDeep();
  return {
    focusedElem: focusedElem,
    selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
  };
}
/**
 * @restoreSelection: If any selection information was potentially lost,
 * restore it. This is useful when performing operations that could remove dom
 * nodes and place them back in, resulting in focus being lost.
 */

function restoreSelection(priorSelectionInformation) {
  var curFocusedElem = getActiveElementDeep();
  var priorFocusedElem = priorSelectionInformation.focusedElem;
  var priorSelectionRange = priorSelectionInformation.selectionRange;

  if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
    if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
      setSelection(priorFocusedElem, priorSelectionRange);
    } // Focusing a node can change the scroll position, which is undesirable


    var ancestors = [];
    var ancestor = priorFocusedElem;

    while (ancestor = ancestor.parentNode) {
      if (ancestor.nodeType === ELEMENT_NODE) {
        ancestors.push({
          element: ancestor,
          left: ancestor.scrollLeft,
          top: ancestor.scrollTop
        });
      }
    }

    if (typeof priorFocusedElem.focus === 'function') {
      priorFocusedElem.focus();
    }

    for (var i = 0; i < ancestors.length; i++) {
      var info = ancestors[i];
      info.element.scrollLeft = info.left;
      info.element.scrollTop = info.top;
    }
  }
}
/**
 * @getSelection: Gets the selection bounds of a focused textarea, input or
 * contentEditable node.
 * -@input: Look up selection bounds of this input
 * -@return {start: selectionStart, end: selectionEnd}
 */

function getSelection(input) {
  var selection;

  if ('selectionStart' in input) {
    // Modern browser with input or textarea.
    selection = {
      start: input.selectionStart,
      end: input.selectionEnd
    };
  } else {
    // Content editable or old IE textarea.
    selection = getOffsets(input);
  }

  return selection || {
    start: 0,
    end: 0
  };
}
/**
 * @setSelection: Sets the selection bounds of a textarea or input and focuses
 * the input.
 * -@input     Set selection bounds of this input or textarea
 * -@offsets   Object of same form that is returned from get*
 */

function setSelection(input, offsets) {
  var start = offsets.start;
  var end = offsets.end;

  if (end === undefined) {
    end = start;
  }

  if ('selectionStart' in input) {
    input.selectionStart = start;
    input.selectionEnd = Math.min(end, input.value.length);
  } else {
    setOffsets(input, offsets);
  }
}

var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;

function registerEvents$3() {
  registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']);
}

var activeElement$1 = null;
var activeElementInst$1 = null;
var lastSelection = null;
var mouseDown = false;
/**
 * Get an object which is a unique representation of the current selection.
 *
 * The return value will not be consistent across nodes or browsers, but
 * two identical selections on the same node will return identical objects.
 */

function getSelection$1(node) {
  if ('selectionStart' in node && hasSelectionCapabilities(node)) {
    return {
      start: node.selectionStart,
      end: node.selectionEnd
    };
  } else {
    var win = node.ownerDocument && node.ownerDocument.defaultView || window;
    var selection = win.getSelection();
    return {
      anchorNode: selection.anchorNode,
      anchorOffset: selection.anchorOffset,
      focusNode: selection.focusNode,
      focusOffset: selection.focusOffset
    };
  }
}
/**
 * Get document associated with the event target.
 */


function getEventTargetDocument(eventTarget) {
  return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
}
/**
 * Poll selection to see whether it's changed.
 *
 * @param {object} nativeEvent
 * @param {object} nativeEventTarget
 * @return {?SyntheticEvent}
 */


function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
  // Ensure we have the right element, and that the user is not dragging a
  // selection (this matches native `select` event behavior). In HTML5, select
  // fires only on input and textarea thus if there's no focused element we
  // won't dispatch.
  var doc = getEventTargetDocument(nativeEventTarget);

  if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
    return;
  } // Only fire when selection has actually changed.


  var currentSelection = getSelection$1(activeElement$1);

  if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
    lastSelection = currentSelection;
    var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect');

    if (listeners.length > 0) {
      var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget);
      dispatchQueue.push({
        event: event,
        listeners: listeners
      });
      event.target = activeElement$1;
    }
  }
}
/**
 * This plugin creates an `onSelect` event that normalizes select events
 * across form elements.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - contentEditable
 *
 * This differs from native browser implementations in the following ways:
 * - Fires on contentEditable fields as well as inputs.
 * - Fires for collapsed selection.
 * - Fires after user input.
 */


function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;

  switch (domEventName) {
    // Track the input node that has focus.
    case 'focusin':
      if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
        activeElement$1 = targetNode;
        activeElementInst$1 = targetInst;
        lastSelection = null;
      }

      break;

    case 'focusout':
      activeElement$1 = null;
      activeElementInst$1 = null;
      lastSelection = null;
      break;
    // Don't fire the event while the user is dragging. This matches the
    // semantics of the native select event.

    case 'mousedown':
      mouseDown = true;
      break;

    case 'contextmenu':
    case 'mouseup':
    case 'dragend':
      mouseDown = false;
      constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
      break;
    // Chrome and IE fire non-standard event when selection is changed (and
    // sometimes when it hasn't). IE's event fires out of order with respect
    // to key and input events on deletion, so we discard it.
    //
    // Firefox doesn't support selectionchange, so check selection status
    // after each key entry. The selection changes after keydown and before
    // keyup, but we check on keydown as well in the case of holding down a
    // key, when multiple keydown events are fired but only one keyup is.
    // This is also our approach for IE handling, for the reason above.

    case 'selectionchange':
      if (skipSelectionChangeEvent) {
        break;
      }

    // falls through

    case 'keydown':
    case 'keyup':
      constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
  }
}

/**
 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
 *
 * @param {string} styleProp
 * @param {string} eventName
 * @returns {object}
 */

function makePrefixMap(styleProp, eventName) {
  var prefixes = {};
  prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  prefixes['Webkit' + styleProp] = 'webkit' + eventName;
  prefixes['Moz' + styleProp] = 'moz' + eventName;
  return prefixes;
}
/**
 * A list of event names to a configurable list of vendor prefixes.
 */


var vendorPrefixes = {
  animationend: makePrefixMap('Animation', 'AnimationEnd'),
  animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
  animationstart: makePrefixMap('Animation', 'AnimationStart'),
  transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
 * Event names that have already been detected and prefixed (if applicable).
 */

var prefixedEventNames = {};
/**
 * Element to check for prefixes on.
 */

var style = {};
/**
 * Bootstrap if a DOM exists.
 */

if (canUseDOM) {
  style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
  // the un-prefixed "animation" and "transition" properties are defined on the
  // style object but the events that fire will still be prefixed, so we need
  // to check if the un-prefixed events are usable, and if not remove them from the map.

  if (!('AnimationEvent' in window)) {
    delete vendorPrefixes.animationend.animation;
    delete vendorPrefixes.animationiteration.animation;
    delete vendorPrefixes.animationstart.animation;
  } // Same as above


  if (!('TransitionEvent' in window)) {
    delete vendorPrefixes.transitionend.transition;
  }
}
/**
 * Attempts to determine the correct vendor prefixed event name.
 *
 * @param {string} eventName
 * @returns {string}
 */


function getVendorPrefixedEventName(eventName) {
  if (prefixedEventNames[eventName]) {
    return prefixedEventNames[eventName];
  } else if (!vendorPrefixes[eventName]) {
    return eventName;
  }

  var prefixMap = vendorPrefixes[eventName];

  for (var styleProp in prefixMap) {
    if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
      return prefixedEventNames[eventName] = prefixMap[styleProp];
    }
  }

  return eventName;
}

var ANIMATION_END = getVendorPrefixedEventName('animationend');
var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration');
var ANIMATION_START = getVendorPrefixedEventName('animationstart');
var TRANSITION_END = getVendorPrefixedEventName('transitionend');

var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list!
//
// E.g. it needs "pointerDown", not "pointerdown".
// This is because we derive both React name ("onPointerDown")
// and DOM name ("pointerdown") from the same list.
//
// Exceptions that don't match this convention are listed separately.
//
// prettier-ignore

var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel'];

function registerSimpleEvent(domEventName, reactName) {
  topLevelEventsToReactNames.set(domEventName, reactName);
  registerTwoPhaseEvent(reactName, [domEventName]);
}

function registerSimpleEvents() {
  for (var i = 0; i < simpleEventPluginEvents.length; i++) {
    var eventName = simpleEventPluginEvents[i];
    var domEventName = eventName.toLowerCase();
    var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
    registerSimpleEvent(domEventName, 'on' + capitalizedEvent);
  } // Special cases where event names don't match.


  registerSimpleEvent(ANIMATION_END, 'onAnimationEnd');
  registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration');
  registerSimpleEvent(ANIMATION_START, 'onAnimationStart');
  registerSimpleEvent('dblclick', 'onDoubleClick');
  registerSimpleEvent('focusin', 'onFocus');
  registerSimpleEvent('focusout', 'onBlur');
  registerSimpleEvent(TRANSITION_END, 'onTransitionEnd');
}

function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  var reactName = topLevelEventsToReactNames.get(domEventName);

  if (reactName === undefined) {
    return;
  }

  var SyntheticEventCtor = SyntheticEvent;
  var reactEventType = domEventName;

  switch (domEventName) {
    case 'keypress':
      // Firefox creates a keypress event for function keys too. This removes
      // the unwanted keypress events. Enter is however both printable and
      // non-printable. One would expect Tab to be as well (but it isn't).
      if (getEventCharCode(nativeEvent) === 0) {
        return;
      }

    /* falls through */

    case 'keydown':
    case 'keyup':
      SyntheticEventCtor = SyntheticKeyboardEvent;
      break;

    case 'focusin':
      reactEventType = 'focus';
      SyntheticEventCtor = SyntheticFocusEvent;
      break;

    case 'focusout':
      reactEventType = 'blur';
      SyntheticEventCtor = SyntheticFocusEvent;
      break;

    case 'beforeblur':
    case 'afterblur':
      SyntheticEventCtor = SyntheticFocusEvent;
      break;

    case 'click':
      // Firefox creates a click event on right mouse clicks. This removes the
      // unwanted click events.
      if (nativeEvent.button === 2) {
        return;
      }

    /* falls through */

    case 'auxclick':
    case 'dblclick':
    case 'mousedown':
    case 'mousemove':
    case 'mouseup': // TODO: Disabled elements should not respond to mouse events

    /* falls through */

    case 'mouseout':
    case 'mouseover':
    case 'contextmenu':
      SyntheticEventCtor = SyntheticMouseEvent;
      break;

    case 'drag':
    case 'dragend':
    case 'dragenter':
    case 'dragexit':
    case 'dragleave':
    case 'dragover':
    case 'dragstart':
    case 'drop':
      SyntheticEventCtor = SyntheticDragEvent;
      break;

    case 'touchcancel':
    case 'touchend':
    case 'touchmove':
    case 'touchstart':
      SyntheticEventCtor = SyntheticTouchEvent;
      break;

    case ANIMATION_END:
    case ANIMATION_ITERATION:
    case ANIMATION_START:
      SyntheticEventCtor = SyntheticAnimationEvent;
      break;

    case TRANSITION_END:
      SyntheticEventCtor = SyntheticTransitionEvent;
      break;

    case 'scroll':
      SyntheticEventCtor = SyntheticUIEvent;
      break;

    case 'wheel':
      SyntheticEventCtor = SyntheticWheelEvent;
      break;

    case 'copy':
    case 'cut':
    case 'paste':
      SyntheticEventCtor = SyntheticClipboardEvent;
      break;

    case 'gotpointercapture':
    case 'lostpointercapture':
    case 'pointercancel':
    case 'pointerdown':
    case 'pointermove':
    case 'pointerout':
    case 'pointerover':
    case 'pointerup':
      SyntheticEventCtor = SyntheticPointerEvent;
      break;
  }

  var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;

  {
    // Some events don't bubble in the browser.
    // In the past, React has always bubbled them, but this can be surprising.
    // We're going to try aligning closer to the browser behavior by not bubbling
    // them in React either. We'll start by not bubbling onScroll, and then expand.
    var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
    // nonDelegatedEvents list in DOMPluginEventSystem.
    // Then we can remove this special list.
    // This is a breaking change that can wait until React 18.
    domEventName === 'scroll';

    var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);

    if (_listeners.length > 0) {
      // Intentionally create event lazily.
      var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);

      dispatchQueue.push({
        event: _event,
        listeners: _listeners
      });
    }
  }
}

// TODO: remove top-level side effect.
registerSimpleEvents();
registerEvents$2();
registerEvents$1();
registerEvents$3();
registerEvents();

function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
  // TODO: we should remove the concept of a "SimpleEventPlugin".
  // This is the basic functionality of the event system. All
  // the other plugins are essentially polyfills. So the plugin
  // should probably be inlined somewhere and have its logic
  // be core the to event system. This would potentially allow
  // us to ship builds of React without the polyfilled plugins below.
  extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
  var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the
  // event's native "bubble" phase, which means that we're
  // not in the capture phase. That's because we emulate
  // the capture phase here still. This is a trade-off,
  // because in an ideal world we would not emulate and use
  // the phases properly, like we do with the SimpleEvent
  // plugin. However, the plugins below either expect
  // emulation (EnterLeave) or use state localized to that
  // plugin (BeforeInput, Change, Select). The state in
  // these modules complicates things, as you'll essentially
  // get the case where the capture phase event might change
  // state, only for the following bubble event to come in
  // later and not trigger anything as the state now
  // invalidates the heuristics of the event plugin. We
  // could alter all these plugins to work in such ways, but
  // that might cause other unknown side-effects that we
  // can't foresee right now.

  if (shouldProcessPolyfillPlugins) {
    extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
    extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
    extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
    extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
  }
} // List of events that need to be individually attached to media elements.


var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather
// set them on the actual target element itself. This is primarily
// because these events do not consistently bubble in the DOM.

var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes));

function executeDispatch(event, listener, currentTarget) {
  var type = event.type || 'unknown-event';
  event.currentTarget = currentTarget;
  invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  event.currentTarget = null;
}

function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
  var previousInstance;

  if (inCapturePhase) {
    for (var i = dispatchListeners.length - 1; i >= 0; i--) {
      var _dispatchListeners$i = dispatchListeners[i],
          instance = _dispatchListeners$i.instance,
          currentTarget = _dispatchListeners$i.currentTarget,
          listener = _dispatchListeners$i.listener;

      if (instance !== previousInstance && event.isPropagationStopped()) {
        return;
      }

      executeDispatch(event, listener, currentTarget);
      previousInstance = instance;
    }
  } else {
    for (var _i = 0; _i < dispatchListeners.length; _i++) {
      var _dispatchListeners$_i = dispatchListeners[_i],
          _instance = _dispatchListeners$_i.instance,
          _currentTarget = _dispatchListeners$_i.currentTarget,
          _listener = _dispatchListeners$_i.listener;

      if (_instance !== previousInstance && event.isPropagationStopped()) {
        return;
      }

      executeDispatch(event, _listener, _currentTarget);
      previousInstance = _instance;
    }
  }
}

function processDispatchQueue(dispatchQueue, eventSystemFlags) {
  var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;

  for (var i = 0; i < dispatchQueue.length; i++) {
    var _dispatchQueue$i = dispatchQueue[i],
        event = _dispatchQueue$i.event,
        listeners = _dispatchQueue$i.listeners;
    processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); //  event system doesn't use pooling.
  } // This would be a good time to rethrow if any of the event handlers threw.


  rethrowCaughtError();
}

function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
  var nativeEventTarget = getEventTarget(nativeEvent);
  var dispatchQueue = [];
  extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
  processDispatchQueue(dispatchQueue, eventSystemFlags);
}

function listenToNonDelegatedEvent(domEventName, targetElement) {
  {
    if (!nonDelegatedEvents.has(domEventName)) {
      error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName);
    }
  }

  var isCapturePhaseListener = false;
  var listenerSet = getEventListenerSet(targetElement);
  var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);

  if (!listenerSet.has(listenerSetKey)) {
    addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
    listenerSet.add(listenerSetKey);
  }
}
function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
  {
    if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
      error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName);
    }
  }

  var eventSystemFlags = 0;

  if (isCapturePhaseListener) {
    eventSystemFlags |= IS_CAPTURE_PHASE;
  }

  addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
} // This is only used by createEventHandle when the
var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2);
function listenToAllSupportedEvents(rootContainerElement) {
  if (!rootContainerElement[listeningMarker]) {
    rootContainerElement[listeningMarker] = true;
    allNativeEvents.forEach(function (domEventName) {
      // We handle selectionchange separately because it
      // doesn't bubble and needs to be on the document.
      if (domEventName !== 'selectionchange') {
        if (!nonDelegatedEvents.has(domEventName)) {
          listenToNativeEvent(domEventName, false, rootContainerElement);
        }

        listenToNativeEvent(domEventName, true, rootContainerElement);
      }
    });
    var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;

    if (ownerDocument !== null) {
      // The selectionchange event also needs deduplication
      // but it is attached to the document.
      if (!ownerDocument[listeningMarker]) {
        ownerDocument[listeningMarker] = true;
        listenToNativeEvent('selectionchange', false, ownerDocument);
      }
    }
  }
}

function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
  var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be
  // active and not passive.

  var isPassiveListener = undefined;

  if (passiveBrowserEventsSupported) {
    // Browsers introduced an intervention, making these events
    // passive by default on document. React doesn't bind them
    // to document anymore, but changing this now would undo
    // the performance wins from the change. So we emulate
    // the existing behavior manually on the roots now.
    // https://github.com/facebook/react/issues/19651
    if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') {
      isPassiveListener = true;
    }
  }

  targetContainer =  targetContainer;
  var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we


  if (isCapturePhaseListener) {
    if (isPassiveListener !== undefined) {
      unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
    } else {
      unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
    }
  } else {
    if (isPassiveListener !== undefined) {
      unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
    } else {
      unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
    }
  }
}

function isMatchingRootContainer(grandContainer, targetContainer) {
  return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
}

function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
  var ancestorInst = targetInst;

  if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
    var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we

    if (targetInst !== null) {
      // The below logic attempts to work out if we need to change
      // the target fiber to a different ancestor. We had similar logic
      // in the legacy event system, except the big difference between
      // systems is that the modern event system now has an event listener
      // attached to each React Root and React Portal Root. Together,
      // the DOM nodes representing these roots are the "rootContainer".
      // To figure out which ancestor instance we should use, we traverse
      // up the fiber tree from the target instance and attempt to find
      // root boundaries that match that of our current "rootContainer".
      // If we find that "rootContainer", we find the parent fiber
      // sub-tree for that root and make that our ancestor instance.
      var node = targetInst;

      mainLoop: while (true) {
        if (node === null) {
          return;
        }

        var nodeTag = node.tag;

        if (nodeTag === HostRoot || nodeTag === HostPortal) {
          var container = node.stateNode.containerInfo;

          if (isMatchingRootContainer(container, targetContainerNode)) {
            break;
          }

          if (nodeTag === HostPortal) {
            // The target is a portal, but it's not the rootContainer we're looking for.
            // Normally portals handle their own events all the way down to the root.
            // So we should be able to stop now. However, we don't know if this portal
            // was part of *our* root.
            var grandNode = node.return;

            while (grandNode !== null) {
              var grandTag = grandNode.tag;

              if (grandTag === HostRoot || grandTag === HostPortal) {
                var grandContainer = grandNode.stateNode.containerInfo;

                if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
                  // This is the rootContainer we're looking for and we found it as
                  // a parent of the Portal. That means we can ignore it because the
                  // Portal will bubble through to us.
                  return;
                }
              }

              grandNode = grandNode.return;
            }
          } // Now we need to find it's corresponding host fiber in the other
          // tree. To do this we can use getClosestInstanceFromNode, but we
          // need to validate that the fiber is a host instance, otherwise
          // we need to traverse up through the DOM till we find the correct
          // node that is from the other tree.


          while (container !== null) {
            var parentNode = getClosestInstanceFromNode(container);

            if (parentNode === null) {
              return;
            }

            var parentTag = parentNode.tag;

            if (parentTag === HostComponent || parentTag === HostText) {
              node = ancestorInst = parentNode;
              continue mainLoop;
            }

            container = container.parentNode;
          }
        }

        node = node.return;
      }
    }
  }

  batchedUpdates(function () {
    return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
  });
}

function createDispatchListener(instance, listener, currentTarget) {
  return {
    instance: instance,
    listener: listener,
    currentTarget: currentTarget
  };
}

function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
  var captureName = reactName !== null ? reactName + 'Capture' : null;
  var reactEventName = inCapturePhase ? captureName : reactName;
  var listeners = [];
  var instance = targetFiber;
  var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path.

  while (instance !== null) {
    var _instance2 = instance,
        stateNode = _instance2.stateNode,
        tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>)

    if (tag === HostComponent && stateNode !== null) {
      lastHostComponent = stateNode; // createEventHandle listeners


      if (reactEventName !== null) {
        var listener = getListener(instance, reactEventName);

        if (listener != null) {
          listeners.push(createDispatchListener(instance, listener, lastHostComponent));
        }
      }
    } // If we are only accumulating events for the target, then we don't
    // continue to propagate through the React fiber tree to find other
    // listeners.


    if (accumulateTargetOnly) {
      break;
    } // If we are processing the onBeforeBlur event, then we need to take

    instance = instance.return;
  }

  return listeners;
} // We should only use this function for:
// - BeforeInputEventPlugin
// - ChangeEventPlugin
// - SelectEventPlugin
// This is because we only process these plugins
// in the bubble phase, so we need to accumulate two
// phase event listeners (via emulation).

function accumulateTwoPhaseListeners(targetFiber, reactName) {
  var captureName = reactName + 'Capture';
  var listeners = [];
  var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path.

  while (instance !== null) {
    var _instance3 = instance,
        stateNode = _instance3.stateNode,
        tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>)

    if (tag === HostComponent && stateNode !== null) {
      var currentTarget = stateNode;
      var captureListener = getListener(instance, captureName);

      if (captureListener != null) {
        listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
      }

      var bubbleListener = getListener(instance, reactName);

      if (bubbleListener != null) {
        listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
      }
    }

    instance = instance.return;
  }

  return listeners;
}

function getParent(inst) {
  if (inst === null) {
    return null;
  }

  do {
    inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
    // That is depending on if we want nested subtrees (layers) to bubble
    // events to their parent. We could also go through parentNode on the
    // host node but that wouldn't work for React Native and doesn't let us
    // do the portal feature.
  } while (inst && inst.tag !== HostComponent);

  if (inst) {
    return inst;
  }

  return null;
}
/**
 * Return the lowest common ancestor of A and B, or null if they are in
 * different trees.
 */


function getLowestCommonAncestor(instA, instB) {
  var nodeA = instA;
  var nodeB = instB;
  var depthA = 0;

  for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
    depthA++;
  }

  var depthB = 0;

  for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
    depthB++;
  } // If A is deeper, crawl up.


  while (depthA - depthB > 0) {
    nodeA = getParent(nodeA);
    depthA--;
  } // If B is deeper, crawl up.


  while (depthB - depthA > 0) {
    nodeB = getParent(nodeB);
    depthB--;
  } // Walk in lockstep until we find a match.


  var depth = depthA;

  while (depth--) {
    if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
      return nodeA;
    }

    nodeA = getParent(nodeA);
    nodeB = getParent(nodeB);
  }

  return null;
}

function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
  var registrationName = event._reactName;
  var listeners = [];
  var instance = target;

  while (instance !== null) {
    if (instance === common) {
      break;
    }

    var _instance4 = instance,
        alternate = _instance4.alternate,
        stateNode = _instance4.stateNode,
        tag = _instance4.tag;

    if (alternate !== null && alternate === common) {
      break;
    }

    if (tag === HostComponent && stateNode !== null) {
      var currentTarget = stateNode;

      if (inCapturePhase) {
        var captureListener = getListener(instance, registrationName);

        if (captureListener != null) {
          listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
        }
      } else if (!inCapturePhase) {
        var bubbleListener = getListener(instance, registrationName);

        if (bubbleListener != null) {
          listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
        }
      }
    }

    instance = instance.return;
  }

  if (listeners.length !== 0) {
    dispatchQueue.push({
      event: event,
      listeners: listeners
    });
  }
} // We should only use this function for:
// - EnterLeaveEventPlugin
// This is because we only process this plugin
// in the bubble phase, so we need to accumulate two
// phase event listeners.


function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
  var common = from && to ? getLowestCommonAncestor(from, to) : null;

  if (from !== null) {
    accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
  }

  if (to !== null && enterEvent !== null) {
    accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
  }
}
function getListenerSetKey(domEventName, capture) {
  return domEventName + "__" + (capture ? 'capture' : 'bubble');
}

var didWarnInvalidHydration = false;
var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
var AUTOFOCUS = 'autoFocus';
var CHILDREN = 'children';
var STYLE = 'style';
var HTML$1 = '__html';
var warnedUnknownTags;
var validatePropertiesInDevelopment;
var warnForPropDifference;
var warnForExtraAttributes;
var warnForInvalidEventListener;
var canDiffStyleForHydrationWarning;
var normalizeHTML;

{
  warnedUnknownTags = {
    // There are working polyfills for <dialog>. Let people use it.
    dialog: true,
    // Electron ships a custom <webview> tag to display external web content in
    // an isolated frame and process.
    // This tag is not present in non Electron environments such as JSDom which
    // is often used for testing purposes.
    // @see https://electronjs.org/docs/api/webview-tag
    webview: true
  };

  validatePropertiesInDevelopment = function (type, props) {
    validateProperties(type, props);
    validateProperties$1(type, props);
    validateProperties$2(type, props, {
      registrationNameDependencies: registrationNameDependencies,
      possibleRegistrationNames: possibleRegistrationNames
    });
  }; // IE 11 parses & normalizes the style attribute as opposed to other
  // browsers. It adds spaces and sorts the properties in some
  // non-alphabetical order. Handling that would require sorting CSS
  // properties in the client & server versions or applying
  // `expectedStyle` to a temporary DOM node to read its `style` attribute
  // normalized. Since it only affects IE, we're skipping style warnings
  // in that browser completely in favor of doing all that work.
  // See https://github.com/facebook/react/issues/11807


  canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;

  warnForPropDifference = function (propName, serverValue, clientValue) {
    if (didWarnInvalidHydration) {
      return;
    }

    var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
    var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);

    if (normalizedServerValue === normalizedClientValue) {
      return;
    }

    didWarnInvalidHydration = true;

    error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
  };

  warnForExtraAttributes = function (attributeNames) {
    if (didWarnInvalidHydration) {
      return;
    }

    didWarnInvalidHydration = true;
    var names = [];
    attributeNames.forEach(function (name) {
      names.push(name);
    });

    error('Extra attributes from the server: %s', names);
  };

  warnForInvalidEventListener = function (registrationName, listener) {
    if (listener === false) {
      error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
    } else {
      error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
    }
  }; // Parse the HTML and read it back to normalize the HTML string so that it
  // can be used for comparison.


  normalizeHTML = function (parent, html) {
    // We could have created a separate document here to avoid
    // re-initializing custom elements if they exist. But this breaks
    // how <noscript> is being handled. So we use the same document.
    // See the discussion in https://github.com/facebook/react/pull/11157.
    var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
    testElement.innerHTML = html;
    return testElement.innerHTML;
  };
} // HTML parsing normalizes CR and CRLF to LF.
// It also can turn \u0000 into \uFFFD inside attributes.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that.
// We will still patch up in this case but not fire the warning.


var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;

function normalizeMarkupForTextOrAttribute(markup) {
  {
    checkHtmlStringCoercion(markup);
  }

  var markupString = typeof markup === 'string' ? markup : '' + markup;
  return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
}

function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
  var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
  var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);

  if (normalizedServerText === normalizedClientText) {
    return;
  }

  if (shouldWarnDev) {
    {
      if (!didWarnInvalidHydration) {
        didWarnInvalidHydration = true;

        error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
      }
    }
  }

  if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
    // In concurrent roots, we throw when there's a text mismatch and revert to
    // client rendering, up to the nearest Suspense boundary.
    throw new Error('Text content does not match server-rendered HTML.');
  }
}

function getOwnerDocumentFromRootContainer(rootContainerElement) {
  return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
}

function noop() {}

function trapClickOnNonInteractiveElement(node) {
  // Mobile Safari does not fire properly bubble click events on
  // non-interactive elements, which means delegated click listeners do not
  // fire. The workaround for this bug involves attaching an empty click
  // listener on the target node.
  // https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
  // Just set it using the onclick property so that we don't have to manage any
  // bookkeeping for it. Not sure if we need to clear it when the listener is
  // removed.
  // TODO: Only do this for the relevant Safaris maybe?
  node.onclick = noop;
}

function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
  for (var propKey in nextProps) {
    if (!nextProps.hasOwnProperty(propKey)) {
      continue;
    }

    var nextProp = nextProps[propKey];

    if (propKey === STYLE) {
      {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      } // Relies on `updateStylesByID` not mutating `styleUpdates`.


      setValueForStyles(domElement, nextProp);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      var nextHtml = nextProp ? nextProp[HTML$1] : undefined;

      if (nextHtml != null) {
        setInnerHTML(domElement, nextHtml);
      }
    } else if (propKey === CHILDREN) {
      if (typeof nextProp === 'string') {
        // Avoid setting initial textContent when the text is empty. In IE11 setting
        // textContent on a <textarea> will cause the placeholder to not
        // show within the <textarea> until it has been focused and blurred again.
        // https://github.com/facebook/react/issues/6731#issuecomment-254874553
        var canSetTextContent = tag !== 'textarea' || nextProp !== '';

        if (canSetTextContent) {
          setTextContent(domElement, nextProp);
        }
      } else if (typeof nextProp === 'number') {
        setTextContent(domElement, '' + nextProp);
      }
    } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        if ( typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }

        if (propKey === 'onScroll') {
          listenToNonDelegatedEvent('scroll', domElement);
        }
      }
    } else if (nextProp != null) {
      setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
    }
  }
}

function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
  // TODO: Handle wasCustomComponentTag
  for (var i = 0; i < updatePayload.length; i += 2) {
    var propKey = updatePayload[i];
    var propValue = updatePayload[i + 1];

    if (propKey === STYLE) {
      setValueForStyles(domElement, propValue);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      setInnerHTML(domElement, propValue);
    } else if (propKey === CHILDREN) {
      setTextContent(domElement, propValue);
    } else {
      setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
    }
  }
}

function createElement(type, props, rootContainerElement, parentNamespace) {
  var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
  // tags get no namespace.

  var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
  var domElement;
  var namespaceURI = parentNamespace;

  if (namespaceURI === HTML_NAMESPACE) {
    namespaceURI = getIntrinsicNamespace(type);
  }

  if (namespaceURI === HTML_NAMESPACE) {
    {
      isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
      // allow <SVG> or <mATH>.

      if (!isCustomComponentTag && type !== type.toLowerCase()) {
        error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
      }
    }

    if (type === 'script') {
      // Create the script via .innerHTML so its "parser-inserted" flag is
      // set to true and it does not execute
      var div = ownerDocument.createElement('div');

      div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
      // This is guaranteed to yield a script element.

      var firstChild = div.firstChild;
      domElement = div.removeChild(firstChild);
    } else if (typeof props.is === 'string') {
      // $FlowIssue `createElement` should be updated for Web Components
      domElement = ownerDocument.createElement(type, {
        is: props.is
      });
    } else {
      // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
      // See discussion in https://github.com/facebook/react/pull/6896
      // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
      domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
      // attributes on `select`s needs to be added before `option`s are inserted.
      // This prevents:
      // - a bug where the `select` does not scroll to the correct option because singular
      //  `select` elements automatically pick the first item #13222
      // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
      // See https://github.com/facebook/react/issues/13222
      // and https://github.com/facebook/react/issues/14239

      if (type === 'select') {
        var node = domElement;

        if (props.multiple) {
          node.multiple = true;
        } else if (props.size) {
          // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
          // it is possible that no option is selected.
          //
          // This is only necessary when a select in "single selection mode".
          node.size = props.size;
        }
      }
    }
  } else {
    domElement = ownerDocument.createElementNS(namespaceURI, type);
  }

  {
    if (namespaceURI === HTML_NAMESPACE) {
      if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) {
        warnedUnknownTags[type] = true;

        error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
      }
    }
  }

  return domElement;
}
function createTextNode(text, rootContainerElement) {
  return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
}
function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
  var isCustomComponentTag = isCustomComponent(tag, rawProps);

  {
    validatePropertiesInDevelopment(tag, rawProps);
  } // TODO: Make sure that we check isMounted before firing any of these events.


  var props;

  switch (tag) {
    case 'dialog':
      listenToNonDelegatedEvent('cancel', domElement);
      listenToNonDelegatedEvent('close', domElement);
      props = rawProps;
      break;

    case 'iframe':
    case 'object':
    case 'embed':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the load event.
      listenToNonDelegatedEvent('load', domElement);
      props = rawProps;
      break;

    case 'video':
    case 'audio':
      // We listen to these events in case to ensure emulated bubble
      // listeners still fire for all the media events.
      for (var i = 0; i < mediaEventTypes.length; i++) {
        listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
      }

      props = rawProps;
      break;

    case 'source':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the error event.
      listenToNonDelegatedEvent('error', domElement);
      props = rawProps;
      break;

    case 'img':
    case 'image':
    case 'link':
      // We listen to these events in case to ensure emulated bubble
      // listeners still fire for error and load events.
      listenToNonDelegatedEvent('error', domElement);
      listenToNonDelegatedEvent('load', domElement);
      props = rawProps;
      break;

    case 'details':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the toggle event.
      listenToNonDelegatedEvent('toggle', domElement);
      props = rawProps;
      break;

    case 'input':
      initWrapperState(domElement, rawProps);
      props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;

    case 'option':
      validateProps(domElement, rawProps);
      props = rawProps;
      break;

    case 'select':
      initWrapperState$1(domElement, rawProps);
      props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;

    case 'textarea':
      initWrapperState$2(domElement, rawProps);
      props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;

    default:
      props = rawProps;
  }

  assertValidProps(tag, props);
  setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);

  switch (tag) {
    case 'input':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper(domElement, rawProps, false);
      break;

    case 'textarea':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper$3(domElement);
      break;

    case 'option':
      postMountWrapper$1(domElement, rawProps);
      break;

    case 'select':
      postMountWrapper$2(domElement, rawProps);
      break;

    default:
      if (typeof props.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }

      break;
  }
} // Calculate the diff between the two objects.

function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
  {
    validatePropertiesInDevelopment(tag, nextRawProps);
  }

  var updatePayload = null;
  var lastProps;
  var nextProps;

  switch (tag) {
    case 'input':
      lastProps = getHostProps(domElement, lastRawProps);
      nextProps = getHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;

    case 'select':
      lastProps = getHostProps$1(domElement, lastRawProps);
      nextProps = getHostProps$1(domElement, nextRawProps);
      updatePayload = [];
      break;

    case 'textarea':
      lastProps = getHostProps$2(domElement, lastRawProps);
      nextProps = getHostProps$2(domElement, nextRawProps);
      updatePayload = [];
      break;

    default:
      lastProps = lastRawProps;
      nextProps = nextRawProps;

      if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }

      break;
  }

  assertValidProps(tag, nextProps);
  var propKey;
  var styleName;
  var styleUpdates = null;

  for (propKey in lastProps) {
    if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
      continue;
    }

    if (propKey === STYLE) {
      var lastStyle = lastProps[propKey];

      for (styleName in lastStyle) {
        if (lastStyle.hasOwnProperty(styleName)) {
          if (!styleUpdates) {
            styleUpdates = {};
          }

          styleUpdates[styleName] = '';
        }
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
      // This is a special case. If any listener updates we need to ensure
      // that the "current" fiber pointer gets updated so we need a commit
      // to update this element.
      if (!updatePayload) {
        updatePayload = [];
      }
    } else {
      // For all other deleted properties we add it to the queue. We use
      // the allowed property list in the commit phase instead.
      (updatePayload = updatePayload || []).push(propKey, null);
    }
  }

  for (propKey in nextProps) {
    var nextProp = nextProps[propKey];
    var lastProp = lastProps != null ? lastProps[propKey] : undefined;

    if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
      continue;
    }

    if (propKey === STYLE) {
      {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      }

      if (lastProp) {
        // Unset styles on `lastProp` but not on `nextProp`.
        for (styleName in lastProp) {
          if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
            if (!styleUpdates) {
              styleUpdates = {};
            }

            styleUpdates[styleName] = '';
          }
        } // Update styles that changed since `lastProp`.


        for (styleName in nextProp) {
          if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
            if (!styleUpdates) {
              styleUpdates = {};
            }

            styleUpdates[styleName] = nextProp[styleName];
          }
        }
      } else {
        // Relies on `updateStylesByID` not mutating `styleUpdates`.
        if (!styleUpdates) {
          if (!updatePayload) {
            updatePayload = [];
          }

          updatePayload.push(propKey, styleUpdates);
        }

        styleUpdates = nextProp;
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
      var lastHtml = lastProp ? lastProp[HTML$1] : undefined;

      if (nextHtml != null) {
        if (lastHtml !== nextHtml) {
          (updatePayload = updatePayload || []).push(propKey, nextHtml);
        }
      }
    } else if (propKey === CHILDREN) {
      if (typeof nextProp === 'string' || typeof nextProp === 'number') {
        (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
      }
    } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        // We eagerly listen to this even though we haven't committed yet.
        if ( typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }

        if (propKey === 'onScroll') {
          listenToNonDelegatedEvent('scroll', domElement);
        }
      }

      if (!updatePayload && lastProp !== nextProp) {
        // This is a special case. If any listener updates we need to ensure
        // that the "current" props pointer gets updated so we need a commit
        // to update this element.
        updatePayload = [];
      }
    } else {
      // For any other property we always add it to the queue and then we
      // filter it out using the allowed property list during the commit.
      (updatePayload = updatePayload || []).push(propKey, nextProp);
    }
  }

  if (styleUpdates) {
    {
      validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
    }

    (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
  }

  return updatePayload;
} // Apply the diff.

function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
  // Update checked *before* name.
  // In the middle of an update, it is possible to have multiple checked.
  // When a checked radio tries to change name, browser makes another radio's checked false.
  if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
    updateChecked(domElement, nextRawProps);
  }

  var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
  var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.

  updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
  // changed.

  switch (tag) {
    case 'input':
      // Update the wrapper around inputs *after* updating props. This has to
      // happen after `updateDOMProperties`. Otherwise HTML5 input validations
      // raise warnings and prevent the new value from being assigned.
      updateWrapper(domElement, nextRawProps);
      break;

    case 'textarea':
      updateWrapper$1(domElement, nextRawProps);
      break;

    case 'select':
      // <select> value update needs to occur after <option> children
      // reconciliation
      postUpdateWrapper(domElement, nextRawProps);
      break;
  }
}

function getPossibleStandardName(propName) {
  {
    var lowerCasedName = propName.toLowerCase();

    if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
      return null;
    }

    return possibleStandardNames[lowerCasedName] || null;
  }
}

function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
  var isCustomComponentTag;
  var extraAttributeNames;

  {
    isCustomComponentTag = isCustomComponent(tag, rawProps);
    validatePropertiesInDevelopment(tag, rawProps);
  } // TODO: Make sure that we check isMounted before firing any of these events.


  switch (tag) {
    case 'dialog':
      listenToNonDelegatedEvent('cancel', domElement);
      listenToNonDelegatedEvent('close', domElement);
      break;

    case 'iframe':
    case 'object':
    case 'embed':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the load event.
      listenToNonDelegatedEvent('load', domElement);
      break;

    case 'video':
    case 'audio':
      // We listen to these events in case to ensure emulated bubble
      // listeners still fire for all the media events.
      for (var i = 0; i < mediaEventTypes.length; i++) {
        listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
      }

      break;

    case 'source':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the error event.
      listenToNonDelegatedEvent('error', domElement);
      break;

    case 'img':
    case 'image':
    case 'link':
      // We listen to these events in case to ensure emulated bubble
      // listeners still fire for error and load events.
      listenToNonDelegatedEvent('error', domElement);
      listenToNonDelegatedEvent('load', domElement);
      break;

    case 'details':
      // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the toggle event.
      listenToNonDelegatedEvent('toggle', domElement);
      break;

    case 'input':
      initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;

    case 'option':
      validateProps(domElement, rawProps);
      break;

    case 'select':
      initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;

    case 'textarea':
      initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
      // listeners still fire for the invalid event.

      listenToNonDelegatedEvent('invalid', domElement);
      break;
  }

  assertValidProps(tag, rawProps);

  {
    extraAttributeNames = new Set();
    var attributes = domElement.attributes;

    for (var _i = 0; _i < attributes.length; _i++) {
      var name = attributes[_i].name.toLowerCase();

      switch (name) {
        // Controlled attributes are not validated
        // TODO: Only ignore them on controlled tags.
        case 'value':
          break;

        case 'checked':
          break;

        case 'selected':
          break;

        default:
          // Intentionally use the original name.
          // See discussion in https://github.com/facebook/react/pull/10676.
          extraAttributeNames.add(attributes[_i].name);
      }
    }
  }

  var updatePayload = null;

  for (var propKey in rawProps) {
    if (!rawProps.hasOwnProperty(propKey)) {
      continue;
    }

    var nextProp = rawProps[propKey];

    if (propKey === CHILDREN) {
      // For text content children we compare against textContent. This
      // might match additional HTML that is hidden when we read it using
      // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
      // satisfies our requirement. Our requirement is not to produce perfect
      // HTML and attributes. Ideally we should preserve structure but it's
      // ok not to if the visible content is still enough to indicate what
      // even listeners these nodes might be wired up to.
      // TODO: Warn if there is more than a single textNode as a child.
      // TODO: Should we use domElement.firstChild.nodeValue to compare?
      if (typeof nextProp === 'string') {
        if (domElement.textContent !== nextProp) {
          if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
            checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
          }

          updatePayload = [CHILDREN, nextProp];
        }
      } else if (typeof nextProp === 'number') {
        if (domElement.textContent !== '' + nextProp) {
          if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
            checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
          }

          updatePayload = [CHILDREN, '' + nextProp];
        }
      }
    } else if (registrationNameDependencies.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        if ( typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }

        if (propKey === 'onScroll') {
          listenToNonDelegatedEvent('scroll', domElement);
        }
      }
    } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
    typeof isCustomComponentTag === 'boolean') {
      // Validate that the properties correspond to their expected values.
      var serverValue = void 0;
      var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey);

      if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
      // TODO: Only ignore them on controlled tags.
      propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
        var serverHTML = domElement.innerHTML;
        var nextHtml = nextProp ? nextProp[HTML$1] : undefined;

        if (nextHtml != null) {
          var expectedHTML = normalizeHTML(domElement, nextHtml);

          if (expectedHTML !== serverHTML) {
            warnForPropDifference(propKey, serverHTML, expectedHTML);
          }
        }
      } else if (propKey === STYLE) {
        // $FlowFixMe - Should be inferred as not undefined.
        extraAttributeNames.delete(propKey);

        if (canDiffStyleForHydrationWarning) {
          var expectedStyle = createDangerousStringForStyles(nextProp);
          serverValue = domElement.getAttribute('style');

          if (expectedStyle !== serverValue) {
            warnForPropDifference(propKey, serverValue, expectedStyle);
          }
        }
      } else if (isCustomComponentTag && !enableCustomElementPropertySupport) {
        // $FlowFixMe - Should be inferred as not undefined.
        extraAttributeNames.delete(propKey.toLowerCase());
        serverValue = getValueForAttribute(domElement, propKey, nextProp);

        if (nextProp !== serverValue) {
          warnForPropDifference(propKey, serverValue, nextProp);
        }
      } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
        var isMismatchDueToBadCasing = false;

        if (propertyInfo !== null) {
          // $FlowFixMe - Should be inferred as not undefined.
          extraAttributeNames.delete(propertyInfo.attributeName);
          serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
        } else {
          var ownNamespace = parentNamespace;

          if (ownNamespace === HTML_NAMESPACE) {
            ownNamespace = getIntrinsicNamespace(tag);
          }

          if (ownNamespace === HTML_NAMESPACE) {
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propKey.toLowerCase());
          } else {
            var standardName = getPossibleStandardName(propKey);

            if (standardName !== null && standardName !== propKey) {
              // If an SVG prop is supplied with bad casing, it will
              // be successfully parsed from HTML, but will produce a mismatch
              // (and would be incorrectly rendered on the client).
              // However, we already warn about bad casing elsewhere.
              // So we'll skip the misleading extra mismatch warning in this case.
              isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.

              extraAttributeNames.delete(standardName);
            } // $FlowFixMe - Should be inferred as not undefined.


            extraAttributeNames.delete(propKey);
          }

          serverValue = getValueForAttribute(domElement, propKey, nextProp);
        }

        var dontWarnCustomElement = enableCustomElementPropertySupport  ;

        if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
          warnForPropDifference(propKey, serverValue, nextProp);
        }
      }
    }
  }

  {
    if (shouldWarnDev) {
      if ( // $FlowFixMe - Should be inferred as not undefined.
      extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
        // $FlowFixMe - Should be inferred as not undefined.
        warnForExtraAttributes(extraAttributeNames);
      }
    }
  }

  switch (tag) {
    case 'input':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper(domElement, rawProps, true);
      break;

    case 'textarea':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track(domElement);
      postMountWrapper$3(domElement);
      break;

    case 'select':
    case 'option':
      // For input and textarea we current always set the value property at
      // post mount to force it to diverge from attributes. However, for
      // option and select we don't quite do the same thing and select
      // is not resilient to the DOM state changing so we don't do that here.
      // TODO: Consider not doing this for input and textarea.
      break;

    default:
      if (typeof rawProps.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(domElement);
      }

      break;
  }

  return updatePayload;
}
function diffHydratedText(textNode, text, isConcurrentMode) {
  var isDifferent = textNode.nodeValue !== text;
  return isDifferent;
}
function warnForDeletedHydratableElement(parentNode, child) {
  {
    if (didWarnInvalidHydration) {
      return;
    }

    didWarnInvalidHydration = true;

    error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
  }
}
function warnForDeletedHydratableText(parentNode, child) {
  {
    if (didWarnInvalidHydration) {
      return;
    }

    didWarnInvalidHydration = true;

    error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
  }
}
function warnForInsertedHydratedElement(parentNode, tag, props) {
  {
    if (didWarnInvalidHydration) {
      return;
    }

    didWarnInvalidHydration = true;

    error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
  }
}
function warnForInsertedHydratedText(parentNode, text) {
  {
    if (text === '') {
      // We expect to insert empty text nodes since they're not represented in
      // the HTML.
      // TODO: Remove this special case if we can just avoid inserting empty
      // text nodes.
      return;
    }

    if (didWarnInvalidHydration) {
      return;
    }

    didWarnInvalidHydration = true;

    error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
  }
}
function restoreControlledState$3(domElement, tag, props) {
  switch (tag) {
    case 'input':
      restoreControlledState(domElement, props);
      return;

    case 'textarea':
      restoreControlledState$2(domElement, props);
      return;

    case 'select':
      restoreControlledState$1(domElement, props);
      return;
  }
}

var validateDOMNesting = function () {};

var updatedAncestorInfo = function () {};

{
  // This validation code was written based on the HTML5 parsing spec:
  // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
  //
  // Note: this does not catch all invalid nesting, nor does it try to (as it's
  // not clear what practical benefit doing so provides); instead, we warn only
  // for cases where the parser will give a parse tree differing from what React
  // intended. For example, <b><div></div></b> is invalid but we don't warn
  // because it still parses correctly; we do warn for other cases like nested
  // <p> tags where the beginning of the second element implicitly closes the
  // first, causing a confusing mess.
  // https://html.spec.whatwg.org/multipage/syntax.html#special
  var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope

  var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
  // TODO: Distinguish by namespace here -- for <title>, including it here
  // errs on the side of fewer warnings
  'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope

  var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags

  var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
  var emptyAncestorInfo = {
    current: null,
    formTag: null,
    aTagInScope: null,
    buttonTagInScope: null,
    nobrTagInScope: null,
    pTagInButtonScope: null,
    listItemTagAutoclosing: null,
    dlItemTagAutoclosing: null
  };

  updatedAncestorInfo = function (oldInfo, tag) {
    var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);

    var info = {
      tag: tag
    };

    if (inScopeTags.indexOf(tag) !== -1) {
      ancestorInfo.aTagInScope = null;
      ancestorInfo.buttonTagInScope = null;
      ancestorInfo.nobrTagInScope = null;
    }

    if (buttonScopeTags.indexOf(tag) !== -1) {
      ancestorInfo.pTagInButtonScope = null;
    } // See rules for 'li', 'dd', 'dt' start tags in
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


    if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
      ancestorInfo.listItemTagAutoclosing = null;
      ancestorInfo.dlItemTagAutoclosing = null;
    }

    ancestorInfo.current = info;

    if (tag === 'form') {
      ancestorInfo.formTag = info;
    }

    if (tag === 'a') {
      ancestorInfo.aTagInScope = info;
    }

    if (tag === 'button') {
      ancestorInfo.buttonTagInScope = info;
    }

    if (tag === 'nobr') {
      ancestorInfo.nobrTagInScope = info;
    }

    if (tag === 'p') {
      ancestorInfo.pTagInButtonScope = info;
    }

    if (tag === 'li') {
      ancestorInfo.listItemTagAutoclosing = info;
    }

    if (tag === 'dd' || tag === 'dt') {
      ancestorInfo.dlItemTagAutoclosing = info;
    }

    return ancestorInfo;
  };
  /**
   * Returns whether
   */


  var isTagValidWithParent = function (tag, parentTag) {
    // First, let's check if we're in an unusual parsing mode...
    switch (parentTag) {
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
      case 'select':
        return tag === 'option' || tag === 'optgroup' || tag === '#text';

      case 'optgroup':
        return tag === 'option' || tag === '#text';
      // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
      // but

      case 'option':
        return tag === '#text';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
      // No special behavior since these rules fall back to "in body" mode for
      // all except special table nodes which cause bad parsing behavior anyway.
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr

      case 'tr':
        return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody

      case 'tbody':
      case 'thead':
      case 'tfoot':
        return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup

      case 'colgroup':
        return tag === 'col' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable

      case 'table':
        return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead

      case 'head':
        return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
      // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element

      case 'html':
        return tag === 'head' || tag === 'body' || tag === 'frameset';

      case 'frameset':
        return tag === 'frame';

      case '#document':
        return tag === 'html';
    } // Probably in the "in body" parsing mode, so we outlaw only tag combos
    // where the parsing rules cause implicit opens or closes to be added.
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


    switch (tag) {
      case 'h1':
      case 'h2':
      case 'h3':
      case 'h4':
      case 'h5':
      case 'h6':
        return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';

      case 'rp':
      case 'rt':
        return impliedEndTags.indexOf(parentTag) === -1;

      case 'body':
      case 'caption':
      case 'col':
      case 'colgroup':
      case 'frameset':
      case 'frame':
      case 'head':
      case 'html':
      case 'tbody':
      case 'td':
      case 'tfoot':
      case 'th':
      case 'thead':
      case 'tr':
        // These tags are only valid with a few parents that have special child
        // parsing rules -- if we're down here, then none of those matched and
        // so we allow it only if we don't know what the parent is, as all other
        // cases are invalid.
        return parentTag == null;
    }

    return true;
  };
  /**
   * Returns whether
   */


  var findInvalidAncestorForTag = function (tag, ancestorInfo) {
    switch (tag) {
      case 'address':
      case 'article':
      case 'aside':
      case 'blockquote':
      case 'center':
      case 'details':
      case 'dialog':
      case 'dir':
      case 'div':
      case 'dl':
      case 'fieldset':
      case 'figcaption':
      case 'figure':
      case 'footer':
      case 'header':
      case 'hgroup':
      case 'main':
      case 'menu':
      case 'nav':
      case 'ol':
      case 'p':
      case 'section':
      case 'summary':
      case 'ul':
      case 'pre':
      case 'listing':
      case 'table':
      case 'hr':
      case 'xmp':
      case 'h1':
      case 'h2':
      case 'h3':
      case 'h4':
      case 'h5':
      case 'h6':
        return ancestorInfo.pTagInButtonScope;

      case 'form':
        return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;

      case 'li':
        return ancestorInfo.listItemTagAutoclosing;

      case 'dd':
      case 'dt':
        return ancestorInfo.dlItemTagAutoclosing;

      case 'button':
        return ancestorInfo.buttonTagInScope;

      case 'a':
        // Spec says something about storing a list of markers, but it sounds
        // equivalent to this check.
        return ancestorInfo.aTagInScope;

      case 'nobr':
        return ancestorInfo.nobrTagInScope;
    }

    return null;
  };

  var didWarn$1 = {};

  validateDOMNesting = function (childTag, childText, ancestorInfo) {
    ancestorInfo = ancestorInfo || emptyAncestorInfo;
    var parentInfo = ancestorInfo.current;
    var parentTag = parentInfo && parentInfo.tag;

    if (childText != null) {
      if (childTag != null) {
        error('validateDOMNesting: when childText is passed, childTag should be null');
      }

      childTag = '#text';
    }

    var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
    var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
    var invalidParentOrAncestor = invalidParent || invalidAncestor;

    if (!invalidParentOrAncestor) {
      return;
    }

    var ancestorTag = invalidParentOrAncestor.tag;
    var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag;

    if (didWarn$1[warnKey]) {
      return;
    }

    didWarn$1[warnKey] = true;
    var tagDisplayName = childTag;
    var whitespaceInfo = '';

    if (childTag === '#text') {
      if (/\S/.test(childText)) {
        tagDisplayName = 'Text nodes';
      } else {
        tagDisplayName = 'Whitespace text nodes';
        whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
      }
    } else {
      tagDisplayName = '<' + childTag + '>';
    }

    if (invalidParent) {
      var info = '';

      if (ancestorTag === 'table' && childTag === 'tr') {
        info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
      }

      error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
    } else {
      error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
    }
  };
}

var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
var SUSPENSE_START_DATA = '$';
var SUSPENSE_END_DATA = '/$';
var SUSPENSE_PENDING_START_DATA = '$?';
var SUSPENSE_FALLBACK_START_DATA = '$!';
var STYLE$1 = 'style';
var eventsEnabled = null;
var selectionInformation = null;
function getRootHostContext(rootContainerInstance) {
  var type;
  var namespace;
  var nodeType = rootContainerInstance.nodeType;

  switch (nodeType) {
    case DOCUMENT_NODE:
    case DOCUMENT_FRAGMENT_NODE:
      {
        type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
        var root = rootContainerInstance.documentElement;
        namespace = root ? root.namespaceURI : getChildNamespace(null, '');
        break;
      }

    default:
      {
        var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
        var ownNamespace = container.namespaceURI || null;
        type = container.tagName;
        namespace = getChildNamespace(ownNamespace, type);
        break;
      }
  }

  {
    var validatedTag = type.toLowerCase();
    var ancestorInfo = updatedAncestorInfo(null, validatedTag);
    return {
      namespace: namespace,
      ancestorInfo: ancestorInfo
    };
  }
}
function getChildHostContext(parentHostContext, type, rootContainerInstance) {
  {
    var parentHostContextDev = parentHostContext;
    var namespace = getChildNamespace(parentHostContextDev.namespace, type);
    var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
    return {
      namespace: namespace,
      ancestorInfo: ancestorInfo
    };
  }
}
function getPublicInstance(instance) {
  return instance;
}
function prepareForCommit(containerInfo) {
  eventsEnabled = isEnabled();
  selectionInformation = getSelectionInformation();
  var activeInstance = null;

  setEnabled(false);
  return activeInstance;
}
function resetAfterCommit(containerInfo) {
  restoreSelection(selectionInformation);
  setEnabled(eventsEnabled);
  eventsEnabled = null;
  selectionInformation = null;
}
function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
  var parentNamespace;

  {
    // TODO: take namespace into account when validating.
    var hostContextDev = hostContext;
    validateDOMNesting(type, null, hostContextDev.ancestorInfo);

    if (typeof props.children === 'string' || typeof props.children === 'number') {
      var string = '' + props.children;
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
      validateDOMNesting(null, string, ownAncestorInfo);
    }

    parentNamespace = hostContextDev.namespace;
  }

  var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
  precacheFiberNode(internalInstanceHandle, domElement);
  updateFiberProps(domElement, props);
  return domElement;
}
function appendInitialChild(parentInstance, child) {
  parentInstance.appendChild(child);
}
function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
  setInitialProperties(domElement, type, props, rootContainerInstance);

  switch (type) {
    case 'button':
    case 'input':
    case 'select':
    case 'textarea':
      return !!props.autoFocus;

    case 'img':
      return true;

    default:
      return false;
  }
}
function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
  {
    var hostContextDev = hostContext;

    if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
      var string = '' + newProps.children;
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
      validateDOMNesting(null, string, ownAncestorInfo);
    }
  }

  return diffProperties(domElement, type, oldProps, newProps);
}
function shouldSetTextContent(type, props) {
  return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
}
function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
  {
    var hostContextDev = hostContext;
    validateDOMNesting(null, text, hostContextDev.ancestorInfo);
  }

  var textNode = createTextNode(text, rootContainerInstance);
  precacheFiberNode(internalInstanceHandle, textNode);
  return textNode;
}
function getCurrentEventPriority() {
  var currentEvent = window.event;

  if (currentEvent === undefined) {
    return DefaultEventPriority;
  }

  return getEventPriority(currentEvent.type);
}
// if a component just imports ReactDOM (e.g. for findDOMNode).
// Some environments might not have setTimeout or clearTimeout.

var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
var noTimeout = -1;
var localPromise = typeof Promise === 'function' ? Promise : undefined; // -------------------
var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) {
  return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
} : scheduleTimeout; // TODO: Determine the best fallback here.

function handleErrorInNextTick(error) {
  setTimeout(function () {
    throw error;
  });
} // -------------------
function commitMount(domElement, type, newProps, internalInstanceHandle) {
  // Despite the naming that might imply otherwise, this method only
  // fires if there is an `Update` effect scheduled during mounting.
  // This happens if `finalizeInitialChildren` returns `true` (which it
  // does to implement the `autoFocus` attribute on the client). But
  // there are also other cases when this might happen (such as patching
  // up text content during hydration mismatch). So we'll check this again.
  switch (type) {
    case 'button':
    case 'input':
    case 'select':
    case 'textarea':
      if (newProps.autoFocus) {
        domElement.focus();
      }

      return;

    case 'img':
      {
        if (newProps.src) {
          domElement.src = newProps.src;
        }

        return;
      }
  }
}
function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
  // Apply the diff to the DOM node.
  updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with
  // with current event handlers.

  updateFiberProps(domElement, newProps);
}
function resetTextContent(domElement) {
  setTextContent(domElement, '');
}
function commitTextUpdate(textInstance, oldText, newText) {
  textInstance.nodeValue = newText;
}
function appendChild(parentInstance, child) {
  parentInstance.appendChild(child);
}
function appendChildToContainer(container, child) {
  var parentNode;

  if (container.nodeType === COMMENT_NODE) {
    parentNode = container.parentNode;
    parentNode.insertBefore(child, container);
  } else {
    parentNode = container;
    parentNode.appendChild(child);
  } // This container might be used for a portal.
  // If something inside a portal is clicked, that click should bubble
  // through the React tree. However, on Mobile Safari the click would
  // never bubble through the *DOM* tree unless an ancestor with onclick
  // event exists. So we wouldn't see it and dispatch it.
  // This is why we ensure that non React root containers have inline onclick
  // defined.
  // https://github.com/facebook/react/issues/11918


  var reactRootContainer = container._reactRootContainer;

  if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
    // TODO: This cast may not be sound for SVG, MathML or custom elements.
    trapClickOnNonInteractiveElement(parentNode);
  }
}
function insertBefore(parentInstance, child, beforeChild) {
  parentInstance.insertBefore(child, beforeChild);
}
function insertInContainerBefore(container, child, beforeChild) {
  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.insertBefore(child, beforeChild);
  } else {
    container.insertBefore(child, beforeChild);
  }
}

function removeChild(parentInstance, child) {
  parentInstance.removeChild(child);
}
function removeChildFromContainer(container, child) {
  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.removeChild(child);
  } else {
    container.removeChild(child);
  }
}
function clearSuspenseBoundary(parentInstance, suspenseInstance) {
  var node = suspenseInstance; // Delete all nodes within this suspense boundary.
  // There might be nested nodes so we need to keep track of how
  // deep we are and only break out when we're back on top.

  var depth = 0;

  do {
    var nextNode = node.nextSibling;
    parentInstance.removeChild(node);

    if (nextNode && nextNode.nodeType === COMMENT_NODE) {
      var data = nextNode.data;

      if (data === SUSPENSE_END_DATA) {
        if (depth === 0) {
          parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.

          retryIfBlockedOn(suspenseInstance);
          return;
        } else {
          depth--;
        }
      } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
        depth++;
      }
    }

    node = nextNode;
  } while (node); // TODO: Warn, we didn't find the end comment boundary.
  // Retry if any event replaying was blocked on this.


  retryIfBlockedOn(suspenseInstance);
}
function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
  if (container.nodeType === COMMENT_NODE) {
    clearSuspenseBoundary(container.parentNode, suspenseInstance);
  } else if (container.nodeType === ELEMENT_NODE) {
    clearSuspenseBoundary(container, suspenseInstance);
  } // Retry if any event replaying was blocked on this.


  retryIfBlockedOn(container);
}
function hideInstance(instance) {
  // TODO: Does this work for all element types? What about MathML? Should we
  // pass host context to this method?
  instance = instance;
  var style = instance.style;

  if (typeof style.setProperty === 'function') {
    style.setProperty('display', 'none', 'important');
  } else {
    style.display = 'none';
  }
}
function hideTextInstance(textInstance) {
  textInstance.nodeValue = '';
}
function unhideInstance(instance, props) {
  instance = instance;
  var styleProp = props[STYLE$1];
  var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
  instance.style.display = dangerousStyleValue('display', display);
}
function unhideTextInstance(textInstance, text) {
  textInstance.nodeValue = text;
}
function clearContainer(container) {
  if (container.nodeType === ELEMENT_NODE) {
    container.textContent = '';
  } else if (container.nodeType === DOCUMENT_NODE) {
    if (container.documentElement) {
      container.removeChild(container.documentElement);
    }
  }
} // -------------------
function canHydrateInstance(instance, type, props) {
  if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
    return null;
  } // This has now been refined to an element node.


  return instance;
}
function canHydrateTextInstance(instance, text) {
  if (text === '' || instance.nodeType !== TEXT_NODE) {
    // Empty strings are not parsed by HTML so there won't be a correct match here.
    return null;
  } // This has now been refined to a text node.


  return instance;
}
function canHydrateSuspenseInstance(instance) {
  if (instance.nodeType !== COMMENT_NODE) {
    // Empty strings are not parsed by HTML so there won't be a correct match here.
    return null;
  } // This has now been refined to a suspense node.


  return instance;
}
function isSuspenseInstancePending(instance) {
  return instance.data === SUSPENSE_PENDING_START_DATA;
}
function isSuspenseInstanceFallback(instance) {
  return instance.data === SUSPENSE_FALLBACK_START_DATA;
}
function getSuspenseInstanceFallbackErrorDetails(instance) {
  var dataset = instance.nextSibling && instance.nextSibling.dataset;
  var digest, message, stack;

  if (dataset) {
    digest = dataset.dgst;

    {
      message = dataset.msg;
      stack = dataset.stck;
    }
  }

  {
    return {
      message: message,
      digest: digest,
      stack: stack
    };
  } // let value = {message: undefined, hash: undefined};
  // const nextSibling = instance.nextSibling;
  // if (nextSibling) {
  //   const dataset = ((nextSibling: any): HTMLTemplateElement).dataset;
  //   value.message = dataset.msg;
  //   value.hash = dataset.hash;
  //   if (true) {
  //     value.stack = dataset.stack;
  //   }
  // }
  // return value;

}
function registerSuspenseInstanceRetry(instance, callback) {
  instance._reactRetry = callback;
}

function getNextHydratable(node) {
  // Skip non-hydratable nodes.
  for (; node != null; node = node.nextSibling) {
    var nodeType = node.nodeType;

    if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
      break;
    }

    if (nodeType === COMMENT_NODE) {
      var nodeData = node.data;

      if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
        break;
      }

      if (nodeData === SUSPENSE_END_DATA) {
        return null;
      }
    }
  }

  return node;
}

function getNextHydratableSibling(instance) {
  return getNextHydratable(instance.nextSibling);
}
function getFirstHydratableChild(parentInstance) {
  return getNextHydratable(parentInstance.firstChild);
}
function getFirstHydratableChildWithinContainer(parentContainer) {
  return getNextHydratable(parentContainer.firstChild);
}
function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
  return getNextHydratable(parentInstance.nextSibling);
}
function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
  precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
  // get attached.

  updateFiberProps(instance, props);
  var parentNamespace;

  {
    var hostContextDev = hostContext;
    parentNamespace = hostContextDev.namespace;
  } // TODO: Temporary hack to check if we're in a concurrent root. We can delete
  // when the legacy root API is removed.


  var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
  return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
}
function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
  precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete
  // when the legacy root API is removed.

  var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
  return diffHydratedText(textInstance, text);
}
function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
  precacheFiberNode(internalInstanceHandle, suspenseInstance);
}
function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
  var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
  // There might be nested nodes so we need to keep track of how
  // deep we are and only break out when we're back on top.

  var depth = 0;

  while (node) {
    if (node.nodeType === COMMENT_NODE) {
      var data = node.data;

      if (data === SUSPENSE_END_DATA) {
        if (depth === 0) {
          return getNextHydratableSibling(node);
        } else {
          depth--;
        }
      } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
        depth++;
      }
    }

    node = node.nextSibling;
  } // TODO: Warn, we didn't find the end comment boundary.


  return null;
} // Returns the SuspenseInstance if this node is a direct child of a
// SuspenseInstance. I.e. if its previous sibling is a Comment with
// SUSPENSE_x_START_DATA. Otherwise, null.

function getParentSuspenseInstance(targetInstance) {
  var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
  // There might be nested nodes so we need to keep track of how
  // deep we are and only break out when we're back on top.

  var depth = 0;

  while (node) {
    if (node.nodeType === COMMENT_NODE) {
      var data = node.data;

      if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
        if (depth === 0) {
          return node;
        } else {
          depth--;
        }
      } else if (data === SUSPENSE_END_DATA) {
        depth++;
      }
    }

    node = node.previousSibling;
  }

  return null;
}
function commitHydratedContainer(container) {
  // Retry if any event replaying was blocked on this.
  retryIfBlockedOn(container);
}
function commitHydratedSuspenseInstance(suspenseInstance) {
  // Retry if any event replaying was blocked on this.
  retryIfBlockedOn(suspenseInstance);
}
function shouldDeleteUnhydratedTailInstances(parentType) {
  return parentType !== 'head' && parentType !== 'body';
}
function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
  var shouldWarnDev = true;
  checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
}
function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
  if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
    var shouldWarnDev = true;
    checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
  }
}
function didNotHydrateInstanceWithinContainer(parentContainer, instance) {
  {
    if (instance.nodeType === ELEMENT_NODE) {
      warnForDeletedHydratableElement(parentContainer, instance);
    } else if (instance.nodeType === COMMENT_NODE) ; else {
      warnForDeletedHydratableText(parentContainer, instance);
    }
  }
}
function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) {
  {
    // $FlowFixMe: Only Element or Document can be parent nodes.
    var parentNode = parentInstance.parentNode;

    if (parentNode !== null) {
      if (instance.nodeType === ELEMENT_NODE) {
        warnForDeletedHydratableElement(parentNode, instance);
      } else if (instance.nodeType === COMMENT_NODE) ; else {
        warnForDeletedHydratableText(parentNode, instance);
      }
    }
  }
}
function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) {
  {
    if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
      if (instance.nodeType === ELEMENT_NODE) {
        warnForDeletedHydratableElement(parentInstance, instance);
      } else if (instance.nodeType === COMMENT_NODE) ; else {
        warnForDeletedHydratableText(parentInstance, instance);
      }
    }
  }
}
function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) {
  {
    warnForInsertedHydratedElement(parentContainer, type);
  }
}
function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
  {
    warnForInsertedHydratedText(parentContainer, text);
  }
}
function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) {
  {
    // $FlowFixMe: Only Element or Document can be parent nodes.
    var parentNode = parentInstance.parentNode;
    if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type);
  }
}
function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
  {
    // $FlowFixMe: Only Element or Document can be parent nodes.
    var parentNode = parentInstance.parentNode;
    if (parentNode !== null) warnForInsertedHydratedText(parentNode, text);
  }
}
function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) {
  {
    if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
      warnForInsertedHydratedElement(parentInstance, type);
    }
  }
}
function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
  {
    if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
      warnForInsertedHydratedText(parentInstance, text);
    }
  }
}
function errorHydratingContainer(parentContainer) {
  {
    // TODO: This gets logged by onRecoverableError, too, so we should be
    // able to remove it.
    error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase());
  }
}
function preparePortalMount(portalInstance) {
  listenToAllSupportedEvents(portalInstance);
}

var randomKey = Math.random().toString(36).slice(2);
var internalInstanceKey = '__reactFiber$' + randomKey;
var internalPropsKey = '__reactProps$' + randomKey;
var internalContainerInstanceKey = '__reactContainer$' + randomKey;
var internalEventHandlersKey = '__reactEvents$' + randomKey;
var internalEventHandlerListenersKey = '__reactListeners$' + randomKey;
var internalEventHandlesSetKey = '__reactHandles$' + randomKey;
function detachDeletedInstance(node) {
  // TODO: This function is only called on host components. I don't think all of
  // these fields are relevant.
  delete node[internalInstanceKey];
  delete node[internalPropsKey];
  delete node[internalEventHandlersKey];
  delete node[internalEventHandlerListenersKey];
  delete node[internalEventHandlesSetKey];
}
function precacheFiberNode(hostInst, node) {
  node[internalInstanceKey] = hostInst;
}
function markContainerAsRoot(hostRoot, node) {
  node[internalContainerInstanceKey] = hostRoot;
}
function unmarkContainerAsRoot(node) {
  node[internalContainerInstanceKey] = null;
}
function isContainerMarkedAsRoot(node) {
  return !!node[internalContainerInstanceKey];
} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
// If the target node is part of a hydrated or not yet rendered subtree, then
// this may also return a SuspenseComponent or HostRoot to indicate that.
// Conceptually the HostRoot fiber is a child of the Container node. So if you
// pass the Container node as the targetNode, you will not actually get the
// HostRoot back. To get to the HostRoot, you need to pass a child of it.
// The same thing applies to Suspense boundaries.

function getClosestInstanceFromNode(targetNode) {
  var targetInst = targetNode[internalInstanceKey];

  if (targetInst) {
    // Don't return HostRoot or SuspenseComponent here.
    return targetInst;
  } // If the direct event target isn't a React owned DOM node, we need to look
  // to see if one of its parents is a React owned DOM node.


  var parentNode = targetNode.parentNode;

  while (parentNode) {
    // We'll check if this is a container root that could include
    // React nodes in the future. We need to check this first because
    // if we're a child of a dehydrated container, we need to first
    // find that inner container before moving on to finding the parent
    // instance. Note that we don't check this field on  the targetNode
    // itself because the fibers are conceptually between the container
    // node and the first child. It isn't surrounding the container node.
    // If it's not a container, we check if it's an instance.
    targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];

    if (targetInst) {
      // Since this wasn't the direct target of the event, we might have
      // stepped past dehydrated DOM nodes to get here. However they could
      // also have been non-React nodes. We need to answer which one.
      // If we the instance doesn't have any children, then there can't be
      // a nested suspense boundary within it. So we can use this as a fast
      // bailout. Most of the time, when people add non-React children to
      // the tree, it is using a ref to a child-less DOM node.
      // Normally we'd only need to check one of the fibers because if it
      // has ever gone from having children to deleting them or vice versa
      // it would have deleted the dehydrated boundary nested inside already.
      // However, since the HostRoot starts out with an alternate it might
      // have one on the alternate so we need to check in case this was a
      // root.
      var alternate = targetInst.alternate;

      if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
        // Next we need to figure out if the node that skipped past is
        // nested within a dehydrated boundary and if so, which one.
        var suspenseInstance = getParentSuspenseInstance(targetNode);

        while (suspenseInstance !== null) {
          // We found a suspense instance. That means that we haven't
          // hydrated it yet. Even though we leave the comments in the
          // DOM after hydrating, and there are boundaries in the DOM
          // that could already be hydrated, we wouldn't have found them
          // through this pass since if the target is hydrated it would
          // have had an internalInstanceKey on it.
          // Let's get the fiber associated with the SuspenseComponent
          // as the deepest instance.
          var targetSuspenseInst = suspenseInstance[internalInstanceKey];

          if (targetSuspenseInst) {
            return targetSuspenseInst;
          } // If we don't find a Fiber on the comment, it might be because
          // we haven't gotten to hydrate it yet. There might still be a
          // parent boundary that hasn't above this one so we need to find
          // the outer most that is known.


          suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
          // host component also hasn't hydrated yet. We can return it
          // below since it will bail out on the isMounted check later.
        }
      }

      return targetInst;
    }

    targetNode = parentNode;
    parentNode = targetNode.parentNode;
  }

  return null;
}
/**
 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
 * instance, or null if the node was not rendered by this React.
 */

function getInstanceFromNode(node) {
  var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];

  if (inst) {
    if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
      return inst;
    } else {
      return null;
    }
  }

  return null;
}
/**
 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
 * DOM node.
 */

function getNodeFromInstance(inst) {
  if (inst.tag === HostComponent || inst.tag === HostText) {
    // In Fiber this, is just the state node right now. We assume it will be
    // a host component or host text.
    return inst.stateNode;
  } // Without this first invariant, passing a non-DOM-component triggers the next
  // invariant for a missing parent, which is super confusing.


  throw new Error('getNodeFromInstance: Invalid argument.');
}
function getFiberCurrentPropsFromNode(node) {
  return node[internalPropsKey] || null;
}
function updateFiberProps(node, props) {
  node[internalPropsKey] = props;
}
function getEventListenerSet(node) {
  var elementListenerSet = node[internalEventHandlersKey];

  if (elementListenerSet === undefined) {
    elementListenerSet = node[internalEventHandlersKey] = new Set();
  }

  return elementListenerSet;
}

var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

function setCurrentlyValidatingElement(element) {
  {
    if (element) {
      var owner = element._owner;
      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
      ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
    } else {
      ReactDebugCurrentFrame$1.setExtraStackFrame(null);
    }
  }
}

function checkPropTypes(typeSpecs, values, location, componentName, element) {
  {
    // $FlowFixMe This is okay but Flow doesn't know it.
    var has = Function.call.bind(hasOwnProperty);

    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            // eslint-disable-next-line react-internal/prod-error-codes
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
        } catch (ex) {
          error$1 = ex;
        }

        if (error$1 && !(error$1 instanceof Error)) {
          setCurrentlyValidatingElement(element);

          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);

          setCurrentlyValidatingElement(null);
        }

        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error$1.message] = true;
          setCurrentlyValidatingElement(element);

          error('Failed %s type: %s', location, error$1.message);

          setCurrentlyValidatingElement(null);
        }
      }
    }
  }
}

var valueStack = [];
var fiberStack;

{
  fiberStack = [];
}

var index = -1;

function createCursor(defaultValue) {
  return {
    current: defaultValue
  };
}

function pop(cursor, fiber) {
  if (index < 0) {
    {
      error('Unexpected pop.');
    }

    return;
  }

  {
    if (fiber !== fiberStack[index]) {
      error('Unexpected Fiber popped.');
    }
  }

  cursor.current = valueStack[index];
  valueStack[index] = null;

  {
    fiberStack[index] = null;
  }

  index--;
}

function push(cursor, value, fiber) {
  index++;
  valueStack[index] = cursor.current;

  {
    fiberStack[index] = fiber;
  }

  cursor.current = value;
}

var warnedAboutMissingGetChildContext;

{
  warnedAboutMissingGetChildContext = {};
}

var emptyContextObject = {};

{
  Object.freeze(emptyContextObject);
} // A cursor to the current merged context object on the stack.


var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.

var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.

var previousContext = emptyContextObject;

function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
  {
    if (didPushOwnContextIfProvider && isContextProvider(Component)) {
      // If the fiber is a context provider itself, when we read its context
      // we may have already pushed its own child context on the stack. A context
      // provider should not "see" its own child context. Therefore we read the
      // previous (parent) context instead for a context provider.
      return previousContext;
    }

    return contextStackCursor.current;
  }
}

function cacheContext(workInProgress, unmaskedContext, maskedContext) {
  {
    var instance = workInProgress.stateNode;
    instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
    instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
  }
}

function getMaskedContext(workInProgress, unmaskedContext) {
  {
    var type = workInProgress.type;
    var contextTypes = type.contextTypes;

    if (!contextTypes) {
      return emptyContextObject;
    } // Avoid recreating masked context unless unmasked context has changed.
    // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
    // This may trigger infinite loops if componentWillReceiveProps calls setState.


    var instance = workInProgress.stateNode;

    if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
      return instance.__reactInternalMemoizedMaskedChildContext;
    }

    var context = {};

    for (var key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    {
      var name = getComponentNameFromFiber(workInProgress) || 'Unknown';
      checkPropTypes(contextTypes, context, 'context', name);
    } // Cache unmasked context so we can avoid recreating masked context unless necessary.
    // Context is created before the class component is instantiated so check for instance.


    if (instance) {
      cacheContext(workInProgress, unmaskedContext, context);
    }

    return context;
  }
}

function hasContextChanged() {
  {
    return didPerformWorkStackCursor.current;
  }
}

function isContextProvider(type) {
  {
    var childContextTypes = type.childContextTypes;
    return childContextTypes !== null && childContextTypes !== undefined;
  }
}

function popContext(fiber) {
  {
    pop(didPerformWorkStackCursor, fiber);
    pop(contextStackCursor, fiber);
  }
}

function popTopLevelContextObject(fiber) {
  {
    pop(didPerformWorkStackCursor, fiber);
    pop(contextStackCursor, fiber);
  }
}

function pushTopLevelContextObject(fiber, context, didChange) {
  {
    if (contextStackCursor.current !== emptyContextObject) {
      throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    push(contextStackCursor, context, fiber);
    push(didPerformWorkStackCursor, didChange, fiber);
  }
}

function processChildContext(fiber, type, parentContext) {
  {
    var instance = fiber.stateNode;
    var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.

    if (typeof instance.getChildContext !== 'function') {
      {
        var componentName = getComponentNameFromFiber(fiber) || 'Unknown';

        if (!warnedAboutMissingGetChildContext[componentName]) {
          warnedAboutMissingGetChildContext[componentName] = true;

          error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
        }
      }

      return parentContext;
    }

    var childContext = instance.getChildContext();

    for (var contextKey in childContext) {
      if (!(contextKey in childContextTypes)) {
        throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
      }
    }

    {
      var name = getComponentNameFromFiber(fiber) || 'Unknown';
      checkPropTypes(childContextTypes, childContext, 'child context', name);
    }

    return assign({}, parentContext, childContext);
  }
}

function pushContextProvider(workInProgress) {
  {
    var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
    // If the instance does not exist yet, we will push null at first,
    // and replace it on the stack later when invalidating the context.

    var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
    // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.

    previousContext = contextStackCursor.current;
    push(contextStackCursor, memoizedMergedChildContext, workInProgress);
    push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
    return true;
  }
}

function invalidateContextProvider(workInProgress, type, didChange) {
  {
    var instance = workInProgress.stateNode;

    if (!instance) {
      throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    if (didChange) {
      // Merge parent and own context.
      // Skip this if we're not updating due to sCU.
      // This avoids unnecessarily recomputing memoized values.
      var mergedContext = processChildContext(workInProgress, type, previousContext);
      instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
      // It is important to unwind the context in the reverse order.

      pop(didPerformWorkStackCursor, workInProgress);
      pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.

      push(contextStackCursor, mergedContext, workInProgress);
      push(didPerformWorkStackCursor, didChange, workInProgress);
    } else {
      pop(didPerformWorkStackCursor, workInProgress);
      push(didPerformWorkStackCursor, didChange, workInProgress);
    }
  }
}

function findCurrentUnmaskedContext(fiber) {
  {
    // Currently this is only used with renderSubtreeIntoContainer; not sure if it
    // makes sense elsewhere
    if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
      throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    var node = fiber;

    do {
      switch (node.tag) {
        case HostRoot:
          return node.stateNode.context;

        case ClassComponent:
          {
            var Component = node.type;

            if (isContextProvider(Component)) {
              return node.stateNode.__reactInternalMemoizedMergedChildContext;
            }

            break;
          }
      }

      node = node.return;
    } while (node !== null);

    throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.');
  }
}

var LegacyRoot = 0;
var ConcurrentRoot = 1;

var syncQueue = null;
var includesLegacySyncCallbacks = false;
var isFlushingSyncQueue = false;
function scheduleSyncCallback(callback) {
  // Push this callback into an internal queue. We'll flush these either in
  // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
  if (syncQueue === null) {
    syncQueue = [callback];
  } else {
    // Push onto existing queue. Don't need to schedule a callback because
    // we already scheduled one when we created the queue.
    syncQueue.push(callback);
  }
}
function scheduleLegacySyncCallback(callback) {
  includesLegacySyncCallbacks = true;
  scheduleSyncCallback(callback);
}
function flushSyncCallbacksOnlyInLegacyMode() {
  // Only flushes the queue if there's a legacy sync callback scheduled.
  // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
  // it might make more sense for the queue to be a list of roots instead of a
  // list of generic callbacks. Then we can have two: one for legacy roots, one
  // for concurrent roots. And this method would only flush the legacy ones.
  if (includesLegacySyncCallbacks) {
    flushSyncCallbacks();
  }
}
function flushSyncCallbacks() {
  if (!isFlushingSyncQueue && syncQueue !== null) {
    // Prevent re-entrance.
    isFlushingSyncQueue = true;
    var i = 0;
    var previousUpdatePriority = getCurrentUpdatePriority();

    try {
      var isSync = true;
      var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this
      // queue is in the render or commit phases.

      setCurrentUpdatePriority(DiscreteEventPriority);

      for (; i < queue.length; i++) {
        var callback = queue[i];

        do {
          callback = callback(isSync);
        } while (callback !== null);
      }

      syncQueue = null;
      includesLegacySyncCallbacks = false;
    } catch (error) {
      // If something throws, leave the remaining callbacks on the queue.
      if (syncQueue !== null) {
        syncQueue = syncQueue.slice(i + 1);
      } // Resume flushing in the next tick


      scheduleCallback(ImmediatePriority, flushSyncCallbacks);
      throw error;
    } finally {
      setCurrentUpdatePriority(previousUpdatePriority);
      isFlushingSyncQueue = false;
    }
  }

  return null;
}

// TODO: Use the unified fiber stack module instead of this local one?
// Intentionally not using it yet to derisk the initial implementation, because
// the way we push/pop these values is a bit unusual. If there's a mistake, I'd
// rather the ids be wrong than crash the whole reconciler.
var forkStack = [];
var forkStackIndex = 0;
var treeForkProvider = null;
var treeForkCount = 0;
var idStack = [];
var idStackIndex = 0;
var treeContextProvider = null;
var treeContextId = 1;
var treeContextOverflow = '';
function isForkedChild(workInProgress) {
  warnIfNotHydrating();
  return (workInProgress.flags & Forked) !== NoFlags;
}
function getForksAtLevel(workInProgress) {
  warnIfNotHydrating();
  return treeForkCount;
}
function getTreeId() {
  var overflow = treeContextOverflow;
  var idWithLeadingBit = treeContextId;
  var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
  return id.toString(32) + overflow;
}
function pushTreeFork(workInProgress, totalChildren) {
  // This is called right after we reconcile an array (or iterator) of child
  // fibers, because that's the only place where we know how many children in
  // the whole set without doing extra work later, or storing addtional
  // information on the fiber.
  //
  // That's why this function is separate from pushTreeId â€” it's called during
  // the render phase of the fork parent, not the child, which is where we push
  // the other context values.
  //
  // In the Fizz implementation this is much simpler because the child is
  // rendered in the same callstack as the parent.
  //
  // It might be better to just add a `forks` field to the Fiber type. It would
  // make this module simpler.
  warnIfNotHydrating();
  forkStack[forkStackIndex++] = treeForkCount;
  forkStack[forkStackIndex++] = treeForkProvider;
  treeForkProvider = workInProgress;
  treeForkCount = totalChildren;
}
function pushTreeId(workInProgress, totalChildren, index) {
  warnIfNotHydrating();
  idStack[idStackIndex++] = treeContextId;
  idStack[idStackIndex++] = treeContextOverflow;
  idStack[idStackIndex++] = treeContextProvider;
  treeContextProvider = workInProgress;
  var baseIdWithLeadingBit = treeContextId;
  var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
  // of the id; we use it to account for leading 0s.

  var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
  var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
  var slot = index + 1;
  var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
  // consideration the leading 1 we use to mark the end of the sequence.

  if (length > 30) {
    // We overflowed the bitwise-safe range. Fall back to slower algorithm.
    // This branch assumes the length of the base id is greater than 5; it won't
    // work for smaller ids, because you need 5 bits per character.
    //
    // We encode the id in multiple steps: first the base id, then the
    // remaining digits.
    //
    // Each 5 bit sequence corresponds to a single base 32 character. So for
    // example, if the current id is 23 bits long, we can convert 20 of those
    // bits into a string of 4 characters, with 3 bits left over.
    //
    // First calculate how many bits in the base id represent a complete
    // sequence of characters.
    var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.

    var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.

    var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.

    var restOfBaseId = baseId >> numberOfOverflowBits;
    var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
    // we made more room, this time it won't overflow.

    var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
    var restOfNewBits = slot << restOfBaseLength;
    var id = restOfNewBits | restOfBaseId;
    var overflow = newOverflow + baseOverflow;
    treeContextId = 1 << restOfLength | id;
    treeContextOverflow = overflow;
  } else {
    // Normal path
    var newBits = slot << baseLength;

    var _id = newBits | baseId;

    var _overflow = baseOverflow;
    treeContextId = 1 << length | _id;
    treeContextOverflow = _overflow;
  }
}
function pushMaterializedTreeId(workInProgress) {
  warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear
  // in its children.

  var returnFiber = workInProgress.return;

  if (returnFiber !== null) {
    var numberOfForks = 1;
    var slotIndex = 0;
    pushTreeFork(workInProgress, numberOfForks);
    pushTreeId(workInProgress, numberOfForks, slotIndex);
  }
}

function getBitLength(number) {
  return 32 - clz32(number);
}

function getLeadingBit(id) {
  return 1 << getBitLength(id) - 1;
}

function popTreeContext(workInProgress) {
  // Restore the previous values.
  // This is a bit more complicated than other context-like modules in Fiber
  // because the same Fiber may appear on the stack multiple times and for
  // different reasons. We have to keep popping until the work-in-progress is
  // no longer at the top of the stack.
  while (workInProgress === treeForkProvider) {
    treeForkProvider = forkStack[--forkStackIndex];
    forkStack[forkStackIndex] = null;
    treeForkCount = forkStack[--forkStackIndex];
    forkStack[forkStackIndex] = null;
  }

  while (workInProgress === treeContextProvider) {
    treeContextProvider = idStack[--idStackIndex];
    idStack[idStackIndex] = null;
    treeContextOverflow = idStack[--idStackIndex];
    idStack[idStackIndex] = null;
    treeContextId = idStack[--idStackIndex];
    idStack[idStackIndex] = null;
  }
}
function getSuspendedTreeContext() {
  warnIfNotHydrating();

  if (treeContextProvider !== null) {
    return {
      id: treeContextId,
      overflow: treeContextOverflow
    };
  } else {
    return null;
  }
}
function restoreSuspendedTreeContext(workInProgress, suspendedContext) {
  warnIfNotHydrating();
  idStack[idStackIndex++] = treeContextId;
  idStack[idStackIndex++] = treeContextOverflow;
  idStack[idStackIndex++] = treeContextProvider;
  treeContextId = suspendedContext.id;
  treeContextOverflow = suspendedContext.overflow;
  treeContextProvider = workInProgress;
}

function warnIfNotHydrating() {
  {
    if (!getIsHydrating()) {
      error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.');
    }
  }
}

// This may have been an insertion or a hydration.

var hydrationParentFiber = null;
var nextHydratableInstance = null;
var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches
// due to earlier mismatches or a suspended fiber.

var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary

var hydrationErrors = null;

function warnIfHydrating() {
  {
    if (isHydrating) {
      error('We should not be hydrating here. This is a bug in React. Please file a bug.');
    }
  }
}

function markDidThrowWhileHydratingDEV() {
  {
    didSuspendOrErrorDEV = true;
  }
}
function didSuspendOrErrorWhileHydratingDEV() {
  {
    return didSuspendOrErrorDEV;
  }
}

function enterHydrationState(fiber) {

  var parentInstance = fiber.stateNode.containerInfo;
  nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
  hydrationParentFiber = fiber;
  isHydrating = true;
  hydrationErrors = null;
  didSuspendOrErrorDEV = false;
  return true;
}

function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {

  nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
  hydrationParentFiber = fiber;
  isHydrating = true;
  hydrationErrors = null;
  didSuspendOrErrorDEV = false;

  if (treeContext !== null) {
    restoreSuspendedTreeContext(fiber, treeContext);
  }

  return true;
}

function warnUnhydratedInstance(returnFiber, instance) {
  {
    switch (returnFiber.tag) {
      case HostRoot:
        {
          didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance);
          break;
        }

      case HostComponent:
        {
          var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
          didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API.
          isConcurrentMode);
          break;
        }

      case SuspenseComponent:
        {
          var suspenseState = returnFiber.memoizedState;
          if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance);
          break;
        }
    }
  }
}

function deleteHydratableInstance(returnFiber, instance) {
  warnUnhydratedInstance(returnFiber, instance);
  var childToDelete = createFiberFromHostInstanceForDeletion();
  childToDelete.stateNode = instance;
  childToDelete.return = returnFiber;
  var deletions = returnFiber.deletions;

  if (deletions === null) {
    returnFiber.deletions = [childToDelete];
    returnFiber.flags |= ChildDeletion;
  } else {
    deletions.push(childToDelete);
  }
}

function warnNonhydratedInstance(returnFiber, fiber) {
  {
    if (didSuspendOrErrorDEV) {
      // Inside a boundary that already suspended. We're currently rendering the
      // siblings of a suspended node. The mismatch may be due to the missing
      // data, so it's probably a false positive.
      return;
    }

    switch (returnFiber.tag) {
      case HostRoot:
        {
          var parentContainer = returnFiber.stateNode.containerInfo;

          switch (fiber.tag) {
            case HostComponent:
              var type = fiber.type;
              var props = fiber.pendingProps;
              didNotFindHydratableInstanceWithinContainer(parentContainer, type);
              break;

            case HostText:
              var text = fiber.pendingProps;
              didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
              break;
          }

          break;
        }

      case HostComponent:
        {
          var parentType = returnFiber.type;
          var parentProps = returnFiber.memoizedProps;
          var parentInstance = returnFiber.stateNode;

          switch (fiber.tag) {
            case HostComponent:
              {
                var _type = fiber.type;
                var _props = fiber.pendingProps;
                var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API.
                isConcurrentMode);
                break;
              }

            case HostText:
              {
                var _text = fiber.pendingProps;

                var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;

                didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API.
                _isConcurrentMode);
                break;
              }
          }

          break;
        }

      case SuspenseComponent:
        {
          var suspenseState = returnFiber.memoizedState;
          var _parentInstance = suspenseState.dehydrated;
          if (_parentInstance !== null) switch (fiber.tag) {
            case HostComponent:
              var _type2 = fiber.type;
              var _props2 = fiber.pendingProps;
              didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
              break;

            case HostText:
              var _text2 = fiber.pendingProps;
              didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
              break;
          }
          break;
        }

      default:
        return;
    }
  }
}

function insertNonHydratedInstance(returnFiber, fiber) {
  fiber.flags = fiber.flags & ~Hydrating | Placement;
  warnNonhydratedInstance(returnFiber, fiber);
}

function tryHydrate(fiber, nextInstance) {
  switch (fiber.tag) {
    case HostComponent:
      {
        var type = fiber.type;
        var props = fiber.pendingProps;
        var instance = canHydrateInstance(nextInstance, type);

        if (instance !== null) {
          fiber.stateNode = instance;
          hydrationParentFiber = fiber;
          nextHydratableInstance = getFirstHydratableChild(instance);
          return true;
        }

        return false;
      }

    case HostText:
      {
        var text = fiber.pendingProps;
        var textInstance = canHydrateTextInstance(nextInstance, text);

        if (textInstance !== null) {
          fiber.stateNode = textInstance;
          hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate.

          nextHydratableInstance = null;
          return true;
        }

        return false;
      }

    case SuspenseComponent:
      {
        var suspenseInstance = canHydrateSuspenseInstance(nextInstance);

        if (suspenseInstance !== null) {
          var suspenseState = {
            dehydrated: suspenseInstance,
            treeContext: getSuspendedTreeContext(),
            retryLane: OffscreenLane
          };
          fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
          // This simplifies the code for getHostSibling and deleting nodes,
          // since it doesn't have to consider all Suspense boundaries and
          // check if they're dehydrated ones or not.

          var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
          dehydratedFragment.return = fiber;
          fiber.child = dehydratedFragment;
          hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into
          // it during the first pass. Instead, we'll reenter it later.

          nextHydratableInstance = null;
          return true;
        }

        return false;
      }

    default:
      return false;
  }
}

function shouldClientRenderOnMismatch(fiber) {
  return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
}

function throwOnHydrationMismatch(fiber) {
  throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.');
}

function tryToClaimNextHydratableInstance(fiber) {
  if (!isHydrating) {
    return;
  }

  var nextInstance = nextHydratableInstance;

  if (!nextInstance) {
    if (shouldClientRenderOnMismatch(fiber)) {
      warnNonhydratedInstance(hydrationParentFiber, fiber);
      throwOnHydrationMismatch();
    } // Nothing to hydrate. Make it an insertion.


    insertNonHydratedInstance(hydrationParentFiber, fiber);
    isHydrating = false;
    hydrationParentFiber = fiber;
    return;
  }

  var firstAttemptedInstance = nextInstance;

  if (!tryHydrate(fiber, nextInstance)) {
    if (shouldClientRenderOnMismatch(fiber)) {
      warnNonhydratedInstance(hydrationParentFiber, fiber);
      throwOnHydrationMismatch();
    } // If we can't hydrate this instance let's try the next one.
    // We use this as a heuristic. It's based on intuition and not data so it
    // might be flawed or unnecessary.


    nextInstance = getNextHydratableSibling(firstAttemptedInstance);
    var prevHydrationParentFiber = hydrationParentFiber;

    if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
      // Nothing to hydrate. Make it an insertion.
      insertNonHydratedInstance(hydrationParentFiber, fiber);
      isHydrating = false;
      hydrationParentFiber = fiber;
      return;
    } // We matched the next one, we'll now assume that the first one was
    // superfluous and we'll delete it. Since we can't eagerly delete it
    // we'll have to schedule a deletion. To do that, this node needs a dummy
    // fiber associated with it.


    deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
  }
}

function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {

  var instance = fiber.stateNode;
  var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
  var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component.

  fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
  // is a new ref we mark this as an update.

  if (updatePayload !== null) {
    return true;
  }

  return false;
}

function prepareToHydrateHostTextInstance(fiber) {

  var textInstance = fiber.stateNode;
  var textContent = fiber.memoizedProps;
  var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);

  if (shouldUpdate) {
    // We assume that prepareToHydrateHostTextInstance is called in a context where the
    // hydration parent is the parent host component of this host text.
    var returnFiber = hydrationParentFiber;

    if (returnFiber !== null) {
      switch (returnFiber.tag) {
        case HostRoot:
          {
            var parentContainer = returnFiber.stateNode.containerInfo;
            var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
            didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
            isConcurrentMode);
            break;
          }

        case HostComponent:
          {
            var parentType = returnFiber.type;
            var parentProps = returnFiber.memoizedProps;
            var parentInstance = returnFiber.stateNode;

            var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;

            didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
            _isConcurrentMode2);
            break;
          }
      }
    }
  }

  return shouldUpdate;
}

function prepareToHydrateHostSuspenseInstance(fiber) {

  var suspenseState = fiber.memoizedState;
  var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;

  if (!suspenseInstance) {
    throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
  }

  hydrateSuspenseInstance(suspenseInstance, fiber);
}

function skipPastDehydratedSuspenseInstance(fiber) {

  var suspenseState = fiber.memoizedState;
  var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;

  if (!suspenseInstance) {
    throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
  }

  return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
}

function popToNextHostParent(fiber) {
  var parent = fiber.return;

  while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
    parent = parent.return;
  }

  hydrationParentFiber = parent;
}

function popHydrationState(fiber) {

  if (fiber !== hydrationParentFiber) {
    // We're deeper than the current hydration context, inside an inserted
    // tree.
    return false;
  }

  if (!isHydrating) {
    // If we're not currently hydrating but we're in a hydration context, then
    // we were an insertion and now need to pop up reenter hydration of our
    // siblings.
    popToNextHostParent(fiber);
    isHydrating = true;
    return false;
  } // If we have any remaining hydratable nodes, we need to delete them now.
  // We only do this deeper than head and body since they tend to have random
  // other nodes in them. We also ignore components with pure text content in
  // side of them. We also don't delete anything inside the root container.


  if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
    var nextInstance = nextHydratableInstance;

    if (nextInstance) {
      if (shouldClientRenderOnMismatch(fiber)) {
        warnIfUnhydratedTailNodes(fiber);
        throwOnHydrationMismatch();
      } else {
        while (nextInstance) {
          deleteHydratableInstance(fiber, nextInstance);
          nextInstance = getNextHydratableSibling(nextInstance);
        }
      }
    }
  }

  popToNextHostParent(fiber);

  if (fiber.tag === SuspenseComponent) {
    nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
  } else {
    nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
  }

  return true;
}

function hasUnhydratedTailNodes() {
  return isHydrating && nextHydratableInstance !== null;
}

function warnIfUnhydratedTailNodes(fiber) {
  var nextInstance = nextHydratableInstance;

  while (nextInstance) {
    warnUnhydratedInstance(fiber, nextInstance);
    nextInstance = getNextHydratableSibling(nextInstance);
  }
}

function resetHydrationState() {

  hydrationParentFiber = null;
  nextHydratableInstance = null;
  isHydrating = false;
  didSuspendOrErrorDEV = false;
}

function upgradeHydrationErrorsToRecoverable() {
  if (hydrationErrors !== null) {
    // Successfully completed a forced client render. The errors that occurred
    // during the hydration attempt are now recovered. We will log them in
    // commit phase, once the entire tree has finished.
    queueRecoverableErrors(hydrationErrors);
    hydrationErrors = null;
  }
}

function getIsHydrating() {
  return isHydrating;
}

function queueHydrationError(error) {
  if (hydrationErrors === null) {
    hydrationErrors = [error];
  } else {
    hydrationErrors.push(error);
  }
}

var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
var NoTransition = null;
function requestCurrentTransition() {
  return ReactCurrentBatchConfig$1.transition;
}

var ReactStrictModeWarnings = {
  recordUnsafeLifecycleWarnings: function (fiber, instance) {},
  flushPendingUnsafeLifecycleWarnings: function () {},
  recordLegacyContextWarning: function (fiber, instance) {},
  flushLegacyContextWarning: function () {},
  discardPendingWarnings: function () {}
};

{
  var findStrictRoot = function (fiber) {
    var maybeStrictRoot = null;
    var node = fiber;

    while (node !== null) {
      if (node.mode & StrictLegacyMode) {
        maybeStrictRoot = node;
      }

      node = node.return;
    }

    return maybeStrictRoot;
  };

  var setToSortedString = function (set) {
    var array = [];
    set.forEach(function (value) {
      array.push(value);
    });
    return array.sort().join(', ');
  };

  var pendingComponentWillMountWarnings = [];
  var pendingUNSAFE_ComponentWillMountWarnings = [];
  var pendingComponentWillReceivePropsWarnings = [];
  var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
  var pendingComponentWillUpdateWarnings = [];
  var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.

  var didWarnAboutUnsafeLifecycles = new Set();

  ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
    // Dedupe strategy: Warn once per component.
    if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
      return;
    }

    if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
    instance.componentWillMount.__suppressDeprecationWarning !== true) {
      pendingComponentWillMountWarnings.push(fiber);
    }

    if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') {
      pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
    }

    if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
      pendingComponentWillReceivePropsWarnings.push(fiber);
    }

    if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
      pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
    }

    if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
      pendingComponentWillUpdateWarnings.push(fiber);
    }

    if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
      pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
    }
  };

  ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
    // We do an initial pass to gather component names
    var componentWillMountUniqueNames = new Set();

    if (pendingComponentWillMountWarnings.length > 0) {
      pendingComponentWillMountWarnings.forEach(function (fiber) {
        componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingComponentWillMountWarnings = [];
    }

    var UNSAFE_componentWillMountUniqueNames = new Set();

    if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
      pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
        UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingUNSAFE_ComponentWillMountWarnings = [];
    }

    var componentWillReceivePropsUniqueNames = new Set();

    if (pendingComponentWillReceivePropsWarnings.length > 0) {
      pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
        componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingComponentWillReceivePropsWarnings = [];
    }

    var UNSAFE_componentWillReceivePropsUniqueNames = new Set();

    if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
      pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
        UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
    }

    var componentWillUpdateUniqueNames = new Set();

    if (pendingComponentWillUpdateWarnings.length > 0) {
      pendingComponentWillUpdateWarnings.forEach(function (fiber) {
        componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingComponentWillUpdateWarnings = [];
    }

    var UNSAFE_componentWillUpdateUniqueNames = new Set();

    if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
      pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
        UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      });
      pendingUNSAFE_ComponentWillUpdateWarnings = [];
    } // Finally, we flush all the warnings
    // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'


    if (UNSAFE_componentWillMountUniqueNames.size > 0) {
      var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);

      error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
    }

    if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
      var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);

      error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
    }

    if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
      var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);

      error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
    }

    if (componentWillMountUniqueNames.size > 0) {
      var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);

      warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
    }

    if (componentWillReceivePropsUniqueNames.size > 0) {
      var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

      warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
    }

    if (componentWillUpdateUniqueNames.size > 0) {
      var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);

      warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
    }
  };

  var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.

  var didWarnAboutLegacyContext = new Set();

  ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
    var strictRoot = findStrictRoot(fiber);

    if (strictRoot === null) {
      error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');

      return;
    } // Dedup strategy: Warn once per component.


    if (didWarnAboutLegacyContext.has(fiber.type)) {
      return;
    }

    var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);

    if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
      if (warningsForRoot === undefined) {
        warningsForRoot = [];
        pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
      }

      warningsForRoot.push(fiber);
    }
  };

  ReactStrictModeWarnings.flushLegacyContextWarning = function () {
    pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
      if (fiberArray.length === 0) {
        return;
      }

      var firstFiber = fiberArray[0];
      var uniqueNames = new Set();
      fiberArray.forEach(function (fiber) {
        uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
        didWarnAboutLegacyContext.add(fiber.type);
      });
      var sortedNames = setToSortedString(uniqueNames);

      try {
        setCurrentFiber(firstFiber);

        error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames);
      } finally {
        resetCurrentFiber();
      }
    });
  };

  ReactStrictModeWarnings.discardPendingWarnings = function () {
    pendingComponentWillMountWarnings = [];
    pendingUNSAFE_ComponentWillMountWarnings = [];
    pendingComponentWillReceivePropsWarnings = [];
    pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
    pendingComponentWillUpdateWarnings = [];
    pendingUNSAFE_ComponentWillUpdateWarnings = [];
    pendingLegacyContextWarning = new Map();
  };
}

var didWarnAboutMaps;
var didWarnAboutGenerators;
var didWarnAboutStringRefs;
var ownerHasKeyUseWarning;
var ownerHasFunctionTypeWarning;

var warnForMissingKey = function (child, returnFiber) {};

{
  didWarnAboutMaps = false;
  didWarnAboutGenerators = false;
  didWarnAboutStringRefs = {};
  /**
   * Warn if there's no key explicitly set on dynamic arrays of children or
   * object keys are not valid. This allows us to keep track of children between
   * updates.
   */

  ownerHasKeyUseWarning = {};
  ownerHasFunctionTypeWarning = {};

  warnForMissingKey = function (child, returnFiber) {
    if (child === null || typeof child !== 'object') {
      return;
    }

    if (!child._store || child._store.validated || child.key != null) {
      return;
    }

    if (typeof child._store !== 'object') {
      throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }

    child._store.validated = true;
    var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

    if (ownerHasKeyUseWarning[componentName]) {
      return;
    }

    ownerHasKeyUseWarning[componentName] = true;

    error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
  };
}

function isReactClass(type) {
  return type.prototype && type.prototype.isReactComponent;
}

function coerceRef(returnFiber, current, element) {
  var mixedRef = element.ref;

  if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
    {
      // TODO: Clean this up once we turn on the string ref warning for
      // everyone, because the strict mode case will no longer be relevant
      if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
      // because these cannot be automatically converted to an arrow function
      // using a codemod. Therefore, we don't have to warn about string refs again.
      !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs"
      !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs"
      !(typeof element.type === 'function' && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set"
      element._owner) {
        var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

        if (!didWarnAboutStringRefs[componentName]) {
          {
            error('Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef);
          }

          didWarnAboutStringRefs[componentName] = true;
        }
      }
    }

    if (element._owner) {
      var owner = element._owner;
      var inst;

      if (owner) {
        var ownerFiber = owner;

        if (ownerFiber.tag !== ClassComponent) {
          throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref');
        }

        inst = ownerFiber.stateNode;
      }

      if (!inst) {
        throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.');
      } // Assigning this to a const so Flow knows it won't change in the closure


      var resolvedInst = inst;

      {
        checkPropStringCoercion(mixedRef, 'ref');
      }

      var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref

      if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
        return current.ref;
      }

      var ref = function (value) {
        var refs = resolvedInst.refs;

        if (value === null) {
          delete refs[stringRef];
        } else {
          refs[stringRef] = value;
        }
      };

      ref._stringRef = stringRef;
      return ref;
    } else {
      if (typeof mixedRef !== 'string') {
        throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
      }

      if (!element._owner) {
        throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.');
      }
    }
  }

  return mixedRef;
}

function throwOnInvalidObjectType(returnFiber, newChild) {
  var childString = Object.prototype.toString.call(newChild);
  throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
}

function warnOnFunctionType(returnFiber) {
  {
    var componentName = getComponentNameFromFiber(returnFiber) || 'Component';

    if (ownerHasFunctionTypeWarning[componentName]) {
      return;
    }

    ownerHasFunctionTypeWarning[componentName] = true;

    error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
  }
}

function resolveLazy(lazyType) {
  var payload = lazyType._payload;
  var init = lazyType._init;
  return init(payload);
} // This wrapper function exists because I expect to clone the code in each path
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.


function ChildReconciler(shouldTrackSideEffects) {
  function deleteChild(returnFiber, childToDelete) {
    if (!shouldTrackSideEffects) {
      // Noop.
      return;
    }

    var deletions = returnFiber.deletions;

    if (deletions === null) {
      returnFiber.deletions = [childToDelete];
      returnFiber.flags |= ChildDeletion;
    } else {
      deletions.push(childToDelete);
    }
  }

  function deleteRemainingChildren(returnFiber, currentFirstChild) {
    if (!shouldTrackSideEffects) {
      // Noop.
      return null;
    } // TODO: For the shouldClone case, this could be micro-optimized a bit by
    // assuming that after the first child we've already added everything.


    var childToDelete = currentFirstChild;

    while (childToDelete !== null) {
      deleteChild(returnFiber, childToDelete);
      childToDelete = childToDelete.sibling;
    }

    return null;
  }

  function mapRemainingChildren(returnFiber, currentFirstChild) {
    // Add the remaining children to a temporary map so that we can find them by
    // keys quickly. Implicit (null) keys get added to this set with their index
    // instead.
    var existingChildren = new Map();
    var existingChild = currentFirstChild;

    while (existingChild !== null) {
      if (existingChild.key !== null) {
        existingChildren.set(existingChild.key, existingChild);
      } else {
        existingChildren.set(existingChild.index, existingChild);
      }

      existingChild = existingChild.sibling;
    }

    return existingChildren;
  }

  function useFiber(fiber, pendingProps) {
    // We currently set sibling to null and index to 0 here because it is easy
    // to forget to do before returning it. E.g. for the single child case.
    var clone = createWorkInProgress(fiber, pendingProps);
    clone.index = 0;
    clone.sibling = null;
    return clone;
  }

  function placeChild(newFiber, lastPlacedIndex, newIndex) {
    newFiber.index = newIndex;

    if (!shouldTrackSideEffects) {
      // During hydration, the useId algorithm needs to know which fibers are
      // part of a list of children (arrays, iterators).
      newFiber.flags |= Forked;
      return lastPlacedIndex;
    }

    var current = newFiber.alternate;

    if (current !== null) {
      var oldIndex = current.index;

      if (oldIndex < lastPlacedIndex) {
        // This is a move.
        newFiber.flags |= Placement;
        return lastPlacedIndex;
      } else {
        // This item can stay in place.
        return oldIndex;
      }
    } else {
      // This is an insertion.
      newFiber.flags |= Placement;
      return lastPlacedIndex;
    }
  }

  function placeSingleChild(newFiber) {
    // This is simpler for the single child case. We only need to do a
    // placement for inserting new children.
    if (shouldTrackSideEffects && newFiber.alternate === null) {
      newFiber.flags |= Placement;
    }

    return newFiber;
  }

  function updateTextNode(returnFiber, current, textContent, lanes) {
    if (current === null || current.tag !== HostText) {
      // Insert
      var created = createFiberFromText(textContent, returnFiber.mode, lanes);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, textContent);
      existing.return = returnFiber;
      return existing;
    }
  }

  function updateElement(returnFiber, current, element, lanes) {
    var elementType = element.type;

    if (elementType === REACT_FRAGMENT_TYPE) {
      return updateFragment(returnFiber, current, element.props.children, lanes, element.key);
    }

    if (current !== null) {
      if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
       isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type.
      // We need to do this after the Hot Reloading check above,
      // because hot reloading has different semantics than prod because
      // it doesn't resuspend. So we can't let the call below suspend.
      typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) {
        // Move based on index
        var existing = useFiber(current, element.props);
        existing.ref = coerceRef(returnFiber, current, element);
        existing.return = returnFiber;

        {
          existing._debugSource = element._source;
          existing._debugOwner = element._owner;
        }

        return existing;
      }
    } // Insert


    var created = createFiberFromElement(element, returnFiber.mode, lanes);
    created.ref = coerceRef(returnFiber, current, element);
    created.return = returnFiber;
    return created;
  }

  function updatePortal(returnFiber, current, portal, lanes) {
    if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
      // Insert
      var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, portal.children || []);
      existing.return = returnFiber;
      return existing;
    }
  }

  function updateFragment(returnFiber, current, fragment, lanes, key) {
    if (current === null || current.tag !== Fragment) {
      // Insert
      var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
      created.return = returnFiber;
      return created;
    } else {
      // Update
      var existing = useFiber(current, fragment);
      existing.return = returnFiber;
      return existing;
    }
  }

  function createChild(returnFiber, newChild, lanes) {
    if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
      // Text nodes don't have keys. If the previous node is implicitly keyed
      // we can continue to replace it without aborting even if it is not a text
      // node.
      var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
      created.return = returnFiber;
      return created;
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);

            _created.ref = coerceRef(returnFiber, null, newChild);
            _created.return = returnFiber;
            return _created;
          }

        case REACT_PORTAL_TYPE:
          {
            var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);

            _created2.return = returnFiber;
            return _created2;
          }

        case REACT_LAZY_TYPE:
          {
            var payload = newChild._payload;
            var init = newChild._init;
            return createChild(returnFiber, init(payload), lanes);
          }
      }

      if (isArray(newChild) || getIteratorFn(newChild)) {
        var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);

        _created3.return = returnFiber;
        return _created3;
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType(returnFiber);
      }
    }

    return null;
  }

  function updateSlot(returnFiber, oldFiber, newChild, lanes) {
    // Update the fiber if the keys match, otherwise return null.
    var key = oldFiber !== null ? oldFiber.key : null;

    if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
      // Text nodes don't have keys. If the previous node is implicitly keyed
      // we can continue to replace it without aborting even if it is not a text
      // node.
      if (key !== null) {
        return null;
      }

      return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            if (newChild.key === key) {
              return updateElement(returnFiber, oldFiber, newChild, lanes);
            } else {
              return null;
            }
          }

        case REACT_PORTAL_TYPE:
          {
            if (newChild.key === key) {
              return updatePortal(returnFiber, oldFiber, newChild, lanes);
            } else {
              return null;
            }
          }

        case REACT_LAZY_TYPE:
          {
            var payload = newChild._payload;
            var init = newChild._init;
            return updateSlot(returnFiber, oldFiber, init(payload), lanes);
          }
      }

      if (isArray(newChild) || getIteratorFn(newChild)) {
        if (key !== null) {
          return null;
        }

        return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType(returnFiber);
      }
    }

    return null;
  }

  function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
    if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
      // Text nodes don't have keys, so we neither have to check the old nor
      // new node for the key. If both are text nodes, they match.
      var matchedFiber = existingChildren.get(newIdx) || null;
      return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
    }

    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          {
            var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

            return updateElement(returnFiber, _matchedFiber, newChild, lanes);
          }

        case REACT_PORTAL_TYPE:
          {
            var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

            return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
          }

        case REACT_LAZY_TYPE:
          var payload = newChild._payload;
          var init = newChild._init;
          return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes);
      }

      if (isArray(newChild) || getIteratorFn(newChild)) {
        var _matchedFiber3 = existingChildren.get(newIdx) || null;

        return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType(returnFiber);
      }
    }

    return null;
  }
  /**
   * Warns if there is a duplicate or missing key
   */


  function warnOnInvalidKey(child, knownKeys, returnFiber) {
    {
      if (typeof child !== 'object' || child === null) {
        return knownKeys;
      }

      switch (child.$$typeof) {
        case REACT_ELEMENT_TYPE:
        case REACT_PORTAL_TYPE:
          warnForMissingKey(child, returnFiber);
          var key = child.key;

          if (typeof key !== 'string') {
            break;
          }

          if (knownKeys === null) {
            knownKeys = new Set();
            knownKeys.add(key);
            break;
          }

          if (!knownKeys.has(key)) {
            knownKeys.add(key);
            break;
          }

          error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted â€” the behavior is unsupported and ' + 'could change in a future version.', key);

          break;

        case REACT_LAZY_TYPE:
          var payload = child._payload;
          var init = child._init;
          warnOnInvalidKey(init(payload), knownKeys, returnFiber);
          break;
      }
    }

    return knownKeys;
  }

  function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
    // This algorithm can't optimize by searching from both ends since we
    // don't have backpointers on fibers. I'm trying to see how far we can get
    // with that model. If it ends up not being worth the tradeoffs, we can
    // add it later.
    // Even with a two ended optimization, we'd want to optimize for the case
    // where there are few changes and brute force the comparison instead of
    // going for the Map. It'd like to explore hitting that path first in
    // forward-only mode and only go for the Map once we notice that we need
    // lots of look ahead. This doesn't handle reversal as well as two ended
    // search but that's unusual. Besides, for the two ended optimization to
    // work on Iterables, we'd need to copy the whole set.
    // In this first iteration, we'll just live with hitting the bad case
    // (adding everything to a Map) in for every insert/move.
    // If you change this code, also update reconcileChildrenIterator() which
    // uses the same algorithm.
    {
      // First, validate keys.
      var knownKeys = null;

      for (var i = 0; i < newChildren.length; i++) {
        var child = newChildren[i];
        knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
      }
    }

    var resultingFirstChild = null;
    var previousNewFiber = null;
    var oldFiber = currentFirstChild;
    var lastPlacedIndex = 0;
    var newIdx = 0;
    var nextOldFiber = null;

    for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
      if (oldFiber.index > newIdx) {
        nextOldFiber = oldFiber;
        oldFiber = null;
      } else {
        nextOldFiber = oldFiber.sibling;
      }

      var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);

      if (newFiber === null) {
        // TODO: This breaks on empty slots like null children. That's
        // unfortunate because it triggers the slow path all the time. We need
        // a better way to communicate whether this was a miss or null,
        // boolean, undefined, etc.
        if (oldFiber === null) {
          oldFiber = nextOldFiber;
        }

        break;
      }

      if (shouldTrackSideEffects) {
        if (oldFiber && newFiber.alternate === null) {
          // We matched the slot, but we didn't reuse the existing fiber, so we
          // need to delete the existing child.
          deleteChild(returnFiber, oldFiber);
        }
      }

      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

      if (previousNewFiber === null) {
        // TODO: Move out of the loop. This only happens for the first run.
        resultingFirstChild = newFiber;
      } else {
        // TODO: Defer siblings if we're not at the right index for this slot.
        // I.e. if we had null values before, then we want to defer this
        // for each null value. However, we also don't want to call updateSlot
        // with the previous one.
        previousNewFiber.sibling = newFiber;
      }

      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }

    if (newIdx === newChildren.length) {
      // We've reached the end of the new children. We can delete the rest.
      deleteRemainingChildren(returnFiber, oldFiber);

      if (getIsHydrating()) {
        var numberOfForks = newIdx;
        pushTreeFork(returnFiber, numberOfForks);
      }

      return resultingFirstChild;
    }

    if (oldFiber === null) {
      // If we don't have any more existing children we can choose a fast path
      // since the rest will all be insertions.
      for (; newIdx < newChildren.length; newIdx++) {
        var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);

        if (_newFiber === null) {
          continue;
        }

        lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = _newFiber;
        } else {
          previousNewFiber.sibling = _newFiber;
        }

        previousNewFiber = _newFiber;
      }

      if (getIsHydrating()) {
        var _numberOfForks = newIdx;
        pushTreeFork(returnFiber, _numberOfForks);
      }

      return resultingFirstChild;
    } // Add all children to a key map for quick lookups.


    var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

    for (; newIdx < newChildren.length; newIdx++) {
      var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);

      if (_newFiber2 !== null) {
        if (shouldTrackSideEffects) {
          if (_newFiber2.alternate !== null) {
            // The new fiber is a work in progress, but if there exists a
            // current, that means that we reused the fiber. We need to delete
            // it from the child list so that we don't add it to the deletion
            // list.
            existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
          }
        }

        lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          resultingFirstChild = _newFiber2;
        } else {
          previousNewFiber.sibling = _newFiber2;
        }

        previousNewFiber = _newFiber2;
      }
    }

    if (shouldTrackSideEffects) {
      // Any existing children that weren't consumed above were deleted. We need
      // to add them to the deletion list.
      existingChildren.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    }

    if (getIsHydrating()) {
      var _numberOfForks2 = newIdx;
      pushTreeFork(returnFiber, _numberOfForks2);
    }

    return resultingFirstChild;
  }

  function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
    // This is the same implementation as reconcileChildrenArray(),
    // but using the iterator instead.
    var iteratorFn = getIteratorFn(newChildrenIterable);

    if (typeof iteratorFn !== 'function') {
      throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.');
    }

    {
      // We don't support rendering Generators because it's a mutation.
      // See https://github.com/facebook/react/issues/12995
      if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
      newChildrenIterable[Symbol.toStringTag] === 'Generator') {
        if (!didWarnAboutGenerators) {
          error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
        }

        didWarnAboutGenerators = true;
      } // Warn about using Maps as children


      if (newChildrenIterable.entries === iteratorFn) {
        if (!didWarnAboutMaps) {
          error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
        }

        didWarnAboutMaps = true;
      } // First, validate keys.
      // We'll get a different iterator later for the main pass.


      var _newChildren = iteratorFn.call(newChildrenIterable);

      if (_newChildren) {
        var knownKeys = null;

        var _step = _newChildren.next();

        for (; !_step.done; _step = _newChildren.next()) {
          var child = _step.value;
          knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
        }
      }
    }

    var newChildren = iteratorFn.call(newChildrenIterable);

    if (newChildren == null) {
      throw new Error('An iterable object provided no iterator.');
    }

    var resultingFirstChild = null;
    var previousNewFiber = null;
    var oldFiber = currentFirstChild;
    var lastPlacedIndex = 0;
    var newIdx = 0;
    var nextOldFiber = null;
    var step = newChildren.next();

    for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
      if (oldFiber.index > newIdx) {
        nextOldFiber = oldFiber;
        oldFiber = null;
      } else {
        nextOldFiber = oldFiber.sibling;
      }

      var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);

      if (newFiber === null) {
        // TODO: This breaks on empty slots like null children. That's
        // unfortunate because it triggers the slow path all the time. We need
        // a better way to communicate whether this was a miss or null,
        // boolean, undefined, etc.
        if (oldFiber === null) {
          oldFiber = nextOldFiber;
        }

        break;
      }

      if (shouldTrackSideEffects) {
        if (oldFiber && newFiber.alternate === null) {
          // We matched the slot, but we didn't reuse the existing fiber, so we
          // need to delete the existing child.
          deleteChild(returnFiber, oldFiber);
        }
      }

      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

      if (previousNewFiber === null) {
        // TODO: Move out of the loop. This only happens for the first run.
        resultingFirstChild = newFiber;
      } else {
        // TODO: Defer siblings if we're not at the right index for this slot.
        // I.e. if we had null values before, then we want to defer this
        // for each null value. However, we also don't want to call updateSlot
        // with the previous one.
        previousNewFiber.sibling = newFiber;
      }

      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }

    if (step.done) {
      // We've reached the end of the new children. We can delete the rest.
      deleteRemainingChildren(returnFiber, oldFiber);

      if (getIsHydrating()) {
        var numberOfForks = newIdx;
        pushTreeFork(returnFiber, numberOfForks);
      }

      return resultingFirstChild;
    }

    if (oldFiber === null) {
      // If we don't have any more existing children we can choose a fast path
      // since the rest will all be insertions.
      for (; !step.done; newIdx++, step = newChildren.next()) {
        var _newFiber3 = createChild(returnFiber, step.value, lanes);

        if (_newFiber3 === null) {
          continue;
        }

        lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          // TODO: Move out of the loop. This only happens for the first run.
          resultingFirstChild = _newFiber3;
        } else {
          previousNewFiber.sibling = _newFiber3;
        }

        previousNewFiber = _newFiber3;
      }

      if (getIsHydrating()) {
        var _numberOfForks3 = newIdx;
        pushTreeFork(returnFiber, _numberOfForks3);
      }

      return resultingFirstChild;
    } // Add all children to a key map for quick lookups.


    var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

    for (; !step.done; newIdx++, step = newChildren.next()) {
      var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);

      if (_newFiber4 !== null) {
        if (shouldTrackSideEffects) {
          if (_newFiber4.alternate !== null) {
            // The new fiber is a work in progress, but if there exists a
            // current, that means that we reused the fiber. We need to delete
            // it from the child list so that we don't add it to the deletion
            // list.
            existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
          }
        }

        lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);

        if (previousNewFiber === null) {
          resultingFirstChild = _newFiber4;
        } else {
          previousNewFiber.sibling = _newFiber4;
        }

        previousNewFiber = _newFiber4;
      }
    }

    if (shouldTrackSideEffects) {
      // Any existing children that weren't consumed above were deleted. We need
      // to add them to the deletion list.
      existingChildren.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    }

    if (getIsHydrating()) {
      var _numberOfForks4 = newIdx;
      pushTreeFork(returnFiber, _numberOfForks4);
    }

    return resultingFirstChild;
  }

  function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
    // There's no need to check for keys on text nodes since we don't have a
    // way to define them.
    if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
      // We already have an existing node so let's just update it and delete
      // the rest.
      deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
      var existing = useFiber(currentFirstChild, textContent);
      existing.return = returnFiber;
      return existing;
    } // The existing first child is not a text node so we need to create one
    // and delete the existing ones.


    deleteRemainingChildren(returnFiber, currentFirstChild);
    var created = createFiberFromText(textContent, returnFiber.mode, lanes);
    created.return = returnFiber;
    return created;
  }

  function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
    var key = element.key;
    var child = currentFirstChild;

    while (child !== null) {
      // TODO: If key === null and child.key === null, then this only applies to
      // the first item in the list.
      if (child.key === key) {
        var elementType = element.type;

        if (elementType === REACT_FRAGMENT_TYPE) {
          if (child.tag === Fragment) {
            deleteRemainingChildren(returnFiber, child.sibling);
            var existing = useFiber(child, element.props.children);
            existing.return = returnFiber;

            {
              existing._debugSource = element._source;
              existing._debugOwner = element._owner;
            }

            return existing;
          }
        } else {
          if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
           isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type.
          // We need to do this after the Hot Reloading check above,
          // because hot reloading has different semantics than prod because
          // it doesn't resuspend. So we can't let the call below suspend.
          typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
            deleteRemainingChildren(returnFiber, child.sibling);

            var _existing = useFiber(child, element.props);

            _existing.ref = coerceRef(returnFiber, child, element);
            _existing.return = returnFiber;

            {
              _existing._debugSource = element._source;
              _existing._debugOwner = element._owner;
            }

            return _existing;
          }
        } // Didn't match.


        deleteRemainingChildren(returnFiber, child);
        break;
      } else {
        deleteChild(returnFiber, child);
      }

      child = child.sibling;
    }

    if (element.type === REACT_FRAGMENT_TYPE) {
      var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
      created.return = returnFiber;
      return created;
    } else {
      var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);

      _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
      _created4.return = returnFiber;
      return _created4;
    }
  }

  function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
    var key = portal.key;
    var child = currentFirstChild;

    while (child !== null) {
      // TODO: If key === null and child.key === null, then this only applies to
      // the first item in the list.
      if (child.key === key) {
        if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
          deleteRemainingChildren(returnFiber, child.sibling);
          var existing = useFiber(child, portal.children || []);
          existing.return = returnFiber;
          return existing;
        } else {
          deleteRemainingChildren(returnFiber, child);
          break;
        }
      } else {
        deleteChild(returnFiber, child);
      }

      child = child.sibling;
    }

    var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
    created.return = returnFiber;
    return created;
  } // This API will tag the children with the side-effect of the reconciliation
  // itself. They will be added to the side-effect list as we pass through the
  // children and the parent.


  function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
    // This function is not recursive.
    // If the top level item is an array, we treat it as a set of children,
    // not as a fragment. Nested arrays on the other hand will be treated as
    // fragment nodes. Recursion happens at the normal flow.
    // Handle top level unkeyed fragments as if they were arrays.
    // This leads to an ambiguity between <>{[...]}</> and <>...</>.
    // We treat the ambiguous cases above the same.
    var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;

    if (isUnkeyedTopLevelFragment) {
      newChild = newChild.props.children;
    } // Handle object types


    if (typeof newChild === 'object' && newChild !== null) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));

        case REACT_PORTAL_TYPE:
          return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));

        case REACT_LAZY_TYPE:
          var payload = newChild._payload;
          var init = newChild._init; // TODO: This function is supposed to be non-recursive.

          return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes);
      }

      if (isArray(newChild)) {
        return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
      }

      if (getIteratorFn(newChild)) {
        return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
      }

      throwOnInvalidObjectType(returnFiber, newChild);
    }

    if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
      return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
    }

    {
      if (typeof newChild === 'function') {
        warnOnFunctionType(returnFiber);
      }
    } // Remaining cases are all treated as empty.


    return deleteRemainingChildren(returnFiber, currentFirstChild);
  }

  return reconcileChildFibers;
}

var reconcileChildFibers = ChildReconciler(true);
var mountChildFibers = ChildReconciler(false);
function cloneChildFibers(current, workInProgress) {
  if (current !== null && workInProgress.child !== current.child) {
    throw new Error('Resuming work not yet implemented.');
  }

  if (workInProgress.child === null) {
    return;
  }

  var currentChild = workInProgress.child;
  var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
  workInProgress.child = newChild;
  newChild.return = workInProgress;

  while (currentChild.sibling !== null) {
    currentChild = currentChild.sibling;
    newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
    newChild.return = workInProgress;
  }

  newChild.sibling = null;
} // Reset a workInProgress child set to prepare it for a second pass.

function resetChildFibers(workInProgress, lanes) {
  var child = workInProgress.child;

  while (child !== null) {
    resetWorkInProgress(child, lanes);
    child = child.sibling;
  }
}

var valueCursor = createCursor(null);
var rendererSigil;

{
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
}

var currentlyRenderingFiber = null;
var lastContextDependency = null;
var lastFullyObservedContext = null;
var isDisallowedContextReadInDEV = false;
function resetContextDependencies() {
  // This is called right before React yields execution, to ensure `readContext`
  // cannot be called outside the render phase.
  currentlyRenderingFiber = null;
  lastContextDependency = null;
  lastFullyObservedContext = null;

  {
    isDisallowedContextReadInDEV = false;
  }
}
function enterDisallowedContextReadInDEV() {
  {
    isDisallowedContextReadInDEV = true;
  }
}
function exitDisallowedContextReadInDEV() {
  {
    isDisallowedContextReadInDEV = false;
  }
}
function pushProvider(providerFiber, context, nextValue) {
  {
    push(valueCursor, context._currentValue, providerFiber);
    context._currentValue = nextValue;

    {
      if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
        error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
      }

      context._currentRenderer = rendererSigil;
    }
  }
}
function popProvider(context, providerFiber) {
  var currentValue = valueCursor.current;
  pop(valueCursor, providerFiber);

  {
    {
      context._currentValue = currentValue;
    }
  }
}
function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {
  // Update the child lanes of all the ancestors, including the alternates.
  var node = parent;

  while (node !== null) {
    var alternate = node.alternate;

    if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
      node.childLanes = mergeLanes(node.childLanes, renderLanes);

      if (alternate !== null) {
        alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
      }
    } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
      alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
    }

    if (node === propagationRoot) {
      break;
    }

    node = node.return;
  }

  {
    if (node !== propagationRoot) {
      error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.');
    }
  }
}
function propagateContextChange(workInProgress, context, renderLanes) {
  {
    propagateContextChange_eager(workInProgress, context, renderLanes);
  }
}

function propagateContextChange_eager(workInProgress, context, renderLanes) {

  var fiber = workInProgress.child;

  if (fiber !== null) {
    // Set the return pointer of the child to the work-in-progress fiber.
    fiber.return = workInProgress;
  }

  while (fiber !== null) {
    var nextFiber = void 0; // Visit this fiber.

    var list = fiber.dependencies;

    if (list !== null) {
      nextFiber = fiber.child;
      var dependency = list.firstContext;

      while (dependency !== null) {
        // Check if the context matches.
        if (dependency.context === context) {
          // Match! Schedule an update on this fiber.
          if (fiber.tag === ClassComponent) {
            // Schedule a force update on the work-in-progress.
            var lane = pickArbitraryLane(renderLanes);
            var update = createUpdate(NoTimestamp, lane);
            update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
            // update to the current fiber, too, which means it will persist even if
            // this render is thrown away. Since it's a race condition, not sure it's
            // worth fixing.
            // Inlined `enqueueUpdate` to remove interleaved update check

            var updateQueue = fiber.updateQueue;

            if (updateQueue === null) ; else {
              var sharedQueue = updateQueue.shared;
              var pending = sharedQueue.pending;

              if (pending === null) {
                // This is the first update. Create a circular list.
                update.next = update;
              } else {
                update.next = pending.next;
                pending.next = update;
              }

              sharedQueue.pending = update;
            }
          }

          fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
          var alternate = fiber.alternate;

          if (alternate !== null) {
            alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
          }

          scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too.

          list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
          // dependency list.

          break;
        }

        dependency = dependency.next;
      }
    } else if (fiber.tag === ContextProvider) {
      // Don't scan deeper if this is a matching provider
      nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
    } else if (fiber.tag === DehydratedFragment) {
      // If a dehydrated suspense boundary is in this subtree, we don't know
      // if it will have any context consumers in it. The best we can do is
      // mark it as having updates.
      var parentSuspense = fiber.return;

      if (parentSuspense === null) {
        throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.');
      }

      parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
      var _alternate = parentSuspense.alternate;

      if (_alternate !== null) {
        _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes);
      } // This is intentionally passing this fiber as the parent
      // because we want to schedule this fiber as having work
      // on its children. We'll use the childLanes on
      // this fiber to indicate that a context has changed.


      scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress);
      nextFiber = fiber.sibling;
    } else {
      // Traverse down.
      nextFiber = fiber.child;
    }

    if (nextFiber !== null) {
      // Set the return pointer of the child to the work-in-progress fiber.
      nextFiber.return = fiber;
    } else {
      // No child. Traverse to next sibling.
      nextFiber = fiber;

      while (nextFiber !== null) {
        if (nextFiber === workInProgress) {
          // We're back to the root of this subtree. Exit.
          nextFiber = null;
          break;
        }

        var sibling = nextFiber.sibling;

        if (sibling !== null) {
          // Set the return pointer of the sibling to the work-in-progress fiber.
          sibling.return = nextFiber.return;
          nextFiber = sibling;
          break;
        } // No more siblings. Traverse up.


        nextFiber = nextFiber.return;
      }
    }

    fiber = nextFiber;
  }
}
function prepareToReadContext(workInProgress, renderLanes) {
  currentlyRenderingFiber = workInProgress;
  lastContextDependency = null;
  lastFullyObservedContext = null;
  var dependencies = workInProgress.dependencies;

  if (dependencies !== null) {
    {
      var firstContext = dependencies.firstContext;

      if (firstContext !== null) {
        if (includesSomeLane(dependencies.lanes, renderLanes)) {
          // Context list has a pending update. Mark that this fiber performed work.
          markWorkInProgressReceivedUpdate();
        } // Reset the work-in-progress list


        dependencies.firstContext = null;
      }
    }
  }
}
function readContext(context) {
  {
    // This warning would fire if you read context inside a Hook like useMemo.
    // Unlike the class check below, it's not enforced in production for perf.
    if (isDisallowedContextReadInDEV) {
      error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
    }
  }

  var value =  context._currentValue ;

  if (lastFullyObservedContext === context) ; else {
    var contextItem = {
      context: context,
      memoizedValue: value,
      next: null
    };

    if (lastContextDependency === null) {
      if (currentlyRenderingFiber === null) {
        throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
      } // This is the first dependency for this component. Create a new list.


      lastContextDependency = contextItem;
      currentlyRenderingFiber.dependencies = {
        lanes: NoLanes,
        firstContext: contextItem
      };
    } else {
      // Append a new context item.
      lastContextDependency = lastContextDependency.next = contextItem;
    }
  }

  return value;
}

// render. When this render exits, either because it finishes or because it is
// interrupted, the interleaved updates will be transferred onto the main part
// of the queue.

var concurrentQueues = null;
function pushConcurrentUpdateQueue(queue) {
  if (concurrentQueues === null) {
    concurrentQueues = [queue];
  } else {
    concurrentQueues.push(queue);
  }
}
function finishQueueingConcurrentUpdates() {
  // Transfer the interleaved updates onto the main queue. Each queue has a
  // `pending` field and an `interleaved` field. When they are not null, they
  // point to the last node in a circular linked list. We need to append the
  // interleaved list to the end of the pending list by joining them into a
  // single, circular list.
  if (concurrentQueues !== null) {
    for (var i = 0; i < concurrentQueues.length; i++) {
      var queue = concurrentQueues[i];
      var lastInterleavedUpdate = queue.interleaved;

      if (lastInterleavedUpdate !== null) {
        queue.interleaved = null;
        var firstInterleavedUpdate = lastInterleavedUpdate.next;
        var lastPendingUpdate = queue.pending;

        if (lastPendingUpdate !== null) {
          var firstPendingUpdate = lastPendingUpdate.next;
          lastPendingUpdate.next = firstInterleavedUpdate;
          lastInterleavedUpdate.next = firstPendingUpdate;
        }

        queue.pending = lastInterleavedUpdate;
      }
    }

    concurrentQueues = null;
  }
}
function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
  var interleaved = queue.interleaved;

  if (interleaved === null) {
    // This is the first update. Create a circular list.
    update.next = update; // At the end of the current render, this queue's interleaved updates will
    // be transferred to the pending queue.

    pushConcurrentUpdateQueue(queue);
  } else {
    update.next = interleaved.next;
    interleaved.next = update;
  }

  queue.interleaved = update;
  return markUpdateLaneFromFiberToRoot(fiber, lane);
}
function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) {
  var interleaved = queue.interleaved;

  if (interleaved === null) {
    // This is the first update. Create a circular list.
    update.next = update; // At the end of the current render, this queue's interleaved updates will
    // be transferred to the pending queue.

    pushConcurrentUpdateQueue(queue);
  } else {
    update.next = interleaved.next;
    interleaved.next = update;
  }

  queue.interleaved = update;
}
function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
  var interleaved = queue.interleaved;

  if (interleaved === null) {
    // This is the first update. Create a circular list.
    update.next = update; // At the end of the current render, this queue's interleaved updates will
    // be transferred to the pending queue.

    pushConcurrentUpdateQueue(queue);
  } else {
    update.next = interleaved.next;
    interleaved.next = update;
  }

  queue.interleaved = update;
  return markUpdateLaneFromFiberToRoot(fiber, lane);
}
function enqueueConcurrentRenderForLane(fiber, lane) {
  return markUpdateLaneFromFiberToRoot(fiber, lane);
} // Calling this function outside this module should only be done for backwards
// compatibility and should always be accompanied by a warning.

var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;

function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
  // Update the source fiber's lanes
  sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
  var alternate = sourceFiber.alternate;

  if (alternate !== null) {
    alternate.lanes = mergeLanes(alternate.lanes, lane);
  }

  {
    if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
      warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
    }
  } // Walk the parent path to the root and update the child lanes.


  var node = sourceFiber;
  var parent = sourceFiber.return;

  while (parent !== null) {
    parent.childLanes = mergeLanes(parent.childLanes, lane);
    alternate = parent.alternate;

    if (alternate !== null) {
      alternate.childLanes = mergeLanes(alternate.childLanes, lane);
    } else {
      {
        if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
          warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
        }
      }
    }

    node = parent;
    parent = parent.return;
  }

  if (node.tag === HostRoot) {
    var root = node.stateNode;
    return root;
  } else {
    return null;
  }
}

var UpdateState = 0;
var ReplaceState = 1;
var ForceUpdate = 2;
var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
// It should only be read right after calling `processUpdateQueue`, via
// `checkHasForceUpdateAfterProcessing`.

var hasForceUpdate = false;
var didWarnUpdateInsideUpdate;
var currentlyProcessingQueue;

{
  didWarnUpdateInsideUpdate = false;
  currentlyProcessingQueue = null;
}

function initializeUpdateQueue(fiber) {
  var queue = {
    baseState: fiber.memoizedState,
    firstBaseUpdate: null,
    lastBaseUpdate: null,
    shared: {
      pending: null,
      interleaved: null,
      lanes: NoLanes
    },
    effects: null
  };
  fiber.updateQueue = queue;
}
function cloneUpdateQueue(current, workInProgress) {
  // Clone the update queue from current. Unless it's already a clone.
  var queue = workInProgress.updateQueue;
  var currentQueue = current.updateQueue;

  if (queue === currentQueue) {
    var clone = {
      baseState: currentQueue.baseState,
      firstBaseUpdate: currentQueue.firstBaseUpdate,
      lastBaseUpdate: currentQueue.lastBaseUpdate,
      shared: currentQueue.shared,
      effects: currentQueue.effects
    };
    workInProgress.updateQueue = clone;
  }
}
function createUpdate(eventTime, lane) {
  var update = {
    eventTime: eventTime,
    lane: lane,
    tag: UpdateState,
    payload: null,
    callback: null,
    next: null
  };
  return update;
}
function enqueueUpdate(fiber, update, lane) {
  var updateQueue = fiber.updateQueue;

  if (updateQueue === null) {
    // Only occurs if the fiber has been unmounted.
    return null;
  }

  var sharedQueue = updateQueue.shared;

  {
    if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
      error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');

      didWarnUpdateInsideUpdate = true;
    }
  }

  if (isUnsafeClassRenderPhaseUpdate()) {
    // This is an unsafe render phase update. Add directly to the update
    // queue so we can process it immediately during the current render.
    var pending = sharedQueue.pending;

    if (pending === null) {
      // This is the first update. Create a circular list.
      update.next = update;
    } else {
      update.next = pending.next;
      pending.next = update;
    }

    sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering
    // this fiber. This is for backwards compatibility in the case where you
    // update a different component during render phase than the one that is
    // currently renderings (a pattern that is accompanied by a warning).

    return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
  } else {
    return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
  }
}
function entangleTransitions(root, fiber, lane) {
  var updateQueue = fiber.updateQueue;

  if (updateQueue === null) {
    // Only occurs if the fiber has been unmounted.
    return;
  }

  var sharedQueue = updateQueue.shared;

  if (isTransitionLane(lane)) {
    var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must
    // have finished. We can remove them from the shared queue, which represents
    // a superset of the actually pending lanes. In some cases we may entangle
    // more than we need to, but that's OK. In fact it's worse if we *don't*
    // entangle when we should.

    queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.

    var newQueueLanes = mergeLanes(queueLanes, lane);
    sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
    // the lane finished since the last time we entangled it. So we need to
    // entangle it again, just to be sure.

    markRootEntangled(root, newQueueLanes);
  }
}
function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
  // Captured updates are updates that are thrown by a child during the render
  // phase. They should be discarded if the render is aborted. Therefore,
  // we should only put them on the work-in-progress queue, not the current one.
  var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.

  var current = workInProgress.alternate;

  if (current !== null) {
    var currentQueue = current.updateQueue;

    if (queue === currentQueue) {
      // The work-in-progress queue is the same as current. This happens when
      // we bail out on a parent fiber that then captures an error thrown by
      // a child. Since we want to append the update only to the work-in
      // -progress queue, we need to clone the updates. We usually clone during
      // processUpdateQueue, but that didn't happen in this case because we
      // skipped over the parent when we bailed out.
      var newFirst = null;
      var newLast = null;
      var firstBaseUpdate = queue.firstBaseUpdate;

      if (firstBaseUpdate !== null) {
        // Loop through the updates and clone them.
        var update = firstBaseUpdate;

        do {
          var clone = {
            eventTime: update.eventTime,
            lane: update.lane,
            tag: update.tag,
            payload: update.payload,
            callback: update.callback,
            next: null
          };

          if (newLast === null) {
            newFirst = newLast = clone;
          } else {
            newLast.next = clone;
            newLast = clone;
          }

          update = update.next;
        } while (update !== null); // Append the captured update the end of the cloned list.


        if (newLast === null) {
          newFirst = newLast = capturedUpdate;
        } else {
          newLast.next = capturedUpdate;
          newLast = capturedUpdate;
        }
      } else {
        // There are no base updates.
        newFirst = newLast = capturedUpdate;
      }

      queue = {
        baseState: currentQueue.baseState,
        firstBaseUpdate: newFirst,
        lastBaseUpdate: newLast,
        shared: currentQueue.shared,
        effects: currentQueue.effects
      };
      workInProgress.updateQueue = queue;
      return;
    }
  } // Append the update to the end of the list.


  var lastBaseUpdate = queue.lastBaseUpdate;

  if (lastBaseUpdate === null) {
    queue.firstBaseUpdate = capturedUpdate;
  } else {
    lastBaseUpdate.next = capturedUpdate;
  }

  queue.lastBaseUpdate = capturedUpdate;
}

function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
  switch (update.tag) {
    case ReplaceState:
      {
        var payload = update.payload;

        if (typeof payload === 'function') {
          // Updater function
          {
            enterDisallowedContextReadInDEV();
          }

          var nextState = payload.call(instance, prevState, nextProps);

          {
            if ( workInProgress.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);

              try {
                payload.call(instance, prevState, nextProps);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }

            exitDisallowedContextReadInDEV();
          }

          return nextState;
        } // State object


        return payload;
      }

    case CaptureUpdate:
      {
        workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
      }
    // Intentional fallthrough

    case UpdateState:
      {
        var _payload = update.payload;
        var partialState;

        if (typeof _payload === 'function') {
          // Updater function
          {
            enterDisallowedContextReadInDEV();
          }

          partialState = _payload.call(instance, prevState, nextProps);

          {
            if ( workInProgress.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);

              try {
                _payload.call(instance, prevState, nextProps);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }

            exitDisallowedContextReadInDEV();
          }
        } else {
          // Partial state object
          partialState = _payload;
        }

        if (partialState === null || partialState === undefined) {
          // Null and undefined are treated as no-ops.
          return prevState;
        } // Merge the partial state and the previous state.


        return assign({}, prevState, partialState);
      }

    case ForceUpdate:
      {
        hasForceUpdate = true;
        return prevState;
      }
  }

  return prevState;
}

function processUpdateQueue(workInProgress, props, instance, renderLanes) {
  // This is always non-null on a ClassComponent or HostRoot
  var queue = workInProgress.updateQueue;
  hasForceUpdate = false;

  {
    currentlyProcessingQueue = queue.shared;
  }

  var firstBaseUpdate = queue.firstBaseUpdate;
  var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.

  var pendingQueue = queue.shared.pending;

  if (pendingQueue !== null) {
    queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
    // and last so that it's non-circular.

    var lastPendingUpdate = pendingQueue;
    var firstPendingUpdate = lastPendingUpdate.next;
    lastPendingUpdate.next = null; // Append pending updates to base queue

    if (lastBaseUpdate === null) {
      firstBaseUpdate = firstPendingUpdate;
    } else {
      lastBaseUpdate.next = firstPendingUpdate;
    }

    lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
    // we need to transfer the updates to that queue, too. Because the base
    // queue is a singly-linked list with no cycles, we can append to both
    // lists and take advantage of structural sharing.
    // TODO: Pass `current` as argument

    var current = workInProgress.alternate;

    if (current !== null) {
      // This is always non-null on a ClassComponent or HostRoot
      var currentQueue = current.updateQueue;
      var currentLastBaseUpdate = currentQueue.lastBaseUpdate;

      if (currentLastBaseUpdate !== lastBaseUpdate) {
        if (currentLastBaseUpdate === null) {
          currentQueue.firstBaseUpdate = firstPendingUpdate;
        } else {
          currentLastBaseUpdate.next = firstPendingUpdate;
        }

        currentQueue.lastBaseUpdate = lastPendingUpdate;
      }
    }
  } // These values may change as we process the queue.


  if (firstBaseUpdate !== null) {
    // Iterate through the list of updates to compute the result.
    var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
    // from the original lanes.

    var newLanes = NoLanes;
    var newBaseState = null;
    var newFirstBaseUpdate = null;
    var newLastBaseUpdate = null;
    var update = firstBaseUpdate;

    do {
      var updateLane = update.lane;
      var updateEventTime = update.eventTime;

      if (!isSubsetOfLanes(renderLanes, updateLane)) {
        // Priority is insufficient. Skip this update. If this is the first
        // skipped update, the previous update/state is the new base
        // update/state.
        var clone = {
          eventTime: updateEventTime,
          lane: updateLane,
          tag: update.tag,
          payload: update.payload,
          callback: update.callback,
          next: null
        };

        if (newLastBaseUpdate === null) {
          newFirstBaseUpdate = newLastBaseUpdate = clone;
          newBaseState = newState;
        } else {
          newLastBaseUpdate = newLastBaseUpdate.next = clone;
        } // Update the remaining priority in the queue.


        newLanes = mergeLanes(newLanes, updateLane);
      } else {
        // This update does have sufficient priority.
        if (newLastBaseUpdate !== null) {
          var _clone = {
            eventTime: updateEventTime,
            // This update is going to be committed so we never want uncommit
            // it. Using NoLane works because 0 is a subset of all bitmasks, so
            // this will never be skipped by the check above.
            lane: NoLane,
            tag: update.tag,
            payload: update.payload,
            callback: update.callback,
            next: null
          };
          newLastBaseUpdate = newLastBaseUpdate.next = _clone;
        } // Process this update.


        newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
        var callback = update.callback;

        if (callback !== null && // If the update was already committed, we should not queue its
        // callback again.
        update.lane !== NoLane) {
          workInProgress.flags |= Callback;
          var effects = queue.effects;

          if (effects === null) {
            queue.effects = [update];
          } else {
            effects.push(update);
          }
        }
      }

      update = update.next;

      if (update === null) {
        pendingQueue = queue.shared.pending;

        if (pendingQueue === null) {
          break;
        } else {
          // An update was scheduled from inside a reducer. Add the new
          // pending updates to the end of the list and keep processing.
          var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
          // unravel them when transferring them to the base queue.

          var _firstPendingUpdate = _lastPendingUpdate.next;
          _lastPendingUpdate.next = null;
          update = _firstPendingUpdate;
          queue.lastBaseUpdate = _lastPendingUpdate;
          queue.shared.pending = null;
        }
      }
    } while (true);

    if (newLastBaseUpdate === null) {
      newBaseState = newState;
    }

    queue.baseState = newBaseState;
    queue.firstBaseUpdate = newFirstBaseUpdate;
    queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to
    // process them during this render, but we do need to track which lanes
    // are remaining.

    var lastInterleaved = queue.shared.interleaved;

    if (lastInterleaved !== null) {
      var interleaved = lastInterleaved;

      do {
        newLanes = mergeLanes(newLanes, interleaved.lane);
        interleaved = interleaved.next;
      } while (interleaved !== lastInterleaved);
    } else if (firstBaseUpdate === null) {
      // `queue.lanes` is used for entangling transitions. We can set it back to
      // zero once the queue is empty.
      queue.shared.lanes = NoLanes;
    } // Set the remaining expiration time to be whatever is remaining in the queue.
    // This should be fine because the only two other things that contribute to
    // expiration time are props and context. We're already in the middle of the
    // begin phase by the time we start processing the queue, so we've already
    // dealt with the props. Context in components that specify
    // shouldComponentUpdate is tricky; but we'll have to account for
    // that regardless.


    markSkippedUpdateLanes(newLanes);
    workInProgress.lanes = newLanes;
    workInProgress.memoizedState = newState;
  }

  {
    currentlyProcessingQueue = null;
  }
}

function callCallback(callback, context) {
  if (typeof callback !== 'function') {
    throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback));
  }

  callback.call(context);
}

function resetHasForceUpdateBeforeProcessing() {
  hasForceUpdate = false;
}
function checkHasForceUpdateAfterProcessing() {
  return hasForceUpdate;
}
function commitUpdateQueue(finishedWork, finishedQueue, instance) {
  // Commit the effects
  var effects = finishedQueue.effects;
  finishedQueue.effects = null;

  if (effects !== null) {
    for (var i = 0; i < effects.length; i++) {
      var effect = effects[i];
      var callback = effect.callback;

      if (callback !== null) {
        effect.callback = null;
        callCallback(callback, instance);
      }
    }
  }
}

var NO_CONTEXT = {};
var contextStackCursor$1 = createCursor(NO_CONTEXT);
var contextFiberStackCursor = createCursor(NO_CONTEXT);
var rootInstanceStackCursor = createCursor(NO_CONTEXT);

function requiredContext(c) {
  if (c === NO_CONTEXT) {
    throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.');
  }

  return c;
}

function getRootHostContainer() {
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
  return rootInstance;
}

function pushHostContainer(fiber, nextRootInstance) {
  // Push current root instance onto the stack;
  // This allows us to reset root when portals are popped.
  push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
  // This enables us to pop only Fibers that provide unique contexts.

  push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
  // However, we can't just call getRootHostContext() and push it because
  // we'd have a different number of entries on the stack depending on
  // whether getRootHostContext() throws somewhere in renderer code or not.
  // So we push an empty value first. This lets us safely unwind on errors.

  push(contextStackCursor$1, NO_CONTEXT, fiber);
  var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.

  pop(contextStackCursor$1, fiber);
  push(contextStackCursor$1, nextRootContext, fiber);
}

function popHostContainer(fiber) {
  pop(contextStackCursor$1, fiber);
  pop(contextFiberStackCursor, fiber);
  pop(rootInstanceStackCursor, fiber);
}

function getHostContext() {
  var context = requiredContext(contextStackCursor$1.current);
  return context;
}

function pushHostContext(fiber) {
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
  var context = requiredContext(contextStackCursor$1.current);
  var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.

  if (context === nextContext) {
    return;
  } // Track the context and the Fiber that provided it.
  // This enables us to pop only Fibers that provide unique contexts.


  push(contextFiberStackCursor, fiber, fiber);
  push(contextStackCursor$1, nextContext, fiber);
}

function popHostContext(fiber) {
  // Do not pop unless this Fiber provided the current context.
  // pushHostContext() only pushes Fibers that provide unique contexts.
  if (contextFiberStackCursor.current !== fiber) {
    return;
  }

  pop(contextStackCursor$1, fiber);
  pop(contextFiberStackCursor, fiber);
}

var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
// inherited deeply down the subtree. The upper bits only affect
// this immediate suspense boundary and gets reset each new
// boundary or suspense list.

var SubtreeSuspenseContextMask = 1; // Subtree Flags:
// InvisibleParentSuspenseContext indicates that one of our parent Suspense
// boundaries is not currently showing visible main content.
// Either because it is already showing a fallback or is not mounted at all.
// We can use this to determine if it is desirable to trigger a fallback at
// the parent. If not, then we might need to trigger undesirable boundaries
// and/or suspend the commit to avoid hiding the parent content.

var InvisibleParentSuspenseContext = 1; // Shallow Flags:
// ForceSuspenseFallback can be used by SuspenseList to force newly added
// items into their fallback state during one of the render passes.

var ForceSuspenseFallback = 2;
var suspenseStackCursor = createCursor(DefaultSuspenseContext);
function hasSuspenseContext(parentContext, flag) {
  return (parentContext & flag) !== 0;
}
function setDefaultShallowSuspenseContext(parentContext) {
  return parentContext & SubtreeSuspenseContextMask;
}
function setShallowSuspenseContext(parentContext, shallowContext) {
  return parentContext & SubtreeSuspenseContextMask | shallowContext;
}
function addSubtreeSuspenseContext(parentContext, subtreeContext) {
  return parentContext | subtreeContext;
}
function pushSuspenseContext(fiber, newContext) {
  push(suspenseStackCursor, newContext, fiber);
}
function popSuspenseContext(fiber) {
  pop(suspenseStackCursor, fiber);
}

function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
  // If it was the primary children that just suspended, capture and render the
  // fallback. Otherwise, don't capture and bubble to the next boundary.
  var nextState = workInProgress.memoizedState;

  if (nextState !== null) {
    if (nextState.dehydrated !== null) {
      // A dehydrated boundary always captures.
      return true;
    }

    return false;
  }

  var props = workInProgress.memoizedProps; // Regular boundaries always capture.

  {
    return true;
  } // If it's a boundary we should avoid, then we prefer to bubble up to the
}
function findFirstSuspended(row) {
  var node = row;

  while (node !== null) {
    if (node.tag === SuspenseComponent) {
      var state = node.memoizedState;

      if (state !== null) {
        var dehydrated = state.dehydrated;

        if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
          return node;
        }
      }
    } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
    // keep track of whether it suspended or not.
    node.memoizedProps.revealOrder !== undefined) {
      var didSuspend = (node.flags & DidCapture) !== NoFlags;

      if (didSuspend) {
        return node;
      }
    } else if (node.child !== null) {
      node.child.return = node;
      node = node.child;
      continue;
    }

    if (node === row) {
      return null;
    }

    while (node.sibling === null) {
      if (node.return === null || node.return === row) {
        return null;
      }

      node = node.return;
    }

    node.sibling.return = node.return;
    node = node.sibling;
  }

  return null;
}

var NoFlags$1 =
/*   */
0; // Represents whether effect should fire.

var HasEffect =
/* */
1; // Represents the phase in which the effect (not the clean-up) fires.

var Insertion =
/*  */
2;
var Layout =
/*    */
4;
var Passive$1 =
/*   */
8;

// and should be reset before starting a new render.
// This tracks which mutable sources need to be reset after a render.

var workInProgressSources = [];
function resetWorkInProgressVersions() {
  for (var i = 0; i < workInProgressSources.length; i++) {
    var mutableSource = workInProgressSources[i];

    {
      mutableSource._workInProgressVersionPrimary = null;
    }
  }

  workInProgressSources.length = 0;
}
// This ensures that the version used for server rendering matches the one
// that is eventually read during hydration.
// If they don't match there's a potential tear and a full deopt render is required.

function registerMutableSourceForHydration(root, mutableSource) {
  var getVersion = mutableSource._getVersion;
  var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished.
  // Retaining it forever may interfere with GC.

  if (root.mutableSourceEagerHydrationData == null) {
    root.mutableSourceEagerHydrationData = [mutableSource, version];
  } else {
    root.mutableSourceEagerHydrationData.push(mutableSource, version);
  }
}

var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
    ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
var didWarnAboutMismatchedHooksForComponent;
var didWarnUncachedGetSnapshot;

{
  didWarnAboutMismatchedHooksForComponent = new Set();
}

// These are set right before calling the component.
var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
// the work-in-progress hook.

var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
// current hook list is the list that belongs to the current fiber. The
// work-in-progress hook list is a new list that will be added to the
// work-in-progress fiber.

var currentHook = null;
var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
// does not get reset if we do another render pass; only when we're completely
// finished evaluating this component. This is an optimization so we know
// whether we need to clear render phase updates after a throw.

var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
// gets reset after each attempt.
// TODO: Maybe there's some way to consolidate this with
// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.

var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component.

var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during
// hydration). This counter is global, so client ids are not stable across
// render attempts.

var globalClientIdCounter = 0;
var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook

var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
// The list stores the order of hooks used during the initial render (mount).
// Subsequent renders (updates) reference this list.

var hookTypesDev = null;
var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
// When true, such Hooks will always be "remounted". Only used during hot reload.

var ignorePreviousDependencies = false;

function mountHookTypesDev() {
  {
    var hookName = currentHookNameInDev;

    if (hookTypesDev === null) {
      hookTypesDev = [hookName];
    } else {
      hookTypesDev.push(hookName);
    }
  }
}

function updateHookTypesDev() {
  {
    var hookName = currentHookNameInDev;

    if (hookTypesDev !== null) {
      hookTypesUpdateIndexDev++;

      if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
        warnOnHookMismatchInDev(hookName);
      }
    }
  }
}

function checkDepsAreArrayDev(deps) {
  {
    if (deps !== undefined && deps !== null && !isArray(deps)) {
      // Verify deps, but only on mount to avoid extra checks.
      // It's unlikely their type would change as usually you define them inline.
      error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
    }
  }
}

function warnOnHookMismatchInDev(currentHookName) {
  {
    var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);

    if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
      didWarnAboutMismatchedHooksForComponent.add(componentName);

      if (hookTypesDev !== null) {
        var table = '';
        var secondColumnStart = 30;

        for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
          var oldHookName = hookTypesDev[i];
          var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
          var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
          // lol @ IE not supporting String#repeat

          while (row.length < secondColumnStart) {
            row += ' ';
          }

          row += newHookName + '\n';
          table += row;
        }

        error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + '   Previous render            Next render\n' + '   ------------------------------------------------------\n' + '%s' + '   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
      }
    }
  }
}

function throwInvalidHookError() {
  throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}

function areHookInputsEqual(nextDeps, prevDeps) {
  {
    if (ignorePreviousDependencies) {
      // Only true when this component is being hot reloaded.
      return false;
    }
  }

  if (prevDeps === null) {
    {
      error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
    }

    return false;
  }

  {
    // Don't bother comparing lengths in prod because these arrays should be
    // passed inline.
    if (nextDeps.length !== prevDeps.length) {
      error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
    }
  }

  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (objectIs(nextDeps[i], prevDeps[i])) {
      continue;
    }

    return false;
  }

  return true;
}

function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
  renderLanes = nextRenderLanes;
  currentlyRenderingFiber$1 = workInProgress;

  {
    hookTypesDev = current !== null ? current._debugHookTypes : null;
    hookTypesUpdateIndexDev = -1; // Used for hot reloading:

    ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
  }

  workInProgress.memoizedState = null;
  workInProgress.updateQueue = null;
  workInProgress.lanes = NoLanes; // The following should have already been reset
  // currentHook = null;
  // workInProgressHook = null;
  // didScheduleRenderPhaseUpdate = false;
  // localIdCounter = 0;
  // TODO Warn if no hooks are used at all during mount, then some are used during update.
  // Currently we will identify the update render as a mount because memoizedState === null.
  // This is tricky because it's valid for certain types of components (e.g. React.lazy)
  // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
  // Non-stateful hooks (e.g. context) don't get added to memoizedState,
  // so memoizedState would be null during updates and mounts.

  {
    if (current !== null && current.memoizedState !== null) {
      ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
    } else if (hookTypesDev !== null) {
      // This dispatcher handles an edge case where a component is updating,
      // but no stateful hooks have been used.
      // We want to match the production code behavior (which will use HooksDispatcherOnMount),
      // but with the extra DEV validation to ensure hooks ordering hasn't changed.
      // This dispatcher does that.
      ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
    } else {
      ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
    }
  }

  var children = Component(props, secondArg); // Check if there was a render phase update

  if (didScheduleRenderPhaseUpdateDuringThisPass) {
    // Keep rendering in a loop for as long as render phase updates continue to
    // be scheduled. Use a counter to prevent infinite loops.
    var numberOfReRenders = 0;

    do {
      didScheduleRenderPhaseUpdateDuringThisPass = false;
      localIdCounter = 0;

      if (numberOfReRenders >= RE_RENDER_LIMIT) {
        throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
      }

      numberOfReRenders += 1;

      {
        // Even when hot reloading, allow dependencies to stabilize
        // after first render to prevent infinite render phase updates.
        ignorePreviousDependencies = false;
      } // Start over from the beginning of the list


      currentHook = null;
      workInProgressHook = null;
      workInProgress.updateQueue = null;

      {
        // Also validate hook order for cascading updates.
        hookTypesUpdateIndexDev = -1;
      }

      ReactCurrentDispatcher$1.current =  HooksDispatcherOnRerenderInDEV ;
      children = Component(props, secondArg);
    } while (didScheduleRenderPhaseUpdateDuringThisPass);
  } // We can assume the previous dispatcher is always this one, since we set it
  // at the beginning of the render phase and there's no re-entrance.


  ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;

  {
    workInProgress._debugHookTypes = hookTypesDev;
  } // This check uses currentHook so that it works the same in DEV and prod bundles.
  // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.


  var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
  renderLanes = NoLanes;
  currentlyRenderingFiber$1 = null;
  currentHook = null;
  workInProgressHook = null;

  {
    currentHookNameInDev = null;
    hookTypesDev = null;
    hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last
    // render. If this fires, it suggests that we incorrectly reset the static
    // flags in some other part of the codebase. This has happened before, for
    // example, in the SuspenseList implementation.

    if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
    // and creates false positives. To make this work in legacy mode, we'd
    // need to mark fibers that commit in an incomplete state, somehow. For
    // now I'll disable the warning that most of the bugs that would trigger
    // it are either exclusive to concurrent mode or exist in both.
    (current.mode & ConcurrentMode) !== NoMode) {
      error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.');
    }
  }

  didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook
  // localIdCounter = 0;

  if (didRenderTooFewHooks) {
    throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.');
  }

  return children;
}
function checkDidRenderIdHook() {
  // This should be called immediately after every renderWithHooks call.
  // Conceptually, it's part of the return value of renderWithHooks; it's only a
  // separate function to avoid using an array tuple.
  var didRenderIdHook = localIdCounter !== 0;
  localIdCounter = 0;
  return didRenderIdHook;
}
function bailoutHooks(current, workInProgress, lanes) {
  workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the
  // complete phase (bubbleProperties).

  if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
    workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update);
  } else {
    workInProgress.flags &= ~(Passive | Update);
  }

  current.lanes = removeLanes(current.lanes, lanes);
}
function resetHooksAfterThrow() {
  // We can assume the previous dispatcher is always this one, since we set it
  // at the beginning of the render phase and there's no re-entrance.
  ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;

  if (didScheduleRenderPhaseUpdate) {
    // There were render phase updates. These are only valid for this render
    // phase, which we are now aborting. Remove the updates from the queues so
    // they do not persist to the next render. Do not remove updates from hooks
    // that weren't processed.
    //
    // Only reset the updates from the queue if it has a clone. If it does
    // not have a clone, that means it wasn't processed, and the updates were
    // scheduled before we entered the render phase.
    var hook = currentlyRenderingFiber$1.memoizedState;

    while (hook !== null) {
      var queue = hook.queue;

      if (queue !== null) {
        queue.pending = null;
      }

      hook = hook.next;
    }

    didScheduleRenderPhaseUpdate = false;
  }

  renderLanes = NoLanes;
  currentlyRenderingFiber$1 = null;
  currentHook = null;
  workInProgressHook = null;

  {
    hookTypesDev = null;
    hookTypesUpdateIndexDev = -1;
    currentHookNameInDev = null;
    isUpdatingOpaqueValueInRenderPhase = false;
  }

  didScheduleRenderPhaseUpdateDuringThisPass = false;
  localIdCounter = 0;
}

function mountWorkInProgressHook() {
  var hook = {
    memoizedState: null,
    baseState: null,
    baseQueue: null,
    queue: null,
    next: null
  };

  if (workInProgressHook === null) {
    // This is the first hook in the list
    currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
  } else {
    // Append to the end of the list
    workInProgressHook = workInProgressHook.next = hook;
  }

  return workInProgressHook;
}

function updateWorkInProgressHook() {
  // This function is used both for updates and for re-renders triggered by a
  // render phase update. It assumes there is either a current hook we can
  // clone, or a work-in-progress hook from a previous render pass that we can
  // use as a base. When we reach the end of the base list, we must switch to
  // the dispatcher used for mounts.
  var nextCurrentHook;

  if (currentHook === null) {
    var current = currentlyRenderingFiber$1.alternate;

    if (current !== null) {
      nextCurrentHook = current.memoizedState;
    } else {
      nextCurrentHook = null;
    }
  } else {
    nextCurrentHook = currentHook.next;
  }

  var nextWorkInProgressHook;

  if (workInProgressHook === null) {
    nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
  } else {
    nextWorkInProgressHook = workInProgressHook.next;
  }

  if (nextWorkInProgressHook !== null) {
    // There's already a work-in-progress. Reuse it.
    workInProgressHook = nextWorkInProgressHook;
    nextWorkInProgressHook = workInProgressHook.next;
    currentHook = nextCurrentHook;
  } else {
    // Clone from the current hook.
    if (nextCurrentHook === null) {
      throw new Error('Rendered more hooks than during the previous render.');
    }

    currentHook = nextCurrentHook;
    var newHook = {
      memoizedState: currentHook.memoizedState,
      baseState: currentHook.baseState,
      baseQueue: currentHook.baseQueue,
      queue: currentHook.queue,
      next: null
    };

    if (workInProgressHook === null) {
      // This is the first hook in the list.
      currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
    } else {
      // Append to the end of the list.
      workInProgressHook = workInProgressHook.next = newHook;
    }
  }

  return workInProgressHook;
}

function createFunctionComponentUpdateQueue() {
  return {
    lastEffect: null,
    stores: null
  };
}

function basicStateReducer(state, action) {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

function mountReducer(reducer, initialArg, init) {
  var hook = mountWorkInProgressHook();
  var initialState;

  if (init !== undefined) {
    initialState = init(initialArg);
  } else {
    initialState = initialArg;
  }

  hook.memoizedState = hook.baseState = initialState;
  var queue = {
    pending: null,
    interleaved: null,
    lanes: NoLanes,
    dispatch: null,
    lastRenderedReducer: reducer,
    lastRenderedState: initialState
  };
  hook.queue = queue;
  var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue);
  return [hook.memoizedState, dispatch];
}

function updateReducer(reducer, initialArg, init) {
  var hook = updateWorkInProgressHook();
  var queue = hook.queue;

  if (queue === null) {
    throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
  }

  queue.lastRenderedReducer = reducer;
  var current = currentHook; // The last rebase update that is NOT part of the base state.

  var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.

  var pendingQueue = queue.pending;

  if (pendingQueue !== null) {
    // We have new updates that haven't been processed yet.
    // We'll add them to the base queue.
    if (baseQueue !== null) {
      // Merge the pending queue and the base queue.
      var baseFirst = baseQueue.next;
      var pendingFirst = pendingQueue.next;
      baseQueue.next = pendingFirst;
      pendingQueue.next = baseFirst;
    }

    {
      if (current.baseQueue !== baseQueue) {
        // Internal invariant that should never happen, but feasibly could in
        // the future if we implement resuming, or some form of that.
        error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
      }
    }

    current.baseQueue = baseQueue = pendingQueue;
    queue.pending = null;
  }

  if (baseQueue !== null) {
    // We have a queue to process.
    var first = baseQueue.next;
    var newState = current.baseState;
    var newBaseState = null;
    var newBaseQueueFirst = null;
    var newBaseQueueLast = null;
    var update = first;

    do {
      var updateLane = update.lane;

      if (!isSubsetOfLanes(renderLanes, updateLane)) {
        // Priority is insufficient. Skip this update. If this is the first
        // skipped update, the previous update/state is the new base
        // update/state.
        var clone = {
          lane: updateLane,
          action: update.action,
          hasEagerState: update.hasEagerState,
          eagerState: update.eagerState,
          next: null
        };

        if (newBaseQueueLast === null) {
          newBaseQueueFirst = newBaseQueueLast = clone;
          newBaseState = newState;
        } else {
          newBaseQueueLast = newBaseQueueLast.next = clone;
        } // Update the remaining priority in the queue.
        // TODO: Don't need to accumulate this. Instead, we can remove
        // renderLanes from the original lanes.


        currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
        markSkippedUpdateLanes(updateLane);
      } else {
        // This update does have sufficient priority.
        if (newBaseQueueLast !== null) {
          var _clone = {
            // This update is going to be committed so we never want uncommit
            // it. Using NoLane works because 0 is a subset of all bitmasks, so
            // this will never be skipped by the check above.
            lane: NoLane,
            action: update.action,
            hasEagerState: update.hasEagerState,
            eagerState: update.eagerState,
            next: null
          };
          newBaseQueueLast = newBaseQueueLast.next = _clone;
        } // Process this update.


        if (update.hasEagerState) {
          // If this update is a state update (not a reducer) and was processed eagerly,
          // we can use the eagerly computed state
          newState = update.eagerState;
        } else {
          var action = update.action;
          newState = reducer(newState, action);
        }
      }

      update = update.next;
    } while (update !== null && update !== first);

    if (newBaseQueueLast === null) {
      newBaseState = newState;
    } else {
      newBaseQueueLast.next = newBaseQueueFirst;
    } // Mark that the fiber performed work, but only if the new state is
    // different from the current state.


    if (!objectIs(newState, hook.memoizedState)) {
      markWorkInProgressReceivedUpdate();
    }

    hook.memoizedState = newState;
    hook.baseState = newBaseState;
    hook.baseQueue = newBaseQueueLast;
    queue.lastRenderedState = newState;
  } // Interleaved updates are stored on a separate queue. We aren't going to
  // process them during this render, but we do need to track which lanes
  // are remaining.


  var lastInterleaved = queue.interleaved;

  if (lastInterleaved !== null) {
    var interleaved = lastInterleaved;

    do {
      var interleavedLane = interleaved.lane;
      currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
      markSkippedUpdateLanes(interleavedLane);
      interleaved = interleaved.next;
    } while (interleaved !== lastInterleaved);
  } else if (baseQueue === null) {
    // `queue.lanes` is used for entangling transitions. We can set it back to
    // zero once the queue is empty.
    queue.lanes = NoLanes;
  }

  var dispatch = queue.dispatch;
  return [hook.memoizedState, dispatch];
}

function rerenderReducer(reducer, initialArg, init) {
  var hook = updateWorkInProgressHook();
  var queue = hook.queue;

  if (queue === null) {
    throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
  }

  queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
  // work-in-progress hook.

  var dispatch = queue.dispatch;
  var lastRenderPhaseUpdate = queue.pending;
  var newState = hook.memoizedState;

  if (lastRenderPhaseUpdate !== null) {
    // The queue doesn't persist past this render pass.
    queue.pending = null;
    var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
    var update = firstRenderPhaseUpdate;

    do {
      // Process this render phase update. We don't have to check the
      // priority because it will always be the same as the current
      // render's.
      var action = update.action;
      newState = reducer(newState, action);
      update = update.next;
    } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
    // different from the current state.


    if (!objectIs(newState, hook.memoizedState)) {
      markWorkInProgressReceivedUpdate();
    }

    hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
    // the base state unless the queue is empty.
    // TODO: Not sure if this is the desired semantics, but it's what we
    // do for gDSFP. I can't remember why.

    if (hook.baseQueue === null) {
      hook.baseState = newState;
    }

    queue.lastRenderedState = newState;
  }

  return [newState, dispatch];
}

function mountMutableSource(source, getSnapshot, subscribe) {
  {
    return undefined;
  }
}

function updateMutableSource(source, getSnapshot, subscribe) {
  {
    return undefined;
  }
}

function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  var fiber = currentlyRenderingFiber$1;
  var hook = mountWorkInProgressHook();
  var nextSnapshot;
  var isHydrating = getIsHydrating();

  if (isHydrating) {
    if (getServerSnapshot === undefined) {
      throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
    }

    nextSnapshot = getServerSnapshot();

    {
      if (!didWarnUncachedGetSnapshot) {
        if (nextSnapshot !== getServerSnapshot()) {
          error('The result of getServerSnapshot should be cached to avoid an infinite loop');

          didWarnUncachedGetSnapshot = true;
        }
      }
    }
  } else {
    nextSnapshot = getSnapshot();

    {
      if (!didWarnUncachedGetSnapshot) {
        var cachedSnapshot = getSnapshot();

        if (!objectIs(nextSnapshot, cachedSnapshot)) {
          error('The result of getSnapshot should be cached to avoid an infinite loop');

          didWarnUncachedGetSnapshot = true;
        }
      }
    } // Unless we're rendering a blocking lane, schedule a consistency check.
    // Right before committing, we will walk the tree and check if any of the
    // stores were mutated.
    //
    // We won't do this if we're hydrating server-rendered content, because if
    // the content is stale, it's already visible anyway. Instead we'll patch
    // it up in a passive effect.


    var root = getWorkInProgressRoot();

    if (root === null) {
      throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
    }

    if (!includesBlockingLane(root, renderLanes)) {
      pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
    }
  } // Read the current snapshot from the store on every render. This breaks the
  // normal rules of React, and only works because store updates are
  // always synchronous.


  hook.memoizedState = nextSnapshot;
  var inst = {
    value: nextSnapshot,
    getSnapshot: getSnapshot
  };
  hook.queue = inst; // Schedule an effect to subscribe to the store.

  mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update
  // this whenever subscribe, getSnapshot, or value changes. Because there's no
  // clean-up function, and we track the deps correctly, we can call pushEffect
  // directly, without storing any additional state. For the same reason, we
  // don't need to set a static flag, either.
  // TODO: We can move this to the passive phase once we add a pre-commit
  // consistency check. See the next comment.

  fiber.flags |= Passive;
  pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null);
  return nextSnapshot;
}

function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  var fiber = currentlyRenderingFiber$1;
  var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the
  // normal rules of React, and only works because store updates are
  // always synchronous.

  var nextSnapshot = getSnapshot();

  {
    if (!didWarnUncachedGetSnapshot) {
      var cachedSnapshot = getSnapshot();

      if (!objectIs(nextSnapshot, cachedSnapshot)) {
        error('The result of getSnapshot should be cached to avoid an infinite loop');

        didWarnUncachedGetSnapshot = true;
      }
    }
  }

  var prevSnapshot = hook.memoizedState;
  var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);

  if (snapshotChanged) {
    hook.memoizedState = nextSnapshot;
    markWorkInProgressReceivedUpdate();
  }

  var inst = hook.queue;
  updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the
  // commit phase if there was an interleaved mutation. In concurrent mode
  // this can happen all the time, but even in synchronous mode, an earlier
  // effect may have mutated the store.

  if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
  // checking whether we scheduled a subscription effect above.
  workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
    fiber.flags |= Passive;
    pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check.
    // Right before committing, we will walk the tree and check if any of the
    // stores were mutated.

    var root = getWorkInProgressRoot();

    if (root === null) {
      throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
    }

    if (!includesBlockingLane(root, renderLanes)) {
      pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
    }
  }

  return nextSnapshot;
}

function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
  fiber.flags |= StoreConsistency;
  var check = {
    getSnapshot: getSnapshot,
    value: renderedSnapshot
  };
  var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;

  if (componentUpdateQueue === null) {
    componentUpdateQueue = createFunctionComponentUpdateQueue();
    currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
    componentUpdateQueue.stores = [check];
  } else {
    var stores = componentUpdateQueue.stores;

    if (stores === null) {
      componentUpdateQueue.stores = [check];
    } else {
      stores.push(check);
    }
  }
}

function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
  // These are updated in the passive phase
  inst.value = nextSnapshot;
  inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could
  // have been in an event that fired before the passive effects, or it could
  // have been in a layout effect. In that case, we would have used the old
  // snapsho and getSnapshot values to bail out. We need to check one more time.

  if (checkIfSnapshotChanged(inst)) {
    // Force a re-render.
    forceStoreRerender(fiber);
  }
}

function subscribeToStore(fiber, inst, subscribe) {
  var handleStoreChange = function () {
    // The store changed. Check if the snapshot changed since the last time we
    // read from the store.
    if (checkIfSnapshotChanged(inst)) {
      // Force a re-render.
      forceStoreRerender(fiber);
    }
  }; // Subscribe to the store and return a clean-up function.


  return subscribe(handleStoreChange);
}

function checkIfSnapshotChanged(inst) {
  var latestGetSnapshot = inst.getSnapshot;
  var prevValue = inst.value;

  try {
    var nextValue = latestGetSnapshot();
    return !objectIs(prevValue, nextValue);
  } catch (error) {
    return true;
  }
}

function forceStoreRerender(fiber) {
  var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

  if (root !== null) {
    scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
  }
}

function mountState(initialState) {
  var hook = mountWorkInProgressHook();

  if (typeof initialState === 'function') {
    // $FlowFixMe: Flow doesn't like mixed types
    initialState = initialState();
  }

  hook.memoizedState = hook.baseState = initialState;
  var queue = {
    pending: null,
    interleaved: null,
    lanes: NoLanes,
    dispatch: null,
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: initialState
  };
  hook.queue = queue;
  var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
  return [hook.memoizedState, dispatch];
}

function updateState(initialState) {
  return updateReducer(basicStateReducer);
}

function rerenderState(initialState) {
  return rerenderReducer(basicStateReducer);
}

function pushEffect(tag, create, destroy, deps) {
  var effect = {
    tag: tag,
    create: create,
    destroy: destroy,
    deps: deps,
    // Circular
    next: null
  };
  var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;

  if (componentUpdateQueue === null) {
    componentUpdateQueue = createFunctionComponentUpdateQueue();
    currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
    componentUpdateQueue.lastEffect = effect.next = effect;
  } else {
    var lastEffect = componentUpdateQueue.lastEffect;

    if (lastEffect === null) {
      componentUpdateQueue.lastEffect = effect.next = effect;
    } else {
      var firstEffect = lastEffect.next;
      lastEffect.next = effect;
      effect.next = firstEffect;
      componentUpdateQueue.lastEffect = effect;
    }
  }

  return effect;
}

function mountRef(initialValue) {
  var hook = mountWorkInProgressHook();

  {
    var _ref2 = {
      current: initialValue
    };
    hook.memoizedState = _ref2;
    return _ref2;
  }
}

function updateRef(initialValue) {
  var hook = updateWorkInProgressHook();
  return hook.memoizedState;
}

function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
  var hook = mountWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  currentlyRenderingFiber$1.flags |= fiberFlags;
  hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
}

function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
  var hook = updateWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  var destroy = undefined;

  if (currentHook !== null) {
    var prevEffect = currentHook.memoizedState;
    destroy = prevEffect.destroy;

    if (nextDeps !== null) {
      var prevDeps = prevEffect.deps;

      if (areHookInputsEqual(nextDeps, prevDeps)) {
        hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps);
        return;
      }
    }
  }

  currentlyRenderingFiber$1.flags |= fiberFlags;
  hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
}

function mountEffect(create, deps) {
  if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
    return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps);
  } else {
    return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps);
  }
}

function updateEffect(create, deps) {
  return updateEffectImpl(Passive, Passive$1, create, deps);
}

function mountInsertionEffect(create, deps) {
  return mountEffectImpl(Update, Insertion, create, deps);
}

function updateInsertionEffect(create, deps) {
  return updateEffectImpl(Update, Insertion, create, deps);
}

function mountLayoutEffect(create, deps) {
  var fiberFlags = Update;

  {
    fiberFlags |= LayoutStatic;
  }

  if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
    fiberFlags |= MountLayoutDev;
  }

  return mountEffectImpl(fiberFlags, Layout, create, deps);
}

function updateLayoutEffect(create, deps) {
  return updateEffectImpl(Update, Layout, create, deps);
}

function imperativeHandleEffect(create, ref) {
  if (typeof ref === 'function') {
    var refCallback = ref;

    var _inst = create();

    refCallback(_inst);
    return function () {
      refCallback(null);
    };
  } else if (ref !== null && ref !== undefined) {
    var refObject = ref;

    {
      if (!refObject.hasOwnProperty('current')) {
        error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
      }
    }

    var _inst2 = create();

    refObject.current = _inst2;
    return function () {
      refObject.current = null;
    };
  }
}

function mountImperativeHandle(ref, create, deps) {
  {
    if (typeof create !== 'function') {
      error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
    }
  } // TODO: If deps are provided, should we skip comparing the ref itself?


  var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
  var fiberFlags = Update;

  {
    fiberFlags |= LayoutStatic;
  }

  if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
    fiberFlags |= MountLayoutDev;
  }

  return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}

function updateImperativeHandle(ref, create, deps) {
  {
    if (typeof create !== 'function') {
      error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
    }
  } // TODO: If deps are provided, should we skip comparing the ref itself?


  var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
  return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}

function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
  // The react-debug-hooks package injects its own implementation
  // so that e.g. DevTools can display custom hook values.
}

var updateDebugValue = mountDebugValue;

function mountCallback(callback, deps) {
  var hook = mountWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  hook.memoizedState = [callback, nextDeps];
  return callback;
}

function updateCallback(callback, deps) {
  var hook = updateWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  var prevState = hook.memoizedState;

  if (prevState !== null) {
    if (nextDeps !== null) {
      var prevDeps = prevState[1];

      if (areHookInputsEqual(nextDeps, prevDeps)) {
        return prevState[0];
      }
    }
  }

  hook.memoizedState = [callback, nextDeps];
  return callback;
}

function mountMemo(nextCreate, deps) {
  var hook = mountWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  var nextValue = nextCreate();
  hook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function updateMemo(nextCreate, deps) {
  var hook = updateWorkInProgressHook();
  var nextDeps = deps === undefined ? null : deps;
  var prevState = hook.memoizedState;

  if (prevState !== null) {
    // Assume these are defined. If they're not, areHookInputsEqual will warn.
    if (nextDeps !== null) {
      var prevDeps = prevState[1];

      if (areHookInputsEqual(nextDeps, prevDeps)) {
        return prevState[0];
      }
    }
  }

  var nextValue = nextCreate();
  hook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}

function mountDeferredValue(value) {
  var hook = mountWorkInProgressHook();
  hook.memoizedState = value;
  return value;
}

function updateDeferredValue(value) {
  var hook = updateWorkInProgressHook();
  var resolvedCurrentHook = currentHook;
  var prevValue = resolvedCurrentHook.memoizedState;
  return updateDeferredValueImpl(hook, prevValue, value);
}

function rerenderDeferredValue(value) {
  var hook = updateWorkInProgressHook();

  if (currentHook === null) {
    // This is a rerender during a mount.
    hook.memoizedState = value;
    return value;
  } else {
    // This is a rerender during an update.
    var prevValue = currentHook.memoizedState;
    return updateDeferredValueImpl(hook, prevValue, value);
  }
}

function updateDeferredValueImpl(hook, prevValue, value) {
  var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);

  if (shouldDeferValue) {
    // This is an urgent update. If the value has changed, keep using the
    // previous value and spawn a deferred render to update it later.
    if (!objectIs(value, prevValue)) {
      // Schedule a deferred render
      var deferredLane = claimNextTransitionLane();
      currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
      markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent
      // from the latest value. The name "baseState" doesn't really match how we
      // use it because we're reusing a state hook field instead of creating a
      // new one.

      hook.baseState = true;
    } // Reuse the previous value


    return prevValue;
  } else {
    // This is not an urgent update, so we can use the latest value regardless
    // of what it is. No need to defer it.
    // However, if we're currently inside a spawned render, then we need to mark
    // this as an update to prevent the fiber from bailing out.
    //
    // `baseState` is true when the current value is different from the rendered
    // value. The name doesn't really match how we use it because we're reusing
    // a state hook field instead of creating a new one.
    if (hook.baseState) {
      // Flip this back to false.
      hook.baseState = false;
      markWorkInProgressReceivedUpdate();
    }

    hook.memoizedState = value;
    return value;
  }
}

function startTransition(setPending, callback, options) {
  var previousPriority = getCurrentUpdatePriority();
  setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
  setPending(true);
  var prevTransition = ReactCurrentBatchConfig$2.transition;
  ReactCurrentBatchConfig$2.transition = {};
  var currentTransition = ReactCurrentBatchConfig$2.transition;

  {
    ReactCurrentBatchConfig$2.transition._updatedFibers = new Set();
  }

  try {
    setPending(false);
    callback();
  } finally {
    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig$2.transition = prevTransition;

    {
      if (prevTransition === null && currentTransition._updatedFibers) {
        var updatedFibersCount = currentTransition._updatedFibers.size;

        if (updatedFibersCount > 10) {
          warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
        }

        currentTransition._updatedFibers.clear();
      }
    }
  }
}

function mountTransition() {
  var _mountState = mountState(false),
      isPending = _mountState[0],
      setPending = _mountState[1]; // The `start` method never changes.


  var start = startTransition.bind(null, setPending);
  var hook = mountWorkInProgressHook();
  hook.memoizedState = start;
  return [isPending, start];
}

function updateTransition() {
  var _updateState = updateState(),
      isPending = _updateState[0];

  var hook = updateWorkInProgressHook();
  var start = hook.memoizedState;
  return [isPending, start];
}

function rerenderTransition() {
  var _rerenderState = rerenderState(),
      isPending = _rerenderState[0];

  var hook = updateWorkInProgressHook();
  var start = hook.memoizedState;
  return [isPending, start];
}

var isUpdatingOpaqueValueInRenderPhase = false;
function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
  {
    return isUpdatingOpaqueValueInRenderPhase;
  }
}

function mountId() {
  var hook = mountWorkInProgressHook();
  var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we
  // should do this in Fiber, too? Deferring this decision for now because
  // there's no other place to store the prefix except for an internal field on
  // the public createRoot object, which the fiber tree does not currently have
  // a reference to.

  var identifierPrefix = root.identifierPrefix;
  var id;

  if (getIsHydrating()) {
    var treeId = getTreeId(); // Use a captial R prefix for server-generated ids.

    id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
    // that represents the position of this useId hook among all the useId
    // hooks for this fiber.

    var localId = localIdCounter++;

    if (localId > 0) {
      id += 'H' + localId.toString(32);
    }

    id += ':';
  } else {
    // Use a lowercase r prefix for client-generated ids.
    var globalClientId = globalClientIdCounter++;
    id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':';
  }

  hook.memoizedState = id;
  return id;
}

function updateId() {
  var hook = updateWorkInProgressHook();
  var id = hook.memoizedState;
  return id;
}

function dispatchReducerAction(fiber, queue, action) {
  {
    if (typeof arguments[3] === 'function') {
      error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
    }
  }

  var lane = requestUpdateLane(fiber);
  var update = {
    lane: lane,
    action: action,
    hasEagerState: false,
    eagerState: null,
    next: null
  };

  if (isRenderPhaseUpdate(fiber)) {
    enqueueRenderPhaseUpdate(queue, update);
  } else {
    var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);

    if (root !== null) {
      var eventTime = requestEventTime();
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
      entangleTransitionUpdate(root, queue, lane);
    }
  }

  markUpdateInDevTools(fiber, lane);
}

function dispatchSetState(fiber, queue, action) {
  {
    if (typeof arguments[3] === 'function') {
      error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
    }
  }

  var lane = requestUpdateLane(fiber);
  var update = {
    lane: lane,
    action: action,
    hasEagerState: false,
    eagerState: null,
    next: null
  };

  if (isRenderPhaseUpdate(fiber)) {
    enqueueRenderPhaseUpdate(queue, update);
  } else {
    var alternate = fiber.alternate;

    if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
      // The queue is currently empty, which means we can eagerly compute the
      // next state before entering the render phase. If the new state is the
      // same as the current state, we may be able to bail out entirely.
      var lastRenderedReducer = queue.lastRenderedReducer;

      if (lastRenderedReducer !== null) {
        var prevDispatcher;

        {
          prevDispatcher = ReactCurrentDispatcher$1.current;
          ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
        }

        try {
          var currentState = queue.lastRenderedState;
          var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
          // it, on the update object. If the reducer hasn't changed by the
          // time we enter the render phase, then the eager state can be used
          // without calling the reducer again.

          update.hasEagerState = true;
          update.eagerState = eagerState;

          if (objectIs(eagerState, currentState)) {
            // Fast path. We can bail out without scheduling React to re-render.
            // It's still possible that we'll need to rebase this update later,
            // if the component re-renders for a different reason and by that
            // time the reducer has changed.
            // TODO: Do we still need to entangle transitions in this case?
            enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane);
            return;
          }
        } catch (error) {// Suppress the error. It will throw again in the render phase.
        } finally {
          {
            ReactCurrentDispatcher$1.current = prevDispatcher;
          }
        }
      }
    }

    var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);

    if (root !== null) {
      var eventTime = requestEventTime();
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
      entangleTransitionUpdate(root, queue, lane);
    }
  }

  markUpdateInDevTools(fiber, lane);
}

function isRenderPhaseUpdate(fiber) {
  var alternate = fiber.alternate;
  return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
}

function enqueueRenderPhaseUpdate(queue, update) {
  // This is a render phase update. Stash it in a lazily-created map of
  // queue -> linked list of updates. After this render pass, we'll restart
  // and apply the stashed updates on top of the work-in-progress hook.
  didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
  var pending = queue.pending;

  if (pending === null) {
    // This is the first update. Create a circular list.
    update.next = update;
  } else {
    update.next = pending.next;
    pending.next = update;
  }

  queue.pending = update;
} // TODO: Move to ReactFiberConcurrentUpdates?


function entangleTransitionUpdate(root, queue, lane) {
  if (isTransitionLane(lane)) {
    var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they
    // must have finished. We can remove them from the shared queue, which
    // represents a superset of the actually pending lanes. In some cases we
    // may entangle more than we need to, but that's OK. In fact it's worse if
    // we *don't* entangle when we should.

    queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.

    var newQueueLanes = mergeLanes(queueLanes, lane);
    queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
    // the lane finished since the last time we entangled it. So we need to
    // entangle it again, just to be sure.

    markRootEntangled(root, newQueueLanes);
  }
}

function markUpdateInDevTools(fiber, lane, action) {

  {
    markStateUpdateScheduled(fiber, lane);
  }
}

var ContextOnlyDispatcher = {
  readContext: readContext,
  useCallback: throwInvalidHookError,
  useContext: throwInvalidHookError,
  useEffect: throwInvalidHookError,
  useImperativeHandle: throwInvalidHookError,
  useInsertionEffect: throwInvalidHookError,
  useLayoutEffect: throwInvalidHookError,
  useMemo: throwInvalidHookError,
  useReducer: throwInvalidHookError,
  useRef: throwInvalidHookError,
  useState: throwInvalidHookError,
  useDebugValue: throwInvalidHookError,
  useDeferredValue: throwInvalidHookError,
  useTransition: throwInvalidHookError,
  useMutableSource: throwInvalidHookError,
  useSyncExternalStore: throwInvalidHookError,
  useId: throwInvalidHookError,
  unstable_isNewReconciler: enableNewReconciler
};

var HooksDispatcherOnMountInDEV = null;
var HooksDispatcherOnMountWithHookTypesInDEV = null;
var HooksDispatcherOnUpdateInDEV = null;
var HooksDispatcherOnRerenderInDEV = null;
var InvalidNestedHooksDispatcherOnMountInDEV = null;
var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
var InvalidNestedHooksDispatcherOnRerenderInDEV = null;

{
  var warnInvalidContextAccess = function () {
    error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
  };

  var warnInvalidHookAccess = function () {
    error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
  };

  HooksDispatcherOnMountInDEV = {
    readContext: function (context) {
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      return mountCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      mountHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      return mountEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      return mountImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      return mountInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      return mountLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      mountHookTypesDev();
      checkDepsAreArrayDev(deps);
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      mountHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      mountHookTypesDev();
      return mountRef(initialValue);
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      mountHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      mountHookTypesDev();
      return mountDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      mountHookTypesDev();
      return mountDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      mountHookTypesDev();
      return mountTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      mountHookTypesDev();
      return mountMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      mountHookTypesDev();
      return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      mountHookTypesDev();
      return mountId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  HooksDispatcherOnMountWithHookTypesInDEV = {
    readContext: function (context) {
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      updateHookTypesDev();
      return mountCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      updateHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      updateHookTypesDev();
      return mountEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      updateHookTypesDev();
      return mountImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      updateHookTypesDev();
      return mountInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      updateHookTypesDev();
      return mountLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      updateHookTypesDev();
      return mountRef(initialValue);
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      updateHookTypesDev();
      return mountDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      updateHookTypesDev();
      return mountDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      updateHookTypesDev();
      return mountTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      updateHookTypesDev();
      return mountMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      updateHookTypesDev();
      return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      updateHookTypesDev();
      return mountId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  HooksDispatcherOnUpdateInDEV = {
    readContext: function (context) {
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      updateHookTypesDev();
      return updateCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      updateHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      updateHookTypesDev();
      return updateEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      updateHookTypesDev();
      return updateImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      updateHookTypesDev();
      return updateInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      updateHookTypesDev();
      return updateLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      updateHookTypesDev();
      return updateRef();
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      updateHookTypesDev();
      return updateDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      updateHookTypesDev();
      return updateDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      updateHookTypesDev();
      return updateTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      updateHookTypesDev();
      return updateMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      updateHookTypesDev();
      return updateSyncExternalStore(subscribe, getSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      updateHookTypesDev();
      return updateId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  HooksDispatcherOnRerenderInDEV = {
    readContext: function (context) {
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      updateHookTypesDev();
      return updateCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      updateHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      updateHookTypesDev();
      return updateEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      updateHookTypesDev();
      return updateImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      updateHookTypesDev();
      return updateInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      updateHookTypesDev();
      return updateLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

      try {
        return updateMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

      try {
        return rerenderReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      updateHookTypesDev();
      return updateRef();
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

      try {
        return rerenderState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      updateHookTypesDev();
      return updateDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      updateHookTypesDev();
      return rerenderDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      updateHookTypesDev();
      return rerenderTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      updateHookTypesDev();
      return updateMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      updateHookTypesDev();
      return updateSyncExternalStore(subscribe, getSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      updateHookTypesDev();
      return updateId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  InvalidNestedHooksDispatcherOnMountInDEV = {
    readContext: function (context) {
      warnInvalidContextAccess();
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      warnInvalidHookAccess();
      mountHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      warnInvalidHookAccess();
      mountHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountRef(initialValue);
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      warnInvalidHookAccess();
      mountHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;

      try {
        return mountState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      warnInvalidHookAccess();
      mountHookTypesDev();
      return mountId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  InvalidNestedHooksDispatcherOnUpdateInDEV = {
    readContext: function (context) {
      warnInvalidContextAccess();
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateRef();
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateSyncExternalStore(subscribe, getSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };

  InvalidNestedHooksDispatcherOnRerenderInDEV = {
    readContext: function (context) {
      warnInvalidContextAccess();
      return readContext(context);
    },
    useCallback: function (callback, deps) {
      currentHookNameInDev = 'useCallback';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateCallback(callback, deps);
    },
    useContext: function (context) {
      currentHookNameInDev = 'useContext';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return readContext(context);
    },
    useEffect: function (create, deps) {
      currentHookNameInDev = 'useEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateEffect(create, deps);
    },
    useImperativeHandle: function (ref, create, deps) {
      currentHookNameInDev = 'useImperativeHandle';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateImperativeHandle(ref, create, deps);
    },
    useInsertionEffect: function (create, deps) {
      currentHookNameInDev = 'useInsertionEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateInsertionEffect(create, deps);
    },
    useLayoutEffect: function (create, deps) {
      currentHookNameInDev = 'useLayoutEffect';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateLayoutEffect(create, deps);
    },
    useMemo: function (create, deps) {
      currentHookNameInDev = 'useMemo';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return updateMemo(create, deps);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useReducer: function (reducer, initialArg, init) {
      currentHookNameInDev = 'useReducer';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return rerenderReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useRef: function (initialValue) {
      currentHookNameInDev = 'useRef';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateRef();
    },
    useState: function (initialState) {
      currentHookNameInDev = 'useState';
      warnInvalidHookAccess();
      updateHookTypesDev();
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

      try {
        return rerenderState(initialState);
      } finally {
        ReactCurrentDispatcher$1.current = prevDispatcher;
      }
    },
    useDebugValue: function (value, formatterFn) {
      currentHookNameInDev = 'useDebugValue';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateDebugValue();
    },
    useDeferredValue: function (value) {
      currentHookNameInDev = 'useDeferredValue';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return rerenderDeferredValue(value);
    },
    useTransition: function () {
      currentHookNameInDev = 'useTransition';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return rerenderTransition();
    },
    useMutableSource: function (source, getSnapshot, subscribe) {
      currentHookNameInDev = 'useMutableSource';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateMutableSource();
    },
    useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
      currentHookNameInDev = 'useSyncExternalStore';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateSyncExternalStore(subscribe, getSnapshot);
    },
    useId: function () {
      currentHookNameInDev = 'useId';
      warnInvalidHookAccess();
      updateHookTypesDev();
      return updateId();
    },
    unstable_isNewReconciler: enableNewReconciler
  };
}

var now$1 = Scheduler.unstable_now;
var commitTime = 0;
var layoutEffectStartTime = -1;
var profilerStartTime = -1;
var passiveEffectStartTime = -1;
/**
 * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
 *
 * The overall sequence is:
 *   1. render
 *   2. commit (and call `onRender`, `onCommit`)
 *   3. check for nested updates
 *   4. flush passive effects (and call `onPostCommit`)
 *
 * Nested updates are identified in step 3 above,
 * but step 4 still applies to the work that was just committed.
 * We use two flags to track nested updates then:
 * one tracks whether the upcoming update is a nested update,
 * and the other tracks whether the current update was a nested update.
 * The first value gets synced to the second at the start of the render phase.
 */

var currentUpdateIsNested = false;
var nestedUpdateScheduled = false;

function isCurrentUpdateNested() {
  return currentUpdateIsNested;
}

function markNestedUpdateScheduled() {
  {
    nestedUpdateScheduled = true;
  }
}

function resetNestedUpdateFlag() {
  {
    currentUpdateIsNested = false;
    nestedUpdateScheduled = false;
  }
}

function syncNestedUpdateFlag() {
  {
    currentUpdateIsNested = nestedUpdateScheduled;
    nestedUpdateScheduled = false;
  }
}

function getCommitTime() {
  return commitTime;
}

function recordCommitTime() {

  commitTime = now$1();
}

function startProfilerTimer(fiber) {

  profilerStartTime = now$1();

  if (fiber.actualStartTime < 0) {
    fiber.actualStartTime = now$1();
  }
}

function stopProfilerTimerIfRunning(fiber) {

  profilerStartTime = -1;
}

function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {

  if (profilerStartTime >= 0) {
    var elapsedTime = now$1() - profilerStartTime;
    fiber.actualDuration += elapsedTime;

    if (overrideBaseTime) {
      fiber.selfBaseDuration = elapsedTime;
    }

    profilerStartTime = -1;
  }
}

function recordLayoutEffectDuration(fiber) {

  if (layoutEffectStartTime >= 0) {
    var elapsedTime = now$1() - layoutEffectStartTime;
    layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
    // Or the root (for the DevTools Profiler to read)

    var parentFiber = fiber.return;

    while (parentFiber !== null) {
      switch (parentFiber.tag) {
        case HostRoot:
          var root = parentFiber.stateNode;
          root.effectDuration += elapsedTime;
          return;

        case Profiler:
          var parentStateNode = parentFiber.stateNode;
          parentStateNode.effectDuration += elapsedTime;
          return;
      }

      parentFiber = parentFiber.return;
    }
  }
}

function recordPassiveEffectDuration(fiber) {

  if (passiveEffectStartTime >= 0) {
    var elapsedTime = now$1() - passiveEffectStartTime;
    passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
    // Or the root (for the DevTools Profiler to read)

    var parentFiber = fiber.return;

    while (parentFiber !== null) {
      switch (parentFiber.tag) {
        case HostRoot:
          var root = parentFiber.stateNode;

          if (root !== null) {
            root.passiveEffectDuration += elapsedTime;
          }

          return;

        case Profiler:
          var parentStateNode = parentFiber.stateNode;

          if (parentStateNode !== null) {
            // Detached fibers have their state node cleared out.
            // In this case, the return pointer is also cleared out,
            // so we won't be able to report the time spent in this Profiler's subtree.
            parentStateNode.passiveEffectDuration += elapsedTime;
          }

          return;
      }

      parentFiber = parentFiber.return;
    }
  }
}

function startLayoutEffectTimer() {

  layoutEffectStartTime = now$1();
}

function startPassiveEffectTimer() {

  passiveEffectStartTime = now$1();
}

function transferActualDuration(fiber) {
  // Transfer time spent rendering these children so we don't lose it
  // after we rerender. This is used as a helper in special cases
  // where we should count the work of multiple passes.
  var child = fiber.child;

  while (child) {
    fiber.actualDuration += child.actualDuration;
    child = child.sibling;
  }
}

function resolveDefaultProps(Component, baseProps) {
  if (Component && Component.defaultProps) {
    // Resolve default props. Taken from ReactElement
    var props = assign({}, baseProps);
    var defaultProps = Component.defaultProps;

    for (var propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }

    return props;
  }

  return baseProps;
}

var fakeInternalInstance = {};
var didWarnAboutStateAssignmentForComponent;
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;
var didWarnAboutLegacyContext$1;

{
  didWarnAboutStateAssignmentForComponent = new Set();
  didWarnAboutUninitializedState = new Set();
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
  didWarnAboutDirectlyAssigningPropsToState = new Set();
  didWarnAboutUndefinedDerivedState = new Set();
  didWarnAboutContextTypeAndContextTypes = new Set();
  didWarnAboutInvalidateContextType = new Set();
  didWarnAboutLegacyContext$1 = new Set();
  var didWarnOnInvalidCallback = new Set();

  warnOnInvalidCallback = function (callback, callerName) {
    if (callback === null || typeof callback === 'function') {
      return;
    }

    var key = callerName + '_' + callback;

    if (!didWarnOnInvalidCallback.has(key)) {
      didWarnOnInvalidCallback.add(key);

      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  };

  warnOnUndefinedDerivedState = function (type, partialState) {
    if (partialState === undefined) {
      var componentName = getComponentNameFromType(type) || 'Component';

      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
        didWarnAboutUndefinedDerivedState.add(componentName);

        error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
      }
    }
  }; // This is so gross but it's at least non-critical and can be removed if
  // it causes problems. This is meant to give a nicer error message for
  // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
  // ...)) which otherwise throws a "_processChildContext is not a function"
  // exception.


  Object.defineProperty(fakeInternalInstance, '_processChildContext', {
    enumerable: false,
    value: function () {
      throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).');
    }
  });
  Object.freeze(fakeInternalInstance);
}

function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
  var prevState = workInProgress.memoizedState;
  var partialState = getDerivedStateFromProps(nextProps, prevState);

  {
    if ( workInProgress.mode & StrictLegacyMode) {
      setIsStrictModeForDevtools(true);

      try {
        // Invoke the function an extra time to help detect side-effects.
        partialState = getDerivedStateFromProps(nextProps, prevState);
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }

    warnOnUndefinedDerivedState(ctor, partialState);
  } // Merge the partial state and the previous state.


  var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
  workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
  // base state.

  if (workInProgress.lanes === NoLanes) {
    // Queue is always non-null for classes
    var updateQueue = workInProgress.updateQueue;
    updateQueue.baseState = memoizedState;
  }
}

var classComponentUpdater = {
  isMounted: isMounted,
  enqueueSetState: function (inst, payload, callback) {
    var fiber = get(inst);
    var eventTime = requestEventTime();
    var lane = requestUpdateLane(fiber);
    var update = createUpdate(eventTime, lane);
    update.payload = payload;

    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback(callback, 'setState');
      }

      update.callback = callback;
    }

    var root = enqueueUpdate(fiber, update, lane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
      entangleTransitions(root, fiber, lane);
    }

    {
      markStateUpdateScheduled(fiber, lane);
    }
  },
  enqueueReplaceState: function (inst, payload, callback) {
    var fiber = get(inst);
    var eventTime = requestEventTime();
    var lane = requestUpdateLane(fiber);
    var update = createUpdate(eventTime, lane);
    update.tag = ReplaceState;
    update.payload = payload;

    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback(callback, 'replaceState');
      }

      update.callback = callback;
    }

    var root = enqueueUpdate(fiber, update, lane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
      entangleTransitions(root, fiber, lane);
    }

    {
      markStateUpdateScheduled(fiber, lane);
    }
  },
  enqueueForceUpdate: function (inst, callback) {
    var fiber = get(inst);
    var eventTime = requestEventTime();
    var lane = requestUpdateLane(fiber);
    var update = createUpdate(eventTime, lane);
    update.tag = ForceUpdate;

    if (callback !== undefined && callback !== null) {
      {
        warnOnInvalidCallback(callback, 'forceUpdate');
      }

      update.callback = callback;
    }

    var root = enqueueUpdate(fiber, update, lane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, lane, eventTime);
      entangleTransitions(root, fiber, lane);
    }

    {
      markForceUpdateScheduled(fiber, lane);
    }
  }
};

function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
  var instance = workInProgress.stateNode;

  if (typeof instance.shouldComponentUpdate === 'function') {
    var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);

    {
      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          // Invoke the function an extra time to help detect side-effects.
          shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }

      if (shouldUpdate === undefined) {
        error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component');
      }
    }

    return shouldUpdate;
  }

  if (ctor.prototype && ctor.prototype.isPureReactComponent) {
    return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
  }

  return true;
}

function checkClassInstance(workInProgress, ctor, newProps) {
  var instance = workInProgress.stateNode;

  {
    var name = getComponentNameFromType(ctor) || 'Component';
    var renderPresent = instance.render;

    if (!renderPresent) {
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
        error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
      } else {
        error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
      }
    }

    if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
      error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
    }

    if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
      error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
    }

    if (instance.propTypes) {
      error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
    }

    if (instance.contextType) {
      error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
    }

    {
      if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
      // this one.
      (workInProgress.mode & StrictLegacyMode) === NoMode) {
        didWarnAboutLegacyContext$1.add(ctor);

        error('%s uses the legacy childContextTypes API which is no longer ' + 'supported and will be removed in the next major release. Use ' + 'React.createContext() instead\n\n.' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
      }

      if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
      // this one.
      (workInProgress.mode & StrictLegacyMode) === NoMode) {
        didWarnAboutLegacyContext$1.add(ctor);

        error('%s uses the legacy contextTypes API which is no longer supported ' + 'and will be removed in the next major release. Use ' + 'React.createContext() with static contextType instead.\n\n' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
      }

      if (instance.contextTypes) {
        error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
      }

      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
        didWarnAboutContextTypeAndContextTypes.add(ctor);

        error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
      }
    }

    if (typeof instance.componentShouldUpdate === 'function') {
      error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
    }

    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
      error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
    }

    if (typeof instance.componentDidUnmount === 'function') {
      error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
    }

    if (typeof instance.componentDidReceiveProps === 'function') {
      error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
    }

    if (typeof instance.componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
    }

    if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
      error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
    }

    var hasMutatedProps = instance.props !== newProps;

    if (instance.props !== undefined && hasMutatedProps) {
      error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
    }

    if (instance.defaultProps) {
      error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);

      error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
    }

    if (typeof instance.getDerivedStateFromProps === 'function') {
      error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof instance.getDerivedStateFromError === 'function') {
      error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
    }

    if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
      error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
    }

    var _state = instance.state;

    if (_state && (typeof _state !== 'object' || isArray(_state))) {
      error('%s.state: must be set to an object or null', name);
    }

    if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
      error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
    }
  }
}

function adoptClassInstance(workInProgress, instance) {
  instance.updater = classComponentUpdater;
  workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates

  set(instance, workInProgress);

  {
    instance._reactInternalInstance = fakeInternalInstance;
  }
}

function constructClassInstance(workInProgress, ctor, props) {
  var isLegacyContextConsumer = false;
  var unmaskedContext = emptyContextObject;
  var context = emptyContextObject;
  var contextType = ctor.contextType;

  {
    if ('contextType' in ctor) {
      var isValid = // Allow null for conditional declaration
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
        didWarnAboutInvalidateContextType.add(ctor);
        var addendum = '';

        if (contextType === undefined) {
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
        } else if (typeof contextType !== 'object') {
          addendum = ' However, it is set to a ' + typeof contextType + '.';
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
          addendum = ' Did you accidentally pass the Context.Provider instead?';
        } else if (contextType._context !== undefined) {
          // <Context.Consumer>
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
        } else {
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
        }

        error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
      }
    }
  }

  if (typeof contextType === 'object' && contextType !== null) {
    context = readContext(contextType);
  } else {
    unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
    var contextTypes = ctor.contextTypes;
    isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
    context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
  }

  var instance = new ctor(props, context); // Instantiate twice to help detect side-effects.

  {
    if ( workInProgress.mode & StrictLegacyMode) {
      setIsStrictModeForDevtools(true);

      try {
        instance = new ctor(props, context); // eslint-disable-line no-new
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }
  }

  var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
  adoptClassInstance(workInProgress, instance);

  {
    if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutUninitializedState.has(componentName)) {
        didWarnAboutUninitializedState.add(componentName);

        error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
      }
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
    // Warn about these lifecycles if they are present.
    // Don't warn about react-lifecycles-compat polyfilled methods though.


    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
      var foundWillMountName = null;
      var foundWillReceivePropsName = null;
      var foundWillUpdateName = null;

      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
        foundWillMountName = 'componentWillMount';
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
        foundWillMountName = 'UNSAFE_componentWillMount';
      }

      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
        foundWillReceivePropsName = 'componentWillReceiveProps';
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
      }

      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
        foundWillUpdateName = 'componentWillUpdate';
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
      }

      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
        var _componentName = getComponentNameFromType(ctor) || 'Component';

        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);

          error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
        }
      }
    }
  } // Cache unmasked context so we can avoid recreating masked context unless necessary.
  // ReactFiberContext usually updates this cache but can't for newly-created instances.


  if (isLegacyContextConsumer) {
    cacheContext(workInProgress, unmaskedContext, context);
  }

  return instance;
}

function callComponentWillMount(workInProgress, instance) {
  var oldState = instance.state;

  if (typeof instance.componentWillMount === 'function') {
    instance.componentWillMount();
  }

  if (typeof instance.UNSAFE_componentWillMount === 'function') {
    instance.UNSAFE_componentWillMount();
  }

  if (oldState !== instance.state) {
    {
      error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component');
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
}

function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
  var oldState = instance.state;

  if (typeof instance.componentWillReceiveProps === 'function') {
    instance.componentWillReceiveProps(newProps, nextContext);
  }

  if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
    instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
  }

  if (instance.state !== oldState) {
    {
      var componentName = getComponentNameFromFiber(workInProgress) || 'Component';

      if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
        didWarnAboutStateAssignmentForComponent.add(componentName);

        error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
      }
    }

    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
} // Invokes the mount life-cycles on a previously never rendered instance.


function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
  {
    checkClassInstance(workInProgress, ctor, newProps);
  }

  var instance = workInProgress.stateNode;
  instance.props = newProps;
  instance.state = workInProgress.memoizedState;
  instance.refs = {};
  initializeUpdateQueue(workInProgress);
  var contextType = ctor.contextType;

  if (typeof contextType === 'object' && contextType !== null) {
    instance.context = readContext(contextType);
  } else {
    var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
    instance.context = getMaskedContext(workInProgress, unmaskedContext);
  }

  {
    if (instance.state === newProps) {
      var componentName = getComponentNameFromType(ctor) || 'Component';

      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);

        error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
      }
    }

    if (workInProgress.mode & StrictLegacyMode) {
      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
    }

    {
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
    }
  }

  instance.state = workInProgress.memoizedState;
  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
    instance.state = workInProgress.memoizedState;
  } // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.


  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
    callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
    // process them now.

    processUpdateQueue(workInProgress, newProps, instance, renderLanes);
    instance.state = workInProgress.memoizedState;
  }

  if (typeof instance.componentDidMount === 'function') {
    var fiberFlags = Update;

    {
      fiberFlags |= LayoutStatic;
    }

    if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
      fiberFlags |= MountLayoutDev;
    }

    workInProgress.flags |= fiberFlags;
  }
}

function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
  var instance = workInProgress.stateNode;
  var oldProps = workInProgress.memoizedProps;
  instance.props = oldProps;
  var oldContext = instance.context;
  var contextType = ctor.contextType;
  var nextContext = emptyContextObject;

  if (typeof contextType === 'object' && contextType !== null) {
    nextContext = readContext(contextType);
  } else {
    var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
    nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
  // ever the previously attempted to render - not the "current". However,
  // during componentDidUpdate we pass the "current" props.
  // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.

  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
    if (oldProps !== newProps || oldContext !== nextContext) {
      callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
    }
  }

  resetHasForceUpdateBeforeProcessing();
  var oldState = workInProgress.memoizedState;
  var newState = instance.state = oldState;
  processUpdateQueue(workInProgress, newProps, instance, renderLanes);
  newState = workInProgress.memoizedState;

  if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidMount === 'function') {
      var fiberFlags = Update;

      {
        fiberFlags |= LayoutStatic;
      }

      if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
        fiberFlags |= MountLayoutDev;
      }

      workInProgress.flags |= fiberFlags;
    }

    return false;
  }

  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
    newState = workInProgress.memoizedState;
  }

  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);

  if (shouldUpdate) {
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
      if (typeof instance.componentWillMount === 'function') {
        instance.componentWillMount();
      }

      if (typeof instance.UNSAFE_componentWillMount === 'function') {
        instance.UNSAFE_componentWillMount();
      }
    }

    if (typeof instance.componentDidMount === 'function') {
      var _fiberFlags = Update;

      {
        _fiberFlags |= LayoutStatic;
      }

      if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
        _fiberFlags |= MountLayoutDev;
      }

      workInProgress.flags |= _fiberFlags;
    }
  } else {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidMount === 'function') {
      var _fiberFlags2 = Update;

      {
        _fiberFlags2 |= LayoutStatic;
      }

      if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
        _fiberFlags2 |= MountLayoutDev;
      }

      workInProgress.flags |= _fiberFlags2;
    } // If shouldComponentUpdate returned false, we should still update the
    // memoized state to indicate that this work can be reused.


    workInProgress.memoizedProps = newProps;
    workInProgress.memoizedState = newState;
  } // Update the existing instance's state, props, and context pointers even
  // if shouldComponentUpdate returns false.


  instance.props = newProps;
  instance.state = newState;
  instance.context = nextContext;
  return shouldUpdate;
} // Invokes the update life-cycles and returns false if it shouldn't rerender.


function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
  var instance = workInProgress.stateNode;
  cloneUpdateQueue(current, workInProgress);
  var unresolvedOldProps = workInProgress.memoizedProps;
  var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
  instance.props = oldProps;
  var unresolvedNewProps = workInProgress.pendingProps;
  var oldContext = instance.context;
  var contextType = ctor.contextType;
  var nextContext = emptyContextObject;

  if (typeof contextType === 'object' && contextType !== null) {
    nextContext = readContext(contextType);
  } else {
    var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
    nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
  }

  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
  // ever the previously attempted to render - not the "current". However,
  // during componentDidUpdate we pass the "current" props.
  // In order to support react-lifecycles-compat polyfilled components,
  // Unsafe lifecycles should not be invoked for components using the new APIs.

  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
    if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
      callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
    }
  }

  resetHasForceUpdateBeforeProcessing();
  var oldState = workInProgress.memoizedState;
  var newState = instance.state = oldState;
  processUpdateQueue(workInProgress, newProps, instance, renderLanes);
  newState = workInProgress.memoizedState;

  if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation   )) {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidUpdate === 'function') {
      if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.flags |= Update;
      }
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.flags |= Snapshot;
      }
    }

    return false;
  }

  if (typeof getDerivedStateFromProps === 'function') {
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
    newState = workInProgress.memoizedState;
  }

  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
  // both before and after `shouldComponentUpdate` has been called. Not ideal,
  // but I'm loath to refactor this function. This only happens for memoized
  // components so it's not that common.
  enableLazyContextPropagation   ;

  if (shouldUpdate) {
    // In order to support react-lifecycles-compat polyfilled components,
    // Unsafe lifecycles should not be invoked for components using the new APIs.
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
      if (typeof instance.componentWillUpdate === 'function') {
        instance.componentWillUpdate(newProps, newState, nextContext);
      }

      if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
        instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
      }
    }

    if (typeof instance.componentDidUpdate === 'function') {
      workInProgress.flags |= Update;
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      workInProgress.flags |= Snapshot;
    }
  } else {
    // If an update was already in progress, we should schedule an Update
    // effect even though we're bailing out, so that cWU/cDU are called.
    if (typeof instance.componentDidUpdate === 'function') {
      if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.flags |= Update;
      }
    }

    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
      if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
        workInProgress.flags |= Snapshot;
      }
    } // If shouldComponentUpdate returned false, we should still update the
    // memoized props/state to indicate that this work can be reused.


    workInProgress.memoizedProps = newProps;
    workInProgress.memoizedState = newState;
  } // Update the existing instance's state, props, and context pointers even
  // if shouldComponentUpdate returns false.


  instance.props = newProps;
  instance.state = newState;
  instance.context = nextContext;
  return shouldUpdate;
}

function createCapturedValueAtFiber(value, source) {
  // If the value is an error, call this function immediately after it is thrown
  // so the stack is accurate.
  return {
    value: value,
    source: source,
    stack: getStackByFiberInDevAndProd(source),
    digest: null
  };
}
function createCapturedValue(value, digest, stack) {
  return {
    value: value,
    source: null,
    stack: stack != null ? stack : null,
    digest: digest != null ? digest : null
  };
}

// This module is forked in different environments.
// By default, return `true` to log errors to the console.
// Forks can return `false` if this isn't desirable.
function showErrorDialog(boundary, errorInfo) {
  return true;
}

function logCapturedError(boundary, errorInfo) {
  try {
    var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
    // This enables renderers like ReactNative to better manage redbox behavior.

    if (logError === false) {
      return;
    }

    var error = errorInfo.value;

    if (true) {
      var source = errorInfo.source;
      var stack = errorInfo.stack;
      var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
      // `preventDefault()` in window `error` handler.
      // We record this information as an expando on the error.

      if (error != null && error._suppressLogging) {
        if (boundary.tag === ClassComponent) {
          // The error is recoverable and was silenced.
          // Ignore it and don't print the stack addendum.
          // This is handy for testing error boundaries without noise.
          return;
        } // The error is fatal. Since the silencing might have
        // been accidental, we'll surface it anyway.
        // However, the browser would have silenced the original error
        // so we'll print it first, and then print the stack addendum.


        console['error'](error); // Don't transform to our wrapper
        // For a more detailed description of this block, see:
        // https://github.com/facebook/react/pull/13384
      }

      var componentName = source ? getComponentNameFromFiber(source) : null;
      var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
      var errorBoundaryMessage;

      if (boundary.tag === HostRoot) {
        errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';
      } else {
        var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous';
        errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
      }

      var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
      // We don't include the original error message and JS stack because the browser
      // has already printed it. Even if the application swallows the error, it is still
      // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.

      console['error'](combinedMessage); // Don't transform to our wrapper
    } else {
      // In production, we print the error directly.
      // This will include the message, the JS stack, and anything the browser wants to show.
      // We pass the error object instead of custom message so that the browser displays the error natively.
      console['error'](error); // Don't transform to our wrapper
    }
  } catch (e) {
    // This method must not throw, or React internal state will get messed up.
    // If console.error is overridden, or logCapturedError() shows a dialog that throws,
    // we want to report this error outside of the normal stack as a last resort.
    // https://github.com/facebook/react/issues/13188
    setTimeout(function () {
      throw e;
    });
  }
}

var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;

function createRootErrorUpdate(fiber, errorInfo, lane) {
  var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.

  update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
  // being called "element".

  update.payload = {
    element: null
  };
  var error = errorInfo.value;

  update.callback = function () {
    onUncaughtError(error);
    logCapturedError(fiber, errorInfo);
  };

  return update;
}

function createClassErrorUpdate(fiber, errorInfo, lane) {
  var update = createUpdate(NoTimestamp, lane);
  update.tag = CaptureUpdate;
  var getDerivedStateFromError = fiber.type.getDerivedStateFromError;

  if (typeof getDerivedStateFromError === 'function') {
    var error$1 = errorInfo.value;

    update.payload = function () {
      return getDerivedStateFromError(error$1);
    };

    update.callback = function () {
      {
        markFailedErrorBoundaryForHotReloading(fiber);
      }

      logCapturedError(fiber, errorInfo);
    };
  }

  var inst = fiber.stateNode;

  if (inst !== null && typeof inst.componentDidCatch === 'function') {
    update.callback = function callback() {
      {
        markFailedErrorBoundaryForHotReloading(fiber);
      }

      logCapturedError(fiber, errorInfo);

      if (typeof getDerivedStateFromError !== 'function') {
        // To preserve the preexisting retry behavior of error boundaries,
        // we keep track of which ones already failed during this batch.
        // This gets reset before we yield back to the browser.
        // TODO: Warn in strict mode if getDerivedStateFromError is
        // not defined.
        markLegacyErrorBoundaryAsFailed(this);
      }

      var error$1 = errorInfo.value;
      var stack = errorInfo.stack;
      this.componentDidCatch(error$1, {
        componentStack: stack !== null ? stack : ''
      });

      {
        if (typeof getDerivedStateFromError !== 'function') {
          // If componentDidCatch is the only error boundary method defined,
          // then it needs to call setState to recover from errors.
          // If no state update is scheduled then the boundary will swallow the error.
          if (!includesSomeLane(fiber.lanes, SyncLane)) {
            error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown');
          }
        }
      }
    };
  }

  return update;
}

function attachPingListener(root, wakeable, lanes) {
  // Attach a ping listener
  //
  // The data might resolve before we have a chance to commit the fallback. Or,
  // in the case of a refresh, we'll never commit a fallback. So we need to
  // attach a listener now. When it resolves ("pings"), we can decide whether to
  // try rendering the tree again.
  //
  // Only attach a listener if one does not already exist for the lanes
  // we're currently rendering (which acts like a "thread ID" here).
  //
  // We only need to do this in concurrent mode. Legacy Suspense always
  // commits fallbacks synchronously, so there are no pings.
  var pingCache = root.pingCache;
  var threadIDs;

  if (pingCache === null) {
    pingCache = root.pingCache = new PossiblyWeakMap$1();
    threadIDs = new Set();
    pingCache.set(wakeable, threadIDs);
  } else {
    threadIDs = pingCache.get(wakeable);

    if (threadIDs === undefined) {
      threadIDs = new Set();
      pingCache.set(wakeable, threadIDs);
    }
  }

  if (!threadIDs.has(lanes)) {
    // Memoize using the thread ID to prevent redundant listeners.
    threadIDs.add(lanes);
    var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);

    {
      if (isDevToolsPresent) {
        // If we have pending work still, restore the original updaters
        restorePendingUpdaters(root, lanes);
      }
    }

    wakeable.then(ping, ping);
  }
}

function attachRetryListener(suspenseBoundary, root, wakeable, lanes) {
  // Retry listener
  //
  // If the fallback does commit, we need to attach a different type of
  // listener. This one schedules an update on the Suspense boundary to turn
  // the fallback state off.
  //
  // Stash the wakeable on the boundary fiber so we can access it in the
  // commit phase.
  //
  // When the wakeable resolves, we'll attempt to render the boundary
  // again ("retry").
  var wakeables = suspenseBoundary.updateQueue;

  if (wakeables === null) {
    var updateQueue = new Set();
    updateQueue.add(wakeable);
    suspenseBoundary.updateQueue = updateQueue;
  } else {
    wakeables.add(wakeable);
  }
}

function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
  // A legacy mode Suspense quirk, only relevant to hook components.


  var tag = sourceFiber.tag;

  if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
    var currentSource = sourceFiber.alternate;

    if (currentSource) {
      sourceFiber.updateQueue = currentSource.updateQueue;
      sourceFiber.memoizedState = currentSource.memoizedState;
      sourceFiber.lanes = currentSource.lanes;
    } else {
      sourceFiber.updateQueue = null;
      sourceFiber.memoizedState = null;
    }
  }
}

function getNearestSuspenseBoundaryToCapture(returnFiber) {
  var node = returnFiber;

  do {
    if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) {
      return node;
    } // This boundary already captured during this render. Continue to the next
    // boundary.


    node = node.return;
  } while (node !== null);

  return null;
}

function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) {
  // This marks a Suspense boundary so that when we're unwinding the stack,
  // it captures the suspended "exception" and does a second (fallback) pass.
  if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
    // Legacy Mode Suspense
    //
    // If the boundary is in legacy mode, we should *not*
    // suspend the commit. Pretend as if the suspended component rendered
    // null and keep rendering. When the Suspense boundary completes,
    // we'll do a second pass to render the fallback.
    if (suspenseBoundary === returnFiber) {
      // Special case where we suspended while reconciling the children of
      // a Suspense boundary's inner Offscreen wrapper fiber. This happens
      // when a React.lazy component is a direct child of a
      // Suspense boundary.
      //
      // Suspense boundaries are implemented as multiple fibers, but they
      // are a single conceptual unit. The legacy mode behavior where we
      // pretend the suspended fiber committed as `null` won't work,
      // because in this case the "suspended" fiber is the inner
      // Offscreen wrapper.
      //
      // Because the contents of the boundary haven't started rendering
      // yet (i.e. nothing in the tree has partially rendered) we can
      // switch to the regular, concurrent mode behavior: mark the
      // boundary with ShouldCapture and enter the unwind phase.
      suspenseBoundary.flags |= ShouldCapture;
    } else {
      suspenseBoundary.flags |= DidCapture;
      sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
      // But we shouldn't call any lifecycle methods or callbacks. Remove
      // all lifecycle effect tags.

      sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);

      if (sourceFiber.tag === ClassComponent) {
        var currentSourceFiber = sourceFiber.alternate;

        if (currentSourceFiber === null) {
          // This is a new mount. Change the tag so it's not mistaken for a
          // completed class component. For example, we should not call
          // componentWillUnmount if it is deleted.
          sourceFiber.tag = IncompleteClassComponent;
        } else {
          // When we try rendering again, we should not reuse the current fiber,
          // since it's known to be in an inconsistent state. Use a force update to
          // prevent a bail out.
          var update = createUpdate(NoTimestamp, SyncLane);
          update.tag = ForceUpdate;
          enqueueUpdate(sourceFiber, update, SyncLane);
        }
      } // The source fiber did not complete. Mark it with Sync priority to
      // indicate that it still has pending work.


      sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
    }

    return suspenseBoundary;
  } // Confirmed that the boundary is in a concurrent mode tree. Continue
  // with the normal suspend path.
  //
  // After this we'll use a set of heuristics to determine whether this
  // render pass will run to completion or restart or "suspend" the commit.
  // The actual logic for this is spread out in different places.
  //
  // This first principle is that if we're going to suspend when we complete
  // a root, then we should also restart if we get an update or ping that
  // might unsuspend it, and vice versa. The only reason to suspend is
  // because you think you might want to restart before committing. However,
  // it doesn't make sense to restart only while in the period we're suspended.
  //
  // Restarting too aggressively is also not good because it starves out any
  // intermediate loading state. So we use heuristics to determine when.
  // Suspense Heuristics
  //
  // If nothing threw a Promise or all the same fallbacks are already showing,
  // then don't suspend/restart.
  //
  // If this is an initial render of a new tree of Suspense boundaries and
  // those trigger a fallback, then don't suspend/restart. We want to ensure
  // that we can show the initial loading state as quickly as possible.
  //
  // If we hit a "Delayed" case, such as when we'd switch from content back into
  // a fallback, then we should always suspend/restart. Transitions apply
  // to this case. If none is defined, JND is used instead.
  //
  // If we're already showing a fallback and it gets "retried", allowing us to show
  // another level, but there's still an inner boundary that would show a fallback,
  // then we suspend/restart for 500ms since the last time we showed a fallback
  // anywhere in the tree. This effectively throttles progressive loading into a
  // consistent train of commits. This also gives us an opportunity to restart to
  // get to the completed state slightly earlier.
  //
  // If there's ambiguity due to batching it's resolved in preference of:
  // 1) "delayed", 2) "initial render", 3) "retry".
  //
  // We want to ensure that a "busy" state doesn't get force committed. We want to
  // ensure that new initial loading states can commit as soon as possible.


  suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in
  // the begin phase to prevent an early bailout.

  suspenseBoundary.lanes = rootRenderLanes;
  return suspenseBoundary;
}

function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
  // The source fiber did not complete.
  sourceFiber.flags |= Incomplete;

  {
    if (isDevToolsPresent) {
      // If we have pending work still, restore the original updaters
      restorePendingUpdaters(root, rootRenderLanes);
    }
  }

  if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
    // This is a wakeable. The component suspended.
    var wakeable = value;
    resetSuspendedComponent(sourceFiber);

    {
      if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
        markDidThrowWhileHydratingDEV();
      }
    }


    var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);

    if (suspenseBoundary !== null) {
      suspenseBoundary.flags &= ~ForceClientRender;
      markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always
      // commits fallbacks synchronously, so there are no pings.

      if (suspenseBoundary.mode & ConcurrentMode) {
        attachPingListener(root, wakeable, rootRenderLanes);
      }

      attachRetryListener(suspenseBoundary, root, wakeable);
      return;
    } else {
      // No boundary was found. Unless this is a sync update, this is OK.
      // We can suspend and wait for more data to arrive.
      if (!includesSyncLane(rootRenderLanes)) {
        // This is not a sync update. Suspend. Since we're not activating a
        // Suspense boundary, this will unwind all the way to the root without
        // performing a second pass to render a fallback. (This is arguably how
        // refresh transitions should work, too, since we're not going to commit
        // the fallbacks anyway.)
        //
        // This case also applies to initial hydration.
        attachPingListener(root, wakeable, rootRenderLanes);
        renderDidSuspendDelayIfPossible();
        return;
      } // This is a sync/discrete update. We treat this case like an error
      // because discrete renders are expected to produce a complete tree
      // synchronously to maintain consistency with external state.


      var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path.
      // The error will be caught by the nearest suspense boundary.

      value = uncaughtSuspenseError;
    }
  } else {
    // This is a regular error, not a Suspense wakeable.
    if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
      markDidThrowWhileHydratingDEV();

      var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by
      // discarding the dehydrated content and switching to a client render.
      // Instead of surfacing the error, find the nearest Suspense boundary
      // and render it again without hydration.


      if (_suspenseBoundary !== null) {
        if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
          // Set a flag to indicate that we should try rendering the normal
          // children again, not the fallback.
          _suspenseBoundary.flags |= ForceClientRender;
        }

        markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should
        // still log it so it can be fixed.

        queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
        return;
      }
    }
  }

  value = createCapturedValueAtFiber(value, sourceFiber);
  renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start
  // over and traverse parent path again, this time treating the exception
  // as an error.

  var workInProgress = returnFiber;

  do {
    switch (workInProgress.tag) {
      case HostRoot:
        {
          var _errorInfo = value;
          workInProgress.flags |= ShouldCapture;
          var lane = pickArbitraryLane(rootRenderLanes);
          workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
          var update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
          enqueueCapturedUpdate(workInProgress, update);
          return;
        }

      case ClassComponent:
        // Capture and retry
        var errorInfo = value;
        var ctor = workInProgress.type;
        var instance = workInProgress.stateNode;

        if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
          workInProgress.flags |= ShouldCapture;

          var _lane = pickArbitraryLane(rootRenderLanes);

          workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state

          var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane);

          enqueueCapturedUpdate(workInProgress, _update);
          return;
        }

        break;
    }

    workInProgress = workInProgress.return;
  } while (workInProgress !== null);
}

function getSuspendedCache() {
  {
    return null;
  } // This function is called when a Suspense boundary suspends. It returns the
}

var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var didReceiveUpdate = false;
var didWarnAboutBadClass;
var didWarnAboutModulePatternComponent;
var didWarnAboutContextTypeOnFunctionComponent;
var didWarnAboutGetDerivedStateOnFunctionComponent;
var didWarnAboutFunctionRefs;
var didWarnAboutReassigningProps;
var didWarnAboutRevealOrder;
var didWarnAboutTailOptions;
var didWarnAboutDefaultPropsOnFunctionComponent;

{
  didWarnAboutBadClass = {};
  didWarnAboutModulePatternComponent = {};
  didWarnAboutContextTypeOnFunctionComponent = {};
  didWarnAboutGetDerivedStateOnFunctionComponent = {};
  didWarnAboutFunctionRefs = {};
  didWarnAboutReassigningProps = false;
  didWarnAboutRevealOrder = {};
  didWarnAboutTailOptions = {};
  didWarnAboutDefaultPropsOnFunctionComponent = {};
}

function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
  if (current === null) {
    // If this is a fresh new component that hasn't been rendered yet, we
    // won't update its child set by applying minimal side-effects. Instead,
    // we will add them all to the child before it gets rendered. That means
    // we can optimize this reconciliation pass by not tracking side-effects.
    workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
  } else {
    // If the current child is the same as the work in progress, it means that
    // we haven't yet started any work on these children. Therefore, we use
    // the clone algorithm to create a copy of all the current children.
    // If we had any progressed work already, that is invalid at this point so
    // let's throw it out.
    workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
  }
}

function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
  // This function is fork of reconcileChildren. It's used in cases where we
  // want to reconcile without matching against the existing set. This has the
  // effect of all current children being unmounted; even if the type and key
  // are the same, the old child is unmounted and a new child is created.
  //
  // To do this, we're going to go through the reconcile algorithm twice. In
  // the first pass, we schedule a deletion for all the current children by
  // passing null.
  workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
  // pass null in place of where we usually pass the current child set. This has
  // the effect of remounting all children regardless of whether their
  // identities match.

  workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
}

function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
  // TODO: current can be non-null here even if the component
  // hasn't yet mounted. This happens after the first render suspends.
  // We'll need to figure out if this is fine or can cause issues.
  {
    if (workInProgress.type !== workInProgress.elementType) {
      // Lazy component props can't be validated in createElement
      // because they're only guaranteed to be resolved here.
      var innerPropTypes = Component.propTypes;

      if (innerPropTypes) {
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
        'prop', getComponentNameFromType(Component));
      }
    }
  }

  var render = Component.render;
  var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent

  var nextChildren;
  var hasId;
  prepareToReadContext(workInProgress, renderLanes);

  {
    markComponentRenderStarted(workInProgress);
  }

  {
    ReactCurrentOwner$1.current = workInProgress;
    setIsRendering(true);
    nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
    hasId = checkDidRenderIdHook();

    if ( workInProgress.mode & StrictLegacyMode) {
      setIsStrictModeForDevtools(true);

      try {
        nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
        hasId = checkDidRenderIdHook();
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }

    setIsRendering(false);
  }

  {
    markComponentRenderStopped();
  }

  if (current !== null && !didReceiveUpdate) {
    bailoutHooks(current, workInProgress, renderLanes);
    return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
  }

  if (getIsHydrating() && hasId) {
    pushMaterializedTreeId(workInProgress);
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
  if (current === null) {
    var type = Component.type;

    if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
    Component.defaultProps === undefined) {
      var resolvedType = type;

      {
        resolvedType = resolveFunctionForHotReloading(type);
      } // If this is a plain function component without default props,
      // and with only the default shallow comparison, we upgrade it
      // to a SimpleMemoComponent to allow fast path updates.


      workInProgress.tag = SimpleMemoComponent;
      workInProgress.type = resolvedType;

      {
        validateFunctionComponentInDev(workInProgress, type);
      }

      return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes);
    }

    {
      var innerPropTypes = type.propTypes;

      if (innerPropTypes) {
        // Inner memo component props aren't currently validated in createElement.
        // We could move it there, but we'd still need this for lazy code path.
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
        'prop', getComponentNameFromType(type));
      }

      if ( Component.defaultProps !== undefined) {
        var componentName = getComponentNameFromType(type) || 'Unknown';

        if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
          error('%s: Support for defaultProps will be removed from memo components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

          didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
        }
      }
    }

    var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
    child.ref = workInProgress.ref;
    child.return = workInProgress;
    workInProgress.child = child;
    return child;
  }

  {
    var _type = Component.type;
    var _innerPropTypes = _type.propTypes;

    if (_innerPropTypes) {
      // Inner memo component props aren't currently validated in createElement.
      // We could move it there, but we'd still need this for lazy code path.
      checkPropTypes(_innerPropTypes, nextProps, // Resolved props
      'prop', getComponentNameFromType(_type));
    }
  }

  var currentChild = current.child; // This is always exactly one child

  var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);

  if (!hasScheduledUpdateOrContext) {
    // This will be the props with resolved defaultProps,
    // unlike current.memoizedProps which will be the unresolved ones.
    var prevProps = currentChild.memoizedProps; // Default to shallow comparison

    var compare = Component.compare;
    compare = compare !== null ? compare : shallowEqual;

    if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;
  var newChild = createWorkInProgress(currentChild, nextProps);
  newChild.ref = workInProgress.ref;
  newChild.return = workInProgress;
  workInProgress.child = newChild;
  return newChild;
}

function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
  // TODO: current can be non-null here even if the component
  // hasn't yet mounted. This happens when the inner render suspends.
  // We'll need to figure out if this is fine or can cause issues.
  {
    if (workInProgress.type !== workInProgress.elementType) {
      // Lazy component props can't be validated in createElement
      // because they're only guaranteed to be resolved here.
      var outerMemoType = workInProgress.elementType;

      if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
        // We warn when you define propTypes on lazy()
        // so let's just skip over it to find memo() outer wrapper.
        // Inner props for memo are validated later.
        var lazyComponent = outerMemoType;
        var payload = lazyComponent._payload;
        var init = lazyComponent._init;

        try {
          outerMemoType = init(payload);
        } catch (x) {
          outerMemoType = null;
        } // Inner propTypes will be validated in the function component path.


        var outerPropTypes = outerMemoType && outerMemoType.propTypes;

        if (outerPropTypes) {
          checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
          'prop', getComponentNameFromType(outerMemoType));
        }
      }
    }
  }

  if (current !== null) {
    var prevProps = current.memoizedProps;

    if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
     workInProgress.type === current.type )) {
      didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we
      // would during a normal fiber bailout.
      //
      // We don't have strong guarantees that the props object is referentially
      // equal during updates where we can't bail out anyway â€” like if the props
      // are shallowly equal, but there's a local state or context update in the
      // same batch.
      //
      // However, as a principle, we should aim to make the behavior consistent
      // across different ways of memoizing a component. For example, React.memo
      // has a different internal Fiber layout if you pass a normal function
      // component (SimpleMemoComponent) versus if you pass a different type
      // like forwardRef (MemoComponent). But this is an implementation detail.
      // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
      // affect whether the props object is reused during a bailout.

      workInProgress.pendingProps = nextProps = prevProps;

      if (!checkScheduledUpdateOrContext(current, renderLanes)) {
        // The pending lanes were cleared at the beginning of beginWork. We're
        // about to bail out, but there might be other lanes that weren't
        // included in the current render. Usually, the priority level of the
        // remaining updates is accumulated during the evaluation of the
        // component (i.e. when processing the update queue). But since since
        // we're bailing out early *without* evaluating the component, we need
        // to account for it here, too. Reset to the value of the current fiber.
        // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
        // because a MemoComponent fiber does not have hooks or an update queue;
        // rather, it wraps around an inner component, which may or may not
        // contains hooks.
        // TODO: Move the reset at in beginWork out of the common path so that
        // this is no longer necessary.
        workInProgress.lanes = current.lanes;
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
      } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
        // This is a special case that only exists for legacy mode.
        // See https://github.com/facebook/react/pull/19216.
        didReceiveUpdate = true;
      }
    }
  }

  return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
}

function updateOffscreenComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps;
  var nextChildren = nextProps.children;
  var prevState = current !== null ? current.memoizedState : null;

  if (nextProps.mode === 'hidden' || enableLegacyHidden ) {
    // Rendering a hidden tree.
    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      // In legacy sync mode, don't defer the subtree. Render it now.
      // TODO: Consider how Offscreen should work with transitions in the future
      var nextState = {
        baseLanes: NoLanes,
        cachePool: null,
        transitions: null
      };
      workInProgress.memoizedState = nextState;

      pushRenderLanes(workInProgress, renderLanes);
    } else if (!includesSomeLane(renderLanes, OffscreenLane)) {
      var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out
      // and resume this tree later.

      var nextBaseLanes;

      if (prevState !== null) {
        var prevBaseLanes = prevState.baseLanes;
        nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
      } else {
        nextBaseLanes = renderLanes;
      } // Schedule this fiber to re-render at offscreen priority. Then bailout.


      workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
      var _nextState = {
        baseLanes: nextBaseLanes,
        cachePool: spawnedCachePool,
        transitions: null
      };
      workInProgress.memoizedState = _nextState;
      workInProgress.updateQueue = null;
      // to avoid a push/pop misalignment.


      pushRenderLanes(workInProgress, nextBaseLanes);

      return null;
    } else {
      // This is the second render. The surrounding visible content has already
      // committed. Now we resume rendering the hidden tree.
      // Rendering at offscreen, so we can clear the base lanes.
      var _nextState2 = {
        baseLanes: NoLanes,
        cachePool: null,
        transitions: null
      };
      workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.

      var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;

      pushRenderLanes(workInProgress, subtreeRenderLanes);
    }
  } else {
    // Rendering a visible tree.
    var _subtreeRenderLanes;

    if (prevState !== null) {
      // We're going from hidden -> visible.
      _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes);

      workInProgress.memoizedState = null;
    } else {
      // We weren't previously hidden, and we still aren't, so there's nothing
      // special to do. Need to push to the stack regardless, though, to avoid
      // a push/pop misalignment.
      _subtreeRenderLanes = renderLanes;
    }

    pushRenderLanes(workInProgress, _subtreeRenderLanes);
  }

  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
} // Note: These happen to have identical begin phases, for now. We shouldn't hold

function updateFragment(current, workInProgress, renderLanes) {
  var nextChildren = workInProgress.pendingProps;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateMode(current, workInProgress, renderLanes) {
  var nextChildren = workInProgress.pendingProps.children;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateProfiler(current, workInProgress, renderLanes) {
  {
    workInProgress.flags |= Update;

    {
      // Reset effect durations for the next eventual effect phase.
      // These are reset during render to allow the DevTools commit hook a chance to read them,
      var stateNode = workInProgress.stateNode;
      stateNode.effectDuration = 0;
      stateNode.passiveEffectDuration = 0;
    }
  }

  var nextProps = workInProgress.pendingProps;
  var nextChildren = nextProps.children;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function markRef(current, workInProgress) {
  var ref = workInProgress.ref;

  if (current === null && ref !== null || current !== null && current.ref !== ref) {
    // Schedule a Ref effect
    workInProgress.flags |= Ref;

    {
      workInProgress.flags |= RefStatic;
    }
  }
}

function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
  {
    if (workInProgress.type !== workInProgress.elementType) {
      // Lazy component props can't be validated in createElement
      // because they're only guaranteed to be resolved here.
      var innerPropTypes = Component.propTypes;

      if (innerPropTypes) {
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
        'prop', getComponentNameFromType(Component));
      }
    }
  }

  var context;

  {
    var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
    context = getMaskedContext(workInProgress, unmaskedContext);
  }

  var nextChildren;
  var hasId;
  prepareToReadContext(workInProgress, renderLanes);

  {
    markComponentRenderStarted(workInProgress);
  }

  {
    ReactCurrentOwner$1.current = workInProgress;
    setIsRendering(true);
    nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
    hasId = checkDidRenderIdHook();

    if ( workInProgress.mode & StrictLegacyMode) {
      setIsStrictModeForDevtools(true);

      try {
        nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
        hasId = checkDidRenderIdHook();
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }

    setIsRendering(false);
  }

  {
    markComponentRenderStopped();
  }

  if (current !== null && !didReceiveUpdate) {
    bailoutHooks(current, workInProgress, renderLanes);
    return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
  }

  if (getIsHydrating() && hasId) {
    pushMaterializedTreeId(workInProgress);
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
  {
    // This is used by DevTools to force a boundary to error.
    switch (shouldError(workInProgress)) {
      case false:
        {
          var _instance = workInProgress.stateNode;
          var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack.
          // Is there a better way to do this?

          var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context);
          var state = tempInstance.state;

          _instance.updater.enqueueSetState(_instance, state, null);

          break;
        }

      case true:
        {
          workInProgress.flags |= DidCapture;
          workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes

          var error$1 = new Error('Simulated error coming from DevTools');
          var lane = pickArbitraryLane(renderLanes);
          workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state

          var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane);
          enqueueCapturedUpdate(workInProgress, update);
          break;
        }
    }

    if (workInProgress.type !== workInProgress.elementType) {
      // Lazy component props can't be validated in createElement
      // because they're only guaranteed to be resolved here.
      var innerPropTypes = Component.propTypes;

      if (innerPropTypes) {
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
        'prop', getComponentNameFromType(Component));
      }
    }
  } // Push context providers early to prevent context stack mismatches.
  // During mounting we don't know the child context yet as the instance doesn't exist.
  // We will invalidate the child context in finishClassComponent() right after rendering.


  var hasContext;

  if (isContextProvider(Component)) {
    hasContext = true;
    pushContextProvider(workInProgress);
  } else {
    hasContext = false;
  }

  prepareToReadContext(workInProgress, renderLanes);
  var instance = workInProgress.stateNode;
  var shouldUpdate;

  if (instance === null) {
    resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance.

    constructClassInstance(workInProgress, Component, nextProps);
    mountClassInstance(workInProgress, Component, nextProps, renderLanes);
    shouldUpdate = true;
  } else if (current === null) {
    // In a resume, we'll already have an instance we can reuse.
    shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
  } else {
    shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
  }

  var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);

  {
    var inst = workInProgress.stateNode;

    if (shouldUpdate && inst.props !== nextProps) {
      if (!didWarnAboutReassigningProps) {
        error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component');
      }

      didWarnAboutReassigningProps = true;
    }
  }

  return nextUnitOfWork;
}

function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
  // Refs should update even if shouldComponentUpdate returns false
  markRef(current, workInProgress);
  var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;

  if (!shouldUpdate && !didCaptureError) {
    // Context providers should defer to sCU for rendering
    if (hasContext) {
      invalidateContextProvider(workInProgress, Component, false);
    }

    return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
  }

  var instance = workInProgress.stateNode; // Rerender

  ReactCurrentOwner$1.current = workInProgress;
  var nextChildren;

  if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
    // If we captured an error, but getDerivedStateFromError is not defined,
    // unmount all the children. componentDidCatch will schedule an update to
    // re-render a fallback. This is temporary until we migrate everyone to
    // the new API.
    // TODO: Warn in a future release.
    nextChildren = null;

    {
      stopProfilerTimerIfRunning();
    }
  } else {
    {
      markComponentRenderStarted(workInProgress);
    }

    {
      setIsRendering(true);
      nextChildren = instance.render();

      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          instance.render();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }

      setIsRendering(false);
    }

    {
      markComponentRenderStopped();
    }
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;

  if (current !== null && didCaptureError) {
    // If we're recovering from an error, reconcile without reusing any of
    // the existing children. Conceptually, the normal children and the children
    // that are shown on error are two different sets, so we shouldn't reuse
    // normal children even if their identities match.
    forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
  } else {
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  } // Memoize state using the values we just used to render.
  // TODO: Restructure so we never read values from the instance.


  workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.

  if (hasContext) {
    invalidateContextProvider(workInProgress, Component, true);
  }

  return workInProgress.child;
}

function pushHostRootContext(workInProgress) {
  var root = workInProgress.stateNode;

  if (root.pendingContext) {
    pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
  } else if (root.context) {
    // Should always be set
    pushTopLevelContextObject(workInProgress, root.context, false);
  }

  pushHostContainer(workInProgress, root.containerInfo);
}

function updateHostRoot(current, workInProgress, renderLanes) {
  pushHostRootContext(workInProgress);

  if (current === null) {
    throw new Error('Should have a current fiber. This is a bug in React.');
  }

  var nextProps = workInProgress.pendingProps;
  var prevState = workInProgress.memoizedState;
  var prevChildren = prevState.element;
  cloneUpdateQueue(current, workInProgress);
  processUpdateQueue(workInProgress, nextProps, null, renderLanes);
  var nextState = workInProgress.memoizedState;
  var root = workInProgress.stateNode;
  // being called "element".


  var nextChildren = nextState.element;

  if ( prevState.isDehydrated) {
    // This is a hydration root whose shell has not yet hydrated. We should
    // attempt to hydrate.
    // Flip isDehydrated to false to indicate that when this render
    // finishes, the root will no longer be dehydrated.
    var overrideState = {
      element: nextChildren,
      isDehydrated: false,
      cache: nextState.cache,
      pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
      transitions: nextState.transitions
    };
    var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't
    // have reducer functions so it doesn't need rebasing.

    updateQueue.baseState = overrideState;
    workInProgress.memoizedState = overrideState;

    if (workInProgress.flags & ForceClientRender) {
      // Something errored during a previous attempt to hydrate the shell, so we
      // forced a client render.
      var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress);
      return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError);
    } else if (nextChildren !== prevChildren) {
      var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress);

      return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError);
    } else {
      // The outermost shell has not hydrated yet. Start hydrating.
      enterHydrationState(workInProgress);

      var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
      workInProgress.child = child;
      var node = child;

      while (node) {
        // Mark each child as hydrating. This is a fast path to know whether this
        // tree is part of a hydrating tree. This is used to determine if a child
        // node has fully mounted yet, and for scheduling event replaying.
        // Conceptually this is similar to Placement in that a new subtree is
        // inserted into the React tree here. It just happens to not need DOM
        // mutations because it already exists.
        node.flags = node.flags & ~Placement | Hydrating;
        node = node.sibling;
      }
    }
  } else {
    // Root is not dehydrated. Either this is a client-only root, or it
    // already hydrated.
    resetHydrationState();

    if (nextChildren === prevChildren) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }

    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  }

  return workInProgress.child;
}

function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) {
  // Revert to client rendering.
  resetHydrationState();
  queueHydrationError(recoverableError);
  workInProgress.flags |= ForceClientRender;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateHostComponent(current, workInProgress, renderLanes) {
  pushHostContext(workInProgress);

  if (current === null) {
    tryToClaimNextHydratableInstance(workInProgress);
  }

  var type = workInProgress.type;
  var nextProps = workInProgress.pendingProps;
  var prevProps = current !== null ? current.memoizedProps : null;
  var nextChildren = nextProps.children;
  var isDirectTextChild = shouldSetTextContent(type, nextProps);

  if (isDirectTextChild) {
    // We special case a direct text child of a host node. This is a common
    // case. We won't handle it as a reified child. We will instead handle
    // this in the host environment that also has access to this prop. That
    // avoids allocating another HostText fiber and traversing it.
    nextChildren = null;
  } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
    // If we're switching from a direct text child to a normal child, or to
    // empty, we need to schedule the text content to be reset.
    workInProgress.flags |= ContentReset;
  }

  markRef(current, workInProgress);
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}

function updateHostText(current, workInProgress) {
  if (current === null) {
    tryToClaimNextHydratableInstance(workInProgress);
  } // Nothing to do here. This is terminal. We'll do the completion step
  // immediately after.


  return null;
}

function mountLazyComponent(_current, workInProgress, elementType, renderLanes) {
  resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
  var props = workInProgress.pendingProps;
  var lazyComponent = elementType;
  var payload = lazyComponent._payload;
  var init = lazyComponent._init;
  var Component = init(payload); // Store the unwrapped component in the type.

  workInProgress.type = Component;
  var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
  var resolvedProps = resolveDefaultProps(Component, props);
  var child;

  switch (resolvedTag) {
    case FunctionComponent:
      {
        {
          validateFunctionComponentInDev(workInProgress, Component);
          workInProgress.type = Component = resolveFunctionForHotReloading(Component);
        }

        child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
        return child;
      }

    case ClassComponent:
      {
        {
          workInProgress.type = Component = resolveClassForHotReloading(Component);
        }

        child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
        return child;
      }

    case ForwardRef:
      {
        {
          workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
        }

        child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
        return child;
      }

    case MemoComponent:
      {
        {
          if (workInProgress.type !== workInProgress.elementType) {
            var outerPropTypes = Component.propTypes;

            if (outerPropTypes) {
              checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
              'prop', getComponentNameFromType(Component));
            }
          }
        }

        child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
        renderLanes);
        return child;
      }
  }

  var hint = '';

  {
    if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
      hint = ' Did you wrap a component in React.lazy() more than once?';
    }
  } // This message intentionally doesn't mention ForwardRef or MemoComponent
  // because the fact that it's a separate type of work is an
  // implementation detail.


  throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint));
}

function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
  resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again.

  workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
  // Push context providers early to prevent context stack mismatches.
  // During mounting we don't know the child context yet as the instance doesn't exist.
  // We will invalidate the child context in finishClassComponent() right after rendering.

  var hasContext;

  if (isContextProvider(Component)) {
    hasContext = true;
    pushContextProvider(workInProgress);
  } else {
    hasContext = false;
  }

  prepareToReadContext(workInProgress, renderLanes);
  constructClassInstance(workInProgress, Component, nextProps);
  mountClassInstance(workInProgress, Component, nextProps, renderLanes);
  return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
}

function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
  resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
  var props = workInProgress.pendingProps;
  var context;

  {
    var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
    context = getMaskedContext(workInProgress, unmaskedContext);
  }

  prepareToReadContext(workInProgress, renderLanes);
  var value;
  var hasId;

  {
    markComponentRenderStarted(workInProgress);
  }

  {
    if (Component.prototype && typeof Component.prototype.render === 'function') {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutBadClass[componentName]) {
        error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

        didWarnAboutBadClass[componentName] = true;
      }
    }

    if (workInProgress.mode & StrictLegacyMode) {
      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
    }

    setIsRendering(true);
    ReactCurrentOwner$1.current = workInProgress;
    value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
    hasId = checkDidRenderIdHook();
    setIsRendering(false);
  }

  {
    markComponentRenderStopped();
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;

  {
    // Support for module components is deprecated and is removed behind a flag.
    // Whether or not it would crash later, we want to show a good message in DEV first.
    if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
      var _componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);

        didWarnAboutModulePatternComponent[_componentName] = true;
      }
    }
  }

  if ( // Run these checks in production only if the flag is off.
  // Eventually we'll delete this branch altogether.
   typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
    {
      var _componentName2 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutModulePatternComponent[_componentName2]) {
        error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);

        didWarnAboutModulePatternComponent[_componentName2] = true;
      }
    } // Proceed under the assumption that this is a class instance


    workInProgress.tag = ClassComponent; // Throw out any hooks that were used.

    workInProgress.memoizedState = null;
    workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
    // During mounting we don't know the child context yet as the instance doesn't exist.
    // We will invalidate the child context in finishClassComponent() right after rendering.

    var hasContext = false;

    if (isContextProvider(Component)) {
      hasContext = true;
      pushContextProvider(workInProgress);
    } else {
      hasContext = false;
    }

    workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
    initializeUpdateQueue(workInProgress);
    adoptClassInstance(workInProgress, value);
    mountClassInstance(workInProgress, Component, props, renderLanes);
    return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
  } else {
    // Proceed under the assumption that this is a function component
    workInProgress.tag = FunctionComponent;

    {

      if ( workInProgress.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);

        try {
          value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
          hasId = checkDidRenderIdHook();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
    }

    if (getIsHydrating() && hasId) {
      pushMaterializedTreeId(workInProgress);
    }

    reconcileChildren(null, workInProgress, value, renderLanes);

    {
      validateFunctionComponentInDev(workInProgress, Component);
    }

    return workInProgress.child;
  }
}

function validateFunctionComponentInDev(workInProgress, Component) {
  {
    if (Component) {
      if (Component.childContextTypes) {
        error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
      }
    }

    if (workInProgress.ref !== null) {
      var info = '';
      var ownerName = getCurrentFiberOwnerNameInDevOrNull();

      if (ownerName) {
        info += '\n\nCheck the render method of `' + ownerName + '`.';
      }

      var warningKey = ownerName || '';
      var debugSource = workInProgress._debugSource;

      if (debugSource) {
        warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
      }

      if (!didWarnAboutFunctionRefs[warningKey]) {
        didWarnAboutFunctionRefs[warningKey] = true;

        error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
      }
    }

    if ( Component.defaultProps !== undefined) {
      var componentName = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
        error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);

        didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
      }
    }

    if (typeof Component.getDerivedStateFromProps === 'function') {
      var _componentName3 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
        error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);

        didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
      }
    }

    if (typeof Component.contextType === 'object' && Component.contextType !== null) {
      var _componentName4 = getComponentNameFromType(Component) || 'Unknown';

      if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
        error('%s: Function components do not support contextType.', _componentName4);

        didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
      }
    }
  }
}

var SUSPENDED_MARKER = {
  dehydrated: null,
  treeContext: null,
  retryLane: NoLane
};

function mountSuspenseOffscreenState(renderLanes) {
  return {
    baseLanes: renderLanes,
    cachePool: getSuspendedCache(),
    transitions: null
  };
}

function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
  var cachePool = null;

  return {
    baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes),
    cachePool: cachePool,
    transitions: prevOffscreenState.transitions
  };
} // TODO: Probably should inline this back


function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
  // If we're already showing a fallback, there are cases where we need to
  // remain on that fallback regardless of whether the content has resolved.
  // For example, SuspenseList coordinates when nested content appears.
  if (current !== null) {
    var suspenseState = current.memoizedState;

    if (suspenseState === null) {
      // Currently showing content. Don't hide it, even if ForceSuspenseFallback
      // is true. More precise name might be "ForceRemainSuspenseFallback".
      // Note: This is a factoring smell. Can't remain on a fallback if there's
      // no fallback to remain on.
      return false;
    }
  } // Not currently showing content. Consult the Suspense context.


  return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
}

function getRemainingWorkInPrimaryTree(current, renderLanes) {
  // TODO: Should not remove render lanes that were pinged during this render
  return removeLanes(current.childLanes, renderLanes);
}

function updateSuspenseComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.

  {
    if (shouldSuspend(workInProgress)) {
      workInProgress.flags |= DidCapture;
    }
  }

  var suspenseContext = suspenseStackCursor.current;
  var showFallback = false;
  var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;

  if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
    // Something in this boundary's subtree already suspended. Switch to
    // rendering the fallback children.
    showFallback = true;
    workInProgress.flags &= ~DidCapture;
  } else {
    // Attempting the main content
    if (current === null || current.memoizedState !== null) {
      // This is a new mount or this boundary is already showing a fallback state.
      // Mark this subtree context as having at least one invisible parent that could
      // handle the fallback state.
      // Avoided boundaries are not considered since they cannot handle preferred fallback states.
      {
        suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
      }
    }
  }

  suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
  pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
  // boundary's children. This involves some custom reconciliation logic. Two
  // main reasons this is so complicated.
  //
  // First, Legacy Mode has different semantics for backwards compatibility. The
  // primary tree will commit in an inconsistent state, so when we do the
  // second pass to render the fallback, we do some exceedingly, uh, clever
  // hacks to make that not totally break. Like transferring effects and
  // deletions from hidden tree. In Concurrent Mode, it's much simpler,
  // because we bailout on the primary tree completely and leave it in its old
  // state, no effects. Same as what we do for Offscreen (except that
  // Offscreen doesn't have the first render pass).
  //
  // Second is hydration. During hydration, the Suspense fiber has a slightly
  // different layout, where the child points to a dehydrated fragment, which
  // contains the DOM rendered by the server.
  //
  // Third, even if you set all that aside, Suspense is like error boundaries in
  // that we first we try to render one tree, and if that fails, we render again
  // and switch to a different tree. Like a try/catch block. So we have to track
  // which branch we're currently rendering. Ideally we would model this using
  // a stack.

  if (current === null) {
    // Initial mount
    // Special path for hydration
    // If we're currently hydrating, try to hydrate this boundary.
    tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.

    var suspenseState = workInProgress.memoizedState;

    if (suspenseState !== null) {
      var dehydrated = suspenseState.dehydrated;

      if (dehydrated !== null) {
        return mountDehydratedSuspenseComponent(workInProgress, dehydrated);
      }
    }

    var nextPrimaryChildren = nextProps.children;
    var nextFallbackChildren = nextProps.fallback;

    if (showFallback) {
      var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
      var primaryChildFragment = workInProgress.child;
      primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
      workInProgress.memoizedState = SUSPENDED_MARKER;

      return fallbackFragment;
    } else {
      return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren);
    }
  } else {
    // This is an update.
    // Special path for hydration
    var prevState = current.memoizedState;

    if (prevState !== null) {
      var _dehydrated = prevState.dehydrated;

      if (_dehydrated !== null) {
        return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes);
      }
    }

    if (showFallback) {
      var _nextFallbackChildren = nextProps.fallback;
      var _nextPrimaryChildren = nextProps.children;
      var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes);
      var _primaryChildFragment2 = workInProgress.child;
      var prevOffscreenState = current.child.memoizedState;
      _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);

      _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
      workInProgress.memoizedState = SUSPENDED_MARKER;
      return fallbackChildFragment;
    } else {
      var _nextPrimaryChildren2 = nextProps.children;

      var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes);

      workInProgress.memoizedState = null;
      return _primaryChildFragment3;
    }
  }
}

function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
  var mode = workInProgress.mode;
  var primaryChildProps = {
    mode: 'visible',
    children: primaryChildren
  };
  var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
  primaryChildFragment.return = workInProgress;
  workInProgress.child = primaryChildFragment;
  return primaryChildFragment;
}

function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
  var mode = workInProgress.mode;
  var progressedPrimaryFragment = workInProgress.child;
  var primaryChildProps = {
    mode: 'hidden',
    children: primaryChildren
  };
  var primaryChildFragment;
  var fallbackChildFragment;

  if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
    // In legacy mode, we commit the primary tree as if it successfully
    // completed, even though it's in an inconsistent state.
    primaryChildFragment = progressedPrimaryFragment;
    primaryChildFragment.childLanes = NoLanes;
    primaryChildFragment.pendingProps = primaryChildProps;

    if ( workInProgress.mode & ProfileMode) {
      // Reset the durations from the first pass so they aren't included in the
      // final amounts. This seems counterintuitive, since we're intentionally
      // not measuring part of the render phase, but this makes it match what we
      // do in Concurrent Mode.
      primaryChildFragment.actualDuration = 0;
      primaryChildFragment.actualStartTime = -1;
      primaryChildFragment.selfBaseDuration = 0;
      primaryChildFragment.treeBaseDuration = 0;
    }

    fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
  } else {
    primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
    fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
  }

  primaryChildFragment.return = workInProgress;
  fallbackChildFragment.return = workInProgress;
  primaryChildFragment.sibling = fallbackChildFragment;
  workInProgress.child = primaryChildFragment;
  return fallbackChildFragment;
}

function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) {
  // The props argument to `createFiberFromOffscreen` is `any` typed, so we use
  // this wrapper function to constrain it.
  return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
}

function updateWorkInProgressOffscreenFiber(current, offscreenProps) {
  // The props argument to `createWorkInProgress` is `any` typed, so we use this
  // wrapper function to constrain it.
  return createWorkInProgress(current, offscreenProps);
}

function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
  var currentPrimaryChildFragment = current.child;
  var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
  var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
    mode: 'visible',
    children: primaryChildren
  });

  if ((workInProgress.mode & ConcurrentMode) === NoMode) {
    primaryChildFragment.lanes = renderLanes;
  }

  primaryChildFragment.return = workInProgress;
  primaryChildFragment.sibling = null;

  if (currentFallbackChildFragment !== null) {
    // Delete the fallback child fragment
    var deletions = workInProgress.deletions;

    if (deletions === null) {
      workInProgress.deletions = [currentFallbackChildFragment];
      workInProgress.flags |= ChildDeletion;
    } else {
      deletions.push(currentFallbackChildFragment);
    }
  }

  workInProgress.child = primaryChildFragment;
  return primaryChildFragment;
}

function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
  var mode = workInProgress.mode;
  var currentPrimaryChildFragment = current.child;
  var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
  var primaryChildProps = {
    mode: 'hidden',
    children: primaryChildren
  };
  var primaryChildFragment;

  if ( // In legacy mode, we commit the primary tree as if it successfully
  // completed, even though it's in an inconsistent state.
  (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
  // already cloned. In legacy mode, the only case where this isn't true is
  // when DevTools forces us to display a fallback; we skip the first render
  // pass entirely and go straight to rendering the fallback. (In Concurrent
  // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
  // only codepath.)
  workInProgress.child !== currentPrimaryChildFragment) {
    var progressedPrimaryFragment = workInProgress.child;
    primaryChildFragment = progressedPrimaryFragment;
    primaryChildFragment.childLanes = NoLanes;
    primaryChildFragment.pendingProps = primaryChildProps;

    if ( workInProgress.mode & ProfileMode) {
      // Reset the durations from the first pass so they aren't included in the
      // final amounts. This seems counterintuitive, since we're intentionally
      // not measuring part of the render phase, but this makes it match what we
      // do in Concurrent Mode.
      primaryChildFragment.actualDuration = 0;
      primaryChildFragment.actualStartTime = -1;
      primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
      primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
    } // The fallback fiber was added as a deletion during the first pass.
    // However, since we're going to remain on the fallback, we no longer want
    // to delete it.


    workInProgress.deletions = null;
  } else {
    primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too.
    // (We don't do this in legacy mode, because in legacy mode we don't re-use
    // the current tree; see previous branch.)

    primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
  }

  var fallbackChildFragment;

  if (currentFallbackChildFragment !== null) {
    fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
  } else {
    fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
    // mounted but this is a new fiber.

    fallbackChildFragment.flags |= Placement;
  }

  fallbackChildFragment.return = workInProgress;
  primaryChildFragment.return = workInProgress;
  primaryChildFragment.sibling = fallbackChildFragment;
  workInProgress.child = primaryChildFragment;
  return fallbackChildFragment;
}

function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) {
  // Falling back to client rendering. Because this has performance
  // implications, it's considered a recoverable error, even though the user
  // likely won't observe anything wrong with the UI.
  //
  // The error is passed in as an argument to enforce that every caller provide
  // a custom message, or explicitly opt out (currently the only path that opts
  // out is legacy mode; every concurrent path provides an error).
  if (recoverableError !== null) {
    queueHydrationError(recoverableError);
  } // This will add the old fiber to the deletion list


  reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated.

  var nextProps = workInProgress.pendingProps;
  var primaryChildren = nextProps.children;
  var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already
  // mounted but this is a new fiber.

  primaryChildFragment.flags |= Placement;
  workInProgress.memoizedState = null;
  return primaryChildFragment;
}

function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
  var fiberMode = workInProgress.mode;
  var primaryChildProps = {
    mode: 'visible',
    children: primaryChildren
  };
  var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
  var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense
  // boundary) already mounted but this is a new fiber.

  fallbackChildFragment.flags |= Placement;
  primaryChildFragment.return = workInProgress;
  fallbackChildFragment.return = workInProgress;
  primaryChildFragment.sibling = fallbackChildFragment;
  workInProgress.child = primaryChildFragment;

  if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
    // We will have dropped the effect list which contains the
    // deletion. We need to reconcile to delete the current child.
    reconcileChildFibers(workInProgress, current.child, null, renderLanes);
  }

  return fallbackChildFragment;
}

function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) {
  // During the first pass, we'll bail out and not drill into the children.
  // Instead, we'll leave the content in place and try to hydrate it later.
  if ((workInProgress.mode & ConcurrentMode) === NoMode) {
    {
      error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
    }

    workInProgress.lanes = laneToLanes(SyncLane);
  } else if (isSuspenseInstanceFallback(suspenseInstance)) {
    // This is a client-only boundary. Since we won't get any content from the server
    // for this, we need to schedule that at a higher priority based on when it would
    // have timed out. In theory we could render it in this pass but it would have the
    // wrong priority associated with it and will prevent hydration of parent path.
    // Instead, we'll leave work left on it to render it in a separate commit.
    // TODO This time should be the time at which the server rendered response that is
    // a parent to this boundary was displayed. However, since we currently don't have
    // a protocol to transfer that time, we'll just estimate it by using the current
    // time. This will mean that Suspense timeouts are slightly shifted to later than
    // they should be.
    // Schedule a normal pri update to render this content.
    workInProgress.lanes = laneToLanes(DefaultHydrationLane);
  } else {
    // We'll continue hydrating the rest at offscreen priority since we'll already
    // be showing the right content coming from the server, it is no rush.
    workInProgress.lanes = laneToLanes(OffscreenLane);
  }

  return null;
}

function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) {
  if (!didSuspend) {
    // This is the first render pass. Attempt to hydrate.
    // We should never be hydrating at this point because it is the first pass,
    // but after we've already committed once.
    warnIfHydrating();

    if ((workInProgress.mode & ConcurrentMode) === NoMode) {
      return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument
      // required â€” every concurrent mode path that causes hydration to
      // de-opt to client rendering should have an error message.
      null);
    }

    if (isSuspenseInstanceFallback(suspenseInstance)) {
      // This boundary is in a permanent fallback state. In this case, we'll never
      // get an update and we'll never be able to hydrate the final content. Let's just try the
      // client side render instead.
      var digest, message, stack;

      {
        var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);

        digest = _getSuspenseInstanceF.digest;
        message = _getSuspenseInstanceF.message;
        stack = _getSuspenseInstanceF.stack;
      }

      var error;

      if (message) {
        // eslint-disable-next-line react-internal/prod-error-codes
        error = new Error(message);
      } else {
        error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.');
      }

      var capturedValue = createCapturedValue(error, digest, stack);
      return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue);
    }
    // any context has changed, we need to treat is as if the input might have changed.


    var hasContextChanged = includesSomeLane(renderLanes, current.childLanes);

    if (didReceiveUpdate || hasContextChanged) {
      // This boundary has changed since the first render. This means that we are now unable to
      // hydrate it. We might still be able to hydrate it using a higher priority lane.
      var root = getWorkInProgressRoot();

      if (root !== null) {
        var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes);

        if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
          // Intentionally mutating since this render will get interrupted. This
          // is one of the very rare times where we mutate the current tree
          // during the render phase.
          suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render

          var eventTime = NoTimestamp;
          enqueueConcurrentRenderForLane(current, attemptHydrationAtLane);
          scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime);
        }
      } // If we have scheduled higher pri work above, this will probably just abort the render
      // since we now have higher priority work, but in case it doesn't, we need to prepare to
      // render something, if we time out. Even if that requires us to delete everything and
      // skip hydration.
      // Delay having to do this as long as the suspense timeout allows us.


      renderDidSuspendDelayIfPossible();

      var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.'));

      return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue);
    } else if (isSuspenseInstancePending(suspenseInstance)) {
      // This component is still pending more data from the server, so we can't hydrate its
      // content. We treat it as if this component suspended itself. It might seem as if
      // we could just try to render it client-side instead. However, this will perform a
      // lot of unnecessary work and is unlikely to complete since it often will suspend
      // on missing data anyway. Additionally, the server might be able to render more
      // than we can on the client yet. In that case we'd end up with more fallback states
      // on the client than if we just leave it alone. If the server times out or errors
      // these should update this boundary to the permanent Fallback state instead.
      // Mark it as having captured (i.e. suspended).
      workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.

      workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result.

      var retry = retryDehydratedSuspenseBoundary.bind(null, current);
      registerSuspenseInstanceRetry(suspenseInstance, retry);
      return null;
    } else {
      // This is the first attempt.
      reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext);
      var primaryChildren = nextProps.children;
      var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this
      // tree is part of a hydrating tree. This is used to determine if a child
      // node has fully mounted yet, and for scheduling event replaying.
      // Conceptually this is similar to Placement in that a new subtree is
      // inserted into the React tree here. It just happens to not need DOM
      // mutations because it already exists.

      primaryChildFragment.flags |= Hydrating;
      return primaryChildFragment;
    }
  } else {
    // This is the second render pass. We already attempted to hydrated, but
    // something either suspended or errored.
    if (workInProgress.flags & ForceClientRender) {
      // Something errored during hydration. Try again without hydrating.
      workInProgress.flags &= ~ForceClientRender;

      var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.'));

      return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2);
    } else if (workInProgress.memoizedState !== null) {
      // Something suspended and we should still be in dehydrated mode.
      // Leave the existing child in place.
      workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there
      // but the normal suspense pass doesn't.

      workInProgress.flags |= DidCapture;
      return null;
    } else {
      // Suspended but we should no longer be in dehydrated mode.
      // Therefore we now have to render the fallback.
      var nextPrimaryChildren = nextProps.children;
      var nextFallbackChildren = nextProps.fallback;
      var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
      var _primaryChildFragment4 = workInProgress.child;
      _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes);
      workInProgress.memoizedState = SUSPENDED_MARKER;
      return fallbackChildFragment;
    }
  }
}

function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {
  fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
  var alternate = fiber.alternate;

  if (alternate !== null) {
    alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
  }

  scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
}

function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
  // Mark any Suspense boundaries with fallbacks as having work to do.
  // If they were previously forced into fallbacks, they may now be able
  // to unblock.
  var node = firstChild;

  while (node !== null) {
    if (node.tag === SuspenseComponent) {
      var state = node.memoizedState;

      if (state !== null) {
        scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
      }
    } else if (node.tag === SuspenseListComponent) {
      // If the tail is hidden there might not be an Suspense boundaries
      // to schedule work on. In this case we have to schedule it on the
      // list itself.
      // We don't have to traverse to the children of the list since
      // the list will propagate the change when it rerenders.
      scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
    } else if (node.child !== null) {
      node.child.return = node;
      node = node.child;
      continue;
    }

    if (node === workInProgress) {
      return;
    }

    while (node.sibling === null) {
      if (node.return === null || node.return === workInProgress) {
        return;
      }

      node = node.return;
    }

    node.sibling.return = node.return;
    node = node.sibling;
  }
}

function findLastContentRow(firstChild) {
  // This is going to find the last row among these children that is already
  // showing content on the screen, as opposed to being in fallback state or
  // new. If a row has multiple Suspense boundaries, any of them being in the
  // fallback state, counts as the whole row being in a fallback state.
  // Note that the "rows" will be workInProgress, but any nested children
  // will still be current since we haven't rendered them yet. The mounted
  // order may not be the same as the new order. We use the new order.
  var row = firstChild;
  var lastContentRow = null;

  while (row !== null) {
    var currentRow = row.alternate; // New rows can't be content rows.

    if (currentRow !== null && findFirstSuspended(currentRow) === null) {
      lastContentRow = row;
    }

    row = row.sibling;
  }

  return lastContentRow;
}

function validateRevealOrder(revealOrder) {
  {
    if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
      didWarnAboutRevealOrder[revealOrder] = true;

      if (typeof revealOrder === 'string') {
        switch (revealOrder.toLowerCase()) {
          case 'together':
          case 'forwards':
          case 'backwards':
            {
              error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());

              break;
            }

          case 'forward':
          case 'backward':
            {
              error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());

              break;
            }

          default:
            error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);

            break;
        }
      } else {
        error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
      }
    }
  }
}

function validateTailOptions(tailMode, revealOrder) {
  {
    if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
      if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
        didWarnAboutTailOptions[tailMode] = true;

        error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
      } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
        didWarnAboutTailOptions[tailMode] = true;

        error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
      }
    }
  }
}

function validateSuspenseListNestedChild(childSlot, index) {
  {
    var isAnArray = isArray(childSlot);
    var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function';

    if (isAnArray || isIterable) {
      var type = isAnArray ? 'array' : 'iterable';

      error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);

      return false;
    }
  }

  return true;
}

function validateSuspenseListChildren(children, revealOrder) {
  {
    if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
      if (isArray(children)) {
        for (var i = 0; i < children.length; i++) {
          if (!validateSuspenseListNestedChild(children[i], i)) {
            return;
          }
        }
      } else {
        var iteratorFn = getIteratorFn(children);

        if (typeof iteratorFn === 'function') {
          var childrenIterator = iteratorFn.call(children);

          if (childrenIterator) {
            var step = childrenIterator.next();
            var _i = 0;

            for (; !step.done; step = childrenIterator.next()) {
              if (!validateSuspenseListNestedChild(step.value, _i)) {
                return;
              }

              _i++;
            }
          }
        } else {
          error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
        }
      }
    }
  }
}

function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
  var renderState = workInProgress.memoizedState;

  if (renderState === null) {
    workInProgress.memoizedState = {
      isBackwards: isBackwards,
      rendering: null,
      renderingStartTime: 0,
      last: lastContentRow,
      tail: tail,
      tailMode: tailMode
    };
  } else {
    // We can reuse the existing object from previous renders.
    renderState.isBackwards = isBackwards;
    renderState.rendering = null;
    renderState.renderingStartTime = 0;
    renderState.last = lastContentRow;
    renderState.tail = tail;
    renderState.tailMode = tailMode;
  }
} // This can end up rendering this component multiple passes.
// The first pass splits the children fibers into two sets. A head and tail.
// We first render the head. If anything is in fallback state, we do another
// pass through beginWork to rerender all children (including the tail) with
// the force suspend context. If the first render didn't have anything in
// in fallback state. Then we render each row in the tail one-by-one.
// That happens in the completeWork phase without going back to beginWork.


function updateSuspenseListComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps;
  var revealOrder = nextProps.revealOrder;
  var tailMode = nextProps.tail;
  var newChildren = nextProps.children;
  validateRevealOrder(revealOrder);
  validateTailOptions(tailMode, revealOrder);
  validateSuspenseListChildren(newChildren, revealOrder);
  reconcileChildren(current, workInProgress, newChildren, renderLanes);
  var suspenseContext = suspenseStackCursor.current;
  var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);

  if (shouldForceFallback) {
    suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
    workInProgress.flags |= DidCapture;
  } else {
    var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;

    if (didSuspendBefore) {
      // If we previously forced a fallback, we need to schedule work
      // on any nested boundaries to let them know to try to render
      // again. This is the same as context updating.
      propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
    }

    suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
  }

  pushSuspenseContext(workInProgress, suspenseContext);

  if ((workInProgress.mode & ConcurrentMode) === NoMode) {
    // In legacy mode, SuspenseList doesn't work so we just
    // use make it a noop by treating it as the default revealOrder.
    workInProgress.memoizedState = null;
  } else {
    switch (revealOrder) {
      case 'forwards':
        {
          var lastContentRow = findLastContentRow(workInProgress.child);
          var tail;

          if (lastContentRow === null) {
            // The whole list is part of the tail.
            // TODO: We could fast path by just rendering the tail now.
            tail = workInProgress.child;
            workInProgress.child = null;
          } else {
            // Disconnect the tail rows after the content row.
            // We're going to render them separately later.
            tail = lastContentRow.sibling;
            lastContentRow.sibling = null;
          }

          initSuspenseListRenderState(workInProgress, false, // isBackwards
          tail, lastContentRow, tailMode);
          break;
        }

      case 'backwards':
        {
          // We're going to find the first row that has existing content.
          // At the same time we're going to reverse the list of everything
          // we pass in the meantime. That's going to be our tail in reverse
          // order.
          var _tail = null;
          var row = workInProgress.child;
          workInProgress.child = null;

          while (row !== null) {
            var currentRow = row.alternate; // New rows can't be content rows.

            if (currentRow !== null && findFirstSuspended(currentRow) === null) {
              // This is the beginning of the main content.
              workInProgress.child = row;
              break;
            }

            var nextRow = row.sibling;
            row.sibling = _tail;
            _tail = row;
            row = nextRow;
          } // TODO: If workInProgress.child is null, we can continue on the tail immediately.


          initSuspenseListRenderState(workInProgress, true, // isBackwards
          _tail, null, // last
          tailMode);
          break;
        }

      case 'together':
        {
          initSuspenseListRenderState(workInProgress, false, // isBackwards
          null, // tail
          null, // last
          undefined);
          break;
        }

      default:
        {
          // The default reveal order is the same as not having
          // a boundary.
          workInProgress.memoizedState = null;
        }
    }
  }

  return workInProgress.child;
}

function updatePortalComponent(current, workInProgress, renderLanes) {
  pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
  var nextChildren = workInProgress.pendingProps;

  if (current === null) {
    // Portals are special because we don't append the children during mount
    // but at commit. Therefore we need to track insertions which the normal
    // flow doesn't do during mount. This doesn't happen at the root because
    // the root always starts with a "current" with a null child.
    // TODO: Consider unifying this with how the root works.
    workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
  } else {
    reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  }

  return workInProgress.child;
}

var hasWarnedAboutUsingNoValuePropOnContextProvider = false;

function updateContextProvider(current, workInProgress, renderLanes) {
  var providerType = workInProgress.type;
  var context = providerType._context;
  var newProps = workInProgress.pendingProps;
  var oldProps = workInProgress.memoizedProps;
  var newValue = newProps.value;

  {
    if (!('value' in newProps)) {
      if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
        hasWarnedAboutUsingNoValuePropOnContextProvider = true;

        error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
      }
    }

    var providerPropTypes = workInProgress.type.propTypes;

    if (providerPropTypes) {
      checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
    }
  }

  pushProvider(workInProgress, context, newValue);

  {
    if (oldProps !== null) {
      var oldValue = oldProps.value;

      if (objectIs(oldValue, newValue)) {
        // No change. Bailout early if children are the same.
        if (oldProps.children === newProps.children && !hasContextChanged()) {
          return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
        }
      } else {
        // The context value changed. Search for matching consumers and schedule
        // them to update.
        propagateContextChange(workInProgress, context, renderLanes);
      }
    }
  }

  var newChildren = newProps.children;
  reconcileChildren(current, workInProgress, newChildren, renderLanes);
  return workInProgress.child;
}

var hasWarnedAboutUsingContextAsConsumer = false;

function updateContextConsumer(current, workInProgress, renderLanes) {
  var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
  // DEV mode, we create a separate object for Context.Consumer that acts
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
  // so we use the old behaviour (Context.Consumer references Context) to
  // reduce size and overhead. The separate object references context via
  // a property called "_context", which also gives us the ability to check
  // in DEV mode if this property exists or not and warn if it does not.

  {
    if (context._context === undefined) {
      // This may be because it's a Context (rather than a Consumer).
      // Or it may be because it's older React where they're the same thing.
      // We only want to warn if we're sure it's a new React.
      if (context !== context.Consumer) {
        if (!hasWarnedAboutUsingContextAsConsumer) {
          hasWarnedAboutUsingContextAsConsumer = true;

          error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
        }
      }
    } else {
      context = context._context;
    }
  }

  var newProps = workInProgress.pendingProps;
  var render = newProps.children;

  {
    if (typeof render !== 'function') {
      error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
    }
  }

  prepareToReadContext(workInProgress, renderLanes);
  var newValue = readContext(context);

  {
    markComponentRenderStarted(workInProgress);
  }

  var newChildren;

  {
    ReactCurrentOwner$1.current = workInProgress;
    setIsRendering(true);
    newChildren = render(newValue);
    setIsRendering(false);
  }

  {
    markComponentRenderStopped();
  } // React DevTools reads this flag.


  workInProgress.flags |= PerformedWork;
  reconcileChildren(current, workInProgress, newChildren, renderLanes);
  return workInProgress.child;
}

function markWorkInProgressReceivedUpdate() {
  didReceiveUpdate = true;
}

function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) {
  if ((workInProgress.mode & ConcurrentMode) === NoMode) {
    if (current !== null) {
      // A lazy component only mounts if it suspended inside a non-
      // concurrent tree, in an inconsistent state. We want to treat it like
      // a new mount, even though an empty version of it already committed.
      // Disconnect the alternate pointers.
      current.alternate = null;
      workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

      workInProgress.flags |= Placement;
    }
  }
}

function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
  if (current !== null) {
    // Reuse previous dependencies
    workInProgress.dependencies = current.dependencies;
  }

  {
    // Don't update "base" render times for bailouts.
    stopProfilerTimerIfRunning();
  }

  markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.

  if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
    // The children don't have any work either. We can skip them.
    // TODO: Once we add back resuming, we should check if the children are
    // a work-in-progress set. If so, we need to transfer their effects.
    {
      return null;
    }
  } // This fiber doesn't have work, but its subtree does. Clone the child
  // fibers and continue.


  cloneChildFibers(current, workInProgress);
  return workInProgress.child;
}

function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
  {
    var returnFiber = oldWorkInProgress.return;

    if (returnFiber === null) {
      // eslint-disable-next-line react-internal/prod-error-codes
      throw new Error('Cannot swap the root fiber.');
    } // Disconnect from the old current.
    // It will get deleted.


    current.alternate = null;
    oldWorkInProgress.alternate = null; // Connect to the new tree.

    newWorkInProgress.index = oldWorkInProgress.index;
    newWorkInProgress.sibling = oldWorkInProgress.sibling;
    newWorkInProgress.return = oldWorkInProgress.return;
    newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.

    if (oldWorkInProgress === returnFiber.child) {
      returnFiber.child = newWorkInProgress;
    } else {
      var prevSibling = returnFiber.child;

      if (prevSibling === null) {
        // eslint-disable-next-line react-internal/prod-error-codes
        throw new Error('Expected parent to have a child.');
      }

      while (prevSibling.sibling !== oldWorkInProgress) {
        prevSibling = prevSibling.sibling;

        if (prevSibling === null) {
          // eslint-disable-next-line react-internal/prod-error-codes
          throw new Error('Expected to find the previous sibling.');
        }
      }

      prevSibling.sibling = newWorkInProgress;
    } // Delete the old fiber and place the new one.
    // Since the old fiber is disconnected, we have to schedule it manually.


    var deletions = returnFiber.deletions;

    if (deletions === null) {
      returnFiber.deletions = [current];
      returnFiber.flags |= ChildDeletion;
    } else {
      deletions.push(current);
    }

    newWorkInProgress.flags |= Placement; // Restart work from the new fiber.

    return newWorkInProgress;
  }
}

function checkScheduledUpdateOrContext(current, renderLanes) {
  // Before performing an early bailout, we must check if there are pending
  // updates or context.
  var updateLanes = current.lanes;

  if (includesSomeLane(updateLanes, renderLanes)) {
    return true;
  } // No pending update, but because context is propagated lazily, we need

  return false;
}

function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) {
  // This fiber does not have any pending work. Bailout without entering
  // the begin phase. There's still some bookkeeping we that needs to be done
  // in this optimized path, mostly pushing stuff onto the stack.
  switch (workInProgress.tag) {
    case HostRoot:
      pushHostRootContext(workInProgress);
      var root = workInProgress.stateNode;

      resetHydrationState();
      break;

    case HostComponent:
      pushHostContext(workInProgress);
      break;

    case ClassComponent:
      {
        var Component = workInProgress.type;

        if (isContextProvider(Component)) {
          pushContextProvider(workInProgress);
        }

        break;
      }

    case HostPortal:
      pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
      break;

    case ContextProvider:
      {
        var newValue = workInProgress.memoizedProps.value;
        var context = workInProgress.type._context;
        pushProvider(workInProgress, context, newValue);
        break;
      }

    case Profiler:
      {
        // Profiler should only call onRender when one of its descendants actually rendered.
        var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);

        if (hasChildWork) {
          workInProgress.flags |= Update;
        }

        {
          // Reset effect durations for the next eventual effect phase.
          // These are reset during render to allow the DevTools commit hook a chance to read them,
          var stateNode = workInProgress.stateNode;
          stateNode.effectDuration = 0;
          stateNode.passiveEffectDuration = 0;
        }
      }

      break;

    case SuspenseComponent:
      {
        var state = workInProgress.memoizedState;

        if (state !== null) {
          if (state.dehydrated !== null) {
            pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
            // been unsuspended it has committed as a resolved Suspense component.
            // If it needs to be retried, it should have work scheduled on it.

            workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we
            // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.

            return null;
          } // If this boundary is currently timed out, we need to decide
          // whether to retry the primary children, or to skip over it and
          // go straight to the fallback. Check the priority of the primary
          // child fragment.


          var primaryChildFragment = workInProgress.child;
          var primaryChildLanes = primaryChildFragment.childLanes;

          if (includesSomeLane(renderLanes, primaryChildLanes)) {
            // The primary children have pending work. Use the normal path
            // to attempt to render the primary children again.
            return updateSuspenseComponent(current, workInProgress, renderLanes);
          } else {
            // The primary child fragment does not have pending work marked
            // on it
            pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
            // priority. Bailout.

            var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);

            if (child !== null) {
              // The fallback children have pending work. Skip over the
              // primary children and work on the fallback.
              return child.sibling;
            } else {
              // Note: We can return `null` here because we already checked
              // whether there were nested context consumers, via the call to
              // `bailoutOnAlreadyFinishedWork` above.
              return null;
            }
          }
        } else {
          pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
        }

        break;
      }

    case SuspenseListComponent:
      {
        var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;

        var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);

        if (didSuspendBefore) {
          if (_hasChildWork) {
            // If something was in fallback state last time, and we have all the
            // same children then we're still in progressive loading state.
            // Something might get unblocked by state updates or retries in the
            // tree which will affect the tail. So we need to use the normal
            // path to compute the correct tail.
            return updateSuspenseListComponent(current, workInProgress, renderLanes);
          } // If none of the children had any work, that means that none of
          // them got retried so they'll still be blocked in the same way
          // as before. We can fast bail out.


          workInProgress.flags |= DidCapture;
        } // If nothing suspended before and we're rendering the same children,
        // then the tail doesn't matter. Anything new that suspends will work
        // in the "together" mode, so we can continue from the state we had.


        var renderState = workInProgress.memoizedState;

        if (renderState !== null) {
          // Reset to the "together" mode in case we've started a different
          // update in the past but didn't complete it.
          renderState.rendering = null;
          renderState.tail = null;
          renderState.lastEffect = null;
        }

        pushSuspenseContext(workInProgress, suspenseStackCursor.current);

        if (_hasChildWork) {
          break;
        } else {
          // If none of the children had any work, that means that none of
          // them got retried so they'll still be blocked in the same way
          // as before. We can fast bail out.
          return null;
        }
      }

    case OffscreenComponent:
    case LegacyHiddenComponent:
      {
        // Need to check if the tree still needs to be deferred. This is
        // almost identical to the logic used in the normal update path,
        // so we'll just enter that. The only difference is we'll bail out
        // at the next level instead of this one, because the child props
        // have not changed. Which is fine.
        // TODO: Probably should refactor `beginWork` to split the bailout
        // path from the normal path. I'm tempted to do a labeled break here
        // but I won't :)
        workInProgress.lanes = NoLanes;
        return updateOffscreenComponent(current, workInProgress, renderLanes);
      }
  }

  return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}

function beginWork(current, workInProgress, renderLanes) {
  {
    if (workInProgress._debugNeedsRemount && current !== null) {
      // This will restart the begin phase with a new fiber.
      return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
    }
  }

  if (current !== null) {
    var oldProps = current.memoizedProps;
    var newProps = workInProgress.pendingProps;

    if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
     workInProgress.type !== current.type )) {
      // If props or context changed, mark the fiber as having performed work.
      // This may be unset if the props are determined to be equal later (memo).
      didReceiveUpdate = true;
    } else {
      // Neither props nor legacy context changes. Check if there's a pending
      // update or context change.
      var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);

      if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
      // may not be work scheduled on `current`, so we check for this flag.
      (workInProgress.flags & DidCapture) === NoFlags) {
        // No pending updates or context. Bail out now.
        didReceiveUpdate = false;
        return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes);
      }

      if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
        // This is a special case that only exists for legacy mode.
        // See https://github.com/facebook/react/pull/19216.
        didReceiveUpdate = true;
      } else {
        // An update was scheduled on this fiber, but there are no new props
        // nor legacy context. Set this to false. If an update queue or context
        // consumer produces a changed value, it will set this to true. Otherwise,
        // the component will assume the children have not changed and bail out.
        didReceiveUpdate = false;
      }
    }
  } else {
    didReceiveUpdate = false;

    if (getIsHydrating() && isForkedChild(workInProgress)) {
      // Check if this child belongs to a list of muliple children in
      // its parent.
      //
      // In a true multi-threaded implementation, we would render children on
      // parallel threads. This would represent the beginning of a new render
      // thread for this subtree.
      //
      // We only use this for id generation during hydration, which is why the
      // logic is located in this special branch.
      var slotIndex = workInProgress.index;
      var numberOfForks = getForksAtLevel();
      pushTreeId(workInProgress, numberOfForks, slotIndex);
    }
  } // Before entering the begin phase, clear pending update priority.
  // TODO: This assumes that we're about to evaluate the component and process
  // the update queue. However, there's an exception: SimpleMemoComponent
  // sometimes bails out later in the begin phase. This indicates that we should
  // move this assignment out of the common path and into each branch.


  workInProgress.lanes = NoLanes;

  switch (workInProgress.tag) {
    case IndeterminateComponent:
      {
        return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
      }

    case LazyComponent:
      {
        var elementType = workInProgress.elementType;
        return mountLazyComponent(current, workInProgress, elementType, renderLanes);
      }

    case FunctionComponent:
      {
        var Component = workInProgress.type;
        var unresolvedProps = workInProgress.pendingProps;
        var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps);
        return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes);
      }

    case ClassComponent:
      {
        var _Component = workInProgress.type;
        var _unresolvedProps = workInProgress.pendingProps;

        var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);

        return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes);
      }

    case HostRoot:
      return updateHostRoot(current, workInProgress, renderLanes);

    case HostComponent:
      return updateHostComponent(current, workInProgress, renderLanes);

    case HostText:
      return updateHostText(current, workInProgress);

    case SuspenseComponent:
      return updateSuspenseComponent(current, workInProgress, renderLanes);

    case HostPortal:
      return updatePortalComponent(current, workInProgress, renderLanes);

    case ForwardRef:
      {
        var type = workInProgress.type;
        var _unresolvedProps2 = workInProgress.pendingProps;

        var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);

        return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
      }

    case Fragment:
      return updateFragment(current, workInProgress, renderLanes);

    case Mode:
      return updateMode(current, workInProgress, renderLanes);

    case Profiler:
      return updateProfiler(current, workInProgress, renderLanes);

    case ContextProvider:
      return updateContextProvider(current, workInProgress, renderLanes);

    case ContextConsumer:
      return updateContextConsumer(current, workInProgress, renderLanes);

    case MemoComponent:
      {
        var _type2 = workInProgress.type;
        var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.

        var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);

        {
          if (workInProgress.type !== workInProgress.elementType) {
            var outerPropTypes = _type2.propTypes;

            if (outerPropTypes) {
              checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
              'prop', getComponentNameFromType(_type2));
            }
          }
        }

        _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
        return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes);
      }

    case SimpleMemoComponent:
      {
        return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes);
      }

    case IncompleteClassComponent:
      {
        var _Component2 = workInProgress.type;
        var _unresolvedProps4 = workInProgress.pendingProps;

        var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);

        return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes);
      }

    case SuspenseListComponent:
      {
        return updateSuspenseListComponent(current, workInProgress, renderLanes);
      }

    case ScopeComponent:
      {

        break;
      }

    case OffscreenComponent:
      {
        return updateOffscreenComponent(current, workInProgress, renderLanes);
      }
  }

  throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
}

function markUpdate(workInProgress) {
  // Tag the fiber with an update effect. This turns a Placement into
  // a PlacementAndUpdate.
  workInProgress.flags |= Update;
}

function markRef$1(workInProgress) {
  workInProgress.flags |= Ref;

  {
    workInProgress.flags |= RefStatic;
  }
}

var appendAllChildren;
var updateHostContainer;
var updateHostComponent$1;
var updateHostText$1;

{
  // Mutation mode
  appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
    // We only have the top Fiber that was created but we need recurse down its
    // children to find all the terminal nodes.
    var node = workInProgress.child;

    while (node !== null) {
      if (node.tag === HostComponent || node.tag === HostText) {
        appendInitialChild(parent, node.stateNode);
      } else if (node.tag === HostPortal) ; else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === workInProgress) {
        return;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === workInProgress) {
          return;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }
  };

  updateHostContainer = function (current, workInProgress) {// Noop
  };

  updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
    // If we have an alternate, that means this is an update and we need to
    // schedule a side-effect to do the updates.
    var oldProps = current.memoizedProps;

    if (oldProps === newProps) {
      // In mutation mode, this is sufficient for a bailout because
      // we won't touch this node even if children changed.
      return;
    } // If we get updated because one of our children updated, we don't
    // have newProps so we'll have to reuse them.
    // TODO: Split the update API as separate for the props vs. children.
    // Even better would be if children weren't special cased at all tho.


    var instance = workInProgress.stateNode;
    var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
    // component is hitting the resume path. Figure out why. Possibly
    // related to `hidden`.

    var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.

    workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
    // is a new ref we mark this as an update. All the work is done in commitWork.

    if (updatePayload) {
      markUpdate(workInProgress);
    }
  };

  updateHostText$1 = function (current, workInProgress, oldText, newText) {
    // If the text differs, mark it as an update. All the work in done in commitWork.
    if (oldText !== newText) {
      markUpdate(workInProgress);
    }
  };
}

function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
  if (getIsHydrating()) {
    // If we're hydrating, we should consume as many items as we can
    // so we don't leave any behind.
    return;
  }

  switch (renderState.tailMode) {
    case 'hidden':
      {
        // Any insertions at the end of the tail list after this point
        // should be invisible. If there are already mounted boundaries
        // anything before them are not considered for collapsing.
        // Therefore we need to go through the whole tail to find if
        // there are any.
        var tailNode = renderState.tail;
        var lastTailNode = null;

        while (tailNode !== null) {
          if (tailNode.alternate !== null) {
            lastTailNode = tailNode;
          }

          tailNode = tailNode.sibling;
        } // Next we're simply going to delete all insertions after the
        // last rendered item.


        if (lastTailNode === null) {
          // All remaining items in the tail are insertions.
          renderState.tail = null;
        } else {
          // Detach the insertion after the last node that was already
          // inserted.
          lastTailNode.sibling = null;
        }

        break;
      }

    case 'collapsed':
      {
        // Any insertions at the end of the tail list after this point
        // should be invisible. If there are already mounted boundaries
        // anything before them are not considered for collapsing.
        // Therefore we need to go through the whole tail to find if
        // there are any.
        var _tailNode = renderState.tail;
        var _lastTailNode = null;

        while (_tailNode !== null) {
          if (_tailNode.alternate !== null) {
            _lastTailNode = _tailNode;
          }

          _tailNode = _tailNode.sibling;
        } // Next we're simply going to delete all insertions after the
        // last rendered item.


        if (_lastTailNode === null) {
          // All remaining items in the tail are insertions.
          if (!hasRenderedATailFallback && renderState.tail !== null) {
            // We suspended during the head. We want to show at least one
            // row at the tail. So we'll keep on and cut off the rest.
            renderState.tail.sibling = null;
          } else {
            renderState.tail = null;
          }
        } else {
          // Detach the insertion after the last node that was already
          // inserted.
          _lastTailNode.sibling = null;
        }

        break;
      }
  }
}

function bubbleProperties(completedWork) {
  var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
  var newChildLanes = NoLanes;
  var subtreeFlags = NoFlags;

  if (!didBailout) {
    // Bubble up the earliest expiration time.
    if ( (completedWork.mode & ProfileMode) !== NoMode) {
      // In profiling mode, resetChildExpirationTime is also used to reset
      // profiler durations.
      var actualDuration = completedWork.actualDuration;
      var treeBaseDuration = completedWork.selfBaseDuration;
      var child = completedWork.child;

      while (child !== null) {
        newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
        subtreeFlags |= child.subtreeFlags;
        subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will
        // only be updated if work is done on the fiber (i.e. it doesn't bailout).
        // When work is done, it should bubble to the parent's actualDuration. If
        // the fiber has not been cloned though, (meaning no work was done), then
        // this value will reflect the amount of time spent working on a previous
        // render. In that case it should not bubble. We determine whether it was
        // cloned by comparing the child pointer.

        actualDuration += child.actualDuration;
        treeBaseDuration += child.treeBaseDuration;
        child = child.sibling;
      }

      completedWork.actualDuration = actualDuration;
      completedWork.treeBaseDuration = treeBaseDuration;
    } else {
      var _child = completedWork.child;

      while (_child !== null) {
        newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
        subtreeFlags |= _child.subtreeFlags;
        subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code
        // smell because it assumes the commit phase is never concurrent with
        // the render phase. Will address during refactor to alternate model.

        _child.return = completedWork;
        _child = _child.sibling;
      }
    }

    completedWork.subtreeFlags |= subtreeFlags;
  } else {
    // Bubble up the earliest expiration time.
    if ( (completedWork.mode & ProfileMode) !== NoMode) {
      // In profiling mode, resetChildExpirationTime is also used to reset
      // profiler durations.
      var _treeBaseDuration = completedWork.selfBaseDuration;
      var _child2 = completedWork.child;

      while (_child2 !== null) {
        newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
        // so we should bubble those up even during a bailout. All the other
        // flags have a lifetime only of a single render + commit, so we should
        // ignore them.

        subtreeFlags |= _child2.subtreeFlags & StaticMask;
        subtreeFlags |= _child2.flags & StaticMask;
        _treeBaseDuration += _child2.treeBaseDuration;
        _child2 = _child2.sibling;
      }

      completedWork.treeBaseDuration = _treeBaseDuration;
    } else {
      var _child3 = completedWork.child;

      while (_child3 !== null) {
        newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
        // so we should bubble those up even during a bailout. All the other
        // flags have a lifetime only of a single render + commit, so we should
        // ignore them.

        subtreeFlags |= _child3.subtreeFlags & StaticMask;
        subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code
        // smell because it assumes the commit phase is never concurrent with
        // the render phase. Will address during refactor to alternate model.

        _child3.return = completedWork;
        _child3 = _child3.sibling;
      }
    }

    completedWork.subtreeFlags |= subtreeFlags;
  }

  completedWork.childLanes = newChildLanes;
  return didBailout;
}

function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) {
  if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) {
    warnIfUnhydratedTailNodes(workInProgress);
    resetHydrationState();
    workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture;
    return false;
  }

  var wasHydrated = popHydrationState(workInProgress);

  if (nextState !== null && nextState.dehydrated !== null) {
    // We might be inside a hydration state the first time we're picking up this
    // Suspense boundary, and also after we've reentered it for further hydration.
    if (current === null) {
      if (!wasHydrated) {
        throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.');
      }

      prepareToHydrateHostSuspenseInstance(workInProgress);
      bubbleProperties(workInProgress);

      {
        if ((workInProgress.mode & ProfileMode) !== NoMode) {
          var isTimedOutSuspense = nextState !== null;

          if (isTimedOutSuspense) {
            // Don't count time spent in a timed out Suspense subtree as part of the base duration.
            var primaryChildFragment = workInProgress.child;

            if (primaryChildFragment !== null) {
              // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
              workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
            }
          }
        }
      }

      return false;
    } else {
      // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
      // state since we're now exiting out of it. popHydrationState doesn't do that for us.
      resetHydrationState();

      if ((workInProgress.flags & DidCapture) === NoFlags) {
        // This boundary did not suspend so it's now hydrated and unsuspended.
        workInProgress.memoizedState = null;
      } // If nothing suspended, we need to schedule an effect to mark this boundary
      // as having hydrated so events know that they're free to be invoked.
      // It's also a signal to replay events and the suspense callback.
      // If something suspended, schedule an effect to attach retry listeners.
      // So we might as well always mark this.


      workInProgress.flags |= Update;
      bubbleProperties(workInProgress);

      {
        if ((workInProgress.mode & ProfileMode) !== NoMode) {
          var _isTimedOutSuspense = nextState !== null;

          if (_isTimedOutSuspense) {
            // Don't count time spent in a timed out Suspense subtree as part of the base duration.
            var _primaryChildFragment = workInProgress.child;

            if (_primaryChildFragment !== null) {
              // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
              workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
            }
          }
        }
      }

      return false;
    }
  } else {
    // Successfully completed this tree. If this was a forced client render,
    // there may have been recoverable errors during first hydration
    // attempt. If so, add them to a queue so we can log them in the
    // commit phase.
    upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path

    return true;
  }
}

function completeWork(current, workInProgress, renderLanes) {
  var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing
  // to the current tree provider fiber is just as fast and less error-prone.
  // Ideally we would have a special version of the work loop only
  // for hydration.

  popTreeContext(workInProgress);

  switch (workInProgress.tag) {
    case IndeterminateComponent:
    case LazyComponent:
    case SimpleMemoComponent:
    case FunctionComponent:
    case ForwardRef:
    case Fragment:
    case Mode:
    case Profiler:
    case ContextConsumer:
    case MemoComponent:
      bubbleProperties(workInProgress);
      return null;

    case ClassComponent:
      {
        var Component = workInProgress.type;

        if (isContextProvider(Component)) {
          popContext(workInProgress);
        }

        bubbleProperties(workInProgress);
        return null;
      }

    case HostRoot:
      {
        var fiberRoot = workInProgress.stateNode;
        popHostContainer(workInProgress);
        popTopLevelContextObject(workInProgress);
        resetWorkInProgressVersions();

        if (fiberRoot.pendingContext) {
          fiberRoot.context = fiberRoot.pendingContext;
          fiberRoot.pendingContext = null;
        }

        if (current === null || current.child === null) {
          // If we hydrated, pop so that we can delete any remaining children
          // that weren't hydrated.
          var wasHydrated = popHydrationState(workInProgress);

          if (wasHydrated) {
            // If we hydrated, then we'll need to schedule an update for
            // the commit side-effects on the root.
            markUpdate(workInProgress);
          } else {
            if (current !== null) {
              var prevState = current.memoizedState;

              if ( // Check if this is a client root
              !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
              (workInProgress.flags & ForceClientRender) !== NoFlags) {
                // Schedule an effect to clear this container at the start of the
                // next commit. This handles the case of React rendering into a
                // container with previous children. It's also safe to do for
                // updates too, because current.child would only be null if the
                // previous render was null (so the container would already
                // be empty).
                workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been
                // recoverable errors during first hydration attempt. If so, add
                // them to a queue so we can log them in the commit phase.

                upgradeHydrationErrorsToRecoverable();
              }
            }
          }
        }

        updateHostContainer(current, workInProgress);
        bubbleProperties(workInProgress);

        return null;
      }

    case HostComponent:
      {
        popHostContext(workInProgress);
        var rootContainerInstance = getRootHostContainer();
        var type = workInProgress.type;

        if (current !== null && workInProgress.stateNode != null) {
          updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);

          if (current.ref !== workInProgress.ref) {
            markRef$1(workInProgress);
          }
        } else {
          if (!newProps) {
            if (workInProgress.stateNode === null) {
              throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
            } // This can happen when we abort work.


            bubbleProperties(workInProgress);
            return null;
          }

          var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
          // "stack" as the parent. Then append children as we go in beginWork
          // or completeWork depending on whether we want to add them top->down or
          // bottom->up. Top->down is faster in IE11.

          var _wasHydrated = popHydrationState(workInProgress);

          if (_wasHydrated) {
            // TODO: Move this and createInstance step into the beginPhase
            // to consolidate.
            if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
              // If changes to the hydrated node need to be applied at the
              // commit-phase we mark this as such.
              markUpdate(workInProgress);
            }
          } else {
            var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
            appendAllChildren(instance, workInProgress, false, false);
            workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
            // (eg DOM renderer supports auto-focus for certain elements).
            // Make sure such renderers get scheduled for later work.

            if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
              markUpdate(workInProgress);
            }
          }

          if (workInProgress.ref !== null) {
            // If there is a ref on a host node we need to schedule a callback
            markRef$1(workInProgress);
          }
        }

        bubbleProperties(workInProgress);
        return null;
      }

    case HostText:
      {
        var newText = newProps;

        if (current && workInProgress.stateNode != null) {
          var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
          // to schedule a side-effect to do the updates.

          updateHostText$1(current, workInProgress, oldText, newText);
        } else {
          if (typeof newText !== 'string') {
            if (workInProgress.stateNode === null) {
              throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
            } // This can happen when we abort work.

          }

          var _rootContainerInstance = getRootHostContainer();

          var _currentHostContext = getHostContext();

          var _wasHydrated2 = popHydrationState(workInProgress);

          if (_wasHydrated2) {
            if (prepareToHydrateHostTextInstance(workInProgress)) {
              markUpdate(workInProgress);
            }
          } else {
            workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
          }
        }

        bubbleProperties(workInProgress);
        return null;
      }

    case SuspenseComponent:
      {
        popSuspenseContext(workInProgress);
        var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this
        // to its own fiber type so that we can add other kinds of hydration
        // boundaries that aren't associated with a Suspense tree. In anticipation
        // of such a refactor, all the hydration logic is contained in
        // this branch.

        if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) {
          var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState);

          if (!fallthroughToNormalSuspensePath) {
            if (workInProgress.flags & ShouldCapture) {
              // Special case. There were remaining unhydrated nodes. We treat
              // this as a mismatch. Revert to client rendering.
              return workInProgress;
            } else {
              // Did not finish hydrating, either because this is the initial
              // render or because something suspended.
              return null;
            }
          } // Continue with the normal Suspense path.

        }

        if ((workInProgress.flags & DidCapture) !== NoFlags) {
          // Something suspended. Re-render with the fallback children.
          workInProgress.lanes = renderLanes; // Do not reset the effect list.

          if ( (workInProgress.mode & ProfileMode) !== NoMode) {
            transferActualDuration(workInProgress);
          } // Don't bubble properties in this case.


          return workInProgress;
        }

        var nextDidTimeout = nextState !== null;
        var prevDidTimeout = current !== null && current.memoizedState !== null;
        // a passive effect, which is when we process the transitions


        if (nextDidTimeout !== prevDidTimeout) {
          // an effect to toggle the subtree's visibility. When we switch from
          // fallback -> primary, the inner Offscreen fiber schedules this effect
          // as part of its normal complete phase. But when we switch from
          // primary -> fallback, the inner Offscreen fiber does not have a complete
          // phase. So we need to schedule its effect here.
          //
          // We also use this flag to connect/disconnect the effects, but the same
          // logic applies: when re-connecting, the Offscreen fiber's complete
          // phase will handle scheduling the effect. It's only when the fallback
          // is active that we have to do anything special.


          if (nextDidTimeout) {
            var _offscreenFiber2 = workInProgress.child;
            _offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything
            // in the concurrent tree already suspended during this render.
            // This is a known bug.

            if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
              // TODO: Move this back to throwException because this is too late
              // if this is a large tree which is common for initial loads. We
              // don't know if we should restart a render or not until we get
              // this marker, and this is too late.
              // If this render already had a ping or lower pri updates,
              // and this is the first time we know we're going to suspend we
              // should be able to immediately restart from within throwException.
              var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback);

              if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
                // If this was in an invisible tree or a new render, then showing
                // this boundary is ok.
                renderDidSuspend();
              } else {
                // Otherwise, we're going to have to hide content so we should
                // suspend for longer if possible.
                renderDidSuspendDelayIfPossible();
              }
            }
          }
        }

        var wakeables = workInProgress.updateQueue;

        if (wakeables !== null) {
          // Schedule an effect to attach a retry listener to the promise.
          // TODO: Move to passive phase
          workInProgress.flags |= Update;
        }

        bubbleProperties(workInProgress);

        {
          if ((workInProgress.mode & ProfileMode) !== NoMode) {
            if (nextDidTimeout) {
              // Don't count time spent in a timed out Suspense subtree as part of the base duration.
              var primaryChildFragment = workInProgress.child;

              if (primaryChildFragment !== null) {
                // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
                workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
              }
            }
          }
        }

        return null;
      }

    case HostPortal:
      popHostContainer(workInProgress);
      updateHostContainer(current, workInProgress);

      if (current === null) {
        preparePortalMount(workInProgress.stateNode.containerInfo);
      }

      bubbleProperties(workInProgress);
      return null;

    case ContextProvider:
      // Pop provider fiber
      var context = workInProgress.type._context;
      popProvider(context, workInProgress);
      bubbleProperties(workInProgress);
      return null;

    case IncompleteClassComponent:
      {
        // Same as class component case. I put it down here so that the tags are
        // sequential to ensure this switch is compiled to a jump table.
        var _Component = workInProgress.type;

        if (isContextProvider(_Component)) {
          popContext(workInProgress);
        }

        bubbleProperties(workInProgress);
        return null;
      }

    case SuspenseListComponent:
      {
        popSuspenseContext(workInProgress);
        var renderState = workInProgress.memoizedState;

        if (renderState === null) {
          // We're running in the default, "independent" mode.
          // We don't do anything in this mode.
          bubbleProperties(workInProgress);
          return null;
        }

        var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
        var renderedTail = renderState.rendering;

        if (renderedTail === null) {
          // We just rendered the head.
          if (!didSuspendAlready) {
            // This is the first pass. We need to figure out if anything is still
            // suspended in the rendered set.
            // If new content unsuspended, but there's still some content that
            // didn't. Then we need to do a second pass that forces everything
            // to keep showing their fallbacks.
            // We might be suspended if something in this render pass suspended, or
            // something in the previous committed pass suspended. Otherwise,
            // there's no chance so we can skip the expensive call to
            // findFirstSuspended.
            var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);

            if (!cannotBeSuspended) {
              var row = workInProgress.child;

              while (row !== null) {
                var suspended = findFirstSuspended(row);

                if (suspended !== null) {
                  didSuspendAlready = true;
                  workInProgress.flags |= DidCapture;
                  cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
                  // part of the second pass. In that case nothing will subscribe to
                  // its thenables. Instead, we'll transfer its thenables to the
                  // SuspenseList so that it can retry if they resolve.
                  // There might be multiple of these in the list but since we're
                  // going to wait for all of them anyway, it doesn't really matter
                  // which ones gets to ping. In theory we could get clever and keep
                  // track of how many dependencies remain but it gets tricky because
                  // in the meantime, we can add/remove/change items and dependencies.
                  // We might bail out of the loop before finding any but that
                  // doesn't matter since that means that the other boundaries that
                  // we did find already has their listeners attached.

                  var newThenables = suspended.updateQueue;

                  if (newThenables !== null) {
                    workInProgress.updateQueue = newThenables;
                    workInProgress.flags |= Update;
                  } // Rerender the whole list, but this time, we'll force fallbacks
                  // to stay in place.
                  // Reset the effect flags before doing the second pass since that's now invalid.
                  // Reset the child fibers to their original state.


                  workInProgress.subtreeFlags = NoFlags;
                  resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
                  // rerender the children.

                  pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case.

                  return workInProgress.child;
                }

                row = row.sibling;
              }
            }

            if (renderState.tail !== null && now() > getRenderTargetTime()) {
              // We have already passed our CPU deadline but we still have rows
              // left in the tail. We'll just give up further attempts to render
              // the main content and only render fallbacks.
              workInProgress.flags |= DidCapture;
              didSuspendAlready = true;
              cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
              // to get it started back up to attempt the next item. While in terms
              // of priority this work has the same priority as this current render,
              // it's not part of the same transition once the transition has
              // committed. If it's sync, we still want to yield so that it can be
              // painted. Conceptually, this is really the same as pinging.
              // We can use any RetryLane even if it's the one currently rendering
              // since we're leaving it behind on this node.

              workInProgress.lanes = SomeRetryLane;
            }
          } else {
            cutOffTailIfNeeded(renderState, false);
          } // Next we're going to render the tail.

        } else {
          // Append the rendered row to the child list.
          if (!didSuspendAlready) {
            var _suspended = findFirstSuspended(renderedTail);

            if (_suspended !== null) {
              workInProgress.flags |= DidCapture;
              didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
              // get lost if this row ends up dropped during a second pass.

              var _newThenables = _suspended.updateQueue;

              if (_newThenables !== null) {
                workInProgress.updateQueue = _newThenables;
                workInProgress.flags |= Update;
              }

              cutOffTailIfNeeded(renderState, true); // This might have been modified.

              if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
              ) {
                  // We're done.
                  bubbleProperties(workInProgress);
                  return null;
                }
            } else if ( // The time it took to render last row is greater than the remaining
            // time we have to render. So rendering one more row would likely
            // exceed it.
            now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
              // We have now passed our CPU deadline and we'll just give up further
              // attempts to render the main content and only render fallbacks.
              // The assumption is that this is usually faster.
              workInProgress.flags |= DidCapture;
              didSuspendAlready = true;
              cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
              // to get it started back up to attempt the next item. While in terms
              // of priority this work has the same priority as this current render,
              // it's not part of the same transition once the transition has
              // committed. If it's sync, we still want to yield so that it can be
              // painted. Conceptually, this is really the same as pinging.
              // We can use any RetryLane even if it's the one currently rendering
              // since we're leaving it behind on this node.

              workInProgress.lanes = SomeRetryLane;
            }
          }

          if (renderState.isBackwards) {
            // The effect list of the backwards tail will have been added
            // to the end. This breaks the guarantee that life-cycles fire in
            // sibling order but that isn't a strong guarantee promised by React.
            // Especially since these might also just pop in during future commits.
            // Append to the beginning of the list.
            renderedTail.sibling = workInProgress.child;
            workInProgress.child = renderedTail;
          } else {
            var previousSibling = renderState.last;

            if (previousSibling !== null) {
              previousSibling.sibling = renderedTail;
            } else {
              workInProgress.child = renderedTail;
            }

            renderState.last = renderedTail;
          }
        }

        if (renderState.tail !== null) {
          // We still have tail rows to render.
          // Pop a row.
          var next = renderState.tail;
          renderState.rendering = next;
          renderState.tail = next.sibling;
          renderState.renderingStartTime = now();
          next.sibling = null; // Restore the context.
          // TODO: We can probably just avoid popping it instead and only
          // setting it the first time we go from not suspended to suspended.

          var suspenseContext = suspenseStackCursor.current;

          if (didSuspendAlready) {
            suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
          } else {
            suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
          }

          pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
          // Don't bubble properties in this case.

          return next;
        }

        bubbleProperties(workInProgress);
        return null;
      }

    case ScopeComponent:
      {

        break;
      }

    case OffscreenComponent:
    case LegacyHiddenComponent:
      {
        popRenderLanes(workInProgress);
        var _nextState = workInProgress.memoizedState;
        var nextIsHidden = _nextState !== null;

        if (current !== null) {
          var _prevState = current.memoizedState;
          var prevIsHidden = _prevState !== null;

          if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding â€” it only pre-renders.
          !enableLegacyHidden )) {
            workInProgress.flags |= Visibility;
          }
        }

        if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) {
          bubbleProperties(workInProgress);
        } else {
          // Don't bubble properties for hidden children unless we're rendering
          // at offscreen priority.
          if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
            bubbleProperties(workInProgress);

            {
              // Check if there was an insertion or update in the hidden subtree.
              // If so, we need to hide those nodes in the commit phase, so
              // schedule a visibility effect.
              if ( workInProgress.subtreeFlags & (Placement | Update)) {
                workInProgress.flags |= Visibility;
              }
            }
          }
        }
        return null;
      }

    case CacheComponent:
      {

        return null;
      }

    case TracingMarkerComponent:
      {

        return null;
      }
  }

  throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
}

function unwindWork(current, workInProgress, renderLanes) {
  // Note: This intentionally doesn't check if we're hydrating because comparing
  // to the current tree provider fiber is just as fast and less error-prone.
  // Ideally we would have a special version of the work loop only
  // for hydration.
  popTreeContext(workInProgress);

  switch (workInProgress.tag) {
    case ClassComponent:
      {
        var Component = workInProgress.type;

        if (isContextProvider(Component)) {
          popContext(workInProgress);
        }

        var flags = workInProgress.flags;

        if (flags & ShouldCapture) {
          workInProgress.flags = flags & ~ShouldCapture | DidCapture;

          if ( (workInProgress.mode & ProfileMode) !== NoMode) {
            transferActualDuration(workInProgress);
          }

          return workInProgress;
        }

        return null;
      }

    case HostRoot:
      {
        var root = workInProgress.stateNode;
        popHostContainer(workInProgress);
        popTopLevelContextObject(workInProgress);
        resetWorkInProgressVersions();
        var _flags = workInProgress.flags;

        if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
          // There was an error during render that wasn't captured by a suspense
          // boundary. Do a second pass on the root to unmount the children.
          workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
          return workInProgress;
        } // We unwound to the root without completing it. Exit.


        return null;
      }

    case HostComponent:
      {
        // TODO: popHydrationState
        popHostContext(workInProgress);
        return null;
      }

    case SuspenseComponent:
      {
        popSuspenseContext(workInProgress);
        var suspenseState = workInProgress.memoizedState;

        if (suspenseState !== null && suspenseState.dehydrated !== null) {
          if (workInProgress.alternate === null) {
            throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.');
          }

          resetHydrationState();
        }

        var _flags2 = workInProgress.flags;

        if (_flags2 & ShouldCapture) {
          workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.

          if ( (workInProgress.mode & ProfileMode) !== NoMode) {
            transferActualDuration(workInProgress);
          }

          return workInProgress;
        }

        return null;
      }

    case SuspenseListComponent:
      {
        popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
        // caught by a nested boundary. If not, it should bubble through.

        return null;
      }

    case HostPortal:
      popHostContainer(workInProgress);
      return null;

    case ContextProvider:
      var context = workInProgress.type._context;
      popProvider(context, workInProgress);
      return null;

    case OffscreenComponent:
    case LegacyHiddenComponent:
      popRenderLanes(workInProgress);
      return null;

    case CacheComponent:

      return null;

    default:
      return null;
  }
}

function unwindInterruptedWork(current, interruptedWork, renderLanes) {
  // Note: This intentionally doesn't check if we're hydrating because comparing
  // to the current tree provider fiber is just as fast and less error-prone.
  // Ideally we would have a special version of the work loop only
  // for hydration.
  popTreeContext(interruptedWork);

  switch (interruptedWork.tag) {
    case ClassComponent:
      {
        var childContextTypes = interruptedWork.type.childContextTypes;

        if (childContextTypes !== null && childContextTypes !== undefined) {
          popContext(interruptedWork);
        }

        break;
      }

    case HostRoot:
      {
        var root = interruptedWork.stateNode;
        popHostContainer(interruptedWork);
        popTopLevelContextObject(interruptedWork);
        resetWorkInProgressVersions();
        break;
      }

    case HostComponent:
      {
        popHostContext(interruptedWork);
        break;
      }

    case HostPortal:
      popHostContainer(interruptedWork);
      break;

    case SuspenseComponent:
      popSuspenseContext(interruptedWork);
      break;

    case SuspenseListComponent:
      popSuspenseContext(interruptedWork);
      break;

    case ContextProvider:
      var context = interruptedWork.type._context;
      popProvider(context, interruptedWork);
      break;

    case OffscreenComponent:
    case LegacyHiddenComponent:
      popRenderLanes(interruptedWork);
      break;
  }
}

var didWarnAboutUndefinedSnapshotBeforeUpdate = null;

{
  didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
} // Used during the commit phase to track the state of the Offscreen component stack.
// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
// Only used when enableSuspenseLayoutEffectSemantics is enabled.


var offscreenSubtreeIsHidden = false;
var offscreenSubtreeWasHidden = false;
var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
var nextEffect = null; // Used for Profiling builds to track updaters.

var inProgressLanes = null;
var inProgressRoot = null;
function reportUncaughtErrorInDEV(error) {
  // Wrapping each small part of the commit phase into a guarded
  // callback is a bit too slow (https://github.com/facebook/react/pull/21666).
  // But we rely on it to surface errors to DEV tools like overlays
  // (https://github.com/facebook/react/issues/21712).
  // As a compromise, rethrow only caught errors in a guard.
  {
    invokeGuardedCallback(null, function () {
      throw error;
    });
    clearCaughtError();
  }
}

var callComponentWillUnmountWithTimer = function (current, instance) {
  instance.props = current.memoizedProps;
  instance.state = current.memoizedState;

  if ( current.mode & ProfileMode) {
    try {
      startLayoutEffectTimer();
      instance.componentWillUnmount();
    } finally {
      recordLayoutEffectDuration(current);
    }
  } else {
    instance.componentWillUnmount();
  }
}; // Capture errors so they don't interrupt mounting.


function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) {
  try {
    commitHookEffectListMount(Layout, current);
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
} // Capture errors so they don't interrupt unmounting.


function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
  try {
    callComponentWillUnmountWithTimer(current, instance);
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
} // Capture errors so they don't interrupt mounting.


function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) {
  try {
    instance.componentDidMount();
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
} // Capture errors so they don't interrupt mounting.


function safelyAttachRef(current, nearestMountedAncestor) {
  try {
    commitAttachRef(current);
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
}

function safelyDetachRef(current, nearestMountedAncestor) {
  var ref = current.ref;

  if (ref !== null) {
    if (typeof ref === 'function') {
      var retVal;

      try {
        if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) {
          try {
            startLayoutEffectTimer();
            retVal = ref(null);
          } finally {
            recordLayoutEffectDuration(current);
          }
        } else {
          retVal = ref(null);
        }
      } catch (error) {
        captureCommitPhaseError(current, nearestMountedAncestor, error);
      }

      {
        if (typeof retVal === 'function') {
          error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current));
        }
      }
    } else {
      ref.current = null;
    }
  }
}

function safelyCallDestroy(current, nearestMountedAncestor, destroy) {
  try {
    destroy();
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
}

var focusedInstanceHandle = null;
var shouldFireAfterActiveInstanceBlur = false;
function commitBeforeMutationEffects(root, firstChild) {
  focusedInstanceHandle = prepareForCommit(root.containerInfo);
  nextEffect = firstChild;
  commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber

  var shouldFire = shouldFireAfterActiveInstanceBlur;
  shouldFireAfterActiveInstanceBlur = false;
  focusedInstanceHandle = null;
  return shouldFire;
}

function commitBeforeMutationEffects_begin() {
  while (nextEffect !== null) {
    var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur.

    var child = fiber.child;

    if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
      child.return = fiber;
      nextEffect = child;
    } else {
      commitBeforeMutationEffects_complete();
    }
  }
}

function commitBeforeMutationEffects_complete() {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    setCurrentFiber(fiber);

    try {
      commitBeforeMutationEffectsOnFiber(fiber);
    } catch (error) {
      captureCommitPhaseError(fiber, fiber.return, error);
    }

    resetCurrentFiber();
    var sibling = fiber.sibling;

    if (sibling !== null) {
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function commitBeforeMutationEffectsOnFiber(finishedWork) {
  var current = finishedWork.alternate;
  var flags = finishedWork.flags;

  if ((flags & Snapshot) !== NoFlags) {
    setCurrentFiber(finishedWork);

    switch (finishedWork.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          break;
        }

      case ClassComponent:
        {
          if (current !== null) {
            var prevProps = current.memoizedProps;
            var prevState = current.memoizedState;
            var instance = finishedWork.stateNode; // We could update instance props and state here,
            // but instead we rely on them being set during last render.
            // TODO: revisit this when we implement resuming.

            {
              if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                if (instance.props !== finishedWork.memoizedProps) {
                  error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                }

                if (instance.state !== finishedWork.memoizedState) {
                  error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                }
              }
            }

            var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);

            {
              var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;

              if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
                didWarnSet.add(finishedWork.type);

                error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork));
              }
            }

            instance.__reactInternalSnapshotBeforeUpdate = snapshot;
          }

          break;
        }

      case HostRoot:
        {
          {
            var root = finishedWork.stateNode;
            clearContainer(root.containerInfo);
          }

          break;
        }

      case HostComponent:
      case HostText:
      case HostPortal:
      case IncompleteClassComponent:
        // Nothing to do for these component types
        break;

      default:
        {
          throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
        }
    }

    resetCurrentFiber();
  }
}

function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
  var updateQueue = finishedWork.updateQueue;
  var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

  if (lastEffect !== null) {
    var firstEffect = lastEffect.next;
    var effect = firstEffect;

    do {
      if ((effect.tag & flags) === flags) {
        // Unmount
        var destroy = effect.destroy;
        effect.destroy = undefined;

        if (destroy !== undefined) {
          {
            if ((flags & Passive$1) !== NoFlags$1) {
              markComponentPassiveEffectUnmountStarted(finishedWork);
            } else if ((flags & Layout) !== NoFlags$1) {
              markComponentLayoutEffectUnmountStarted(finishedWork);
            }
          }

          {
            if ((flags & Insertion) !== NoFlags$1) {
              setIsRunningInsertionEffect(true);
            }
          }

          safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);

          {
            if ((flags & Insertion) !== NoFlags$1) {
              setIsRunningInsertionEffect(false);
            }
          }

          {
            if ((flags & Passive$1) !== NoFlags$1) {
              markComponentPassiveEffectUnmountStopped();
            } else if ((flags & Layout) !== NoFlags$1) {
              markComponentLayoutEffectUnmountStopped();
            }
          }
        }
      }

      effect = effect.next;
    } while (effect !== firstEffect);
  }
}

function commitHookEffectListMount(flags, finishedWork) {
  var updateQueue = finishedWork.updateQueue;
  var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

  if (lastEffect !== null) {
    var firstEffect = lastEffect.next;
    var effect = firstEffect;

    do {
      if ((effect.tag & flags) === flags) {
        {
          if ((flags & Passive$1) !== NoFlags$1) {
            markComponentPassiveEffectMountStarted(finishedWork);
          } else if ((flags & Layout) !== NoFlags$1) {
            markComponentLayoutEffectMountStarted(finishedWork);
          }
        } // Mount


        var create = effect.create;

        {
          if ((flags & Insertion) !== NoFlags$1) {
            setIsRunningInsertionEffect(true);
          }
        }

        effect.destroy = create();

        {
          if ((flags & Insertion) !== NoFlags$1) {
            setIsRunningInsertionEffect(false);
          }
        }

        {
          if ((flags & Passive$1) !== NoFlags$1) {
            markComponentPassiveEffectMountStopped();
          } else if ((flags & Layout) !== NoFlags$1) {
            markComponentLayoutEffectMountStopped();
          }
        }

        {
          var destroy = effect.destroy;

          if (destroy !== undefined && typeof destroy !== 'function') {
            var hookName = void 0;

            if ((effect.tag & Layout) !== NoFlags) {
              hookName = 'useLayoutEffect';
            } else if ((effect.tag & Insertion) !== NoFlags) {
              hookName = 'useInsertionEffect';
            } else {
              hookName = 'useEffect';
            }

            var addendum = void 0;

            if (destroy === null) {
              addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
            } else if (typeof destroy.then === 'function') {
              addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + '  async function fetchData() {\n' + '    // You can await here\n' + '    const response = await MyAPI.getData(someId);\n' + '    // ...\n' + '  }\n' + '  fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
            } else {
              addendum = ' You returned: ' + destroy;
            }

            error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum);
          }
        }
      }

      effect = effect.next;
    } while (effect !== firstEffect);
  }
}

function commitPassiveEffectDurations(finishedRoot, finishedWork) {
  {
    // Only Profilers with work in their subtree will have an Update effect scheduled.
    if ((finishedWork.flags & Update) !== NoFlags) {
      switch (finishedWork.tag) {
        case Profiler:
          {
            var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
            var _finishedWork$memoize = finishedWork.memoizedProps,
                id = _finishedWork$memoize.id,
                onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase.
            // It does not get reset until the start of the next commit phase.

            var commitTime = getCommitTime();
            var phase = finishedWork.alternate === null ? 'mount' : 'update';

            {
              if (isCurrentUpdateNested()) {
                phase = 'nested-update';
              }
            }

            if (typeof onPostCommit === 'function') {
              onPostCommit(id, phase, passiveEffectDuration, commitTime);
            } // Bubble times to the next nearest ancestor Profiler.
            // After we process that Profiler, we'll bubble further up.


            var parentFiber = finishedWork.return;

            outer: while (parentFiber !== null) {
              switch (parentFiber.tag) {
                case HostRoot:
                  var root = parentFiber.stateNode;
                  root.passiveEffectDuration += passiveEffectDuration;
                  break outer;

                case Profiler:
                  var parentStateNode = parentFiber.stateNode;
                  parentStateNode.passiveEffectDuration += passiveEffectDuration;
                  break outer;
              }

              parentFiber = parentFiber.return;
            }

            break;
          }
      }
    }
  }
}

function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) {
  if ((finishedWork.flags & LayoutMask) !== NoFlags) {
    switch (finishedWork.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          if ( !offscreenSubtreeWasHidden) {
            // At this point layout effects have already been destroyed (during mutation phase).
            // This is done to prevent sibling component effects from interfering with each other,
            // e.g. a destroy function in one component should never override a ref set
            // by a create function in another component during the same commit.
            if ( finishedWork.mode & ProfileMode) {
              try {
                startLayoutEffectTimer();
                commitHookEffectListMount(Layout | HasEffect, finishedWork);
              } finally {
                recordLayoutEffectDuration(finishedWork);
              }
            } else {
              commitHookEffectListMount(Layout | HasEffect, finishedWork);
            }
          }

          break;
        }

      case ClassComponent:
        {
          var instance = finishedWork.stateNode;

          if (finishedWork.flags & Update) {
            if (!offscreenSubtreeWasHidden) {
              if (current === null) {
                // We could update instance props and state here,
                // but instead we rely on them being set during last render.
                // TODO: revisit this when we implement resuming.
                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance.props !== finishedWork.memoizedProps) {
                      error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                    }

                    if (instance.state !== finishedWork.memoizedState) {
                      error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                    }
                  }
                }

                if ( finishedWork.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    instance.componentDidMount();
                  } finally {
                    recordLayoutEffectDuration(finishedWork);
                  }
                } else {
                  instance.componentDidMount();
                }
              } else {
                var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
                var prevState = current.memoizedState; // We could update instance props and state here,
                // but instead we rely on them being set during last render.
                // TODO: revisit this when we implement resuming.

                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance.props !== finishedWork.memoizedProps) {
                      error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                    }

                    if (instance.state !== finishedWork.memoizedState) {
                      error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                    }
                  }
                }

                if ( finishedWork.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                  } finally {
                    recordLayoutEffectDuration(finishedWork);
                  }
                } else {
                  instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                }
              }
            }
          } // TODO: I think this is now always non-null by the time it reaches the
          // commit phase. Consider removing the type check.


          var updateQueue = finishedWork.updateQueue;

          if (updateQueue !== null) {
            {
              if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                if (instance.props !== finishedWork.memoizedProps) {
                  error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                }

                if (instance.state !== finishedWork.memoizedState) {
                  error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
                }
              }
            } // We could update instance props and state here,
            // but instead we rely on them being set during last render.
            // TODO: revisit this when we implement resuming.


            commitUpdateQueue(finishedWork, updateQueue, instance);
          }

          break;
        }

      case HostRoot:
        {
          // TODO: I think this is now always non-null by the time it reaches the
          // commit phase. Consider removing the type check.
          var _updateQueue = finishedWork.updateQueue;

          if (_updateQueue !== null) {
            var _instance = null;

            if (finishedWork.child !== null) {
              switch (finishedWork.child.tag) {
                case HostComponent:
                  _instance = getPublicInstance(finishedWork.child.stateNode);
                  break;

                case ClassComponent:
                  _instance = finishedWork.child.stateNode;
                  break;
              }
            }

            commitUpdateQueue(finishedWork, _updateQueue, _instance);
          }

          break;
        }

      case HostComponent:
        {
          var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
          // (eg DOM renderer may schedule auto-focus for inputs and form controls).
          // These effects should only be committed when components are first mounted,
          // aka when there is no current/alternate.

          if (current === null && finishedWork.flags & Update) {
            var type = finishedWork.type;
            var props = finishedWork.memoizedProps;
            commitMount(_instance2, type, props);
          }

          break;
        }

      case HostText:
        {
          // We have no life-cycles associated with text.
          break;
        }

      case HostPortal:
        {
          // We have no life-cycles associated with portals.
          break;
        }

      case Profiler:
        {
          {
            var _finishedWork$memoize2 = finishedWork.memoizedProps,
                onCommit = _finishedWork$memoize2.onCommit,
                onRender = _finishedWork$memoize2.onRender;
            var effectDuration = finishedWork.stateNode.effectDuration;
            var commitTime = getCommitTime();
            var phase = current === null ? 'mount' : 'update';

            {
              if (isCurrentUpdateNested()) {
                phase = 'nested-update';
              }
            }

            if (typeof onRender === 'function') {
              onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime);
            }

            {
              if (typeof onCommit === 'function') {
                onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime);
              } // Schedule a passive effect for this Profiler to call onPostCommit hooks.
              // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
              // because the effect is also where times bubble to parent Profilers.


              enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor.
              // Do not reset these values until the next render so DevTools has a chance to read them first.

              var parentFiber = finishedWork.return;

              outer: while (parentFiber !== null) {
                switch (parentFiber.tag) {
                  case HostRoot:
                    var root = parentFiber.stateNode;
                    root.effectDuration += effectDuration;
                    break outer;

                  case Profiler:
                    var parentStateNode = parentFiber.stateNode;
                    parentStateNode.effectDuration += effectDuration;
                    break outer;
                }

                parentFiber = parentFiber.return;
              }
            }
          }

          break;
        }

      case SuspenseComponent:
        {
          commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          break;
        }

      case SuspenseListComponent:
      case IncompleteClassComponent:
      case ScopeComponent:
      case OffscreenComponent:
      case LegacyHiddenComponent:
      case TracingMarkerComponent:
        {
          break;
        }

      default:
        throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
    }
  }

  if ( !offscreenSubtreeWasHidden) {
    {
      if (finishedWork.flags & Ref) {
        commitAttachRef(finishedWork);
      }
    }
  }
}

function reappearLayoutEffectsOnFiber(node) {
  // Turn on layout effects in a tree that previously disappeared.
  // TODO (Offscreen) Check: flags & LayoutStatic
  switch (node.tag) {
    case FunctionComponent:
    case ForwardRef:
    case SimpleMemoComponent:
      {
        if ( node.mode & ProfileMode) {
          try {
            startLayoutEffectTimer();
            safelyCallCommitHookLayoutEffectListMount(node, node.return);
          } finally {
            recordLayoutEffectDuration(node);
          }
        } else {
          safelyCallCommitHookLayoutEffectListMount(node, node.return);
        }

        break;
      }

    case ClassComponent:
      {
        var instance = node.stateNode;

        if (typeof instance.componentDidMount === 'function') {
          safelyCallComponentDidMount(node, node.return, instance);
        }

        safelyAttachRef(node, node.return);
        break;
      }

    case HostComponent:
      {
        safelyAttachRef(node, node.return);
        break;
      }
  }
}

function hideOrUnhideAllChildren(finishedWork, isHidden) {
  // Only hide or unhide the top-most host nodes.
  var hostSubtreeRoot = null;

  {
    // We only have the top Fiber that was inserted but we need to recurse down its
    // children to find all the terminal nodes.
    var node = finishedWork;

    while (true) {
      if (node.tag === HostComponent) {
        if (hostSubtreeRoot === null) {
          hostSubtreeRoot = node;

          try {
            var instance = node.stateNode;

            if (isHidden) {
              hideInstance(instance);
            } else {
              unhideInstance(node.stateNode, node.memoizedProps);
            }
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      } else if (node.tag === HostText) {
        if (hostSubtreeRoot === null) {
          try {
            var _instance3 = node.stateNode;

            if (isHidden) {
              hideTextInstance(_instance3);
            } else {
              unhideTextInstance(_instance3, node.memoizedProps);
            }
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === finishedWork) {
        return;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === finishedWork) {
          return;
        }

        if (hostSubtreeRoot === node) {
          hostSubtreeRoot = null;
        }

        node = node.return;
      }

      if (hostSubtreeRoot === node) {
        hostSubtreeRoot = null;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }
  }
}

function commitAttachRef(finishedWork) {
  var ref = finishedWork.ref;

  if (ref !== null) {
    var instance = finishedWork.stateNode;
    var instanceToUse;

    switch (finishedWork.tag) {
      case HostComponent:
        instanceToUse = getPublicInstance(instance);
        break;

      default:
        instanceToUse = instance;
    } // Moved outside to ensure DCE works with this flag

    if (typeof ref === 'function') {
      var retVal;

      if ( finishedWork.mode & ProfileMode) {
        try {
          startLayoutEffectTimer();
          retVal = ref(instanceToUse);
        } finally {
          recordLayoutEffectDuration(finishedWork);
        }
      } else {
        retVal = ref(instanceToUse);
      }

      {
        if (typeof retVal === 'function') {
          error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork));
        }
      }
    } else {
      {
        if (!ref.hasOwnProperty('current')) {
          error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork));
        }
      }

      ref.current = instanceToUse;
    }
  }
}

function detachFiberMutation(fiber) {
  // Cut off the return pointer to disconnect it from the tree.
  // This enables us to detect and warn against state updates on an unmounted component.
  // It also prevents events from bubbling from within disconnected components.
  //
  // Ideally, we should also clear the child pointer of the parent alternate to let this
  // get GC:ed but we don't know which for sure which parent is the current
  // one so we'll settle for GC:ing the subtree of this child.
  // This child itself will be GC:ed when the parent updates the next time.
  //
  // Note that we can't clear child or sibling pointers yet.
  // They're needed for passive effects and for findDOMNode.
  // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
  //
  // Don't reset the alternate yet, either. We need that so we can detach the
  // alternate's fields in the passive phase. Clearing the return pointer is
  // sufficient for findDOMNode semantics.
  var alternate = fiber.alternate;

  if (alternate !== null) {
    alternate.return = null;
  }

  fiber.return = null;
}

function detachFiberAfterEffects(fiber) {
  var alternate = fiber.alternate;

  if (alternate !== null) {
    fiber.alternate = null;
    detachFiberAfterEffects(alternate);
  } // Note: Defensively using negation instead of < in case
  // `deletedTreeCleanUpLevel` is undefined.


  {
    // Clear cyclical Fiber fields. This level alone is designed to roughly
    // approximate the planned Fiber refactor. In that world, `setState` will be
    // bound to a special "instance" object instead of a Fiber. The Instance
    // object will not have any of these fields. It will only be connected to
    // the fiber tree via a single link at the root. So if this level alone is
    // sufficient to fix memory issues, that bodes well for our plans.
    fiber.child = null;
    fiber.deletions = null;
    fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host
    // tree, which has its own pointers to children, parents, and siblings.
    // The other host nodes also point back to fibers, so we should detach that
    // one, too.

    if (fiber.tag === HostComponent) {
      var hostInstance = fiber.stateNode;

      if (hostInstance !== null) {
        detachDeletedInstance(hostInstance);
      }
    }

    fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We
    // already disconnect the `return` pointer at the root of the deleted
    // subtree (in `detachFiberMutation`). Besides, `return` by itself is not
    // cyclical â€” it's only cyclical when combined with `child`, `sibling`, and
    // `alternate`. But we'll clear it in the next level anyway, just in case.

    {
      fiber._debugOwner = null;
    }

    {
      // Theoretically, nothing in here should be necessary, because we already
      // disconnected the fiber from the tree. So even if something leaks this
      // particular fiber, it won't leak anything else
      //
      // The purpose of this branch is to be super aggressive so we can measure
      // if there's any difference in memory impact. If there is, that could
      // indicate a React leak we don't know about.
      fiber.return = null;
      fiber.dependencies = null;
      fiber.memoizedProps = null;
      fiber.memoizedState = null;
      fiber.pendingProps = null;
      fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.

      fiber.updateQueue = null;
    }
  }
}

function getHostParentFiber(fiber) {
  var parent = fiber.return;

  while (parent !== null) {
    if (isHostParent(parent)) {
      return parent;
    }

    parent = parent.return;
  }

  throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.');
}

function isHostParent(fiber) {
  return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
}

function getHostSibling(fiber) {
  // We're going to search forward into the tree until we find a sibling host
  // node. Unfortunately, if multiple insertions are done in a row we have to
  // search past them. This leads to exponential search for the next sibling.
  // TODO: Find a more efficient way to do this.
  var node = fiber;

  siblings: while (true) {
    // If we didn't find anything, let's try the next sibling.
    while (node.sibling === null) {
      if (node.return === null || isHostParent(node.return)) {
        // If we pop out of the root or hit the parent the fiber we are the
        // last sibling.
        return null;
      }

      node = node.return;
    }

    node.sibling.return = node.return;
    node = node.sibling;

    while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
      // If it is not host node and, we might have a host node inside it.
      // Try to search down until we find one.
      if (node.flags & Placement) {
        // If we don't have a child, try the siblings instead.
        continue siblings;
      } // If we don't have a child, try the siblings instead.
      // We also skip portals because they are not part of this host tree.


      if (node.child === null || node.tag === HostPortal) {
        continue siblings;
      } else {
        node.child.return = node;
        node = node.child;
      }
    } // Check if this host node is stable or about to be placed.


    if (!(node.flags & Placement)) {
      // Found it!
      return node.stateNode;
    }
  }
}

function commitPlacement(finishedWork) {


  var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.

  switch (parentFiber.tag) {
    case HostComponent:
      {
        var parent = parentFiber.stateNode;

        if (parentFiber.flags & ContentReset) {
          // Reset the text content of the parent before doing any insertions
          resetTextContent(parent); // Clear ContentReset from the effect tag

          parentFiber.flags &= ~ContentReset;
        }

        var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
        // children to find all the terminal nodes.

        insertOrAppendPlacementNode(finishedWork, before, parent);
        break;
      }

    case HostRoot:
    case HostPortal:
      {
        var _parent = parentFiber.stateNode.containerInfo;

        var _before = getHostSibling(finishedWork);

        insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
        break;
      }
    // eslint-disable-next-line-no-fallthrough

    default:
      throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.');
  }
}

function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
  var tag = node.tag;
  var isHost = tag === HostComponent || tag === HostText;

  if (isHost) {
    var stateNode = node.stateNode;

    if (before) {
      insertInContainerBefore(parent, stateNode, before);
    } else {
      appendChildToContainer(parent, stateNode);
    }
  } else if (tag === HostPortal) ; else {
    var child = node.child;

    if (child !== null) {
      insertOrAppendPlacementNodeIntoContainer(child, before, parent);
      var sibling = child.sibling;

      while (sibling !== null) {
        insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
        sibling = sibling.sibling;
      }
    }
  }
}

function insertOrAppendPlacementNode(node, before, parent) {
  var tag = node.tag;
  var isHost = tag === HostComponent || tag === HostText;

  if (isHost) {
    var stateNode = node.stateNode;

    if (before) {
      insertBefore(parent, stateNode, before);
    } else {
      appendChild(parent, stateNode);
    }
  } else if (tag === HostPortal) ; else {
    var child = node.child;

    if (child !== null) {
      insertOrAppendPlacementNode(child, before, parent);
      var sibling = child.sibling;

      while (sibling !== null) {
        insertOrAppendPlacementNode(sibling, before, parent);
        sibling = sibling.sibling;
      }
    }
  }
} // These are tracked on the stack as we recursively traverse a
// deleted subtree.
// TODO: Update these during the whole mutation phase, not just during
// a deletion.


var hostParent = null;
var hostParentIsContainer = false;

function commitDeletionEffects(root, returnFiber, deletedFiber) {
  {
    // We only have the top Fiber that was deleted but we need to recurse down its
    // children to find all the terminal nodes.
    // Recursively delete all host nodes from the parent, detach refs, clean
    // up mounted layout effects, and call componentWillUnmount.
    // We only need to remove the topmost host child in each branch. But then we
    // still need to keep traversing to unmount effects, refs, and cWU. TODO: We
    // could split this into two separate traversals functions, where the second
    // one doesn't include any removeChild logic. This is maybe the same
    // function as "disappearLayoutEffects" (or whatever that turns into after
    // the layout phase is refactored to use recursion).
    // Before starting, find the nearest host parent on the stack so we know
    // which instance/container to remove the children from.
    // TODO: Instead of searching up the fiber return path on every deletion, we
    // can track the nearest host component on the JS stack as we traverse the
    // tree during the commit phase. This would make insertions faster, too.
    var parent = returnFiber;

    findParent: while (parent !== null) {
      switch (parent.tag) {
        case HostComponent:
          {
            hostParent = parent.stateNode;
            hostParentIsContainer = false;
            break findParent;
          }

        case HostRoot:
          {
            hostParent = parent.stateNode.containerInfo;
            hostParentIsContainer = true;
            break findParent;
          }

        case HostPortal:
          {
            hostParent = parent.stateNode.containerInfo;
            hostParentIsContainer = true;
            break findParent;
          }
      }

      parent = parent.return;
    }

    if (hostParent === null) {
      throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.');
    }

    commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
    hostParent = null;
    hostParentIsContainer = false;
  }

  detachFiberMutation(deletedFiber);
}

function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
  // TODO: Use a static flag to skip trees that don't have unmount effects
  var child = parent.child;

  while (child !== null) {
    commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
    child = child.sibling;
  }
}

function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
  onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse
  // into their subtree. There are simpler cases in the inner switch
  // that don't modify the stack.

  switch (deletedFiber.tag) {
    case HostComponent:
      {
        if (!offscreenSubtreeWasHidden) {
          safelyDetachRef(deletedFiber, nearestMountedAncestor);
        } // Intentional fallthrough to next branch

      }
    // eslint-disable-next-line-no-fallthrough

    case HostText:
      {
        // We only need to remove the nearest host child. Set the host parent
        // to `null` on the stack to indicate that nested children don't
        // need to be removed.
        {
          var prevHostParent = hostParent;
          var prevHostParentIsContainer = hostParentIsContainer;
          hostParent = null;
          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;

          if (hostParent !== null) {
            // Now that all the child effects have unmounted, we can remove the
            // node from the tree.
            if (hostParentIsContainer) {
              removeChildFromContainer(hostParent, deletedFiber.stateNode);
            } else {
              removeChild(hostParent, deletedFiber.stateNode);
            }
          }
        }

        return;
      }

    case DehydratedFragment:
      {
        // Delete the dehydrated suspense boundary and all of its content.


        {
          if (hostParent !== null) {
            if (hostParentIsContainer) {
              clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
            } else {
              clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
            }
          }
        }

        return;
      }

    case HostPortal:
      {
        {
          // When we go into a portal, it becomes the parent to remove from.
          var _prevHostParent = hostParent;
          var _prevHostParentIsContainer = hostParentIsContainer;
          hostParent = deletedFiber.stateNode.containerInfo;
          hostParentIsContainer = true;
          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          hostParent = _prevHostParent;
          hostParentIsContainer = _prevHostParentIsContainer;
        }

        return;
      }

    case FunctionComponent:
    case ForwardRef:
    case MemoComponent:
    case SimpleMemoComponent:
      {
        if (!offscreenSubtreeWasHidden) {
          var updateQueue = deletedFiber.updateQueue;

          if (updateQueue !== null) {
            var lastEffect = updateQueue.lastEffect;

            if (lastEffect !== null) {
              var firstEffect = lastEffect.next;
              var effect = firstEffect;

              do {
                var _effect = effect,
                    destroy = _effect.destroy,
                    tag = _effect.tag;

                if (destroy !== undefined) {
                  if ((tag & Insertion) !== NoFlags$1) {
                    safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                  } else if ((tag & Layout) !== NoFlags$1) {
                    {
                      markComponentLayoutEffectUnmountStarted(deletedFiber);
                    }

                    if ( deletedFiber.mode & ProfileMode) {
                      startLayoutEffectTimer();
                      safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                      recordLayoutEffectDuration(deletedFiber);
                    } else {
                      safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                    }

                    {
                      markComponentLayoutEffectUnmountStopped();
                    }
                  }
                }

                effect = effect.next;
              } while (effect !== firstEffect);
            }
          }
        }

        recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
        return;
      }

    case ClassComponent:
      {
        if (!offscreenSubtreeWasHidden) {
          safelyDetachRef(deletedFiber, nearestMountedAncestor);
          var instance = deletedFiber.stateNode;

          if (typeof instance.componentWillUnmount === 'function') {
            safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance);
          }
        }

        recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
        return;
      }

    case ScopeComponent:
      {

        recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
        return;
      }

    case OffscreenComponent:
      {
        if ( // TODO: Remove this dead flag
         deletedFiber.mode & ConcurrentMode) {
          // If this offscreen component is hidden, we already unmounted it. Before
          // deleting the children, track that it's already unmounted so that we
          // don't attempt to unmount the effects again.
          // TODO: If the tree is hidden, in most cases we should be able to skip
          // over the nested children entirely. An exception is we haven't yet found
          // the topmost host node to delete, which we already track on the stack.
          // But the other case is portals, which need to be detached no matter how
          // deeply they are nested. We should use a subtree flag to track whether a
          // subtree includes a nested portal.
          var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
        } else {
          recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
        }

        break;
      }

    default:
      {
        recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
        return;
      }
  }
}

function commitSuspenseCallback(finishedWork) {
  // TODO: Move this to passive phase
  var newState = finishedWork.memoizedState;
}

function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {

  var newState = finishedWork.memoizedState;

  if (newState === null) {
    var current = finishedWork.alternate;

    if (current !== null) {
      var prevState = current.memoizedState;

      if (prevState !== null) {
        var suspenseInstance = prevState.dehydrated;

        if (suspenseInstance !== null) {
          commitHydratedSuspenseInstance(suspenseInstance);
        }
      }
    }
  }
}

function attachSuspenseRetryListeners(finishedWork) {
  // If this boundary just timed out, then it will have a set of wakeables.
  // For each wakeable, attach a listener so that when it resolves, React
  // attempts to re-render the boundary in the primary (pre-timeout) state.
  var wakeables = finishedWork.updateQueue;

  if (wakeables !== null) {
    finishedWork.updateQueue = null;
    var retryCache = finishedWork.stateNode;

    if (retryCache === null) {
      retryCache = finishedWork.stateNode = new PossiblyWeakSet();
    }

    wakeables.forEach(function (wakeable) {
      // Memoize using the boundary fiber to prevent redundant listeners.
      var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);

      if (!retryCache.has(wakeable)) {
        retryCache.add(wakeable);

        {
          if (isDevToolsPresent) {
            if (inProgressLanes !== null && inProgressRoot !== null) {
              // If we have pending work still, associate the original updaters with it.
              restorePendingUpdaters(inProgressRoot, inProgressLanes);
            } else {
              throw Error('Expected finished root and lanes to be set. This is a bug in React.');
            }
          }
        }

        wakeable.then(retry, retry);
      }
    });
  }
} // This function detects when a Suspense boundary goes from visible to hidden.
function commitMutationEffects(root, finishedWork, committedLanes) {
  inProgressLanes = committedLanes;
  inProgressRoot = root;
  setCurrentFiber(finishedWork);
  commitMutationEffectsOnFiber(finishedWork, root);
  setCurrentFiber(finishedWork);
  inProgressLanes = null;
  inProgressRoot = null;
}

function recursivelyTraverseMutationEffects(root, parentFiber, lanes) {
  // Deletions effects can be scheduled on any fiber type. They need to happen
  // before the children effects hae fired.
  var deletions = parentFiber.deletions;

  if (deletions !== null) {
    for (var i = 0; i < deletions.length; i++) {
      var childToDelete = deletions[i];

      try {
        commitDeletionEffects(root, parentFiber, childToDelete);
      } catch (error) {
        captureCommitPhaseError(childToDelete, parentFiber, error);
      }
    }
  }

  var prevDebugFiber = getCurrentFiber();

  if (parentFiber.subtreeFlags & MutationMask) {
    var child = parentFiber.child;

    while (child !== null) {
      setCurrentFiber(child);
      commitMutationEffectsOnFiber(child, root);
      child = child.sibling;
    }
  }

  setCurrentFiber(prevDebugFiber);
}

function commitMutationEffectsOnFiber(finishedWork, root, lanes) {
  var current = finishedWork.alternate;
  var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber,
  // because the fiber tag is more specific. An exception is any flag related
  // to reconcilation, because those can be set on all fiber types.

  switch (finishedWork.tag) {
    case FunctionComponent:
    case ForwardRef:
    case MemoComponent:
    case SimpleMemoComponent:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Update) {
          try {
            commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
            commitHookEffectListMount(Insertion | HasEffect, finishedWork);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          } // Layout effects are destroyed during the mutation phase so that all
          // destroy functions for all fibers are called before any create functions.
          // This prevents sibling component effects from interfering with each other,
          // e.g. a destroy function in one component should never override a ref set
          // by a create function in another component during the same commit.


          if ( finishedWork.mode & ProfileMode) {
            try {
              startLayoutEffectTimer();
              commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }

            recordLayoutEffectDuration(finishedWork);
          } else {
            try {
              commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
        }

        return;
      }

    case ClassComponent:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Ref) {
          if (current !== null) {
            safelyDetachRef(current, current.return);
          }
        }

        return;
      }

    case HostComponent:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Ref) {
          if (current !== null) {
            safelyDetachRef(current, current.return);
          }
        }

        {
          // TODO: ContentReset gets cleared by the children during the commit
          // phase. This is a refactor hazard because it means we must read
          // flags the flags after `commitReconciliationEffects` has already run;
          // the order matters. We should refactor so that ContentReset does not
          // rely on mutating the flag during commit. Like by setting a flag
          // during the render phase instead.
          if (finishedWork.flags & ContentReset) {
            var instance = finishedWork.stateNode;

            try {
              resetTextContent(instance);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }

          if (flags & Update) {
            var _instance4 = finishedWork.stateNode;

            if (_instance4 != null) {
              // Commit the work prepared earlier.
              var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
              // as the newProps. The updatePayload will contain the real change in
              // this case.

              var oldProps = current !== null ? current.memoizedProps : newProps;
              var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.

              var updatePayload = finishedWork.updateQueue;
              finishedWork.updateQueue = null;

              if (updatePayload !== null) {
                try {
                  commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork);
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              }
            }
          }
        }

        return;
      }

    case HostText:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Update) {
          {
            if (finishedWork.stateNode === null) {
              throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.');
            }

            var textInstance = finishedWork.stateNode;
            var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
            // as the newProps. The updatePayload will contain the real change in
            // this case.

            var oldText = current !== null ? current.memoizedProps : newText;

            try {
              commitTextUpdate(textInstance, oldText, newText);
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
        }

        return;
      }

    case HostRoot:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Update) {
          {
            if (current !== null) {
              var prevRootState = current.memoizedState;

              if (prevRootState.isDehydrated) {
                try {
                  commitHydratedContainer(root.containerInfo);
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              }
            }
          }
        }

        return;
      }

    case HostPortal:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        return;
      }

    case SuspenseComponent:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);
        var offscreenFiber = finishedWork.child;

        if (offscreenFiber.flags & Visibility) {
          var offscreenInstance = offscreenFiber.stateNode;
          var newState = offscreenFiber.memoizedState;
          var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can
          // read it during an event

          offscreenInstance.isHidden = isHidden;

          if (isHidden) {
            var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;

            if (!wasHidden) {
              // TODO: Move to passive phase
              markCommitTimeOfFallback();
            }
          }
        }

        if (flags & Update) {
          try {
            commitSuspenseCallback(finishedWork);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }

          attachSuspenseRetryListeners(finishedWork);
        }

        return;
      }

    case OffscreenComponent:
      {
        var _wasHidden = current !== null && current.memoizedState !== null;

        if ( // TODO: Remove this dead flag
         finishedWork.mode & ConcurrentMode) {
          // Before committing the children, track on the stack whether this
          // offscreen subtree was already hidden, so that we don't unmount the
          // effects again.
          var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
          recursivelyTraverseMutationEffects(root, finishedWork);
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
        } else {
          recursivelyTraverseMutationEffects(root, finishedWork);
        }

        commitReconciliationEffects(finishedWork);

        if (flags & Visibility) {
          var _offscreenInstance = finishedWork.stateNode;
          var _newState = finishedWork.memoizedState;

          var _isHidden = _newState !== null;

          var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can
          // read it during an event

          _offscreenInstance.isHidden = _isHidden;

          {
            if (_isHidden) {
              if (!_wasHidden) {
                if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
                  nextEffect = offscreenBoundary;
                  var offscreenChild = offscreenBoundary.child;

                  while (offscreenChild !== null) {
                    nextEffect = offscreenChild;
                    disappearLayoutEffects_begin(offscreenChild);
                    offscreenChild = offscreenChild.sibling;
                  }
                }
              }
            }
          }

          {
            // TODO: This needs to run whenever there's an insertion or update
            // inside a hidden Offscreen tree.
            hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
          }
        }

        return;
      }

    case SuspenseListComponent:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);

        if (flags & Update) {
          attachSuspenseRetryListeners(finishedWork);
        }

        return;
      }

    case ScopeComponent:
      {

        return;
      }

    default:
      {
        recursivelyTraverseMutationEffects(root, finishedWork);
        commitReconciliationEffects(finishedWork);
        return;
      }
  }
}

function commitReconciliationEffects(finishedWork) {
  // Placement effects (insertions, reorders) can be scheduled on any fiber
  // type. They needs to happen after the children effects have fired, but
  // before the effects on this fiber have fired.
  var flags = finishedWork.flags;

  if (flags & Placement) {
    try {
      commitPlacement(finishedWork);
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    } // Clear the "placement" from effect tag so that we know that this is
    // inserted, before any life-cycles like componentDidMount gets called.
    // TODO: findDOMNode doesn't rely on this any more but isMounted does
    // and isMounted is deprecated anyway so we should be able to kill this.


    finishedWork.flags &= ~Placement;
  }

  if (flags & Hydrating) {
    finishedWork.flags &= ~Hydrating;
  }
}

function commitLayoutEffects(finishedWork, root, committedLanes) {
  inProgressLanes = committedLanes;
  inProgressRoot = root;
  nextEffect = finishedWork;
  commitLayoutEffects_begin(finishedWork, root, committedLanes);
  inProgressLanes = null;
  inProgressRoot = null;
}

function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) {
  // Suspense layout effects semantics don't change for legacy roots.
  var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;

  while (nextEffect !== null) {
    var fiber = nextEffect;
    var firstChild = fiber.child;

    if ( fiber.tag === OffscreenComponent && isModernRoot) {
      // Keep track of the current Offscreen stack's state.
      var isHidden = fiber.memoizedState !== null;
      var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden;

      if (newOffscreenSubtreeIsHidden) {
        // The Offscreen tree is hidden. Skip over its layout effects.
        commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
        continue;
      } else {
        // TODO (Offscreen) Also check: subtreeFlags & LayoutMask
        var current = fiber.alternate;
        var wasHidden = current !== null && current.memoizedState !== null;
        var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
        var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
        var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root.

        offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
        offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;

        if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
          // This is the root of a reappearing boundary. Turn its layout effects
          // back on.
          nextEffect = fiber;
          reappearLayoutEffects_begin(fiber);
        }

        var child = firstChild;

        while (child !== null) {
          nextEffect = child;
          commitLayoutEffects_begin(child, // New root; bubble back up to here and stop.
          root, committedLanes);
          child = child.sibling;
        } // Restore Offscreen state and resume in our-progress traversal.


        nextEffect = fiber;
        offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
        offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
        commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
        continue;
      }
    }

    if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
      firstChild.return = fiber;
      nextEffect = firstChild;
    } else {
      commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
    }
  }
}

function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) {
  while (nextEffect !== null) {
    var fiber = nextEffect;

    if ((fiber.flags & LayoutMask) !== NoFlags) {
      var current = fiber.alternate;
      setCurrentFiber(fiber);

      try {
        commitLayoutEffectOnFiber(root, current, fiber, committedLanes);
      } catch (error) {
        captureCommitPhaseError(fiber, fiber.return, error);
      }

      resetCurrentFiber();
    }

    if (fiber === subtreeRoot) {
      nextEffect = null;
      return;
    }

    var sibling = fiber.sibling;

    if (sibling !== null) {
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function disappearLayoutEffects_begin(subtreeRoot) {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)

    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case MemoComponent:
      case SimpleMemoComponent:
        {
          if ( fiber.mode & ProfileMode) {
            try {
              startLayoutEffectTimer();
              commitHookEffectListUnmount(Layout, fiber, fiber.return);
            } finally {
              recordLayoutEffectDuration(fiber);
            }
          } else {
            commitHookEffectListUnmount(Layout, fiber, fiber.return);
          }

          break;
        }

      case ClassComponent:
        {
          // TODO (Offscreen) Check: flags & RefStatic
          safelyDetachRef(fiber, fiber.return);
          var instance = fiber.stateNode;

          if (typeof instance.componentWillUnmount === 'function') {
            safelyCallComponentWillUnmount(fiber, fiber.return, instance);
          }

          break;
        }

      case HostComponent:
        {
          safelyDetachRef(fiber, fiber.return);
          break;
        }

      case OffscreenComponent:
        {
          // Check if this is a
          var isHidden = fiber.memoizedState !== null;

          if (isHidden) {
            // Nested Offscreen tree is already hidden. Don't disappear
            // its effects.
            disappearLayoutEffects_complete(subtreeRoot);
            continue;
          }

          break;
        }
    } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic


    if (firstChild !== null) {
      firstChild.return = fiber;
      nextEffect = firstChild;
    } else {
      disappearLayoutEffects_complete(subtreeRoot);
    }
  }
}

function disappearLayoutEffects_complete(subtreeRoot) {
  while (nextEffect !== null) {
    var fiber = nextEffect;

    if (fiber === subtreeRoot) {
      nextEffect = null;
      return;
    }

    var sibling = fiber.sibling;

    if (sibling !== null) {
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function reappearLayoutEffects_begin(subtreeRoot) {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    var firstChild = fiber.child;

    if (fiber.tag === OffscreenComponent) {
      var isHidden = fiber.memoizedState !== null;

      if (isHidden) {
        // Nested Offscreen tree is still hidden. Don't re-appear its effects.
        reappearLayoutEffects_complete(subtreeRoot);
        continue;
      }
    } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic


    if (firstChild !== null) {
      // This node may have been reused from a previous render, so we can't
      // assume its return pointer is correct.
      firstChild.return = fiber;
      nextEffect = firstChild;
    } else {
      reappearLayoutEffects_complete(subtreeRoot);
    }
  }
}

function reappearLayoutEffects_complete(subtreeRoot) {
  while (nextEffect !== null) {
    var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic

    setCurrentFiber(fiber);

    try {
      reappearLayoutEffectsOnFiber(fiber);
    } catch (error) {
      captureCommitPhaseError(fiber, fiber.return, error);
    }

    resetCurrentFiber();

    if (fiber === subtreeRoot) {
      nextEffect = null;
      return;
    }

    var sibling = fiber.sibling;

    if (sibling !== null) {
      // This node may have been reused from a previous render, so we can't
      // assume its return pointer is correct.
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) {
  nextEffect = finishedWork;
  commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions);
}

function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    var firstChild = fiber.child;

    if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
      firstChild.return = fiber;
      nextEffect = firstChild;
    } else {
      commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions);
    }
  }
}

function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) {
  while (nextEffect !== null) {
    var fiber = nextEffect;

    if ((fiber.flags & Passive) !== NoFlags) {
      setCurrentFiber(fiber);

      try {
        commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions);
      } catch (error) {
        captureCommitPhaseError(fiber, fiber.return, error);
      }

      resetCurrentFiber();
    }

    if (fiber === subtreeRoot) {
      nextEffect = null;
      return;
    }

    var sibling = fiber.sibling;

    if (sibling !== null) {
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
  switch (finishedWork.tag) {
    case FunctionComponent:
    case ForwardRef:
    case SimpleMemoComponent:
      {
        if ( finishedWork.mode & ProfileMode) {
          startPassiveEffectTimer();

          try {
            commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
          } finally {
            recordPassiveEffectDuration(finishedWork);
          }
        } else {
          commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
        }

        break;
      }
  }
}

function commitPassiveUnmountEffects(firstChild) {
  nextEffect = firstChild;
  commitPassiveUnmountEffects_begin();
}

function commitPassiveUnmountEffects_begin() {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    var child = fiber.child;

    if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
      var deletions = fiber.deletions;

      if (deletions !== null) {
        for (var i = 0; i < deletions.length; i++) {
          var fiberToDelete = deletions[i];
          nextEffect = fiberToDelete;
          commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
        }

        {
          // A fiber was deleted from this parent fiber, but it's still part of
          // the previous (alternate) parent fiber's list of children. Because
          // children are a linked list, an earlier sibling that's still alive
          // will be connected to the deleted fiber via its `alternate`:
          //
          //   live fiber
          //   --alternate--> previous live fiber
          //   --sibling--> deleted fiber
          //
          // We can't disconnect `alternate` on nodes that haven't been deleted
          // yet, but we can disconnect the `sibling` and `child` pointers.
          var previousFiber = fiber.alternate;

          if (previousFiber !== null) {
            var detachedChild = previousFiber.child;

            if (detachedChild !== null) {
              previousFiber.child = null;

              do {
                var detachedSibling = detachedChild.sibling;
                detachedChild.sibling = null;
                detachedChild = detachedSibling;
              } while (detachedChild !== null);
            }
          }
        }

        nextEffect = fiber;
      }
    }

    if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
      child.return = fiber;
      nextEffect = child;
    } else {
      commitPassiveUnmountEffects_complete();
    }
  }
}

function commitPassiveUnmountEffects_complete() {
  while (nextEffect !== null) {
    var fiber = nextEffect;

    if ((fiber.flags & Passive) !== NoFlags) {
      setCurrentFiber(fiber);
      commitPassiveUnmountOnFiber(fiber);
      resetCurrentFiber();
    }

    var sibling = fiber.sibling;

    if (sibling !== null) {
      sibling.return = fiber.return;
      nextEffect = sibling;
      return;
    }

    nextEffect = fiber.return;
  }
}

function commitPassiveUnmountOnFiber(finishedWork) {
  switch (finishedWork.tag) {
    case FunctionComponent:
    case ForwardRef:
    case SimpleMemoComponent:
      {
        if ( finishedWork.mode & ProfileMode) {
          startPassiveEffectTimer();
          commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
          recordPassiveEffectDuration(finishedWork);
        } else {
          commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
        }

        break;
      }
  }
}

function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
  while (nextEffect !== null) {
    var fiber = nextEffect; // Deletion effects fire in parent -> child order
    // TODO: Check if fiber has a PassiveStatic flag

    setCurrentFiber(fiber);
    commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
    resetCurrentFiber();
    var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
    // do this, still need to handle `deletedTreeCleanUpLevel` correctly.)

    if (child !== null) {
      child.return = fiber;
      nextEffect = child;
    } else {
      commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
    }
  }
}

function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
  while (nextEffect !== null) {
    var fiber = nextEffect;
    var sibling = fiber.sibling;
    var returnFiber = fiber.return;

    {
      // Recursively traverse the entire deleted tree and clean up fiber fields.
      // This is more aggressive than ideal, and the long term goal is to only
      // have to detach the deleted tree at the root.
      detachFiberAfterEffects(fiber);

      if (fiber === deletedSubtreeRoot) {
        nextEffect = null;
        return;
      }
    }

    if (sibling !== null) {
      sibling.return = returnFiber;
      nextEffect = sibling;
      return;
    }

    nextEffect = returnFiber;
  }
}

function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) {
  switch (current.tag) {
    case FunctionComponent:
    case ForwardRef:
    case SimpleMemoComponent:
      {
        if ( current.mode & ProfileMode) {
          startPassiveEffectTimer();
          commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
          recordPassiveEffectDuration(current);
        } else {
          commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
        }

        break;
      }
  }
} // TODO: Reuse reappearLayoutEffects traversal here?


function invokeLayoutEffectMountInDEV(fiber) {
  {
    // We don't need to re-check StrictEffectsMode here.
    // This function is only called if that check has already passed.
    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          try {
            commitHookEffectListMount(Layout | HasEffect, fiber);
          } catch (error) {
            captureCommitPhaseError(fiber, fiber.return, error);
          }

          break;
        }

      case ClassComponent:
        {
          var instance = fiber.stateNode;

          try {
            instance.componentDidMount();
          } catch (error) {
            captureCommitPhaseError(fiber, fiber.return, error);
          }

          break;
        }
    }
  }
}

function invokePassiveEffectMountInDEV(fiber) {
  {
    // We don't need to re-check StrictEffectsMode here.
    // This function is only called if that check has already passed.
    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          try {
            commitHookEffectListMount(Passive$1 | HasEffect, fiber);
          } catch (error) {
            captureCommitPhaseError(fiber, fiber.return, error);
          }

          break;
        }
    }
  }
}

function invokeLayoutEffectUnmountInDEV(fiber) {
  {
    // We don't need to re-check StrictEffectsMode here.
    // This function is only called if that check has already passed.
    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          try {
            commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
          } catch (error) {
            captureCommitPhaseError(fiber, fiber.return, error);
          }

          break;
        }

      case ClassComponent:
        {
          var instance = fiber.stateNode;

          if (typeof instance.componentWillUnmount === 'function') {
            safelyCallComponentWillUnmount(fiber, fiber.return, instance);
          }

          break;
        }
    }
  }
}

function invokePassiveEffectUnmountInDEV(fiber) {
  {
    // We don't need to re-check StrictEffectsMode here.
    // This function is only called if that check has already passed.
    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case SimpleMemoComponent:
        {
          try {
            commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
          } catch (error) {
            captureCommitPhaseError(fiber, fiber.return, error);
          }
        }
    }
  }
}

var COMPONENT_TYPE = 0;
var HAS_PSEUDO_CLASS_TYPE = 1;
var ROLE_TYPE = 2;
var TEST_NAME_TYPE = 3;
var TEXT_TYPE = 4;

if (typeof Symbol === 'function' && Symbol.for) {
  var symbolFor = Symbol.for;
  COMPONENT_TYPE = symbolFor('selector.component');
  HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class');
  ROLE_TYPE = symbolFor('selector.role');
  TEST_NAME_TYPE = symbolFor('selector.test_id');
  TEXT_TYPE = symbolFor('selector.text');
}
var commitHooks = [];
function onCommitRoot$1() {
  {
    commitHooks.forEach(function (commitHook) {
      return commitHook();
    });
  }
}

var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
function isLegacyActEnvironment(fiber) {
  {
    // Legacy mode. We preserve the behavior of React 17's act. It assumes an
    // act environment whenever `jest` is defined, but you can still turn off
    // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
    // to false.
    var isReactActEnvironmentGlobal = // $FlowExpectedError â€“ Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
    typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest

    var jestIsDefined = typeof jest !== 'undefined';
    return  jestIsDefined && isReactActEnvironmentGlobal !== false;
  }
}
function isConcurrentActEnvironment() {
  {
    var isReactActEnvironmentGlobal = // $FlowExpectedError â€“ Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
    typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined;

    if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
      // TODO: Include link to relevant documentation page.
      error('The current testing environment is not configured to support ' + 'act(...)');
    }

    return isReactActEnvironmentGlobal;
  }
}

var ceil = Math.ceil;
var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
    ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
    ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig,
    ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
var NoContext =
/*             */
0;
var BatchedContext =
/*               */
1;
var RenderContext =
/*                */
2;
var CommitContext =
/*                */
4;
var RootInProgress = 0;
var RootFatalErrored = 1;
var RootErrored = 2;
var RootSuspended = 3;
var RootSuspendedWithDelay = 4;
var RootCompleted = 5;
var RootDidNotComplete = 6; // Describes where we are in the React execution stack

var executionContext = NoContext; // The root we're working on

var workInProgressRoot = null; // The fiber we're working on

var workInProgress = null; // The lanes we're rendering

var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
// This is a superset of the lanes we started working on at the root. The only
// case where it's different from `workInProgressRootRenderLanes` is when we
// enter a subtree that is hidden and needs to be unhidden: Suspense and
// Offscreen component.
//
// Most things in the work loop should deal with workInProgressRootRenderLanes.
// Most things in begin/complete phases should deal with subtreeRenderLanes.

var subtreeRenderLanes = NoLanes;
var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.

var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown

var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
// slightly different than `renderLanes` because `renderLanes` can change as you
// enter and exit an Offscreen tree. This value is the combination of all render
// lanes for the entire render phase.

var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
// includes unprocessed updates, not work in bailed out children.

var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.

var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event).

var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase.

var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI.
// We will log them once the tree commits.

var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train
// model where we don't commit new loading states in too quick succession.

var globalMostRecentFallbackTime = 0;
var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
// more and prefer CPU suspense heuristics instead.

var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
// suspense heuristics and opt out of rendering more content.

var RENDER_TIMEOUT_MS = 500;
var workInProgressTransitions = null;

function resetRenderTimer() {
  workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
}

function getRenderTargetTime() {
  return workInProgressRootRenderTargetTime;
}
var hasUncaughtError = false;
var firstUncaughtError = null;
var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true;
var rootDoesHavePassiveEffects = false;
var rootWithPendingPassiveEffects = null;
var pendingPassiveEffectsLanes = NoLanes;
var pendingPassiveProfilerEffects = [];
var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates

var NESTED_UPDATE_LIMIT = 50;
var nestedUpdateCount = 0;
var rootWithNestedUpdates = null;
var isFlushingPassiveEffects = false;
var didScheduleUpdateDuringPassiveEffects = false;
var NESTED_PASSIVE_UPDATE_LIMIT = 50;
var nestedPassiveUpdateCount = 0;
var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their
// event times as simultaneous, even if the actual clock time has advanced
// between the first and second call.

var currentEventTime = NoTimestamp;
var currentEventTransitionLane = NoLanes;
var isRunningInsertionEffect = false;
function getWorkInProgressRoot() {
  return workInProgressRoot;
}
function requestEventTime() {
  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    // We're inside React, so it's fine to read the actual time.
    return now();
  } // We're not inside React, so we may be in the middle of a browser event.


  if (currentEventTime !== NoTimestamp) {
    // Use the same start time for all updates until we enter React again.
    return currentEventTime;
  } // This is the first update since React yielded. Compute a new start time.


  currentEventTime = now();
  return currentEventTime;
}
function requestUpdateLane(fiber) {
  // Special cases
  var mode = fiber.mode;

  if ((mode & ConcurrentMode) === NoMode) {
    return SyncLane;
  } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
    // This is a render phase update. These are not officially supported. The
    // old behavior is to give this the same "thread" (lanes) as
    // whatever is currently rendering. So if you call `setState` on a component
    // that happens later in the same render, it will flush. Ideally, we want to
    // remove the special case and treat them as if they came from an
    // interleaved event. Regardless, this pattern is not officially supported.
    // This behavior is only a fallback. The flag only exists until we can roll
    // out the setState warning, since existing code might accidentally rely on
    // the current behavior.
    return pickArbitraryLane(workInProgressRootRenderLanes);
  }

  var isTransition = requestCurrentTransition() !== NoTransition;

  if (isTransition) {
    if ( ReactCurrentBatchConfig$3.transition !== null) {
      var transition = ReactCurrentBatchConfig$3.transition;

      if (!transition._updatedFibers) {
        transition._updatedFibers = new Set();
      }

      transition._updatedFibers.add(fiber);
    } // The algorithm for assigning an update to a lane should be stable for all
    // updates at the same priority within the same event. To do this, the
    // inputs to the algorithm must be the same.
    //
    // The trick we use is to cache the first of each of these inputs within an
    // event. Then reset the cached values once we can be sure the event is
    // over. Our heuristic for that is whenever we enter a concurrent work loop.


    if (currentEventTransitionLane === NoLane) {
      // All transitions within the same event are assigned the same lane.
      currentEventTransitionLane = claimNextTransitionLane();
    }

    return currentEventTransitionLane;
  } // Updates originating inside certain React methods, like flushSync, have
  // their priority set by tracking it with a context variable.
  //
  // The opaque type returned by the host config is internally a lane, so we can
  // use that directly.
  // TODO: Move this type conversion to the event priority module.


  var updateLane = getCurrentUpdatePriority();

  if (updateLane !== NoLane) {
    return updateLane;
  } // This update originated outside React. Ask the host environment for an
  // appropriate priority, based on the type of event.
  //
  // The opaque type returned by the host config is internally a lane, so we can
  // use that directly.
  // TODO: Move this type conversion to the event priority module.


  var eventLane = getCurrentEventPriority();
  return eventLane;
}

function requestRetryLane(fiber) {
  // This is a fork of `requestUpdateLane` designed specifically for Suspense
  // "retries" â€” a special update that attempts to flip a Suspense boundary
  // from its placeholder state to its primary/resolved state.
  // Special cases
  var mode = fiber.mode;

  if ((mode & ConcurrentMode) === NoMode) {
    return SyncLane;
  }

  return claimNextRetryLane();
}

function scheduleUpdateOnFiber(root, fiber, lane, eventTime) {
  checkForNestedUpdates();

  {
    if (isRunningInsertionEffect) {
      error('useInsertionEffect must not schedule updates.');
    }
  }

  {
    if (isFlushingPassiveEffects) {
      didScheduleUpdateDuringPassiveEffects = true;
    }
  } // Mark that the root has a pending update.


  markRootUpdated(root, lane, eventTime);

  if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) {
    // This update was dispatched during the render phase. This is a mistake
    // if the update originates from user space (with the exception of local
    // hook updates, which are handled differently and don't reach this
    // function), but there are some internal React features that use this as
    // an implementation detail, like selective hydration.
    warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase
  } else {
    // This is a normal update, scheduled from outside the render phase. For
    // example, during an input event.
    {
      if (isDevToolsPresent) {
        addFiberToLanesMap(root, fiber, lane);
      }
    }

    warnIfUpdatesNotWrappedWithActDEV(fiber);

    if (root === workInProgressRoot) {
      // Received an update to a tree that's in the middle of rendering. Mark
      // that there was an interleaved update work on this root. Unless the
      // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
      // phase update. In that case, we don't treat render phase updates as if
      // they were interleaved, for backwards compat reasons.
      if ( (executionContext & RenderContext) === NoContext) {
        workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
      }

      if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
        // The root already suspended with a delay, which means this render
        // definitely won't finish. Since we have a new update, let's mark it as
        // suspended now, right before marking the incoming update. This has the
        // effect of interrupting the current render and switching to the update.
        // TODO: Make sure this doesn't override pings that happen while we've
        // already started rendering.
        markRootSuspended$1(root, workInProgressRootRenderLanes);
      }
    }

    ensureRootIsScheduled(root, eventTime);

    if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
    !( ReactCurrentActQueue$1.isBatchingLegacy)) {
      // Flush the synchronous work now, unless we're already working or inside
      // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
      // scheduleCallbackForFiber to preserve the ability to schedule a callback
      // without immediately flushing it. We only do this for user-initiated
      // updates, to preserve historical behavior of legacy mode.
      resetRenderTimer();
      flushSyncCallbacksOnlyInLegacyMode();
    }
  }
}
function scheduleInitialHydrationOnRoot(root, lane, eventTime) {
  // This is a special fork of scheduleUpdateOnFiber that is only used to
  // schedule the initial hydration of a root that has just been created. Most
  // of the stuff in scheduleUpdateOnFiber can be skipped.
  //
  // The main reason for this separate path, though, is to distinguish the
  // initial children from subsequent updates. In fully client-rendered roots
  // (createRoot instead of hydrateRoot), all top-level renders are modeled as
  // updates, but hydration roots are special because the initial render must
  // match what was rendered on the server.
  var current = root.current;
  current.lanes = lane;
  markRootUpdated(root, lane, eventTime);
  ensureRootIsScheduled(root, eventTime);
}
function isUnsafeClassRenderPhaseUpdate(fiber) {
  // Check if this is a render phase update. Only called by class components,
  // which special (deprecated) behavior for UNSAFE_componentWillReceive props.
  return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
    // decided not to enable it.
     (executionContext & RenderContext) !== NoContext
  );
} // Use this function to schedule a task for a root. There's only one task per
// root; if a task was already scheduled, we'll check to make sure the priority
// of the existing task is the same as the priority of the next level that the
// root has work on. This function is called on every update, and right before
// exiting a task.

function ensureRootIsScheduled(root, currentTime) {
  var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
  // expired so we know to work on those next.

  markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.

  var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);

  if (nextLanes === NoLanes) {
    // Special case: There's nothing to work on.
    if (existingCallbackNode !== null) {
      cancelCallback$1(existingCallbackNode);
    }

    root.callbackNode = null;
    root.callbackPriority = NoLane;
    return;
  } // We use the highest priority lane to represent the priority of the callback.


  var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it.

  var existingCallbackPriority = root.callbackPriority;

  if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
  // Scheduler task, rather than an `act` task, cancel it and re-scheduled
  // on the `act` queue.
  !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
    {
      // If we're going to re-use an existing task, it needs to exist.
      // Assume that discrete update microtasks are non-cancellable and null.
      // TODO: Temporary until we confirm this warning is not fired.
      if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
        error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.');
      }
    } // The priority hasn't changed. We can reuse the existing task. Exit.


    return;
  }

  if (existingCallbackNode != null) {
    // Cancel the existing callback. We'll schedule a new one below.
    cancelCallback$1(existingCallbackNode);
  } // Schedule a new callback.


  var newCallbackNode;

  if (newCallbackPriority === SyncLane) {
    // Special case: Sync React callbacks are scheduled on a special
    // internal queue
    if (root.tag === LegacyRoot) {
      if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) {
        ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
      }

      scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root));
    } else {
      scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
    }

    {
      // Flush the queue in a microtask.
      if ( ReactCurrentActQueue$1.current !== null) {
        // Inside `act`, use our internal `act` queue so that these get flushed
        // at the end of the current scope even when using the sync version
        // of `act`.
        ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
      } else {
        scheduleMicrotask(function () {
          // In Safari, appending an iframe forces microtasks to run.
          // https://github.com/facebook/react/issues/22459
          // We don't support running callbacks in the middle of render
          // or commit so we need to check against that.
          if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
            // Note that this would still prematurely flush the callbacks
            // if this happens outside render or commit phase (e.g. in an event).
            flushSyncCallbacks();
          }
        });
      }
    }

    newCallbackNode = null;
  } else {
    var schedulerPriorityLevel;

    switch (lanesToEventPriority(nextLanes)) {
      case DiscreteEventPriority:
        schedulerPriorityLevel = ImmediatePriority;
        break;

      case ContinuousEventPriority:
        schedulerPriorityLevel = UserBlockingPriority;
        break;

      case DefaultEventPriority:
        schedulerPriorityLevel = NormalPriority;
        break;

      case IdleEventPriority:
        schedulerPriorityLevel = IdlePriority;
        break;

      default:
        schedulerPriorityLevel = NormalPriority;
        break;
    }

    newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
  }

  root.callbackPriority = newCallbackPriority;
  root.callbackNode = newCallbackNode;
} // This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.


function performConcurrentWorkOnRoot(root, didTimeout) {
  {
    resetNestedUpdateFlag();
  } // Since we know we're in a React event, we can clear the current
  // event time. The next update will compute a new event time.


  currentEventTime = NoTimestamp;
  currentEventTransitionLane = NoLanes;

  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    throw new Error('Should not already be working.');
  } // Flush any pending passive effects before deciding which lanes to work on,
  // in case they schedule additional work.


  var originalCallbackNode = root.callbackNode;
  var didFlushPassiveEffects = flushPassiveEffects();

  if (didFlushPassiveEffects) {
    // Something in the passive effect phase may have canceled the current task.
    // Check if the task node for this root was changed.
    if (root.callbackNode !== originalCallbackNode) {
      // The current task was canceled. Exit. We don't need to call
      // `ensureRootIsScheduled` because the check above implies either that
      // there's a new task, or that there's no remaining work on this root.
      return null;
    }
  } // Determine the next lanes to work on, using the fields stored
  // on the root.


  var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);

  if (lanes === NoLanes) {
    // Defensive coding. This is never expected to happen.
    return null;
  } // We disable time-slicing in some cases: if the work has been CPU-bound
  // for too long ("expired" work, to prevent starvation), or we're in
  // sync-updates-by-default mode.
  // TODO: We only check `didTimeout` defensively, to account for a Scheduler
  // bug we're still investigating. Once the bug in Scheduler is fixed,
  // we can remove this, since we track expiration ourselves.


  var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout);
  var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes);

  if (exitStatus !== RootInProgress) {
    if (exitStatus === RootErrored) {
      // If something threw an error, try rendering one more time. We'll
      // render synchronously to block concurrent data mutations, and we'll
      // includes all pending updates are included. If it still fails after
      // the second attempt, we'll give up and commit the resulting tree.
      var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

      if (errorRetryLanes !== NoLanes) {
        lanes = errorRetryLanes;
        exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
      }
    }

    if (exitStatus === RootFatalErrored) {
      var fatalError = workInProgressRootFatalError;
      prepareFreshStack(root, NoLanes);
      markRootSuspended$1(root, lanes);
      ensureRootIsScheduled(root, now());
      throw fatalError;
    }

    if (exitStatus === RootDidNotComplete) {
      // The render unwound without completing the tree. This happens in special
      // cases where need to exit the current render without producing a
      // consistent tree or committing.
      //
      // This should only happen during a concurrent render, not a discrete or
      // synchronous update. We should have already checked for this when we
      // unwound the stack.
      markRootSuspended$1(root, lanes);
    } else {
      // The render completed.
      // Check if this render may have yielded to a concurrent event, and if so,
      // confirm that any newly rendered stores are consistent.
      // TODO: It's possible that even a concurrent render may never have yielded
      // to the main thread, if it was fast enough, or if it expired. We could
      // skip the consistency check in that case, too.
      var renderWasConcurrent = !includesBlockingLane(root, lanes);
      var finishedWork = root.current.alternate;

      if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
        // A store was mutated in an interleaved event. Render again,
        // synchronously, to block further mutations.
        exitStatus = renderRootSync(root, lanes); // We need to check again if something threw

        if (exitStatus === RootErrored) {
          var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

          if (_errorRetryLanes !== NoLanes) {
            lanes = _errorRetryLanes;
            exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any
            // concurrent events.
          }
        }

        if (exitStatus === RootFatalErrored) {
          var _fatalError = workInProgressRootFatalError;
          prepareFreshStack(root, NoLanes);
          markRootSuspended$1(root, lanes);
          ensureRootIsScheduled(root, now());
          throw _fatalError;
        }
      } // We now have a consistent tree. The next step is either to commit it,
      // or, if something suspended, wait to commit it after a timeout.


      root.finishedWork = finishedWork;
      root.finishedLanes = lanes;
      finishConcurrentRender(root, exitStatus, lanes);
    }
  }

  ensureRootIsScheduled(root, now());

  if (root.callbackNode === originalCallbackNode) {
    // The task node scheduled for this root is the same one that's
    // currently executed. Need to return a continuation.
    return performConcurrentWorkOnRoot.bind(null, root);
  }

  return null;
}

function recoverFromConcurrentError(root, errorRetryLanes) {
  // If an error occurred during hydration, discard server response and fall
  // back to client side render.
  // Before rendering again, save the errors from the previous attempt.
  var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;

  if (isRootDehydrated(root)) {
    // The shell failed to hydrate. Set a flag to force a client rendering
    // during the next attempt. To do this, we call prepareFreshStack now
    // to create the root work-in-progress fiber. This is a bit weird in terms
    // of factoring, because it relies on renderRootSync not calling
    // prepareFreshStack again in the call below, which happens because the
    // root and lanes haven't changed.
    //
    // TODO: I think what we should do is set ForceClientRender inside
    // throwException, like we do for nested Suspense boundaries. The reason
    // it's here instead is so we can switch to the synchronous work loop, too.
    // Something to consider for a future refactor.
    var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
    rootWorkInProgress.flags |= ForceClientRender;

    {
      errorHydratingContainer(root.containerInfo);
    }
  }

  var exitStatus = renderRootSync(root, errorRetryLanes);

  if (exitStatus !== RootErrored) {
    // Successfully finished rendering on retry
    // The errors from the failed first attempt have been recovered. Add
    // them to the collection of recoverable errors. We'll log them in the
    // commit phase.
    var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
    workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors
    // from the first attempt, to preserve the causal sequence.

    if (errorsFromSecondAttempt !== null) {
      queueRecoverableErrors(errorsFromSecondAttempt);
    }
  }

  return exitStatus;
}

function queueRecoverableErrors(errors) {
  if (workInProgressRootRecoverableErrors === null) {
    workInProgressRootRecoverableErrors = errors;
  } else {
    workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors);
  }
}

function finishConcurrentRender(root, exitStatus, lanes) {
  switch (exitStatus) {
    case RootInProgress:
    case RootFatalErrored:
      {
        throw new Error('Root did not complete. This is a bug in React.');
      }
    // Flow knows about invariant, so it complains if I add a break
    // statement, but eslint doesn't know about invariant, so it complains
    // if I do. eslint-disable-next-line no-fallthrough

    case RootErrored:
      {
        // We should have already attempted to retry this tree. If we reached
        // this point, it errored again. Commit it.
        commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
        break;
      }

    case RootSuspended:
      {
        markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
        // should immediately commit it or wait a bit.

        if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
        !shouldForceFlushFallbacksInDEV()) {
          // This render only included retries, no updates. Throttle committing
          // retries so that we don't show too many loading states too quickly.
          var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.

          if (msUntilTimeout > 10) {
            var nextLanes = getNextLanes(root, NoLanes);

            if (nextLanes !== NoLanes) {
              // There's additional work on this root.
              break;
            }

            var suspendedLanes = root.suspendedLanes;

            if (!isSubsetOfLanes(suspendedLanes, lanes)) {
              // We should prefer to render the fallback of at the last
              // suspended level. Ping the last suspended level to try
              // rendering it again.
              // FIXME: What if the suspended lanes are Idle? Should not restart.
              var eventTime = requestEventTime();
              markRootPinged(root, suspendedLanes);
              break;
            } // The render is suspended, it hasn't timed out, and there's no
            // lower priority work to do. Instead of committing the fallback
            // immediately, wait for more data to arrive.


            root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
            break;
          }
        } // The work expired. Commit immediately.


        commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
        break;
      }

    case RootSuspendedWithDelay:
      {
        markRootSuspended$1(root, lanes);

        if (includesOnlyTransitions(lanes)) {
          // This is a transition, so we should exit without committing a
          // placeholder and without scheduling a timeout. Delay indefinitely
          // until we receive more data.
          break;
        }

        if (!shouldForceFlushFallbacksInDEV()) {
          // This is not a transition, but we did trigger an avoided state.
          // Schedule a placeholder to display after a short delay, using the Just
          // Noticeable Difference.
          // TODO: Is the JND optimization worth the added complexity? If this is
          // the only reason we track the event time, then probably not.
          // Consider removing.
          var mostRecentEventTime = getMostRecentEventTime(root, lanes);
          var eventTimeMs = mostRecentEventTime;
          var timeElapsedMs = now() - eventTimeMs;

          var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.


          if (_msUntilTimeout > 10) {
            // Instead of committing the fallback immediately, wait for more data
            // to arrive.
            root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
            break;
          }
        } // Commit the placeholder.


        commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
        break;
      }

    case RootCompleted:
      {
        // The work completed. Ready to commit.
        commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
        break;
      }

    default:
      {
        throw new Error('Unknown root exit status.');
      }
  }
}

function isRenderConsistentWithExternalStores(finishedWork) {
  // Search the rendered tree for external store reads, and check whether the
  // stores were mutated in a concurrent event. Intentionally using an iterative
  // loop instead of recursion so we can exit early.
  var node = finishedWork;

  while (true) {
    if (node.flags & StoreConsistency) {
      var updateQueue = node.updateQueue;

      if (updateQueue !== null) {
        var checks = updateQueue.stores;

        if (checks !== null) {
          for (var i = 0; i < checks.length; i++) {
            var check = checks[i];
            var getSnapshot = check.getSnapshot;
            var renderedValue = check.value;

            try {
              if (!objectIs(getSnapshot(), renderedValue)) {
                // Found an inconsistent store.
                return false;
              }
            } catch (error) {
              // If `getSnapshot` throws, return `false`. This will schedule
              // a re-render, and the error will be rethrown during render.
              return false;
            }
          }
        }
      }
    }

    var child = node.child;

    if (node.subtreeFlags & StoreConsistency && child !== null) {
      child.return = node;
      node = child;
      continue;
    }

    if (node === finishedWork) {
      return true;
    }

    while (node.sibling === null) {
      if (node.return === null || node.return === finishedWork) {
        return true;
      }

      node = node.return;
    }

    node.sibling.return = node.return;
    node = node.sibling;
  } // Flow doesn't know this is unreachable, but eslint does
  // eslint-disable-next-line no-unreachable


  return true;
}

function markRootSuspended$1(root, suspendedLanes) {
  // When suspending, we should always exclude lanes that were pinged or (more
  // rarely, since we try to avoid it) updated during the render phase.
  // TODO: Lol maybe there's a better way to factor this besides this
  // obnoxiously named function :)
  suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
  suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
  markRootSuspended(root, suspendedLanes);
} // This is the entry point for synchronous tasks that don't go
// through Scheduler


function performSyncWorkOnRoot(root) {
  {
    syncNestedUpdateFlag();
  }

  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    throw new Error('Should not already be working.');
  }

  flushPassiveEffects();
  var lanes = getNextLanes(root, NoLanes);

  if (!includesSomeLane(lanes, SyncLane)) {
    // There's no remaining sync work left.
    ensureRootIsScheduled(root, now());
    return null;
  }

  var exitStatus = renderRootSync(root, lanes);

  if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
    // If something threw an error, try rendering one more time. We'll render
    // synchronously to block concurrent data mutations, and we'll includes
    // all pending updates are included. If it still fails after the second
    // attempt, we'll give up and commit the resulting tree.
    var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);

    if (errorRetryLanes !== NoLanes) {
      lanes = errorRetryLanes;
      exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
    }
  }

  if (exitStatus === RootFatalErrored) {
    var fatalError = workInProgressRootFatalError;
    prepareFreshStack(root, NoLanes);
    markRootSuspended$1(root, lanes);
    ensureRootIsScheduled(root, now());
    throw fatalError;
  }

  if (exitStatus === RootDidNotComplete) {
    throw new Error('Root did not complete. This is a bug in React.');
  } // We now have a consistent tree. Because this is a sync render, we
  // will commit it even if something suspended.


  var finishedWork = root.current.alternate;
  root.finishedWork = finishedWork;
  root.finishedLanes = lanes;
  commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next
  // pending level.

  ensureRootIsScheduled(root, now());
  return null;
}

function flushRoot(root, lanes) {
  if (lanes !== NoLanes) {
    markRootEntangled(root, mergeLanes(lanes, SyncLane));
    ensureRootIsScheduled(root, now());

    if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
      resetRenderTimer();
      flushSyncCallbacks();
    }
  }
}
function batchedUpdates$1(fn, a) {
  var prevExecutionContext = executionContext;
  executionContext |= BatchedContext;

  try {
    return fn(a);
  } finally {
    executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer
    // most batchedUpdates-like method.

    if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
    !( ReactCurrentActQueue$1.isBatchingLegacy)) {
      resetRenderTimer();
      flushSyncCallbacksOnlyInLegacyMode();
    }
  }
}
function discreteUpdates(fn, a, b, c, d) {
  var previousPriority = getCurrentUpdatePriority();
  var prevTransition = ReactCurrentBatchConfig$3.transition;

  try {
    ReactCurrentBatchConfig$3.transition = null;
    setCurrentUpdatePriority(DiscreteEventPriority);
    return fn(a, b, c, d);
  } finally {
    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig$3.transition = prevTransition;

    if (executionContext === NoContext) {
      resetRenderTimer();
    }
  }
} // Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.

// eslint-disable-next-line no-redeclare
function flushSync(fn) {
  // In legacy mode, we flush pending passive effects at the beginning of the
  // next event, not at the end of the previous one.
  if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
    flushPassiveEffects();
  }

  var prevExecutionContext = executionContext;
  executionContext |= BatchedContext;
  var prevTransition = ReactCurrentBatchConfig$3.transition;
  var previousPriority = getCurrentUpdatePriority();

  try {
    ReactCurrentBatchConfig$3.transition = null;
    setCurrentUpdatePriority(DiscreteEventPriority);

    if (fn) {
      return fn();
    } else {
      return undefined;
    }
  } finally {
    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig$3.transition = prevTransition;
    executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
    // Note that this will happen even if batchedUpdates is higher up
    // the stack.

    if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
      flushSyncCallbacks();
    }
  }
}
function isAlreadyRendering() {
  // Used by the renderer to print a warning if certain APIs are called from
  // the wrong context.
  return  (executionContext & (RenderContext | CommitContext)) !== NoContext;
}
function pushRenderLanes(fiber, lanes) {
  push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
  subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
  workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
}
function popRenderLanes(fiber) {
  subtreeRenderLanes = subtreeRenderLanesCursor.current;
  pop(subtreeRenderLanesCursor, fiber);
}

function prepareFreshStack(root, lanes) {
  root.finishedWork = null;
  root.finishedLanes = NoLanes;
  var timeoutHandle = root.timeoutHandle;

  if (timeoutHandle !== noTimeout) {
    // The root previous suspended and scheduled a timeout to commit a fallback
    // state. Now that we have additional work, cancel the timeout.
    root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above

    cancelTimeout(timeoutHandle);
  }

  if (workInProgress !== null) {
    var interruptedWork = workInProgress.return;

    while (interruptedWork !== null) {
      var current = interruptedWork.alternate;
      unwindInterruptedWork(current, interruptedWork);
      interruptedWork = interruptedWork.return;
    }
  }

  workInProgressRoot = root;
  var rootWorkInProgress = createWorkInProgress(root.current, null);
  workInProgress = rootWorkInProgress;
  workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
  workInProgressRootExitStatus = RootInProgress;
  workInProgressRootFatalError = null;
  workInProgressRootSkippedLanes = NoLanes;
  workInProgressRootInterleavedUpdatedLanes = NoLanes;
  workInProgressRootPingedLanes = NoLanes;
  workInProgressRootConcurrentErrors = null;
  workInProgressRootRecoverableErrors = null;
  finishQueueingConcurrentUpdates();

  {
    ReactStrictModeWarnings.discardPendingWarnings();
  }

  return rootWorkInProgress;
}

function handleError(root, thrownValue) {
  do {
    var erroredWork = workInProgress;

    try {
      // Reset module-level state that was set during the render phase.
      resetContextDependencies();
      resetHooksAfterThrow();
      resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
      // separate issue. Write a regression test using string refs.

      ReactCurrentOwner$2.current = null;

      if (erroredWork === null || erroredWork.return === null) {
        // Expected to be working on a non-root fiber. This is a fatal error
        // because there's no ancestor that can handle it; the root is
        // supposed to capture all errors that weren't caught by an error
        // boundary.
        workInProgressRootExitStatus = RootFatalErrored;
        workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
        // sibling, or the parent if there are no siblings. But since the root
        // has no siblings nor a parent, we set it to null. Usually this is
        // handled by `completeUnitOfWork` or `unwindWork`, but since we're
        // intentionally not calling those, we need set it here.
        // TODO: Consider calling `unwindWork` to pop the contexts.

        workInProgress = null;
        return;
      }

      if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
        // Record the time spent rendering before an error was thrown. This
        // avoids inaccurate Profiler durations in the case of a
        // suspended render.
        stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
      }

      if (enableSchedulingProfiler) {
        markComponentRenderStopped();

        if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
          var wakeable = thrownValue;
          markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
        } else {
          markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
        }
      }

      throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
      completeUnitOfWork(erroredWork);
    } catch (yetAnotherThrownValue) {
      // Something in the return path also threw.
      thrownValue = yetAnotherThrownValue;

      if (workInProgress === erroredWork && erroredWork !== null) {
        // If this boundary has already errored, then we had trouble processing
        // the error. Bubble it to the next boundary.
        erroredWork = erroredWork.return;
        workInProgress = erroredWork;
      } else {
        erroredWork = workInProgress;
      }

      continue;
    } // Return to the normal work loop.


    return;
  } while (true);
}

function pushDispatcher() {
  var prevDispatcher = ReactCurrentDispatcher$2.current;
  ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;

  if (prevDispatcher === null) {
    // The React isomorphic package does not include a default dispatcher.
    // Instead the first renderer will lazily attach one, in order to give
    // nicer error messages.
    return ContextOnlyDispatcher;
  } else {
    return prevDispatcher;
  }
}

function popDispatcher(prevDispatcher) {
  ReactCurrentDispatcher$2.current = prevDispatcher;
}

function markCommitTimeOfFallback() {
  globalMostRecentFallbackTime = now();
}
function markSkippedUpdateLanes(lane) {
  workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
}
function renderDidSuspend() {
  if (workInProgressRootExitStatus === RootInProgress) {
    workInProgressRootExitStatus = RootSuspended;
  }
}
function renderDidSuspendDelayIfPossible() {
  if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
    workInProgressRootExitStatus = RootSuspendedWithDelay;
  } // Check if there are updates that we skipped tree that might have unblocked
  // this render.


  if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
    // Mark the current render as suspended so that we switch to working on
    // the updates that were skipped. Usually we only suspend at the end of
    // the render phase.
    // TODO: We should probably always mark the root as suspended immediately
    // (inside this function), since by suspending at the end of the render
    // phase introduces a potential mistake where we suspend lanes that were
    // pinged or updated while we were rendering.
    markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
  }
}
function renderDidError(error) {
  if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
    workInProgressRootExitStatus = RootErrored;
  }

  if (workInProgressRootConcurrentErrors === null) {
    workInProgressRootConcurrentErrors = [error];
  } else {
    workInProgressRootConcurrentErrors.push(error);
  }
} // Called during render to determine if anything has suspended.
// Returns false if we're not sure.

function renderHasNotSuspendedYet() {
  // If something errored or completed, we can't really be sure,
  // so those are false.
  return workInProgressRootExitStatus === RootInProgress;
}

function renderRootSync(root, lanes) {
  var prevExecutionContext = executionContext;
  executionContext |= RenderContext;
  var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
  // and prepare a fresh one. Otherwise we'll continue where we left off.

  if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
    {
      if (isDevToolsPresent) {
        var memoizedUpdaters = root.memoizedUpdaters;

        if (memoizedUpdaters.size > 0) {
          restorePendingUpdaters(root, workInProgressRootRenderLanes);
          memoizedUpdaters.clear();
        } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
        // If we bailout on this work, we'll move them back (like above).
        // It's important to move them now in case the work spawns more work at the same priority with different updaters.
        // That way we can keep the current update and future updates separate.


        movePendingFibersToMemoized(root, lanes);
      }
    }

    workInProgressTransitions = getTransitionsForLanes();
    prepareFreshStack(root, lanes);
  }

  {
    markRenderStarted(lanes);
  }

  do {
    try {
      workLoopSync();
      break;
    } catch (thrownValue) {
      handleError(root, thrownValue);
    }
  } while (true);

  resetContextDependencies();
  executionContext = prevExecutionContext;
  popDispatcher(prevDispatcher);

  if (workInProgress !== null) {
    // This is a sync render, so we should have finished the whole tree.
    throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.');
  }

  {
    markRenderStopped();
  } // Set this to null to indicate there's no in-progress render.


  workInProgressRoot = null;
  workInProgressRootRenderLanes = NoLanes;
  return workInProgressRootExitStatus;
} // The work loop is an extremely hot path. Tell Closure not to inline it.

/** @noinline */


function workLoopSync() {
  // Already timed out, so perform work without checking if we need to yield.
  while (workInProgress !== null) {
    performUnitOfWork(workInProgress);
  }
}

function renderRootConcurrent(root, lanes) {
  var prevExecutionContext = executionContext;
  executionContext |= RenderContext;
  var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
  // and prepare a fresh one. Otherwise we'll continue where we left off.

  if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
    {
      if (isDevToolsPresent) {
        var memoizedUpdaters = root.memoizedUpdaters;

        if (memoizedUpdaters.size > 0) {
          restorePendingUpdaters(root, workInProgressRootRenderLanes);
          memoizedUpdaters.clear();
        } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
        // If we bailout on this work, we'll move them back (like above).
        // It's important to move them now in case the work spawns more work at the same priority with different updaters.
        // That way we can keep the current update and future updates separate.


        movePendingFibersToMemoized(root, lanes);
      }
    }

    workInProgressTransitions = getTransitionsForLanes();
    resetRenderTimer();
    prepareFreshStack(root, lanes);
  }

  {
    markRenderStarted(lanes);
  }

  do {
    try {
      workLoopConcurrent();
      break;
    } catch (thrownValue) {
      handleError(root, thrownValue);
    }
  } while (true);

  resetContextDependencies();
  popDispatcher(prevDispatcher);
  executionContext = prevExecutionContext;


  if (workInProgress !== null) {
    // Still work remaining.
    {
      markRenderYielded();
    }

    return RootInProgress;
  } else {
    // Completed the tree.
    {
      markRenderStopped();
    } // Set this to null to indicate there's no in-progress render.


    workInProgressRoot = null;
    workInProgressRootRenderLanes = NoLanes; // Return the final exit status.

    return workInProgressRootExitStatus;
  }
}
/** @noinline */


function workLoopConcurrent() {
  // Perform work until Scheduler asks us to yield
  while (workInProgress !== null && !shouldYield()) {
    performUnitOfWork(workInProgress);
  }
}

function performUnitOfWork(unitOfWork) {
  // The current, flushed, state of this fiber is the alternate. Ideally
  // nothing should rely on this, but relying on it here means that we don't
  // need an additional field on the work in progress.
  var current = unitOfWork.alternate;
  setCurrentFiber(unitOfWork);
  var next;

  if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
    startProfilerTimer(unitOfWork);
    next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
    stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
  } else {
    next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
  }

  resetCurrentFiber();
  unitOfWork.memoizedProps = unitOfWork.pendingProps;

  if (next === null) {
    // If this doesn't spawn new work, complete the current work.
    completeUnitOfWork(unitOfWork);
  } else {
    workInProgress = next;
  }

  ReactCurrentOwner$2.current = null;
}

function completeUnitOfWork(unitOfWork) {
  // Attempt to complete the current unit of work, then move to the next
  // sibling. If there are no more siblings, return to the parent fiber.
  var completedWork = unitOfWork;

  do {
    // The current, flushed, state of this fiber is the alternate. Ideally
    // nothing should rely on this, but relying on it here means that we don't
    // need an additional field on the work in progress.
    var current = completedWork.alternate;
    var returnFiber = completedWork.return; // Check if the work completed or if something threw.

    if ((completedWork.flags & Incomplete) === NoFlags) {
      setCurrentFiber(completedWork);
      var next = void 0;

      if ( (completedWork.mode & ProfileMode) === NoMode) {
        next = completeWork(current, completedWork, subtreeRenderLanes);
      } else {
        startProfilerTimer(completedWork);
        next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.

        stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
      }

      resetCurrentFiber();

      if (next !== null) {
        // Completing this fiber spawned new work. Work on that next.
        workInProgress = next;
        return;
      }
    } else {
      // This fiber did not complete because something threw. Pop values off
      // the stack without entering the complete phase. If this is a boundary,
      // capture values if possible.
      var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes.


      if (_next !== null) {
        // If completing this work spawned new work, do that next. We'll come
        // back here again.
        // Since we're restarting, remove anything that is not a host effect
        // from the effect tag.
        _next.flags &= HostEffectMask;
        workInProgress = _next;
        return;
      }

      if ( (completedWork.mode & ProfileMode) !== NoMode) {
        // Record the render duration for the fiber that errored.
        stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.

        var actualDuration = completedWork.actualDuration;
        var child = completedWork.child;

        while (child !== null) {
          actualDuration += child.actualDuration;
          child = child.sibling;
        }

        completedWork.actualDuration = actualDuration;
      }

      if (returnFiber !== null) {
        // Mark the parent fiber as incomplete and clear its subtree flags.
        returnFiber.flags |= Incomplete;
        returnFiber.subtreeFlags = NoFlags;
        returnFiber.deletions = null;
      } else {
        // We've unwound all the way to the root.
        workInProgressRootExitStatus = RootDidNotComplete;
        workInProgress = null;
        return;
      }
    }

    var siblingFiber = completedWork.sibling;

    if (siblingFiber !== null) {
      // If there is more work to do in this returnFiber, do that next.
      workInProgress = siblingFiber;
      return;
    } // Otherwise, return to the parent


    completedWork = returnFiber; // Update the next thing we're working on in case something throws.

    workInProgress = completedWork;
  } while (completedWork !== null); // We've reached the root.


  if (workInProgressRootExitStatus === RootInProgress) {
    workInProgressRootExitStatus = RootCompleted;
  }
}

function commitRoot(root, recoverableErrors, transitions) {
  // TODO: This no longer makes any sense. We already wrap the mutation and
  // layout phases. Should be able to remove.
  var previousUpdateLanePriority = getCurrentUpdatePriority();
  var prevTransition = ReactCurrentBatchConfig$3.transition;

  try {
    ReactCurrentBatchConfig$3.transition = null;
    setCurrentUpdatePriority(DiscreteEventPriority);
    commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority);
  } finally {
    ReactCurrentBatchConfig$3.transition = prevTransition;
    setCurrentUpdatePriority(previousUpdateLanePriority);
  }

  return null;
}

function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) {
  do {
    // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
    // means `flushPassiveEffects` will sometimes result in additional
    // passive effects. So we need to keep flushing in a loop until there are
    // no more pending effects.
    // TODO: Might be better if `flushPassiveEffects` did not automatically
    // flush synchronous work at the end, to avoid factoring hazards like this.
    flushPassiveEffects();
  } while (rootWithPendingPassiveEffects !== null);

  flushRenderPhaseStrictModeWarningsInDEV();

  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    throw new Error('Should not already be working.');
  }

  var finishedWork = root.finishedWork;
  var lanes = root.finishedLanes;

  {
    markCommitStarted(lanes);
  }

  if (finishedWork === null) {

    {
      markCommitStopped();
    }

    return null;
  } else {
    {
      if (lanes === NoLanes) {
        error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.');
      }
    }
  }

  root.finishedWork = null;
  root.finishedLanes = NoLanes;

  if (finishedWork === root.current) {
    throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.');
  } // commitRoot never returns a continuation; it always finishes synchronously.
  // So we can clear these now to allow a new callback to be scheduled.


  root.callbackNode = null;
  root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first
  // pending time is whatever is left on the root fiber.

  var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
  markRootFinished(root, remainingLanes);

  if (root === workInProgressRoot) {
    // We can reset these now that they are finished.
    workInProgressRoot = null;
    workInProgress = null;
    workInProgressRootRenderLanes = NoLanes;
  } // If there are pending passive effects, schedule a callback to process them.
  // Do this as early as possible, so it is queued before anything else that
  // might get scheduled in the commit phase. (See #16714.)
  // TODO: Delete all other places that schedule the passive effect callback
  // They're redundant.


  if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
    if (!rootDoesHavePassiveEffects) {
      rootDoesHavePassiveEffects = true;
      // to store it in pendingPassiveTransitions until they get processed
      // We need to pass this through as an argument to commitRoot
      // because workInProgressTransitions might have changed between
      // the previous render and commit if we throttle the commit
      // with setTimeout

      pendingPassiveTransitions = transitions;
      scheduleCallback$1(NormalPriority, function () {
        flushPassiveEffects(); // This render triggered passive effects: release the root cache pool
        // *after* passive effects fire to avoid freeing a cache pool that may
        // be referenced by a node in the tree (HostRoot, Cache boundary etc)

        return null;
      });
    }
  } // Check if there are any effects in the whole tree.
  // TODO: This is left over from the effect list implementation, where we had
  // to check for the existence of `firstEffect` to satisfy Flow. I think the
  // only other reason this optimization exists is because it affects profiling.
  // Reconsider whether this is necessary.


  var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
  var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;

  if (subtreeHasEffects || rootHasEffect) {
    var prevTransition = ReactCurrentBatchConfig$3.transition;
    ReactCurrentBatchConfig$3.transition = null;
    var previousPriority = getCurrentUpdatePriority();
    setCurrentUpdatePriority(DiscreteEventPriority);
    var prevExecutionContext = executionContext;
    executionContext |= CommitContext; // Reset this to null before calling lifecycles

    ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
    // of the effect list for each phase: all mutation effects come before all
    // layout effects, and so on.
    // The first phase a "before mutation" phase. We use this phase to read the
    // state of the host tree right before we mutate it. This is where
    // getSnapshotBeforeUpdate is called.

    var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork);

    {
      // Mark the current commit time to be shared by all Profilers in this
      // batch. This enables them to be grouped later.
      recordCommitTime();
    }


    commitMutationEffects(root, finishedWork, lanes);

    resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
    // the mutation phase, so that the previous tree is still current during
    // componentWillUnmount, but before the layout phase, so that the finished
    // work is current during componentDidMount/Update.

    root.current = finishedWork; // The next phase is the layout phase, where we call effects that read

    {
      markLayoutEffectsStarted(lanes);
    }

    commitLayoutEffects(finishedWork, root, lanes);

    {
      markLayoutEffectsStopped();
    }
    // opportunity to paint.


    requestPaint();
    executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value.

    setCurrentUpdatePriority(previousPriority);
    ReactCurrentBatchConfig$3.transition = prevTransition;
  } else {
    // No effects.
    root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
    // no effects.
    // TODO: Maybe there's a better way to report this.

    {
      recordCommitTime();
    }
  }

  var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;

  if (rootDoesHavePassiveEffects) {
    // This commit has passive effects. Stash a reference to them. But don't
    // schedule a callback until after flushing layout work.
    rootDoesHavePassiveEffects = false;
    rootWithPendingPassiveEffects = root;
    pendingPassiveEffectsLanes = lanes;
  } else {

    {
      nestedPassiveUpdateCount = 0;
      rootWithPassiveNestedUpdates = null;
    }
  } // Read this again, since an effect might have updated it


  remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
  // TODO: This is part of the `componentDidCatch` implementation. Its purpose
  // is to detect whether something might have called setState inside
  // `componentDidCatch`. The mechanism is known to be flawed because `setState`
  // inside `componentDidCatch` is itself flawed â€” that's why we recommend
  // `getDerivedStateFromError` instead. However, it could be improved by
  // checking if remainingLanes includes Sync work, instead of whether there's
  // any work remaining at all (which would also include stuff like Suspense
  // retries or transitions). It's been like this for a while, though, so fixing
  // it probably isn't that urgent.

  if (remainingLanes === NoLanes) {
    // If there's no remaining work, we can clear the set of already failed
    // error boundaries.
    legacyErrorBoundariesThatAlreadyFailed = null;
  }

  {
    if (!rootDidHavePassiveEffects) {
      commitDoubleInvokeEffectsInDEV(root.current, false);
    }
  }

  onCommitRoot(finishedWork.stateNode, renderPriorityLevel);

  {
    if (isDevToolsPresent) {
      root.memoizedUpdaters.clear();
    }
  }

  {
    onCommitRoot$1();
  } // Always call this before exiting `commitRoot`, to ensure that any
  // additional work on this root is scheduled.


  ensureRootIsScheduled(root, now());

  if (recoverableErrors !== null) {
    // There were errors during this render, but recovered from them without
    // needing to surface it to the UI. We log them here.
    var onRecoverableError = root.onRecoverableError;

    for (var i = 0; i < recoverableErrors.length; i++) {
      var recoverableError = recoverableErrors[i];
      var componentStack = recoverableError.stack;
      var digest = recoverableError.digest;
      onRecoverableError(recoverableError.value, {
        componentStack: componentStack,
        digest: digest
      });
    }
  }

  if (hasUncaughtError) {
    hasUncaughtError = false;
    var error$1 = firstUncaughtError;
    firstUncaughtError = null;
    throw error$1;
  } // If the passive effects are the result of a discrete render, flush them
  // synchronously at the end of the current task so that the result is
  // immediately observable. Otherwise, we assume that they are not
  // order-dependent and do not need to be observed by external systems, so we
  // can wait until after paint.
  // TODO: We can optimize this by not scheduling the callback earlier. Since we
  // currently schedule the callback in multiple places, will wait until those
  // are consolidated.


  if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) {
    flushPassiveEffects();
  } // Read this again, since a passive effect might have updated it


  remainingLanes = root.pendingLanes;

  if (includesSomeLane(remainingLanes, SyncLane)) {
    {
      markNestedUpdateScheduled();
    } // Count the number of times the root synchronously re-renders without
    // finishing. If there are too many, it indicates an infinite update loop.


    if (root === rootWithNestedUpdates) {
      nestedUpdateCount++;
    } else {
      nestedUpdateCount = 0;
      rootWithNestedUpdates = root;
    }
  } else {
    nestedUpdateCount = 0;
  } // If layout work was scheduled, flush it now.


  flushSyncCallbacks();

  {
    markCommitStopped();
  }

  return null;
}

function flushPassiveEffects() {
  // Returns whether passive effects were flushed.
  // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
  // probably just combine the two functions. I believe they were only separate
  // in the first place because we used to wrap it with
  // `Scheduler.runWithPriority`, which accepts a function. But now we track the
  // priority within React itself, so we can mutate the variable directly.
  if (rootWithPendingPassiveEffects !== null) {
    var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
    var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
    var prevTransition = ReactCurrentBatchConfig$3.transition;
    var previousPriority = getCurrentUpdatePriority();

    try {
      ReactCurrentBatchConfig$3.transition = null;
      setCurrentUpdatePriority(priority);
      return flushPassiveEffectsImpl();
    } finally {
      setCurrentUpdatePriority(previousPriority);
      ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a
    }
  }

  return false;
}
function enqueuePendingPassiveProfilerEffect(fiber) {
  {
    pendingPassiveProfilerEffects.push(fiber);

    if (!rootDoesHavePassiveEffects) {
      rootDoesHavePassiveEffects = true;
      scheduleCallback$1(NormalPriority, function () {
        flushPassiveEffects();
        return null;
      });
    }
  }
}

function flushPassiveEffectsImpl() {
  if (rootWithPendingPassiveEffects === null) {
    return false;
  } // Cache and clear the transitions flag


  var transitions = pendingPassiveTransitions;
  pendingPassiveTransitions = null;
  var root = rootWithPendingPassiveEffects;
  var lanes = pendingPassiveEffectsLanes;
  rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
  // Figure out why and fix it. It's not causing any known issues (probably
  // because it's only used for profiling), but it's a refactor hazard.

  pendingPassiveEffectsLanes = NoLanes;

  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    throw new Error('Cannot flush passive effects while already rendering.');
  }

  {
    isFlushingPassiveEffects = true;
    didScheduleUpdateDuringPassiveEffects = false;
  }

  {
    markPassiveEffectsStarted(lanes);
  }

  var prevExecutionContext = executionContext;
  executionContext |= CommitContext;
  commitPassiveUnmountEffects(root.current);
  commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects

  {
    var profilerEffects = pendingPassiveProfilerEffects;
    pendingPassiveProfilerEffects = [];

    for (var i = 0; i < profilerEffects.length; i++) {
      var _fiber = profilerEffects[i];
      commitPassiveEffectDurations(root, _fiber);
    }
  }

  {
    markPassiveEffectsStopped();
  }

  {
    commitDoubleInvokeEffectsInDEV(root.current, true);
  }

  executionContext = prevExecutionContext;
  flushSyncCallbacks();

  {
    // If additional passive effects were scheduled, increment a counter. If this
    // exceeds the limit, we'll fire a warning.
    if (didScheduleUpdateDuringPassiveEffects) {
      if (root === rootWithPassiveNestedUpdates) {
        nestedPassiveUpdateCount++;
      } else {
        nestedPassiveUpdateCount = 0;
        rootWithPassiveNestedUpdates = root;
      }
    } else {
      nestedPassiveUpdateCount = 0;
    }

    isFlushingPassiveEffects = false;
    didScheduleUpdateDuringPassiveEffects = false;
  } // TODO: Move to commitPassiveMountEffects


  onPostCommitRoot(root);

  {
    var stateNode = root.current.stateNode;
    stateNode.effectDuration = 0;
    stateNode.passiveEffectDuration = 0;
  }

  return true;
}

function isAlreadyFailedLegacyErrorBoundary(instance) {
  return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
}
function markLegacyErrorBoundaryAsFailed(instance) {
  if (legacyErrorBoundariesThatAlreadyFailed === null) {
    legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
  } else {
    legacyErrorBoundariesThatAlreadyFailed.add(instance);
  }
}

function prepareToThrowUncaughtError(error) {
  if (!hasUncaughtError) {
    hasUncaughtError = true;
    firstUncaughtError = error;
  }
}

var onUncaughtError = prepareToThrowUncaughtError;

function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
  var errorInfo = createCapturedValueAtFiber(error, sourceFiber);
  var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
  var root = enqueueUpdate(rootFiber, update, SyncLane);
  var eventTime = requestEventTime();

  if (root !== null) {
    markRootUpdated(root, SyncLane, eventTime);
    ensureRootIsScheduled(root, eventTime);
  }
}

function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
  {
    reportUncaughtErrorInDEV(error$1);
    setIsRunningInsertionEffect(false);
  }

  if (sourceFiber.tag === HostRoot) {
    // Error was thrown at the root. There is no parent, so the root
    // itself should capture it.
    captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
    return;
  }

  var fiber = null;

  {
    fiber = nearestMountedAncestor;
  }

  while (fiber !== null) {
    if (fiber.tag === HostRoot) {
      captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
      return;
    } else if (fiber.tag === ClassComponent) {
      var ctor = fiber.type;
      var instance = fiber.stateNode;

      if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
        var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
        var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
        var root = enqueueUpdate(fiber, update, SyncLane);
        var eventTime = requestEventTime();

        if (root !== null) {
          markRootUpdated(root, SyncLane, eventTime);
          ensureRootIsScheduled(root, eventTime);
        }

        return;
      }
    }

    fiber = fiber.return;
  }

  {
    // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
    // will fire for errors that are thrown by destroy functions inside deleted
    // trees. What it should instead do is propagate the error to the parent of
    // the deleted tree. In the meantime, do not add this warning to the
    // allowlist; this is only for our internal use.
    error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1);
  }
}
function pingSuspendedRoot(root, wakeable, pingedLanes) {
  var pingCache = root.pingCache;

  if (pingCache !== null) {
    // The wakeable resolved, so we no longer need to memoize, because it will
    // never be thrown again.
    pingCache.delete(wakeable);
  }

  var eventTime = requestEventTime();
  markRootPinged(root, pingedLanes);
  warnIfSuspenseResolutionNotWrappedWithActDEV(root);

  if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
    // Received a ping at the same priority level at which we're currently
    // rendering. We might want to restart this render. This should mirror
    // the logic of whether or not a root suspends once it completes.
    // TODO: If we're rendering sync either due to Sync, Batched or expired,
    // we should probably never restart.
    // If we're suspended with delay, or if it's a retry, we'll always suspend
    // so we can always restart.
    if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
      // Restart from the root.
      prepareFreshStack(root, NoLanes);
    } else {
      // Even though we can't restart right now, we might get an
      // opportunity later. So we mark this render as having a ping.
      workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
    }
  }

  ensureRootIsScheduled(root, eventTime);
}

function retryTimedOutBoundary(boundaryFiber, retryLane) {
  // The boundary fiber (a Suspense component or SuspenseList component)
  // previously was rendered in its fallback state. One of the promises that
  // suspended it has resolved, which means at least part of the tree was
  // likely unblocked. Try rendering again, at a new lanes.
  if (retryLane === NoLane) {
    // TODO: Assign this to `suspenseState.retryLane`? to avoid
    // unnecessary entanglement?
    retryLane = requestRetryLane(boundaryFiber);
  } // TODO: Special case idle priority?


  var eventTime = requestEventTime();
  var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);

  if (root !== null) {
    markRootUpdated(root, retryLane, eventTime);
    ensureRootIsScheduled(root, eventTime);
  }
}

function retryDehydratedSuspenseBoundary(boundaryFiber) {
  var suspenseState = boundaryFiber.memoizedState;
  var retryLane = NoLane;

  if (suspenseState !== null) {
    retryLane = suspenseState.retryLane;
  }

  retryTimedOutBoundary(boundaryFiber, retryLane);
}
function resolveRetryWakeable(boundaryFiber, wakeable) {
  var retryLane = NoLane; // Default

  var retryCache;

  switch (boundaryFiber.tag) {
    case SuspenseComponent:
      retryCache = boundaryFiber.stateNode;
      var suspenseState = boundaryFiber.memoizedState;

      if (suspenseState !== null) {
        retryLane = suspenseState.retryLane;
      }

      break;

    case SuspenseListComponent:
      retryCache = boundaryFiber.stateNode;
      break;

    default:
      throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.');
  }

  if (retryCache !== null) {
    // The wakeable resolved, so we no longer need to memoize, because it will
    // never be thrown again.
    retryCache.delete(wakeable);
  }

  retryTimedOutBoundary(boundaryFiber, retryLane);
} // Computes the next Just Noticeable Difference (JND) boundary.
// The theory is that a person can't tell the difference between small differences in time.
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
// difference in the experience. However, waiting for longer might mean that we can avoid
// showing an intermediate loading state. The longer we have already waited, the harder it
// is to tell small differences in time. Therefore, the longer we've already waited,
// the longer we can wait additionally. At some point we have to give up though.
// We pick a train model where the next boundary commits at a consistent schedule.
// These particular numbers are vague estimates. We expect to adjust them based on research.

function jnd(timeElapsed) {
  return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
}

function checkForNestedUpdates() {
  if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
    nestedUpdateCount = 0;
    rootWithNestedUpdates = null;
    throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.');
  }

  {
    if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
      nestedPassiveUpdateCount = 0;
      rootWithPassiveNestedUpdates = null;

      error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
    }
  }
}

function flushRenderPhaseStrictModeWarningsInDEV() {
  {
    ReactStrictModeWarnings.flushLegacyContextWarning();

    {
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
    }
  }
}

function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
  {
    // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
    // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
    // Maybe not a big deal since this is DEV only behavior.
    setCurrentFiber(fiber);
    invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);

    if (hasPassiveEffects) {
      invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
    }

    invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);

    if (hasPassiveEffects) {
      invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
    }

    resetCurrentFiber();
  }
}

function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
  {
    // We don't need to re-check StrictEffectsMode here.
    // This function is only called if that check has already passed.
    var current = firstChild;
    var subtreeRoot = null;

    while (current !== null) {
      var primarySubtreeFlag = current.subtreeFlags & fiberFlags;

      if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) {
        current = current.child;
      } else {
        if ((current.flags & fiberFlags) !== NoFlags) {
          invokeEffectFn(current);
        }

        if (current.sibling !== null) {
          current = current.sibling;
        } else {
          current = subtreeRoot = current.return;
        }
      }
    }
  }
}

var didWarnStateUpdateForNotYetMountedComponent = null;
function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
  {
    if ((executionContext & RenderContext) !== NoContext) {
      // We let the other warning about render phase updates deal with this one.
      return;
    }

    if (!(fiber.mode & ConcurrentMode)) {
      return;
    }

    var tag = fiber.tag;

    if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
      // Only warn for user-defined components, not internal ones like Suspense.
      return;
    } // We show the whole stack but dedupe on the top component's name because
    // the problematic code almost always lies inside that component.


    var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';

    if (didWarnStateUpdateForNotYetMountedComponent !== null) {
      if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
        return;
      }

      didWarnStateUpdateForNotYetMountedComponent.add(componentName);
    } else {
      didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
    }

    var previousFiber = current;

    try {
      setCurrentFiber(fiber);

      error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.');
    } finally {
      if (previousFiber) {
        setCurrentFiber(fiber);
      } else {
        resetCurrentFiber();
      }
    }
  }
}
var beginWork$1;

{
  var dummyFiber = null;

  beginWork$1 = function (current, unitOfWork, lanes) {
    // If a component throws an error, we replay it again in a synchronously
    // dispatched event, so that the debugger will treat it as an uncaught
    // error See ReactErrorUtils for more information.
    // Before entering the begin phase, copy the work-in-progress onto a dummy
    // fiber. If beginWork throws, we'll use this to reset the state.
    var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);

    try {
      return beginWork(current, unitOfWork, lanes);
    } catch (originalError) {
      if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
        // Don't replay promises.
        // Don't replay errors if we are hydrating and have already suspended or handled an error
        throw originalError;
      } // Keep this code in sync with handleError; any changes here must have
      // corresponding changes there.


      resetContextDependencies();
      resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
      // same fiber again.
      // Unwind the failed stack frame

      unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber.

      assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);

      if ( unitOfWork.mode & ProfileMode) {
        // Reset the profiler timer.
        startProfilerTimer(unitOfWork);
      } // Run beginWork again.


      invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);

      if (hasCaughtError()) {
        var replayError = clearCaughtError();

        if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) {
          // If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
          originalError._suppressLogging = true;
        }
      } // We always throw the original error in case the second render pass is not idempotent.
      // This can happen if a memoized function or CommonJS module doesn't throw after first invocation.


      throw originalError;
    }
  };
}

var didWarnAboutUpdateInRender = false;
var didWarnAboutUpdateInRenderForAnotherComponent;

{
  didWarnAboutUpdateInRenderForAnotherComponent = new Set();
}

function warnAboutRenderPhaseUpdatesInDEV(fiber) {
  {
    if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
      switch (fiber.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
          {
            var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.

            var dedupeKey = renderingComponentName;

            if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
              didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
              var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown';

              error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
            }

            break;
          }

        case ClassComponent:
          {
            if (!didWarnAboutUpdateInRender) {
              error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');

              didWarnAboutUpdateInRender = true;
            }

            break;
          }
      }
    }
  }
}

function restorePendingUpdaters(root, lanes) {
  {
    if (isDevToolsPresent) {
      var memoizedUpdaters = root.memoizedUpdaters;
      memoizedUpdaters.forEach(function (schedulingFiber) {
        addFiberToLanesMap(root, schedulingFiber, lanes);
      }); // This function intentionally does not clear memoized updaters.
      // Those may still be relevant to the current commit
      // and a future one (e.g. Suspense).
    }
  }
}
var fakeActCallbackNode = {};

function scheduleCallback$1(priorityLevel, callback) {
  {
    // If we're currently inside an `act` scope, bypass Scheduler and push to
    // the `act` queue instead.
    var actQueue = ReactCurrentActQueue$1.current;

    if (actQueue !== null) {
      actQueue.push(callback);
      return fakeActCallbackNode;
    } else {
      return scheduleCallback(priorityLevel, callback);
    }
  }
}

function cancelCallback$1(callbackNode) {
  if ( callbackNode === fakeActCallbackNode) {
    return;
  } // In production, always call Scheduler. This function will be stripped out.


  return cancelCallback(callbackNode);
}

function shouldForceFlushFallbacksInDEV() {
  // Never force flush in production. This function should get stripped out.
  return  ReactCurrentActQueue$1.current !== null;
}

function warnIfUpdatesNotWrappedWithActDEV(fiber) {
  {
    if (fiber.mode & ConcurrentMode) {
      if (!isConcurrentActEnvironment()) {
        // Not in an act environment. No need to warn.
        return;
      }
    } else {
      // Legacy mode has additional cases where we suppress a warning.
      if (!isLegacyActEnvironment()) {
        // Not in an act environment. No need to warn.
        return;
      }

      if (executionContext !== NoContext) {
        // Legacy mode doesn't warn if the update is batched, i.e.
        // batchedUpdates or flushSync.
        return;
      }

      if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
        // For backwards compatibility with pre-hooks code, legacy mode only
        // warns for updates that originate from a hook.
        return;
      }
    }

    if (ReactCurrentActQueue$1.current === null) {
      var previousFiber = current;

      try {
        setCurrentFiber(fiber);

        error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber));
      } finally {
        if (previousFiber) {
          setCurrentFiber(fiber);
        } else {
          resetCurrentFiber();
        }
      }
    }
  }
}

function warnIfSuspenseResolutionNotWrappedWithActDEV(root) {
  {
    if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
      error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + '  /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act');
    }
  }
}

function setIsRunningInsertionEffect(isRunning) {
  {
    isRunningInsertionEffect = isRunning;
  }
}

/* eslint-disable react-internal/prod-error-codes */
var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.

var failedBoundaries = null;
var setRefreshHandler = function (handler) {
  {
    resolveFamily = handler;
  }
};
function resolveFunctionForHotReloading(type) {
  {
    if (resolveFamily === null) {
      // Hot reloading is disabled.
      return type;
    }

    var family = resolveFamily(type);

    if (family === undefined) {
      return type;
    } // Use the latest known implementation.


    return family.current;
  }
}
function resolveClassForHotReloading(type) {
  // No implementation differences.
  return resolveFunctionForHotReloading(type);
}
function resolveForwardRefForHotReloading(type) {
  {
    if (resolveFamily === null) {
      // Hot reloading is disabled.
      return type;
    }

    var family = resolveFamily(type);

    if (family === undefined) {
      // Check if we're dealing with a real forwardRef. Don't want to crash early.
      if (type !== null && type !== undefined && typeof type.render === 'function') {
        // ForwardRef is special because its resolved .type is an object,
        // but it's possible that we only have its inner render function in the map.
        // If that inner render function is different, we'll build a new forwardRef type.
        var currentRender = resolveFunctionForHotReloading(type.render);

        if (type.render !== currentRender) {
          var syntheticType = {
            $$typeof: REACT_FORWARD_REF_TYPE,
            render: currentRender
          };

          if (type.displayName !== undefined) {
            syntheticType.displayName = type.displayName;
          }

          return syntheticType;
        }
      }

      return type;
    } // Use the latest known implementation.


    return family.current;
  }
}
function isCompatibleFamilyForHotReloading(fiber, element) {
  {
    if (resolveFamily === null) {
      // Hot reloading is disabled.
      return false;
    }

    var prevType = fiber.elementType;
    var nextType = element.type; // If we got here, we know types aren't === equal.

    var needsCompareFamilies = false;
    var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;

    switch (fiber.tag) {
      case ClassComponent:
        {
          if (typeof nextType === 'function') {
            needsCompareFamilies = true;
          }

          break;
        }

      case FunctionComponent:
        {
          if (typeof nextType === 'function') {
            needsCompareFamilies = true;
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
            // We don't know the inner type yet.
            // We're going to assume that the lazy inner type is stable,
            // and so it is sufficient to avoid reconciling it away.
            // We're not going to unwrap or actually use the new lazy type.
            needsCompareFamilies = true;
          }

          break;
        }

      case ForwardRef:
        {
          if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
            needsCompareFamilies = true;
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
            needsCompareFamilies = true;
          }

          break;
        }

      case MemoComponent:
      case SimpleMemoComponent:
        {
          if ($$typeofNextType === REACT_MEMO_TYPE) {
            // TODO: if it was but can no longer be simple,
            // we shouldn't set this.
            needsCompareFamilies = true;
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
            needsCompareFamilies = true;
          }

          break;
        }

      default:
        return false;
    } // Check if both types have a family and it's the same one.


    if (needsCompareFamilies) {
      // Note: memo() and forwardRef() we'll compare outer rather than inner type.
      // This means both of them need to be registered to preserve state.
      // If we unwrapped and compared the inner types for wrappers instead,
      // then we would risk falsely saying two separate memo(Foo)
      // calls are equivalent because they wrap the same Foo function.
      var prevFamily = resolveFamily(prevType);

      if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
        return true;
      }
    }

    return false;
  }
}
function markFailedErrorBoundaryForHotReloading(fiber) {
  {
    if (resolveFamily === null) {
      // Hot reloading is disabled.
      return;
    }

    if (typeof WeakSet !== 'function') {
      return;
    }

    if (failedBoundaries === null) {
      failedBoundaries = new WeakSet();
    }

    failedBoundaries.add(fiber);
  }
}
var scheduleRefresh = function (root, update) {
  {
    if (resolveFamily === null) {
      // Hot reloading is disabled.
      return;
    }

    var staleFamilies = update.staleFamilies,
        updatedFamilies = update.updatedFamilies;
    flushPassiveEffects();
    flushSync(function () {
      scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
    });
  }
};
var scheduleRoot = function (root, element) {
  {
    if (root.context !== emptyContextObject) {
      // Super edge case: root has a legacy _renderSubtree context
      // but we don't know the parentComponent so we can't pass it.
      // Just ignore. We'll delete this with _renderSubtree code path later.
      return;
    }

    flushPassiveEffects();
    flushSync(function () {
      updateContainer(element, root, null, null);
    });
  }
};

function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
  {
    var alternate = fiber.alternate,
        child = fiber.child,
        sibling = fiber.sibling,
        tag = fiber.tag,
        type = fiber.type;
    var candidateType = null;

    switch (tag) {
      case FunctionComponent:
      case SimpleMemoComponent:
      case ClassComponent:
        candidateType = type;
        break;

      case ForwardRef:
        candidateType = type.render;
        break;
    }

    if (resolveFamily === null) {
      throw new Error('Expected resolveFamily to be set during hot reload.');
    }

    var needsRender = false;
    var needsRemount = false;

    if (candidateType !== null) {
      var family = resolveFamily(candidateType);

      if (family !== undefined) {
        if (staleFamilies.has(family)) {
          needsRemount = true;
        } else if (updatedFamilies.has(family)) {
          if (tag === ClassComponent) {
            needsRemount = true;
          } else {
            needsRender = true;
          }
        }
      }
    }

    if (failedBoundaries !== null) {
      if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
        needsRemount = true;
      }
    }

    if (needsRemount) {
      fiber._debugNeedsRemount = true;
    }

    if (needsRemount || needsRender) {
      var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (_root !== null) {
        scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
      }
    }

    if (child !== null && !needsRemount) {
      scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
    }

    if (sibling !== null) {
      scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
    }
  }
}

var findHostInstancesForRefresh = function (root, families) {
  {
    var hostInstances = new Set();
    var types = new Set(families.map(function (family) {
      return family.current;
    }));
    findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
    return hostInstances;
  }
};

function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
  {
    var child = fiber.child,
        sibling = fiber.sibling,
        tag = fiber.tag,
        type = fiber.type;
    var candidateType = null;

    switch (tag) {
      case FunctionComponent:
      case SimpleMemoComponent:
      case ClassComponent:
        candidateType = type;
        break;

      case ForwardRef:
        candidateType = type.render;
        break;
    }

    var didMatch = false;

    if (candidateType !== null) {
      if (types.has(candidateType)) {
        didMatch = true;
      }
    }

    if (didMatch) {
      // We have a match. This only drills down to the closest host components.
      // There's no need to search deeper because for the purpose of giving
      // visual feedback, "flashing" outermost parent rectangles is sufficient.
      findHostInstancesForFiberShallowly(fiber, hostInstances);
    } else {
      // If there's no match, maybe there will be one further down in the child tree.
      if (child !== null) {
        findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
      }
    }

    if (sibling !== null) {
      findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
    }
  }
}

function findHostInstancesForFiberShallowly(fiber, hostInstances) {
  {
    var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);

    if (foundHostInstances) {
      return;
    } // If we didn't find any host children, fallback to closest host parent.


    var node = fiber;

    while (true) {
      switch (node.tag) {
        case HostComponent:
          hostInstances.add(node.stateNode);
          return;

        case HostPortal:
          hostInstances.add(node.stateNode.containerInfo);
          return;

        case HostRoot:
          hostInstances.add(node.stateNode.containerInfo);
          return;
      }

      if (node.return === null) {
        throw new Error('Expected to reach root first.');
      }

      node = node.return;
    }
  }
}

function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
  {
    var node = fiber;
    var foundHostInstances = false;

    while (true) {
      if (node.tag === HostComponent) {
        // We got a match.
        foundHostInstances = true;
        hostInstances.add(node.stateNode); // There may still be more, so keep searching.
      } else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }

      if (node === fiber) {
        return foundHostInstances;
      }

      while (node.sibling === null) {
        if (node.return === null || node.return === fiber) {
          return foundHostInstances;
        }

        node = node.return;
      }

      node.sibling.return = node.return;
      node = node.sibling;
    }
  }

  return false;
}

var hasBadMapPolyfill;

{
  hasBadMapPolyfill = false;

  try {
    var nonExtensibleObject = Object.preventExtensions({});
    /* eslint-disable no-new */

    new Map([[nonExtensibleObject, null]]);
    new Set([nonExtensibleObject]);
    /* eslint-enable no-new */
  } catch (e) {
    // TODO: Consider warning about bad polyfills
    hasBadMapPolyfill = true;
  }
}

function FiberNode(tag, pendingProps, key, mode) {
  // Instance
  this.tag = tag;
  this.key = key;
  this.elementType = null;
  this.type = null;
  this.stateNode = null; // Fiber

  this.return = null;
  this.child = null;
  this.sibling = null;
  this.index = 0;
  this.ref = null;
  this.pendingProps = pendingProps;
  this.memoizedProps = null;
  this.updateQueue = null;
  this.memoizedState = null;
  this.dependencies = null;
  this.mode = mode; // Effects

  this.flags = NoFlags;
  this.subtreeFlags = NoFlags;
  this.deletions = null;
  this.lanes = NoLanes;
  this.childLanes = NoLanes;
  this.alternate = null;

  {
    // Note: The following is done to avoid a v8 performance cliff.
    //
    // Initializing the fields below to smis and later updating them with
    // double values will cause Fibers to end up having separate shapes.
    // This behavior/bug has something to do with Object.preventExtension().
    // Fortunately this only impacts DEV builds.
    // Unfortunately it makes React unusably slow for some applications.
    // To work around this, initialize the fields below with doubles.
    //
    // Learn more about this here:
    // https://github.com/facebook/react/issues/14365
    // https://bugs.chromium.org/p/v8/issues/detail?id=8538
    this.actualDuration = Number.NaN;
    this.actualStartTime = Number.NaN;
    this.selfBaseDuration = Number.NaN;
    this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
    // This won't trigger the performance cliff mentioned above,
    // and it simplifies other profiler code (including DevTools).

    this.actualDuration = 0;
    this.actualStartTime = -1;
    this.selfBaseDuration = 0;
    this.treeBaseDuration = 0;
  }

  {
    // This isn't directly used but is handy for debugging internals:
    this._debugSource = null;
    this._debugOwner = null;
    this._debugNeedsRemount = false;
    this._debugHookTypes = null;

    if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
      Object.preventExtensions(this);
    }
  }
} // This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. Instance methods can be
//    more difficult to predict when they get optimized and they are almost
//    never inlined properly in static compilers.
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
//    always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
//    to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
//    is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
//    compatible.


var createFiber = function (tag, pendingProps, key, mode) {
  // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
  return new FiberNode(tag, pendingProps, key, mode);
};

function shouldConstruct$1(Component) {
  var prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

function isSimpleFunctionComponent(type) {
  return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
}
function resolveLazyComponentTag(Component) {
  if (typeof Component === 'function') {
    return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
  } else if (Component !== undefined && Component !== null) {
    var $$typeof = Component.$$typeof;

    if ($$typeof === REACT_FORWARD_REF_TYPE) {
      return ForwardRef;
    }

    if ($$typeof === REACT_MEMO_TYPE) {
      return MemoComponent;
    }
  }

  return IndeterminateComponent;
} // This is used to create an alternate fiber to do work on.

function createWorkInProgress(current, pendingProps) {
  var workInProgress = current.alternate;

  if (workInProgress === null) {
    // We use a double buffering pooling technique because we know that we'll
    // only ever need at most two versions of a tree. We pool the "other" unused
    // node that we're free to reuse. This is lazily created to avoid allocating
    // extra objects for things that are never updated. It also allow us to
    // reclaim the extra memory if needed.
    workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
    workInProgress.elementType = current.elementType;
    workInProgress.type = current.type;
    workInProgress.stateNode = current.stateNode;

    {
      // DEV-only fields
      workInProgress._debugSource = current._debugSource;
      workInProgress._debugOwner = current._debugOwner;
      workInProgress._debugHookTypes = current._debugHookTypes;
    }

    workInProgress.alternate = current;
    current.alternate = workInProgress;
  } else {
    workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.

    workInProgress.type = current.type; // We already have an alternate.
    // Reset the effect tag.

    workInProgress.flags = NoFlags; // The effects are no longer valid.

    workInProgress.subtreeFlags = NoFlags;
    workInProgress.deletions = null;

    {
      // We intentionally reset, rather than copy, actualDuration & actualStartTime.
      // This prevents time from endlessly accumulating in new commits.
      // This has the downside of resetting values for different priority renders,
      // But works for yielding (the common case) and should support resuming.
      workInProgress.actualDuration = 0;
      workInProgress.actualStartTime = -1;
    }
  } // Reset all effects except static ones.
  // Static effects are not specific to a render.


  workInProgress.flags = current.flags & StaticMask;
  workInProgress.childLanes = current.childLanes;
  workInProgress.lanes = current.lanes;
  workInProgress.child = current.child;
  workInProgress.memoizedProps = current.memoizedProps;
  workInProgress.memoizedState = current.memoizedState;
  workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
  // it cannot be shared with the current fiber.

  var currentDependencies = current.dependencies;
  workInProgress.dependencies = currentDependencies === null ? null : {
    lanes: currentDependencies.lanes,
    firstContext: currentDependencies.firstContext
  }; // These will be overridden during the parent's reconciliation

  workInProgress.sibling = current.sibling;
  workInProgress.index = current.index;
  workInProgress.ref = current.ref;

  {
    workInProgress.selfBaseDuration = current.selfBaseDuration;
    workInProgress.treeBaseDuration = current.treeBaseDuration;
  }

  {
    workInProgress._debugNeedsRemount = current._debugNeedsRemount;

    switch (workInProgress.tag) {
      case IndeterminateComponent:
      case FunctionComponent:
      case SimpleMemoComponent:
        workInProgress.type = resolveFunctionForHotReloading(current.type);
        break;

      case ClassComponent:
        workInProgress.type = resolveClassForHotReloading(current.type);
        break;

      case ForwardRef:
        workInProgress.type = resolveForwardRefForHotReloading(current.type);
        break;
    }
  }

  return workInProgress;
} // Used to reuse a Fiber for a second pass.

function resetWorkInProgress(workInProgress, renderLanes) {
  // This resets the Fiber to what createFiber or createWorkInProgress would
  // have set the values to before during the first pass. Ideally this wouldn't
  // be necessary but unfortunately many code paths reads from the workInProgress
  // when they should be reading from current and writing to workInProgress.
  // We assume pendingProps, index, key, ref, return are still untouched to
  // avoid doing another reconciliation.
  // Reset the effect flags but keep any Placement tags, since that's something
  // that child fiber is setting, not the reconciliation.
  workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid.

  var current = workInProgress.alternate;

  if (current === null) {
    // Reset to createFiber's initial values.
    workInProgress.childLanes = NoLanes;
    workInProgress.lanes = renderLanes;
    workInProgress.child = null;
    workInProgress.subtreeFlags = NoFlags;
    workInProgress.memoizedProps = null;
    workInProgress.memoizedState = null;
    workInProgress.updateQueue = null;
    workInProgress.dependencies = null;
    workInProgress.stateNode = null;

    {
      // Note: We don't reset the actualTime counts. It's useful to accumulate
      // actual time across multiple render passes.
      workInProgress.selfBaseDuration = 0;
      workInProgress.treeBaseDuration = 0;
    }
  } else {
    // Reset to the cloned values that createWorkInProgress would've.
    workInProgress.childLanes = current.childLanes;
    workInProgress.lanes = current.lanes;
    workInProgress.child = current.child;
    workInProgress.subtreeFlags = NoFlags;
    workInProgress.deletions = null;
    workInProgress.memoizedProps = current.memoizedProps;
    workInProgress.memoizedState = current.memoizedState;
    workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.

    workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
    // it cannot be shared with the current fiber.

    var currentDependencies = current.dependencies;
    workInProgress.dependencies = currentDependencies === null ? null : {
      lanes: currentDependencies.lanes,
      firstContext: currentDependencies.firstContext
    };

    {
      // Note: We don't reset the actualTime counts. It's useful to accumulate
      // actual time across multiple render passes.
      workInProgress.selfBaseDuration = current.selfBaseDuration;
      workInProgress.treeBaseDuration = current.treeBaseDuration;
    }
  }

  return workInProgress;
}
function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
  var mode;

  if (tag === ConcurrentRoot) {
    mode = ConcurrentMode;

    if (isStrictMode === true) {
      mode |= StrictLegacyMode;

      {
        mode |= StrictEffectsMode;
      }
    }
  } else {
    mode = NoMode;
  }

  if ( isDevToolsPresent) {
    // Always collect profile timings when DevTools are present.
    // This enables DevTools to start capturing timing at any pointâ€“
    // Without some nodes in the tree having empty base times.
    mode |= ProfileMode;
  }

  return createFiber(HostRoot, null, null, mode);
}
function createFiberFromTypeAndProps(type, // React$ElementType
key, pendingProps, owner, mode, lanes) {
  var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.

  var resolvedType = type;

  if (typeof type === 'function') {
    if (shouldConstruct$1(type)) {
      fiberTag = ClassComponent;

      {
        resolvedType = resolveClassForHotReloading(resolvedType);
      }
    } else {
      {
        resolvedType = resolveFunctionForHotReloading(resolvedType);
      }
    }
  } else if (typeof type === 'string') {
    fiberTag = HostComponent;
  } else {
    getTag: switch (type) {
      case REACT_FRAGMENT_TYPE:
        return createFiberFromFragment(pendingProps.children, mode, lanes, key);

      case REACT_STRICT_MODE_TYPE:
        fiberTag = Mode;
        mode |= StrictLegacyMode;

        if ( (mode & ConcurrentMode) !== NoMode) {
          // Strict effects should never run on legacy roots
          mode |= StrictEffectsMode;
        }

        break;

      case REACT_PROFILER_TYPE:
        return createFiberFromProfiler(pendingProps, mode, lanes, key);

      case REACT_SUSPENSE_TYPE:
        return createFiberFromSuspense(pendingProps, mode, lanes, key);

      case REACT_SUSPENSE_LIST_TYPE:
        return createFiberFromSuspenseList(pendingProps, mode, lanes, key);

      case REACT_OFFSCREEN_TYPE:
        return createFiberFromOffscreen(pendingProps, mode, lanes, key);

      case REACT_LEGACY_HIDDEN_TYPE:

      // eslint-disable-next-line no-fallthrough

      case REACT_SCOPE_TYPE:

      // eslint-disable-next-line no-fallthrough

      case REACT_CACHE_TYPE:

      // eslint-disable-next-line no-fallthrough

      case REACT_TRACING_MARKER_TYPE:

      // eslint-disable-next-line no-fallthrough

      case REACT_DEBUG_TRACING_MODE_TYPE:

      // eslint-disable-next-line no-fallthrough

      default:
        {
          if (typeof type === 'object' && type !== null) {
            switch (type.$$typeof) {
              case REACT_PROVIDER_TYPE:
                fiberTag = ContextProvider;
                break getTag;

              case REACT_CONTEXT_TYPE:
                // This is a consumer
                fiberTag = ContextConsumer;
                break getTag;

              case REACT_FORWARD_REF_TYPE:
                fiberTag = ForwardRef;

                {
                  resolvedType = resolveForwardRefForHotReloading(resolvedType);
                }

                break getTag;

              case REACT_MEMO_TYPE:
                fiberTag = MemoComponent;
                break getTag;

              case REACT_LAZY_TYPE:
                fiberTag = LazyComponent;
                resolvedType = null;
                break getTag;
            }
          }

          var info = '';

          {
            if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
              info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
            }

            var ownerName = owner ? getComponentNameFromFiber(owner) : null;

            if (ownerName) {
              info += '\n\nCheck the render method of `' + ownerName + '`.';
            }
          }

          throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
        }
    }
  }

  var fiber = createFiber(fiberTag, pendingProps, key, mode);
  fiber.elementType = type;
  fiber.type = resolvedType;
  fiber.lanes = lanes;

  {
    fiber._debugOwner = owner;
  }

  return fiber;
}
function createFiberFromElement(element, mode, lanes) {
  var owner = null;

  {
    owner = element._owner;
  }

  var type = element.type;
  var key = element.key;
  var pendingProps = element.props;
  var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);

  {
    fiber._debugSource = element._source;
    fiber._debugOwner = element._owner;
  }

  return fiber;
}
function createFiberFromFragment(elements, mode, lanes, key) {
  var fiber = createFiber(Fragment, elements, key, mode);
  fiber.lanes = lanes;
  return fiber;
}

function createFiberFromProfiler(pendingProps, mode, lanes, key) {
  {
    if (typeof pendingProps.id !== 'string') {
      error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
    }
  }

  var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
  fiber.elementType = REACT_PROFILER_TYPE;
  fiber.lanes = lanes;

  {
    fiber.stateNode = {
      effectDuration: 0,
      passiveEffectDuration: 0
    };
  }

  return fiber;
}

function createFiberFromSuspense(pendingProps, mode, lanes, key) {
  var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
  fiber.elementType = REACT_SUSPENSE_TYPE;
  fiber.lanes = lanes;
  return fiber;
}
function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
  var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
  fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
  fiber.lanes = lanes;
  return fiber;
}
function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
  var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
  fiber.elementType = REACT_OFFSCREEN_TYPE;
  fiber.lanes = lanes;
  var primaryChildInstance = {
    isHidden: false
  };
  fiber.stateNode = primaryChildInstance;
  return fiber;
}
function createFiberFromText(content, mode, lanes) {
  var fiber = createFiber(HostText, content, null, mode);
  fiber.lanes = lanes;
  return fiber;
}
function createFiberFromHostInstanceForDeletion() {
  var fiber = createFiber(HostComponent, null, null, NoMode);
  fiber.elementType = 'DELETED';
  return fiber;
}
function createFiberFromDehydratedFragment(dehydratedNode) {
  var fiber = createFiber(DehydratedFragment, null, null, NoMode);
  fiber.stateNode = dehydratedNode;
  return fiber;
}
function createFiberFromPortal(portal, mode, lanes) {
  var pendingProps = portal.children !== null ? portal.children : [];
  var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
  fiber.lanes = lanes;
  fiber.stateNode = {
    containerInfo: portal.containerInfo,
    pendingChildren: null,
    // Used by persistent updates
    implementation: portal.implementation
  };
  return fiber;
} // Used for stashing WIP properties to replay failed work in DEV.

function assignFiberPropertiesInDEV(target, source) {
  if (target === null) {
    // This Fiber's initial properties will always be overwritten.
    // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
    target = createFiber(IndeterminateComponent, null, null, NoMode);
  } // This is intentionally written as a list of all properties.
  // We tried to use Object.assign() instead but this is called in
  // the hottest path, and Object.assign() was too slow:
  // https://github.com/facebook/react/issues/12502
  // This code is DEV-only so size is not a concern.


  target.tag = source.tag;
  target.key = source.key;
  target.elementType = source.elementType;
  target.type = source.type;
  target.stateNode = source.stateNode;
  target.return = source.return;
  target.child = source.child;
  target.sibling = source.sibling;
  target.index = source.index;
  target.ref = source.ref;
  target.pendingProps = source.pendingProps;
  target.memoizedProps = source.memoizedProps;
  target.updateQueue = source.updateQueue;
  target.memoizedState = source.memoizedState;
  target.dependencies = source.dependencies;
  target.mode = source.mode;
  target.flags = source.flags;
  target.subtreeFlags = source.subtreeFlags;
  target.deletions = source.deletions;
  target.lanes = source.lanes;
  target.childLanes = source.childLanes;
  target.alternate = source.alternate;

  {
    target.actualDuration = source.actualDuration;
    target.actualStartTime = source.actualStartTime;
    target.selfBaseDuration = source.selfBaseDuration;
    target.treeBaseDuration = source.treeBaseDuration;
  }

  target._debugSource = source._debugSource;
  target._debugOwner = source._debugOwner;
  target._debugNeedsRemount = source._debugNeedsRemount;
  target._debugHookTypes = source._debugHookTypes;
  return target;
}

function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) {
  this.tag = tag;
  this.containerInfo = containerInfo;
  this.pendingChildren = null;
  this.current = null;
  this.pingCache = null;
  this.finishedWork = null;
  this.timeoutHandle = noTimeout;
  this.context = null;
  this.pendingContext = null;
  this.callbackNode = null;
  this.callbackPriority = NoLane;
  this.eventTimes = createLaneMap(NoLanes);
  this.expirationTimes = createLaneMap(NoTimestamp);
  this.pendingLanes = NoLanes;
  this.suspendedLanes = NoLanes;
  this.pingedLanes = NoLanes;
  this.expiredLanes = NoLanes;
  this.mutableReadLanes = NoLanes;
  this.finishedLanes = NoLanes;
  this.entangledLanes = NoLanes;
  this.entanglements = createLaneMap(NoLanes);
  this.identifierPrefix = identifierPrefix;
  this.onRecoverableError = onRecoverableError;

  {
    this.mutableSourceEagerHydrationData = null;
  }

  {
    this.effectDuration = 0;
    this.passiveEffectDuration = 0;
  }

  {
    this.memoizedUpdaters = new Set();
    var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];

    for (var _i = 0; _i < TotalLanes; _i++) {
      pendingUpdatersLaneMap.push(new Set());
    }
  }

  {
    switch (tag) {
      case ConcurrentRoot:
        this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
        break;

      case LegacyRoot:
        this._debugRootType = hydrate ? 'hydrate()' : 'render()';
        break;
    }
  }
}

function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the
// host config, but because they are passed in at runtime, we have to thread
// them through the root constructor. Perhaps we should put them all into a
// single type, like a DynamicHostConfig that is defined by the renderer.
identifierPrefix, onRecoverableError, transitionCallbacks) {
  var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError);
  // stateNode is any.


  var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
  root.current = uninitializedFiber;
  uninitializedFiber.stateNode = root;

  {
    var _initialState = {
      element: initialChildren,
      isDehydrated: hydrate,
      cache: null,
      // not enabled yet
      transitions: null,
      pendingSuspenseBoundaries: null
    };
    uninitializedFiber.memoizedState = _initialState;
  }

  initializeUpdateQueue(uninitializedFiber);
  return root;
}

var ReactVersion = '18.3.1';

function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
implementation) {
  var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

  {
    checkKeyStringCoercion(key);
  }

  return {
    // This tag allow us to uniquely identify this as a React Portal
    $$typeof: REACT_PORTAL_TYPE,
    key: key == null ? null : '' + key,
    children: children,
    containerInfo: containerInfo,
    implementation: implementation
  };
}

var didWarnAboutNestedUpdates;
var didWarnAboutFindNodeInStrictMode;

{
  didWarnAboutNestedUpdates = false;
  didWarnAboutFindNodeInStrictMode = {};
}

function getContextForSubtree(parentComponent) {
  if (!parentComponent) {
    return emptyContextObject;
  }

  var fiber = get(parentComponent);
  var parentContext = findCurrentUnmaskedContext(fiber);

  if (fiber.tag === ClassComponent) {
    var Component = fiber.type;

    if (isContextProvider(Component)) {
      return processChildContext(fiber, Component, parentContext);
    }
  }

  return parentContext;
}

function findHostInstanceWithWarning(component, methodName) {
  {
    var fiber = get(component);

    if (fiber === undefined) {
      if (typeof component.render === 'function') {
        throw new Error('Unable to find node on an unmounted component.');
      } else {
        var keys = Object.keys(component).join(',');
        throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
      }
    }

    var hostFiber = findCurrentHostFiber(fiber);

    if (hostFiber === null) {
      return null;
    }

    if (hostFiber.mode & StrictLegacyMode) {
      var componentName = getComponentNameFromFiber(fiber) || 'Component';

      if (!didWarnAboutFindNodeInStrictMode[componentName]) {
        didWarnAboutFindNodeInStrictMode[componentName] = true;
        var previousFiber = current;

        try {
          setCurrentFiber(hostFiber);

          if (fiber.mode & StrictLegacyMode) {
            error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
          } else {
            error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
          }
        } finally {
          // Ideally this should reset to previous but this shouldn't be called in
          // render and there's another warning for that anyway.
          if (previousFiber) {
            setCurrentFiber(previousFiber);
          } else {
            resetCurrentFiber();
          }
        }
      }
    }

    return hostFiber.stateNode;
  }
}

function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
  var hydrate = false;
  var initialChildren = null;
  return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
}
function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode.
callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
  var hydrate = true;
  var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor

  root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from
  // a regular update because the initial render must match was was rendered
  // on the server.
  // NOTE: This update intentionally doesn't have a payload. We're only using
  // the update to schedule work on the root fiber (and, for legacy roots, to
  // enqueue the callback if one is provided).

  var current = root.current;
  var eventTime = requestEventTime();
  var lane = requestUpdateLane(current);
  var update = createUpdate(eventTime, lane);
  update.callback = callback !== undefined && callback !== null ? callback : null;
  enqueueUpdate(current, update, lane);
  scheduleInitialHydrationOnRoot(root, lane, eventTime);
  return root;
}
function updateContainer(element, container, parentComponent, callback) {
  {
    onScheduleRoot(container, element);
  }

  var current$1 = container.current;
  var eventTime = requestEventTime();
  var lane = requestUpdateLane(current$1);

  {
    markRenderScheduled(lane);
  }

  var context = getContextForSubtree(parentComponent);

  if (container.context === null) {
    container.context = context;
  } else {
    container.pendingContext = context;
  }

  {
    if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
      didWarnAboutNestedUpdates = true;

      error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown');
    }
  }

  var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
  // being called "element".

  update.payload = {
    element: element
  };
  callback = callback === undefined ? null : callback;

  if (callback !== null) {
    {
      if (typeof callback !== 'function') {
        error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
      }
    }

    update.callback = callback;
  }

  var root = enqueueUpdate(current$1, update, lane);

  if (root !== null) {
    scheduleUpdateOnFiber(root, current$1, lane, eventTime);
    entangleTransitions(root, current$1, lane);
  }

  return lane;
}
function getPublicRootInstance(container) {
  var containerFiber = container.current;

  if (!containerFiber.child) {
    return null;
  }

  switch (containerFiber.child.tag) {
    case HostComponent:
      return getPublicInstance(containerFiber.child.stateNode);

    default:
      return containerFiber.child.stateNode;
  }
}
function attemptSynchronousHydration$1(fiber) {
  switch (fiber.tag) {
    case HostRoot:
      {
        var root = fiber.stateNode;

        if (isRootDehydrated(root)) {
          // Flush the first scheduled "update".
          var lanes = getHighestPriorityPendingLanes(root);
          flushRoot(root, lanes);
        }

        break;
      }

    case SuspenseComponent:
      {
        flushSync(function () {
          var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

          if (root !== null) {
            var eventTime = requestEventTime();
            scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime);
          }
        }); // If we're still blocked after this, we need to increase
        // the priority of any promises resolving within this
        // boundary so that they next attempt also has higher pri.

        var retryLane = SyncLane;
        markRetryLaneIfNotHydrated(fiber, retryLane);
        break;
      }
  }
}

function markRetryLaneImpl(fiber, retryLane) {
  var suspenseState = fiber.memoizedState;

  if (suspenseState !== null && suspenseState.dehydrated !== null) {
    suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
  }
} // Increases the priority of thenables when they resolve within this boundary.


function markRetryLaneIfNotHydrated(fiber, retryLane) {
  markRetryLaneImpl(fiber, retryLane);
  var alternate = fiber.alternate;

  if (alternate) {
    markRetryLaneImpl(alternate, retryLane);
  }
}
function attemptContinuousHydration$1(fiber) {
  if (fiber.tag !== SuspenseComponent) {
    // We ignore HostRoots here because we can't increase
    // their priority and they should not suspend on I/O,
    // since you have to wrap anything that might suspend in
    // Suspense.
    return;
  }

  var lane = SelectiveHydrationLane;
  var root = enqueueConcurrentRenderForLane(fiber, lane);

  if (root !== null) {
    var eventTime = requestEventTime();
    scheduleUpdateOnFiber(root, fiber, lane, eventTime);
  }

  markRetryLaneIfNotHydrated(fiber, lane);
}
function attemptHydrationAtCurrentPriority$1(fiber) {
  if (fiber.tag !== SuspenseComponent) {
    // We ignore HostRoots here because we can't increase
    // their priority other than synchronously flush it.
    return;
  }

  var lane = requestUpdateLane(fiber);
  var root = enqueueConcurrentRenderForLane(fiber, lane);

  if (root !== null) {
    var eventTime = requestEventTime();
    scheduleUpdateOnFiber(root, fiber, lane, eventTime);
  }

  markRetryLaneIfNotHydrated(fiber, lane);
}
function findHostInstanceWithNoPortals(fiber) {
  var hostFiber = findCurrentHostFiberWithNoPortals(fiber);

  if (hostFiber === null) {
    return null;
  }

  return hostFiber.stateNode;
}

var shouldErrorImpl = function (fiber) {
  return null;
};

function shouldError(fiber) {
  return shouldErrorImpl(fiber);
}

var shouldSuspendImpl = function (fiber) {
  return false;
};

function shouldSuspend(fiber) {
  return shouldSuspendImpl(fiber);
}
var overrideHookState = null;
var overrideHookStateDeletePath = null;
var overrideHookStateRenamePath = null;
var overrideProps = null;
var overridePropsDeletePath = null;
var overridePropsRenamePath = null;
var scheduleUpdate = null;
var setErrorHandler = null;
var setSuspenseHandler = null;

{
  var copyWithDeleteImpl = function (obj, path, index) {
    var key = path[index];
    var updated = isArray(obj) ? obj.slice() : assign({}, obj);

    if (index + 1 === path.length) {
      if (isArray(updated)) {
        updated.splice(key, 1);
      } else {
        delete updated[key];
      }

      return updated;
    } // $FlowFixMe number or string is fine here


    updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
    return updated;
  };

  var copyWithDelete = function (obj, path) {
    return copyWithDeleteImpl(obj, path, 0);
  };

  var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
    var oldKey = oldPath[index];
    var updated = isArray(obj) ? obj.slice() : assign({}, obj);

    if (index + 1 === oldPath.length) {
      var newKey = newPath[index]; // $FlowFixMe number or string is fine here

      updated[newKey] = updated[oldKey];

      if (isArray(updated)) {
        updated.splice(oldKey, 1);
      } else {
        delete updated[oldKey];
      }
    } else {
      // $FlowFixMe number or string is fine here
      updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
      obj[oldKey], oldPath, newPath, index + 1);
    }

    return updated;
  };

  var copyWithRename = function (obj, oldPath, newPath) {
    if (oldPath.length !== newPath.length) {
      warn('copyWithRename() expects paths of the same length');

      return;
    } else {
      for (var i = 0; i < newPath.length - 1; i++) {
        if (oldPath[i] !== newPath[i]) {
          warn('copyWithRename() expects paths to be the same except for the deepest key');

          return;
        }
      }
    }

    return copyWithRenameImpl(obj, oldPath, newPath, 0);
  };

  var copyWithSetImpl = function (obj, path, index, value) {
    if (index >= path.length) {
      return value;
    }

    var key = path[index];
    var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here

    updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
    return updated;
  };

  var copyWithSet = function (obj, path, value) {
    return copyWithSetImpl(obj, path, 0, value);
  };

  var findHook = function (fiber, id) {
    // For now, the "id" of stateful hooks is just the stateful hook index.
    // This may change in the future with e.g. nested hooks.
    var currentHook = fiber.memoizedState;

    while (currentHook !== null && id > 0) {
      currentHook = currentHook.next;
      id--;
    }

    return currentHook;
  }; // Support DevTools editable values for useState and useReducer.


  overrideHookState = function (fiber, id, path, value) {
    var hook = findHook(fiber, id);

    if (hook !== null) {
      var newState = copyWithSet(hook.memoizedState, path, value);
      hook.memoizedState = newState;
      hook.baseState = newState; // We aren't actually adding an update to the queue,
      // because there is no update we can add for useReducer hooks that won't trigger an error.
      // (There's no appropriate action type for DevTools overrides.)
      // As a result though, React will see the scheduled update as a noop and bailout.
      // Shallow cloning props works as a workaround for now to bypass the bailout check.

      fiber.memoizedProps = assign({}, fiber.memoizedProps);
      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    }
  };

  overrideHookStateDeletePath = function (fiber, id, path) {
    var hook = findHook(fiber, id);

    if (hook !== null) {
      var newState = copyWithDelete(hook.memoizedState, path);
      hook.memoizedState = newState;
      hook.baseState = newState; // We aren't actually adding an update to the queue,
      // because there is no update we can add for useReducer hooks that won't trigger an error.
      // (There's no appropriate action type for DevTools overrides.)
      // As a result though, React will see the scheduled update as a noop and bailout.
      // Shallow cloning props works as a workaround for now to bypass the bailout check.

      fiber.memoizedProps = assign({}, fiber.memoizedProps);
      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    }
  };

  overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
    var hook = findHook(fiber, id);

    if (hook !== null) {
      var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
      hook.memoizedState = newState;
      hook.baseState = newState; // We aren't actually adding an update to the queue,
      // because there is no update we can add for useReducer hooks that won't trigger an error.
      // (There's no appropriate action type for DevTools overrides.)
      // As a result though, React will see the scheduled update as a noop and bailout.
      // Shallow cloning props works as a workaround for now to bypass the bailout check.

      fiber.memoizedProps = assign({}, fiber.memoizedProps);
      var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

      if (root !== null) {
        scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
      }
    }
  }; // Support DevTools props for function components, forwardRef, memo, host components, etc.


  overrideProps = function (fiber, path, value) {
    fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);

    if (fiber.alternate) {
      fiber.alternate.pendingProps = fiber.pendingProps;
    }

    var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
    }
  };

  overridePropsDeletePath = function (fiber, path) {
    fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);

    if (fiber.alternate) {
      fiber.alternate.pendingProps = fiber.pendingProps;
    }

    var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
    }
  };

  overridePropsRenamePath = function (fiber, oldPath, newPath) {
    fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);

    if (fiber.alternate) {
      fiber.alternate.pendingProps = fiber.pendingProps;
    }

    var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
    }
  };

  scheduleUpdate = function (fiber) {
    var root = enqueueConcurrentRenderForLane(fiber, SyncLane);

    if (root !== null) {
      scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
    }
  };

  setErrorHandler = function (newShouldErrorImpl) {
    shouldErrorImpl = newShouldErrorImpl;
  };

  setSuspenseHandler = function (newShouldSuspendImpl) {
    shouldSuspendImpl = newShouldSuspendImpl;
  };
}

function findHostInstanceByFiber(fiber) {
  var hostFiber = findCurrentHostFiber(fiber);

  if (hostFiber === null) {
    return null;
  }

  return hostFiber.stateNode;
}

function emptyFindFiberByHostInstance(instance) {
  return null;
}

function getCurrentFiberForDevTools() {
  return current;
}

function injectIntoDevTools(devToolsConfig) {
  var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  return injectInternals({
    bundleType: devToolsConfig.bundleType,
    version: devToolsConfig.version,
    rendererPackageName: devToolsConfig.rendererPackageName,
    rendererConfig: devToolsConfig.rendererConfig,
    overrideHookState: overrideHookState,
    overrideHookStateDeletePath: overrideHookStateDeletePath,
    overrideHookStateRenamePath: overrideHookStateRenamePath,
    overrideProps: overrideProps,
    overridePropsDeletePath: overridePropsDeletePath,
    overridePropsRenamePath: overridePropsRenamePath,
    setErrorHandler: setErrorHandler,
    setSuspenseHandler: setSuspenseHandler,
    scheduleUpdate: scheduleUpdate,
    currentDispatcherRef: ReactCurrentDispatcher,
    findHostInstanceByFiber: findHostInstanceByFiber,
    findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
    // React Refresh
    findHostInstancesForRefresh:  findHostInstancesForRefresh ,
    scheduleRefresh:  scheduleRefresh ,
    scheduleRoot:  scheduleRoot ,
    setRefreshHandler:  setRefreshHandler ,
    // Enables DevTools to append owner stacks to error messages in DEV mode.
    getCurrentFiber:  getCurrentFiberForDevTools ,
    // Enables DevTools to detect reconciler version rather than renderer version
    // which may not match for third party renderers.
    reconcilerVersion: ReactVersion
  });
}

/* global reportError */

var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError : function (error) {
  // In older browsers and test environments, fallback to console.error.
  // eslint-disable-next-line react-internal/no-production-logging
  console['error'](error);
};

function ReactDOMRoot(internalRoot) {
  this._internalRoot = internalRoot;
}

ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) {
  var root = this._internalRoot;

  if (root === null) {
    throw new Error('Cannot update an unmounted root.');
  }

  {
    if (typeof arguments[1] === 'function') {
      error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
    } else if (isValidContainer(arguments[1])) {
      error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root.");
    } else if (typeof arguments[1] !== 'undefined') {
      error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.');
    }

    var container = root.containerInfo;

    if (container.nodeType !== COMMENT_NODE) {
      var hostInstance = findHostInstanceWithNoPortals(root.current);

      if (hostInstance) {
        if (hostInstance.parentNode !== container) {
          error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
        }
      }
    }
  }

  updateContainer(children, root, null, null);
};

ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () {
  {
    if (typeof arguments[0] === 'function') {
      error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
    }
  }

  var root = this._internalRoot;

  if (root !== null) {
    this._internalRoot = null;
    var container = root.containerInfo;

    {
      if (isAlreadyRendering()) {
        error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.');
      }
    }

    flushSync(function () {
      updateContainer(null, root, null, null);
    });
    unmarkContainerAsRoot(container);
  }
};

function createRoot(container, options) {
  if (!isValidContainer(container)) {
    throw new Error('createRoot(...): Target container is not a DOM element.');
  }

  warnIfReactDOMContainerInDEV(container);
  var isStrictMode = false;
  var concurrentUpdatesByDefaultOverride = false;
  var identifierPrefix = '';
  var onRecoverableError = defaultOnRecoverableError;
  var transitionCallbacks = null;

  if (options !== null && options !== undefined) {
    {
      if (options.hydrate) {
        warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.');
      } else {
        if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) {
          error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + '  let root = createRoot(domContainer);\n' + '  root.render(<App />);');
        }
      }
    }

    if (options.unstable_strictMode === true) {
      isStrictMode = true;
    }

    if (options.identifierPrefix !== undefined) {
      identifierPrefix = options.identifierPrefix;
    }

    if (options.onRecoverableError !== undefined) {
      onRecoverableError = options.onRecoverableError;
    }

    if (options.transitionCallbacks !== undefined) {
      transitionCallbacks = options.transitionCallbacks;
    }
  }

  var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
  markContainerAsRoot(root.current, container);
  var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
  listenToAllSupportedEvents(rootContainerElement);
  return new ReactDOMRoot(root);
}

function ReactDOMHydrationRoot(internalRoot) {
  this._internalRoot = internalRoot;
}

function scheduleHydration(target) {
  if (target) {
    queueExplicitHydrationTarget(target);
  }
}

ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
function hydrateRoot(container, initialChildren, options) {
  if (!isValidContainer(container)) {
    throw new Error('hydrateRoot(...): Target container is not a DOM element.');
  }

  warnIfReactDOMContainerInDEV(container);

  {
    if (initialChildren === undefined) {
      error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)');
    }
  } // For now we reuse the whole bag of options since they contain
  // the hydration callbacks.


  var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option

  var mutableSources = options != null && options.hydratedSources || null;
  var isStrictMode = false;
  var concurrentUpdatesByDefaultOverride = false;
  var identifierPrefix = '';
  var onRecoverableError = defaultOnRecoverableError;

  if (options !== null && options !== undefined) {
    if (options.unstable_strictMode === true) {
      isStrictMode = true;
    }

    if (options.identifierPrefix !== undefined) {
      identifierPrefix = options.identifierPrefix;
    }

    if (options.onRecoverableError !== undefined) {
      onRecoverableError = options.onRecoverableError;
    }
  }

  var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
  markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway.

  listenToAllSupportedEvents(container);

  if (mutableSources) {
    for (var i = 0; i < mutableSources.length; i++) {
      var mutableSource = mutableSources[i];
      registerMutableSourceForHydration(root, mutableSource);
    }
  }

  return new ReactDOMHydrationRoot(root);
}
function isValidContainer(node) {
  return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers  ));
} // TODO: Remove this function which also includes comment nodes.
// We only use it in places that are currently more relaxed.

function isValidContainerLegacy(node) {
  return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
}

function warnIfReactDOMContainerInDEV(container) {
  {
    if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
      error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.');
    }

    if (isContainerMarkedAsRoot(container)) {
      if (container._reactRootContainer) {
        error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.');
      } else {
        error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.');
      }
    }
  }
}

var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
var topLevelUpdateWarnings;

{
  topLevelUpdateWarnings = function (container) {
    if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
      var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);

      if (hostInstance) {
        if (hostInstance.parentNode !== container) {
          error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
        }
      }
    }

    var isRootRenderedBySomeReact = !!container._reactRootContainer;
    var rootEl = getReactRootElementInContainer(container);
    var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));

    if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
      error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
    }

    if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
      error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
    }
  };
}

function getReactRootElementInContainer(container) {
  if (!container) {
    return null;
  }

  if (container.nodeType === DOCUMENT_NODE) {
    return container.documentElement;
  } else {
    return container.firstChild;
  }
}

function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the
  // legacy API.
}

function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
  if (isHydrationContainer) {
    if (typeof callback === 'function') {
      var originalCallback = callback;

      callback = function () {
        var instance = getPublicRootInstance(root);
        originalCallback.call(instance);
      };
    }

    var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks
    false, // isStrictMode
    false, // concurrentUpdatesByDefaultOverride,
    '', // identifierPrefix
    noopOnRecoverableError);
    container._reactRootContainer = root;
    markContainerAsRoot(root.current, container);
    var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
    listenToAllSupportedEvents(rootContainerElement);
    flushSync();
    return root;
  } else {
    // First clear any existing content.
    var rootSibling;

    while (rootSibling = container.lastChild) {
      container.removeChild(rootSibling);
    }

    if (typeof callback === 'function') {
      var _originalCallback = callback;

      callback = function () {
        var instance = getPublicRootInstance(_root);

        _originalCallback.call(instance);
      };
    }

    var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks
    false, // isStrictMode
    false, // concurrentUpdatesByDefaultOverride,
    '', // identifierPrefix
    noopOnRecoverableError);

    container._reactRootContainer = _root;
    markContainerAsRoot(_root.current, container);

    var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;

    listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched.

    flushSync(function () {
      updateContainer(initialChildren, _root, parentComponent, callback);
    });
    return _root;
  }
}

function warnOnInvalidCallback$1(callback, callerName) {
  {
    if (callback !== null && typeof callback !== 'function') {
      error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
    }
  }
}

function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
  {
    topLevelUpdateWarnings(container);
    warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
  }

  var maybeRoot = container._reactRootContainer;
  var root;

  if (!maybeRoot) {
    // Initial mount
    root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
  } else {
    root = maybeRoot;

    if (typeof callback === 'function') {
      var originalCallback = callback;

      callback = function () {
        var instance = getPublicRootInstance(root);
        originalCallback.call(instance);
      };
    } // Update


    updateContainer(children, root, parentComponent, callback);
  }

  return getPublicRootInstance(root);
}

var didWarnAboutFindDOMNode = false;
function findDOMNode(componentOrElement) {
  {
    if (!didWarnAboutFindDOMNode) {
      didWarnAboutFindDOMNode = true;

      error('findDOMNode is deprecated and will be removed in the next major ' + 'release. Instead, add a ref directly to the element you want ' + 'to reference. Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node');
    }

    var owner = ReactCurrentOwner$3.current;

    if (owner !== null && owner.stateNode !== null) {
      var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;

      if (!warnedAboutRefsInRender) {
        error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component');
      }

      owner.stateNode._warnedAboutRefsInRender = true;
    }
  }

  if (componentOrElement == null) {
    return null;
  }

  if (componentOrElement.nodeType === ELEMENT_NODE) {
    return componentOrElement;
  }

  {
    return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
  }
}
function hydrate(element, container, callback) {
  {
    error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
  }

  if (!isValidContainerLegacy(container)) {
    throw new Error('Target container is not a DOM element.');
  }

  {
    var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

    if (isModernRoot) {
      error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?');
    }
  } // TODO: throw or warn if we couldn't hydrate?


  return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
}
function render(element, container, callback) {
  {
    error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
  }

  if (!isValidContainerLegacy(container)) {
    throw new Error('Target container is not a DOM element.');
  }

  {
    var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

    if (isModernRoot) {
      error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
    }
  }

  return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
}
function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
  {
    error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot');
  }

  if (!isValidContainerLegacy(containerNode)) {
    throw new Error('Target container is not a DOM element.');
  }

  if (parentComponent == null || !has(parentComponent)) {
    throw new Error('parentComponent must be a valid React Component');
  }

  return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
}
var didWarnAboutUnmountComponentAtNode = false;
function unmountComponentAtNode(container) {
  {
    if (!didWarnAboutUnmountComponentAtNode) {
      didWarnAboutUnmountComponentAtNode = true;

      error('unmountComponentAtNode is deprecated and will be removed in the ' + 'next major release. Switch to the createRoot API. Learn ' + 'more: https://reactjs.org/link/switch-to-createroot');
    }
  }

  if (!isValidContainerLegacy(container)) {
    throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.');
  }

  {
    var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

    if (isModernRoot) {
      error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?');
    }
  }

  if (container._reactRootContainer) {
    {
      var rootEl = getReactRootElementInContainer(container);
      var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);

      if (renderedByDifferentReact) {
        error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
      }
    } // Unmount should not be batched.


    flushSync(function () {
      legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
        // $FlowFixMe This should probably use `delete container._reactRootContainer`
        container._reactRootContainer = null;
        unmarkContainerAsRoot(container);
      });
    }); // If you call unmountComponentAtNode twice in quick succession, you'll
    // get `true` twice. That's probably fine?

    return true;
  } else {
    {
      var _rootEl = getReactRootElementInContainer(container);

      var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node.

      var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;

      if (hasNonRootReactChild) {
        error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
      }
    }

    return false;
  }
}

setAttemptSynchronousHydration(attemptSynchronousHydration$1);
setAttemptContinuousHydration(attemptContinuousHydration$1);
setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
setGetCurrentUpdatePriority(getCurrentUpdatePriority);
setAttemptHydrationAtPriority(runWithPriority);

{
  if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
  Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
  Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
    error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
  }
}

setRestoreImplementation(restoreControlledState$3);
setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync);

function createPortal$1(children, container) {
  var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  if (!isValidContainer(container)) {
    throw new Error('Target container is not a DOM element.');
  } // TODO: pass ReactDOM portal implementation as third argument
  // $FlowFixMe The Flow type is opaque but there's no way to actually create it.


  return createPortal(children, container, null, key);
}

function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
  return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
}

var Internals = {
  usingClientEntryPoint: false,
  // Keep in sync with ReactTestUtils.js.
  // This is an array for better minification.
  Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
};

function createRoot$1(container, options) {
  {
    if (!Internals.usingClientEntryPoint && !false) {
      error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
    }
  }

  return createRoot(container, options);
}

function hydrateRoot$1(container, initialChildren, options) {
  {
    if (!Internals.usingClientEntryPoint && !false) {
      error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
    }
  }

  return hydrateRoot(container, initialChildren, options);
} // Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.


// eslint-disable-next-line no-redeclare
function flushSync$1(fn) {
  {
    if (isAlreadyRendering()) {
      error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.');
    }
  }

  return flushSync(fn);
}
var foundDevTools = injectIntoDevTools({
  findFiberByHostInstance: getClosestInstanceFromNode,
  bundleType:  1 ,
  version: ReactVersion,
  rendererPackageName: 'react-dom'
});

{
  if (!foundDevTools && canUseDOM && window.top === window.self) {
    // If we're in Chrome or Firefox, provide a download link if not installed.
    if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
      var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.

      if (/^(https?|file):$/.test(protocol)) {
        // eslint-disable-next-line react-internal/no-production-logging
        console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold');
      }
    }
  }
}

exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
exports.createPortal = createPortal$1;
exports.createRoot = createRoot$1;
exports.findDOMNode = findDOMNode;
exports.flushSync = flushSync$1;
exports.hydrate = hydrate;
exports.hydrateRoot = hydrateRoot$1;
exports.render = render;
exports.unmountComponentAtNode = unmountComponentAtNode;
exports.unstable_batchedUpdates = batchedUpdates$1;
exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
exports.version = ReactVersion;
          /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
        
  })();
}
/**
 * @license React
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
'use strict';var aa=require("react"),ca=require("scheduler");function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+"Capture",b)}
function ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a])}
var ia=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,la=
{},ma={};function oa(a){if(ja.call(ma,a))return!0;if(ja.call(la,a))return!1;if(ka.test(a))return ma[a]=!0;la[a]=!0;return!1}function pa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}
function qa(a,b,c,d){if(null===b||"undefined"===typeof b||pa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra,
sa);z[b]=new v(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});
z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});
function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])qa(b,c,e,d)&&(c=null),d||null===e?oa(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}
var ua=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,va=Symbol.for("react.element"),wa=Symbol.for("react.portal"),ya=Symbol.for("react.fragment"),za=Symbol.for("react.strict_mode"),Aa=Symbol.for("react.profiler"),Ba=Symbol.for("react.provider"),Ca=Symbol.for("react.context"),Da=Symbol.for("react.forward_ref"),Ea=Symbol.for("react.suspense"),Fa=Symbol.for("react.suspense_list"),Ga=Symbol.for("react.memo"),Ha=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");
var Ia=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var Ja=Symbol.iterator;function Ka(a){if(null===a||"object"!==typeof a)return null;a=Ja&&a[Ja]||a["@@iterator"];return"function"===typeof a?a:null}var A=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\n( *(at )?)/);La=b&&b[1]||""}return"\n"+La+a}var Na=!1;
function Oa(a,b){if(!a||Na)return"";Na=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(l){var d=l}Reflect.construct(a,[],b)}else{try{b.call()}catch(l){d=l}a.call(b.prototype)}else{try{throw Error();}catch(l){d=l}a()}}catch(l){if(l&&d&&"string"===typeof l.stack){for(var e=l.stack.split("\n"),
f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?Ma(a):""}
function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return""}}
function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return"Fragment";case wa:return"Portal";case Aa:return"Profiler";case za:return"StrictMode";case Ea:return"Suspense";case Fa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||"Context")+".Consumer";case Ba:return(a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}
function Ra(a){var b=a.type;switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return"Offscreen";
case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}}
function Ta(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}
function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1)}
function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}
function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}
function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var eb=Array.isArray;
function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}
function gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return A({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(eb(c)){if(1<c.length)throw Error(p(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:Sa(c)}}
function ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}function kb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}
function lb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?kb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var mb,nb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{mb=mb||document.createElement("div");mb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});
function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}
var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,
zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"}
function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});
function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}}
function vb(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;
function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(){}var Ib=!1;function Jb(a,b,c){if(Ib)return a(b,c);Ib=!0;try{return Gb(a,b,c)}finally{if(Ib=!1,null!==zb||null!==Ab)Hb(),Fb()}}
function Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==
typeof c)throw Error(p(231,b,typeof c));return c}var Lb=!1;if(ia)try{var Mb={};Object.defineProperty(Mb,"passive",{get:function(){Lb=!0}});window.addEventListener("test",Mb,Mb);window.removeEventListener("test",Mb,Mb)}catch(a){Lb=!1}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var Ob=!1,Pb=null,Qb=!1,Rb=null,Sb={onError:function(a){Ob=!0;Pb=a}};function Tb(a,b,c,d,e,f,g,h,k){Ob=!1;Pb=null;Nb.apply(Sb,arguments)}
function Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=!1;Pb=null}else throw Error(p(198));Qb||(Qb=!0,Rb=l)}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}
function Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===
c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling}return null}
var ac=ca.unstable_scheduleCallback,bc=ca.unstable_cancelCallback,cc=ca.unstable_shouldYield,dc=ca.unstable_requestPaint,B=ca.unstable_now,ec=ca.unstable_getCurrentPriorityLevel,fc=ca.unstable_ImmediatePriority,gc=ca.unstable_UserBlockingPriority,hc=ca.unstable_NormalPriority,ic=ca.unstable_LowPriority,jc=ca.unstable_IdlePriority,kc=null,lc=null;function mc(a){if(lc&&"function"===typeof lc.onCommitFiberRoot)try{lc.onCommitFiberRoot(kc,a,void 0,128===(a.current.flags&128))}catch(b){}}
var oc=Math.clz32?Math.clz32:nc,pc=Math.log,qc=Math.LN2;function nc(a){a>>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;
function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;
default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-oc(b),e=1<<c,d|=a[c],b&=~e;return d}
function vc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}
function wc(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-oc(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=vc(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function xc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function yc(){var a=rc;rc<<=1;0===(rc&4194240)&&(rc=64);return a}function zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}
function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-oc(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}
function Cc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-oc(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}var C=0;function Dc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Ec,Fc,Gc,Hc,Ic,Jc=!1,Kc=[],Lc=null,Mc=null,Nc=null,Oc=new Map,Pc=new Map,Qc=[],Rc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
function Sc(a,b){switch(a){case "focusin":case "focusout":Lc=null;break;case "dragenter":case "dragleave":Mc=null;break;case "mouseover":case "mouseout":Nc=null;break;case "pointerover":case "pointerout":Oc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":Pc.delete(b.pointerId)}}
function Tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}
function Uc(a,b,c,d,e){switch(b){case "focusin":return Lc=Tc(Lc,a,b,c,d,e),!0;case "dragenter":return Mc=Tc(Mc,a,b,c,d,e),!0;case "mouseover":return Nc=Tc(Nc,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;Oc.set(f,Tc(Oc.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,Pc.set(f,Tc(Pc.get(f)||null,a,b,c,d,e)),!0}return!1}
function Vc(a){var b=Wc(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Ic(a.priority,function(){Gc(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}
function Xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=Yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null}else return b=Cb(c),null!==b&&Fc(b),a.blockedOn=c,!1;b.shift()}return!0}function Zc(a,b,c){Xc(a)&&c.delete(b)}function $c(){Jc=!1;null!==Lc&&Xc(Lc)&&(Lc=null);null!==Mc&&Xc(Mc)&&(Mc=null);null!==Nc&&Xc(Nc)&&(Nc=null);Oc.forEach(Zc);Pc.forEach(Zc)}
function ad(a,b){a.blockedOn===b&&(a.blockedOn=null,Jc||(Jc=!0,ca.unstable_scheduleCallback(ca.unstable_NormalPriority,$c)))}
function bd(a){function b(b){return ad(b,a)}if(0<Kc.length){ad(Kc[0],a);for(var c=1;c<Kc.length;c++){var d=Kc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Lc&&ad(Lc,a);null!==Mc&&ad(Mc,a);null!==Nc&&ad(Nc,a);Oc.forEach(b);Pc.forEach(b);for(c=0;c<Qc.length;c++)d=Qc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Qc.length&&(c=Qc[0],null===c.blockedOn);)Vc(c),null===c.blockedOn&&Qc.shift()}var cd=ua.ReactCurrentBatchConfig,dd=!0;
function ed(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=1,fd(a,b,c,d)}finally{C=e,cd.transition=f}}function gd(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=4,fd(a,b,c,d)}finally{C=e,cd.transition=f}}
function fd(a,b,c,d){if(dd){var e=Yc(a,b,c,d);if(null===e)hd(a,b,d,id,c),Sc(a,d);else if(Uc(e,a,b,c,d))d.stopPropagation();else if(Sc(a,d),b&4&&-1<Rc.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Ec(f);f=Yc(a,b,c,d);null===f&&hd(a,b,d,id,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else hd(a,b,d,null,c)}}var id=null;
function Yc(a,b,c,d){id=null;a=xb(d);a=Wc(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);id=a;return null}
function jd(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;
case "message":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,b=ld,c=b.length,d,e="value"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}
function od(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}
function rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}A(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&
(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd});return b}
var sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=A({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=A({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in
a)return a.movementX;a!==yd&&(yd&&"mousemove"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return"movementY"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=A({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=A({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=A({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=A({},sd,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=A({},sd,{data:0}),Ld=rd(Kd),Md={Esc:"Escape",
Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Nd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",
119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Od={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:!1}function zd(){return Pd}
var Qd=A({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=od(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?Nd[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return"keypress"===a.type?od(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
a.type?od(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=A({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=A({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=A({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=A({},Ad,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},
deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=ia&&"CompositionEvent"in window,be=null;ia&&"documentMode"in document&&(be=document.documentMode);var ce=ia&&"TextEvent"in window&&!be,de=ia&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;
function ge(a,b){switch(a){case "keyup":return-1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function he(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=!0;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}}
function ke(a,b){if(ie)return"compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return de&&"ko"!==b.locale?null:b.data;default:return null}}
var le={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!le[a.type]:"textarea"===b?!0:!1}function ne(a,b,c,d){Eb(d);b=oe(b,"onChange");0<b.length&&(c=new td("onChange","change",null,c,d),a.push({event:c,listeners:b}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var b=ue(a);if(Wa(b))return a}
function ve(a,b){if("change"===a)return b}var we=!1;if(ia){var xe;if(ia){var ye="oninput"in document;if(!ye){var ze=document.createElement("div");ze.setAttribute("oninput","return;");ye="function"===typeof ze.oninput}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent("onpropertychange",Be),qe=pe=null)}function Be(a){if("value"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));Jb(re,b)}}
function Ce(a,b,c){"focusin"===a?(Ae(),pe=b,qe=c,pe.attachEvent("onpropertychange",Be)):"focusout"===a&&Ae()}function De(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return te(qe)}function Ee(a,b){if("click"===a)return te(b)}function Fe(a,b){if("input"===a||"change"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He="function"===typeof Object.is?Object.is:Ge;
function Ie(a,b){if(He(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!He(a[e],b[e]))return!1}return!0}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}
function Ke(a,b){var c=Je(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}
function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}
function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,
d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}
var Pe=ia&&"documentMode"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;
function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0<d.length&&(b=new td("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)))}
function Ve(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var We={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},Xe={},Ye={};
ia&&(Ye=document.createElement("div").style,"AnimationEvent"in window||(delete We.animationend.animation,delete We.animationiteration.animation,delete We.animationstart.animation),"TransitionEvent"in window||delete We.transitionend.transition);function Ze(a){if(Xe[a])return Xe[a];if(!We[a])return a;var b=We[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Ye)return Xe[a]=b[c];return a}var $e=Ze("animationend"),af=Ze("animationiteration"),bf=Ze("animationstart"),cf=Ze("transitionend"),df=new Map,ef="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
function ff(a,b){df.set(a,b);fa(b,[a])}for(var gf=0;gf<ef.length;gf++){var hf=ef[gf],jf=hf.toLowerCase(),kf=hf[0].toUpperCase()+hf.slice(1);ff(jf,"on"+kf)}ff($e,"onAnimationEnd");ff(af,"onAnimationIteration");ff(bf,"onAnimationStart");ff("dblclick","onDoubleClick");ff("focusin","onFocus");ff("focusout","onBlur");ff(cf,"onTransitionEnd");ha("onMouseEnter",["mouseout","mouseover"]);ha("onMouseLeave",["mouseout","mouseover"]);ha("onPointerEnter",["pointerout","pointerover"]);
ha("onPointerLeave",["pointerout","pointerover"]);fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));fa("onBeforeInput",["compositionend","keypress","textInput","paste"]);fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));
fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var lf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),mf=new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
function nf(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null}
function se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}}}if(Qb)throw a=Rb,Qb=!1,Rb=null,a;}
function D(a,b){var c=b[of];void 0===c&&(c=b[of]=new Set);var d=a+"__bubble";c.has(d)||(pf(b,a,2,!1),c.add(d))}function qf(a,b,c){var d=0;b&&(d|=4);pf(c,a,d,b)}var rf="_reactListening"+Math.random().toString(36).slice(2);function sf(a){if(!a[rf]){a[rf]=!0;da.forEach(function(b){"selectionchange"!==b&&(mf.has(b)||qf(b,!1,a),qf(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[rf]||(b[rf]=!0,qf("selectionchange",!1,b))}}
function pf(a,b,c,d){switch(jd(b)){case 1:var e=ed;break;case 4:e=gd;break;default:e=fd}c=e.bind(null,b,c,a);e=void 0;!Lb||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}
function hd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=Wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Jb(function(){var d=f,e=xb(c),g=[];
a:{var h=df.get(a);if(void 0!==h){var k=td,n=a;switch(a){case "keypress":if(0===od(c))break a;case "keydown":case "keyup":k=Rd;break;case "focusin":n="focus";k=Fd;break;case "focusout":n="blur";k=Fd;break;case "beforeblur":case "afterblur":k=Fd;break;case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=Bd;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=
Dd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=Vd;break;case $e:case af:case bf:k=Hd;break;case cf:k=Xd;break;case "scroll":k=vd;break;case "wheel":k=Zd;break;case "copy":case "cut":case "paste":k=Jd;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=Td}var t=0!==(b&4),J=!t&&"scroll"===a,x=t?null!==h?h+"Capture":null:h;t=[];for(var w=d,u;null!==
w;){u=w;var F=u.stateNode;5===u.tag&&null!==F&&(u=F,null!==x&&(F=Kb(w,x),null!=F&&t.push(tf(w,F,u))));if(J)break;w=w.return}0<t.length&&(h=new k(h,n,null,c,e),g.push({event:h,listeners:t}))}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===a;k="mouseout"===a||"pointerout"===a;if(h&&c!==wb&&(n=c.relatedTarget||c.fromElement)&&(Wc(n)||n[uf]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(n=c.relatedTarget||c.toElement,k=d,n=n?Wc(n):null,null!==
n&&(J=Vb(n),n!==J||5!==n.tag&&6!==n.tag))n=null}else k=null,n=d;if(k!==n){t=Bd;F="onMouseLeave";x="onMouseEnter";w="mouse";if("pointerout"===a||"pointerover"===a)t=Td,F="onPointerLeave",x="onPointerEnter",w="pointer";J=null==k?h:ue(k);u=null==n?h:ue(n);h=new t(F,w+"leave",k,c,e);h.target=J;h.relatedTarget=u;F=null;Wc(e)===d&&(t=new t(x,w+"enter",n,c,e),t.target=u,t.relatedTarget=J,F=t);J=F;if(k&&n)b:{t=k;x=n;w=0;for(u=t;u;u=vf(u))w++;u=0;for(F=x;F;F=vf(F))u++;for(;0<w-u;)t=vf(t),w--;for(;0<u-w;)x=
vf(x),u--;for(;w--;){if(t===x||null!==x&&t===x.alternate)break b;t=vf(t);x=vf(x)}t=null}else t=null;null!==k&&wf(g,h,k,t,!1);null!==n&&null!==J&&wf(g,J,n,t,!0)}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===k&&"file"===h.type)var na=ve;else if(me(h))if(we)na=Fe;else{na=De;var xa=Ce}else(k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(na=Ee);if(na&&(na=na(a,d))){ne(g,na,c,e);break a}xa&&xa(a,h,d);"focusout"===a&&(xa=h._wrapperState)&&
xa.controlled&&"number"===h.type&&cb(h,"number",h.value)}xa=d?ue(d):window;switch(a){case "focusin":if(me(xa)||"true"===xa.contentEditable)Qe=xa,Re=d,Se=null;break;case "focusout":Se=Re=Qe=null;break;case "mousedown":Te=!0;break;case "contextmenu":case "mouseup":case "dragend":Te=!1;Ue(g,c,e);break;case "selectionchange":if(Pe)break;case "keydown":case "keyup":Ue(g,c,e)}var $a;if(ae)b:{switch(a){case "compositionstart":var ba="onCompositionStart";break b;case "compositionend":ba="onCompositionEnd";
break b;case "compositionupdate":ba="onCompositionUpdate";break b}ba=void 0}else ie?ge(a,c)&&(ba="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(ba="onCompositionStart");ba&&(de&&"ko"!==c.locale&&(ie||"onCompositionStart"!==ba?"onCompositionEnd"===ba&&ie&&($a=nd()):(kd=e,ld="value"in kd?kd.value:kd.textContent,ie=!0)),xa=oe(d,ba),0<xa.length&&(ba=new Ld(ba,a,null,c,e),g.push({event:ba,listeners:xa}),$a?ba.data=$a:($a=he(c),null!==$a&&(ba.data=$a))));if($a=ce?je(a,c):ke(a,c))d=oe(d,"onBeforeInput"),
0<d.length&&(e=new Ld("onBeforeInput","beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=$a)}se(g,b)})}function tf(a,b,c){return{instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(tf(a,f,e)),f=Kb(a,b),null!=f&&d.push(tf(a,f,e)));a=a.return}return d}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}
function wf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(tf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(tf(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}var xf=/\r\n?/g,yf=/\u0000|\uFFFD/g;function zf(a){return("string"===typeof a?a:""+a).replace(xf,"\n").replace(yf,"")}function Af(a,b,c){b=zf(b);if(zf(a)!==b&&c)throw Error(p(425));}function Bf(){}
var Cf=null,Df=null;function Ef(a,b){return"textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}
var Ff="function"===typeof setTimeout?setTimeout:void 0,Gf="function"===typeof clearTimeout?clearTimeout:void 0,Hf="function"===typeof Promise?Promise:void 0,Jf="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof Hf?function(a){return Hf.resolve(null).then(a).catch(If)}:Ff;function If(a){setTimeout(function(){throw a;})}
function Kf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,"/$"===c){if(0===d){a.removeChild(e);bd(b);return}d--}else"$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e}while(c);bd(b)}function Lf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}
function Mf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--}else"/$"===c&&b++}a=a.previousSibling}return null}var Nf=Math.random().toString(36).slice(2),Of="__reactFiber$"+Nf,Pf="__reactProps$"+Nf,uf="__reactContainer$"+Nf,of="__reactEvents$"+Nf,Qf="__reactListeners$"+Nf,Rf="__reactHandles$"+Nf;
function Wc(a){var b=a[Of];if(b)return b;for(var c=a.parentNode;c;){if(b=c[uf]||c[Of]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Mf(a);null!==a;){if(c=a[Of])return c;a=Mf(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[Of]||a[uf];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[Pf]||null}var Sf=[],Tf=-1;function Uf(a){return{current:a}}
function E(a){0>Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}
function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)}
function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}
function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}eg=null;fg=!1}catch(e){throw null!==eg&&(eg=eg.slice(a+1)),ac(fc,jg),e;}finally{C=b,gg=!1}}return null}var kg=[],lg=0,mg=null,ng=0,og=[],pg=0,qg=null,rg=1,sg="";function tg(a,b){kg[lg++]=ng;kg[lg++]=mg;mg=a;ng=b}
function ug(a,b,c){og[pg++]=rg;og[pg++]=sg;og[pg++]=qg;qg=a;var d=rg;a=sg;var e=32-oc(d)-1;d&=~(1<<e);c+=1;var f=32-oc(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;rg=1<<32-oc(b)+e|c<<e|d;sg=f+a}else rg=1<<f|c<<e|d,sg=a}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0))}function wg(a){for(;a===mg;)mg=kg[--lg],kg[lg]=null,ng=kg[--lg],kg[lg]=null;for(;a===qg;)qg=og[--pg],og[pg]=null,sg=og[--pg],og[pg]=null,rg=og[--pg],og[pg]=null}var xg=null,yg=null,I=!1,zg=null;
function Ag(a,b){var c=Bg(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}
function Cg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,xg=a,yg=Lf(b.firstChild),!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,xg=a,yg=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==qg?{id:rg,overflow:sg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Bg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,xg=a,yg=
null,!0):!1;default:return!1}}function Dg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Eg(a){if(I){var b=yg;if(b){var c=b;if(!Cg(a,b)){if(Dg(a))throw Error(p(418));b=Lf(c.nextSibling);var d=xg;b&&Cg(a,b)?Ag(d,c):(a.flags=a.flags&-4097|2,I=!1,xg=a)}}else{if(Dg(a))throw Error(p(418));a.flags=a.flags&-4097|2;I=!1;xg=a}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;xg=a}
function Gg(a){if(a!==xg)return!1;if(!I)return Fg(a),I=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!Ef(a.type,a.memoizedProps));if(b&&(b=yg)){if(Dg(a))throw Hg(),Error(p(418));for(;b;)Ag(a,b),b=Lf(b.nextSibling)}Fg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){yg=Lf(a.nextSibling);break a}b--}else"$"!==c&&"$!"!==c&&"$?"!==c||b++}a=a.nextSibling}yg=
null}}else yg=xg?Lf(a.stateNode.nextSibling):null;return!0}function Hg(){for(var a=yg;a;)a=Lf(a.nextSibling)}function Ig(){yg=xg=null;I=!1}function Jg(a){null===zg?zg=[a]:zg.push(a)}var Kg=ua.ReactCurrentBatchConfig;
function Lg(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode}if(!d)throw Error(p(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if("string"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}
function Mg(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function Ng(a){var b=a._init;return b(a._payload)}
function Og(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=Pg(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&
null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=Qg(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return m(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ha&&Ng(f)===b.type))return d=e(b,c.props),d.ref=Lg(a,b,c),d.return=a,d;d=Rg(c.type,c.key,c.props,null,a.mode,d);d.ref=Lg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||
b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=Sg(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Tg(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if("string"===typeof b&&""!==b||"number"===typeof b)return b=Qg(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case va:return c=Rg(b.type,b.key,b.props,null,a.mode,c),
c.ref=Lg(a,null,b),c.return=a,c;case wa:return b=Sg(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(eb(b)||Ka(b))return b=Tg(b,a.mode,c,null),b.return=a,b;Mg(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case va:return c.key===e?k(a,b,c,d):null;case wa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,
b,e(c._payload),d)}if(eb(c)||Ka(c))return null!==e?null:m(a,b,c,d,null);Mg(a,c)}return null}function y(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case va:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case wa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return y(a,b,c,f(d._payload),e)}if(eb(d)||Ka(d))return a=a.get(c)||null,m(b,a,d,e,null);Mg(b,d)}return null}
function n(e,g,h,k){for(var l=null,m=null,u=g,w=g=0,x=null;null!==u&&w<h.length;w++){u.index>w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;w<h.length;w++)u=q(e,h[w],k),null!==u&&(g=f(u,g,w),null===m?l=u:m.sibling=u,m=u);I&&tg(e,w);return l}for(u=d(e,u);w<h.length;w++)x=y(u,e,w,h[w],k),null!==x&&(a&&null!==x.alternate&&u.delete(null===
x.key?w:x.key),g=f(x,g,w),null===m?l=x:m.sibling=x,m=x);a&&u.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function t(e,g,h,k){var l=Ka(h);if("function"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var u=l=null,m=g,w=g=0,x=null,n=h.next();null!==m&&!n.done;w++,n=h.next()){m.index>w?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,
m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=
f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==
d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):
(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}
function ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}
function hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}
function lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}
function nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}
function ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=
b;c.lastBaseUpdate=b}
function qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,
next:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if("function"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r="function"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;
h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}
function sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(p(191,e));e.call(d)}}}var th={},uh=Uf(th),vh=Uf(th),wh=Uf(th);function xh(a){if(a===th)throw Error(p(174));return a}
function yh(a,b){G(wh,b);G(vh,a);G(uh,th);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(uh);G(uh,b)}function zh(){E(uh);E(vh);E(wh)}function Ah(a){xh(wh.current);var b=xh(uh.current);var c=lb(b,a.type);b!==c&&(G(vh,a),G(uh,c))}function Bh(a){vh.current===a&&(E(uh),E(vh))}var L=Uf(0);
function Ch(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Dh=[];
function Eh(){for(var a=0;a<Dh.length;a++)Dh[a]._workInProgressVersionPrimary=null;Dh.length=0}var Fh=ua.ReactCurrentDispatcher,Gh=ua.ReactCurrentBatchConfig,Hh=0,M=null,N=null,O=null,Ih=!1,Jh=!1,Kh=0,Lh=0;function P(){throw Error(p(321));}function Mh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return!1;return!0}
function Nh(a,b,c,d,e,f){Hh=f;M=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Fh.current=null===a||null===a.memoizedState?Oh:Ph;a=c(d,e);if(Jh){f=0;do{Jh=!1;Kh=0;if(25<=f)throw Error(p(301));f+=1;O=N=null;b.updateQueue=null;Fh.current=Qh;a=c(d,e)}while(Jh)}Fh.current=Rh;b=null!==N&&null!==N.next;Hh=0;O=N=M=null;Ih=!1;if(b)throw Error(p(300));return a}function Sh(){var a=0!==Kh;Kh=0;return a}
function Th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===O?M.memoizedState=O=a:O=O.next=a;return O}function Uh(){if(null===N){var a=M.alternate;a=null!==a?a.memoizedState:null}else a=N.next;var b=null===O?M.memoizedState:O.next;if(null!==b)O=b,N=a;else{if(null===a)throw Error(p(310));N=a;a={memoizedState:N.memoizedState,baseState:N.baseState,baseQueue:N.baseQueue,queue:N.queue,next:null};null===O?M.memoizedState=O=a:O=O.next=a}return O}
function Vh(a,b){return"function"===typeof b?b(a):b}
function Wh(a){var b=Uh(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=N,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var m=l.lane;if((Hh&m)===m)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else{var q={lane:m,action:l.action,hasEagerState:l.hasEagerState,
eagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;M.lanes|=m;rh|=m}l=l.next}while(null!==l&&l!==f);null===k?g=d:k.next=h;He(d,b.memoizedState)||(dh=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=e.lane,M.lanes|=f,rh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}
function Xh(a){var b=Uh(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(dh=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function Yh(){}
function Zh(a,b){var c=M,d=Uh(),e=b(),f=!He(d.memoizedState,e);f&&(d.memoizedState=e,dh=!0);d=d.queue;$h(ai.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==O&&O.memoizedState.tag&1){c.flags|=2048;bi(9,ci.bind(null,c,d,e,b),void 0,null);if(null===Q)throw Error(p(349));0!==(Hh&30)||di(c,b,e)}return e}function di(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}
function ci(a,b,c,d){b.value=c;b.getSnapshot=d;ei(b)&&fi(a)}function ai(a,b,c){return c(function(){ei(b)&&fi(a)})}function ei(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!He(a,c)}catch(d){return!0}}function fi(a){var b=ih(a,1);null!==b&&gi(b,a,1,-1)}
function hi(a){var b=Th();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Vh,lastRenderedState:a};b.queue=a;a=a.dispatch=ii.bind(null,M,a);return[b.memoizedState,a]}
function bi(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function ji(){return Uh().memoizedState}function ki(a,b,c,d){var e=Th();M.flags|=a;e.memoizedState=bi(1|b,c,void 0,void 0===d?null:d)}
function li(a,b,c,d){var e=Uh();d=void 0===d?null:d;var f=void 0;if(null!==N){var g=N.memoizedState;f=g.destroy;if(null!==d&&Mh(d,g.deps)){e.memoizedState=bi(b,c,f,d);return}}M.flags|=a;e.memoizedState=bi(1|b,c,f,d)}function mi(a,b){return ki(8390656,8,a,b)}function $h(a,b){return li(2048,8,a,b)}function ni(a,b){return li(4,2,a,b)}function oi(a,b){return li(4,4,a,b)}
function pi(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function qi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return li(4,4,pi.bind(null,b,a),c)}function ri(){}function si(a,b){var c=Uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Mh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function ti(a,b){var c=Uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Mh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function ui(a,b,c){if(0===(Hh&21))return a.baseState&&(a.baseState=!1,dh=!0),a.memoizedState=c;He(c,b)||(c=yc(),M.lanes|=c,rh|=c,a.baseState=!0);return b}function vi(a,b){var c=C;C=0!==c&&4>c?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}
function xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}
function ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}
function zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}
var Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,
4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=
Th();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,
f,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Kh++;0<c&&(b+="H"+c.toString(32));b+=":"}else c=Lh++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:!1},Ph={readContext:eh,useCallback:si,useContext:eh,useEffect:$h,useImperativeHandle:qi,useInsertionEffect:ni,useLayoutEffect:oi,useMemo:ti,useReducer:Wh,useRef:ji,useState:function(){return Wh(Vh)},
useDebugValue:ri,useDeferredValue:function(a){var b=Uh();return ui(b,N.memoizedState,a)},useTransition:function(){var a=Wh(Vh)[0],b=Uh().memoizedState;return[a,b]},useMutableSource:Yh,useSyncExternalStore:Zh,useId:wi,unstable_isNewReconciler:!1},Qh={readContext:eh,useCallback:si,useContext:eh,useEffect:$h,useImperativeHandle:qi,useInsertionEffect:ni,useLayoutEffect:oi,useMemo:ti,useReducer:Xh,useRef:ji,useState:function(){return Xh(Vh)},useDebugValue:ri,useDeferredValue:function(a){var b=Uh();return null===
N?b.memoizedState=a:ui(b,N.memoizedState,a)},useTransition:function(){var a=Xh(Vh)[0],b=Uh().memoizedState;return[a,b]},useMutableSource:Yh,useSyncExternalStore:Zh,useId:wi,unstable_isNewReconciler:!1};function Ci(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function Di(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:A({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}
var Ei={isMounted:function(a){return(a=a._reactInternals)?Vb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=R(),e=yi(a),f=mh(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=nh(a,f,e);null!==b&&(gi(b,a,e,d),oh(b,a,e))},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=R(),e=yi(a),f=mh(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=nh(a,f,e);null!==b&&(gi(b,a,e,d),oh(b,a,e))},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=R(),d=
yi(a),e=mh(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=nh(a,e,d);null!==b&&(gi(b,a,d,c),oh(b,a,d))}};function Fi(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Ie(c,d)||!Ie(e,f):!0}
function Gi(a,b,c){var d=!1,e=Vf;var f=b.contextType;"object"===typeof f&&null!==f?f=eh(f):(e=Zf(b)?Xf:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Yf(a,e):Vf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Ei;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function Hi(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Ei.enqueueReplaceState(b,b.state,null)}
function Ii(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs={};kh(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=eh(f):(f=Zf(b)?Xf:H.current,e.context=Yf(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(Di(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,
"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Ei.enqueueReplaceState(e,e.state,null),qh(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308)}function Ji(a,b){try{var c="",d=b;do c+=Pa(d),d=d.return;while(d);var e=c}catch(f){e="\nError generating stack: "+f.message+"\n"+f.stack}return{value:a,source:b,stack:e,digest:null}}
function Ki(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}function Li(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Mi="function"===typeof WeakMap?WeakMap:Map;function Ni(a,b,c){c=mh(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Oi||(Oi=!0,Pi=d);Li(a,b)};return c}
function Qi(a,b,c){c=mh(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Li(a,b)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){Li(a,b);"function"!==typeof d&&(null===Ri?Ri=new Set([this]):Ri.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}
function Si(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new Mi;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=Ti.bind(null,a,b,c),b.then(a,a))}function Ui(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}
function Vi(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=mh(-1,1),b.tag=2,nh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var Wi=ua.ReactCurrentOwner,dh=!1;function Xi(a,b,c,d){b.child=null===a?Vg(b,null,c,d):Ug(b,a.child,c,d)}
function Yi(a,b,c,d,e){c=c.render;var f=b.ref;ch(b,e);d=Nh(a,b,c,d,f,e);c=Sh();if(null!==a&&!dh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi(a,b,e);I&&c&&vg(b);b.flags|=1;Xi(a,b,d,e);return b.child}
function $i(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!aj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bj(a,b,f,d,e);a=Rg(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ie;if(c(g,d)&&a.ref===b.ref)return Zi(a,b,e)}b.flags|=1;a=Pg(f,d);a.ref=b.ref;a.return=b;return b.child=a}
function bj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ie(f,d)&&a.ref===b.ref)if(dh=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(dh=!0);else return b.lanes=a.lanes,Zi(a,b,e)}return cj(a,b,c,d,e)}
function dj(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(ej,fj),fj|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,G(ej,fj),fj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;G(ej,fj);fj|=d}else null!==
f?(d=f.baseLanes|c,b.memoizedState=null):d=c,G(ej,fj),fj|=d;Xi(a,b,e,c);return b.child}function gj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function cj(a,b,c,d,e){var f=Zf(c)?Xf:H.current;f=Yf(b,f);ch(b,e);c=Nh(a,b,c,d,f,e);d=Sh();if(null!==a&&!dh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi(a,b,e);I&&d&&vg(b);b.flags|=1;Xi(a,b,c,e);return b.child}
function hj(a,b,c,d,e){if(Zf(c)){var f=!0;cg(b)}else f=!1;ch(b,e);if(null===b.stateNode)ij(a,b),Gi(b,c,d),Ii(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=eh(l):(l=Zf(c)?Xf:H.current,l=Yf(b,l));var m=c.getDerivedStateFromProps,q="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;q||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||
(h!==d||k!==l)&&Hi(b,g,d,l);jh=!1;var r=b.memoizedState;g.state=r;qh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||Wf.current||jh?("function"===typeof m&&(Di(b,c,m,d),k=b.memoizedState),(h=jh||Fi(b,c,h,d,r,k,l))?(q||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):
("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;lh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:Ci(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=eh(k):(k=Zf(c)?Xf:H.current,k=Yf(b,k));var y=c.getDerivedStateFromProps;(m="function"===typeof y||"function"===typeof g.getSnapshotBeforeUpdate)||
"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&Hi(b,g,d,k);jh=!1;r=b.memoizedState;g.state=r;qh(b,d,g,e);var n=b.memoizedState;h!==q||r!==n||Wf.current||jh?("function"===typeof y&&(Di(b,c,y,d),n=b.memoizedState),(l=jh||Fi(b,c,l,d,r,n,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,n,k),"function"===typeof g.UNSAFE_componentWillUpdate&&
g.UNSAFE_componentWillUpdate(d,n,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context=k,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===
a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return jj(a,b,c,d,f,e)}
function jj(a,b,c,d,e,f){gj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&dg(b,c,!1),Zi(a,b,f);d=b.stateNode;Wi.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Ug(b,a.child,null,f),b.child=Ug(b,null,h,f)):Xi(a,b,h,f);b.memoizedState=d.state;e&&dg(b,c,!0);return b.child}function kj(a){var b=a.stateNode;b.pendingContext?ag(a,b.pendingContext,b.pendingContext!==b.context):b.context&&ag(a,b.context,!1);yh(a,b.containerInfo)}
function lj(a,b,c,d,e){Ig();Jg(e);b.flags|=256;Xi(a,b,c,d);return b.child}var mj={dehydrated:null,treeContext:null,retryLane:0};function nj(a){return{baseLanes:a,cachePool:null,transitions:null}}
function oj(a,b,c){var d=b.pendingProps,e=L.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;G(L,e&1);if(null===a){Eg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=
g):f=pj(g,d,0,null),a=Tg(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=nj(c),b.memoizedState=mj,a):qj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return rj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=Pg(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=Pg(h,f):(f=Tg(f,g,c,null),f.flags|=2);f.return=
b;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?nj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=mj;return d}f=a.child;a=f.sibling;d=Pg(f,{mode:"visible",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}
function qj(a,b){b=pj({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sj(a,b,c,d){null!==d&&Jg(d);Ug(b,a.child,null,c);a=qj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}
function rj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Ki(Error(p(422))),sj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=pj({mode:"visible",children:d.children},e,0,null);f=Tg(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Ug(b,a.child,null,g);b.child.memoizedState=nj(g);b.memoizedState=mj;return f}if(0===(b.mode&1))return sj(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;
if(d)var h=d.dgst;d=h;f=Error(p(419));d=Ki(f,d,void 0);return sj(a,b,g,d)}h=0!==(g&a.childLanes);if(dh||h){d=Q;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;
0!==e&&e!==f.retryLane&&(f.retryLane=e,ih(a,e),gi(d,a,e,-1))}tj();d=Ki(Error(p(421)));return sj(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=uj.bind(null,a),e._reactRetry=b,null;a=f.treeContext;yg=Lf(e.nextSibling);xg=b;I=!0;zg=null;null!==a&&(og[pg++]=rg,og[pg++]=sg,og[pg++]=qg,rg=a.id,sg=a.overflow,qg=b);b=qj(b,d.children);b.flags|=4096;return b}function vj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);bh(a.return,b,c)}
function wj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}
function xj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Xi(a,b,d.children,c);d=L.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&vj(a,c,b);else if(19===a.tag)vj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}G(L,d);if(0===(b.mode&1))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Ch(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);wj(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Ch(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}wj(b,!0,c,null,f);break;case "together":wj(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}
function ij(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function Zi(a,b,c){null!==a&&(b.dependencies=a.dependencies);rh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=Pg(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Pg(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}
function yj(a,b,c){switch(b.tag){case 3:kj(b);Ig();break;case 5:Ah(b);break;case 1:Zf(b.type)&&cg(b);break;case 4:yh(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;G(Wg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return G(L,L.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return oj(a,b,c);G(L,L.current&1);a=Zi(a,b,c);return null!==a?a.sibling:null}G(L,L.current&1);break;case 19:d=0!==(c&
b.childLanes);if(0!==(a.flags&128)){if(d)return xj(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);G(L,L.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dj(a,b,c)}return Zi(a,b,c)}var zj,Aj,Bj,Cj;
zj=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Aj=function(){};
Bj=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;xh(uh.current);var f=null;switch(c){case "input":e=Ya(a,e);d=Ya(a,d);f=[];break;case "select":e=A({},e,{value:void 0});d=A({},d,{value:void 0});f=[];break;case "textarea":e=gb(a,e);d=gb(a,d);f=[];break;default:"function"!==typeof e.onClick&&"function"===typeof d.onClick&&(a.onclick=Bf)}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if("style"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&
(c||(c={}),c[g]="")}else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,
c)),c=k;else"dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(f=f||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(ea.hasOwnProperty(l)?(null!=k&&"onScroll"===l&&D("scroll",a),f||h===k||(f=[])):(f=f||[]).push(l,k))}c&&(f=f||[]).push("style",c);var l=f;if(b.updateQueue=l)b.flags|=4}};Cj=function(a,b,c,d){c!==d&&(b.flags|=4)};
function Dj(a,b){if(!I)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}
function S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}
function Ej(a,b,c){var d=b.pendingProps;wg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return Zf(b.type)&&$f(),S(b),null;case 3:d=b.stateNode;zh();E(Wf);E(H);Eh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Gg(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==zg&&(Fj(zg),zg=null));Aj(a,b);S(b);return null;case 5:Bh(b);var e=xh(wh.current);
c=b.type;if(null!==a&&null!=b.stateNode)Bj(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=xh(uh.current);if(Gg(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Of]=b;d[Pf]=f;a=0!==(b.mode&1);switch(c){case "dialog":D("cancel",d);D("close",d);break;case "iframe":case "object":case "embed":D("load",d);break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],d);break;case "source":D("error",d);break;case "img":case "image":case "link":D("error",
d);D("load",d);break;case "details":D("toggle",d);break;case "input":Za(d,f);D("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!f.multiple};D("invalid",d);break;case "textarea":hb(d,f),D("invalid",d)}ub(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,h,a),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,
h,a),e=["children",""+h]):ea.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&D("scroll",d)}switch(c){case "input":Va(d);db(d,f,!0);break;case "textarea":Va(d);jb(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&(d.onclick=Bf)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===a&&(a=kb(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):
"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],a);e=d;break;case "source":D("error",a);e=d;break;case "img":case "image":case "link":D("error",
a);D("load",a);e=d;break;case "details":D("toggle",a);e=d;break;case "input":Za(a,d);e=Ya(a,d);D("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=A({},d,{value:void 0});D("invalid",a);break;case "textarea":hb(a,d);e=gb(a,d);D("invalid",a);break;default:e=d}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];"style"===f?sb(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):"children"===f?"string"===typeof k?("textarea"!==
c||""!==k)&&ob(a,k):"number"===typeof k&&ob(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(ea.hasOwnProperty(f)?null!=k&&"onScroll"===f&&D("scroll",a):null!=k&&ta(a,f,k,g))}switch(c){case "input":Va(a);db(a,d,!1);break;case "textarea":Va(a);jb(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Sa(d.value));break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,!1):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,
!0);break;default:"function"===typeof e.onClick&&(a.onclick=Bf)}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}S(b);return null;case 6:if(a&&null!=b.stateNode)Cj(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===b.stateNode)throw Error(p(166));c=xh(wh.current);xh(uh.current);if(Gg(b)){d=b.stateNode;c=b.memoizedProps;d[Of]=b;if(f=d.nodeValue!==c)if(a=
xg,null!==a)switch(a.tag){case 3:Af(d.nodeValue,c,0!==(a.mode&1));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&Af(d.nodeValue,c,0!==(a.mode&1))}f&&(b.flags|=4)}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Of]=b,b.stateNode=d}S(b);return null;case 13:E(L);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(I&&null!==yg&&0!==(b.mode&1)&&0===(b.flags&128))Hg(),Ig(),b.flags|=98560,f=!1;else if(f=Gg(b),null!==d&&null!==d.dehydrated){if(null===
a){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[Of]=b}else Ig(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;S(b);f=!1}else null!==zg&&(Fj(zg),zg=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(L.current&1)?0===T&&(T=3):tj()));null!==b.updateQueue&&(b.flags|=4);S(b);return null;case 4:return zh(),
Aj(a,b),null===a&&sf(b.stateNode.containerInfo),S(b),null;case 10:return ah(b.type._context),S(b),null;case 17:return Zf(b.type)&&$f(),S(b),null;case 19:E(L);f=b.memoizedState;if(null===f)return S(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Dj(f,!1);else{if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Ch(a);if(null!==g){b.flags|=128;Dj(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,
g=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;G(L,L.current&1|2);return b.child}a=
a.sibling}null!==f.tail&&B()>Gj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=
b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}
function Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),
null;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj="function"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;
function Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=
q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;
case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}
function Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}"function"===typeof b?b(a):b.current=a}}
function Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}
function Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}
function Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}
function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}
function Zj(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;
Yj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==
c.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}
function ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Xj=!1;break a;case 3:X=h.stateNode.containerInfo;Xj=!0;break a;case 4:X=h.stateNode.containerInfo;Xj=!0;break a}h=h.return}if(null===X)throw Error(p(160));Zj(f,g,e);X=null;Xj=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(l){W(e,b,l)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)dk(b,a),b=b.sibling}
function dk(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:ck(b,a);ek(a);if(d&4){try{Pj(3,a,a.return),Qj(3,a)}catch(t){W(a,a.return,t)}try{Pj(5,a,a.return)}catch(t){W(a,a.return,t)}}break;case 1:ck(b,a);ek(a);d&512&&null!==c&&Lj(c,c.return);break;case 5:ck(b,a);ek(a);d&512&&null!==c&&Lj(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,"")}catch(t){W(a,a.return,t)}}if(d&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;
a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&ab(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var m=k[g],q=k[g+1];"style"===m?sb(e,q):"dangerouslySetInnerHTML"===m?nb(e,q):"children"===m?ob(e,q):ta(e,m,q,l)}switch(h){case "input":bb(e,f);break;case "textarea":ib(e,f);break;case "select":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var y=f.value;null!=y?fb(e,!!f.multiple,y,!1):r!==!!f.multiple&&(null!=f.defaultValue?fb(e,!!f.multiple,
f.defaultValue,!0):fb(e,!!f.multiple,f.multiple?[]:"",!1))}e[Pf]=f}catch(t){W(a,a.return,t)}}break;case 6:ck(b,a);ek(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(t){W(a,a.return,t)}}break;case 3:ck(b,a);ek(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{bd(b.containerInfo)}catch(t){W(a,a.return,t)}break;case 4:ck(b,a);ek(a);break;case 13:ck(b,a);ek(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||
null!==e.alternate&&null!==e.alternate.memoizedState||(fk=B()));d&4&&ak(a);break;case 22:m=null!==c&&null!==c.memoizedState;a.mode&1?(U=(l=U)||m,ck(b,a),U=l):ck(b,a);ek(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!m&&0!==(a.mode&1))for(V=a,m=a.child;null!==m;){for(q=V=m;null!==V;){r=V;y=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Pj(4,r,r.return);break;case 1:Lj(r,r.return);var n=r.stateNode;if("function"===typeof n.componentWillUnmount){d=r;c=r.return;try{b=d,n.props=
b.memoizedProps,n.state=b.memoizedState,n.componentWillUnmount()}catch(t){W(d,c,t)}}break;case 5:Lj(r,r.return);break;case 22:if(null!==r.memoizedState){gk(q);continue}}null!==y?(y.return=r,V=y):gk(q)}m=m.sibling}a:for(m=null,q=a;;){if(5===q.tag){if(null===m){m=q;try{e=q.stateNode,l?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=
rb("display",g))}catch(t){W(a,a.return,t)}}}else if(6===q.tag){if(null===m)try{q.stateNode.nodeValue=l?"":q.memoizedProps}catch(t){W(a,a.return,t)}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;m===q&&(m=null);q=q.return}m===q&&(m=null);q.sibling.return=q.return;q=q.sibling}}break;case 19:ck(b,a);ek(a);d&4&&ak(a);break;case 21:break;default:ck(b,
a),ek(a)}}function ek(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Tj(c)){var d=c;break a}c=c.return}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,""),d.flags&=-33);var f=Uj(a);Wj(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Uj(a);Vj(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function hk(a,b,c){V=a;ik(a,b,c)}
function ik(a,b,c){for(var d=0!==(a.mode&1);null!==V;){var e=V,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Jj;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||U;h=Jj;var l=U;Jj=g;if((U=k)&&!l)for(V=e;null!==V;)g=V,k=g.child,22===g.tag&&null!==g.memoizedState?jk(e):null!==k?(k.return=g,V=k):jk(e);for(;null!==f;)V=f,ik(f,b,c),f=f.sibling;V=e;Jj=h;U=l}kk(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,V=f):kk(a,b,c)}}
function kk(a){for(;null!==V;){var b=V;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:U||Qj(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!U)if(null===c)d.componentDidMount();else{var e=b.elementType===b.type?c.memoizedProps:Ci(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}var f=b.updateQueue;null!==f&&sh(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=
b.child.stateNode;break;case 1:c=b.child.stateNode}sh(b,g,c)}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":k.autoFocus&&c.focus();break;case "img":k.src&&(c.src=k.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var l=b.alternate;if(null!==l){var m=l.memoizedState;if(null!==m){var q=m.dehydrated;null!==q&&bd(q)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;
default:throw Error(p(163));}U||b.flags&512&&Rj(b)}catch(r){W(b,b.return,r)}}if(b===a){V=null;break}c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}function gk(a){for(;null!==V;){var b=V;if(b===a){V=null;break}var c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}
function jk(a){for(;null!==V;){var b=V;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Qj(4,b)}catch(k){W(b,c,k)}break;case 1:var d=b.stateNode;if("function"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount()}catch(k){W(b,e,k)}}var f=b.return;try{Rj(b)}catch(k){W(b,f,k)}break;case 5:var g=b.return;try{Rj(b)}catch(k){W(b,g,k)}}}catch(k){W(b,b.return,k)}if(b===a){V=null;break}var h=b.sibling;if(null!==h){h.return=b.return;V=h;break}V=b.return}}
var lk=Math.ceil,mk=ua.ReactCurrentDispatcher,nk=ua.ReactCurrentOwner,ok=ua.ReactCurrentBatchConfig,K=0,Q=null,Y=null,Z=0,fj=0,ej=Uf(0),T=0,pk=null,rh=0,qk=0,rk=0,sk=null,tk=null,fk=0,Gj=Infinity,uk=null,Oi=!1,Pi=null,Ri=null,vk=!1,wk=null,xk=0,yk=0,zk=null,Ak=-1,Bk=0;function R(){return 0!==(K&6)?B():-1!==Ak?Ak:Ak=B()}
function yi(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Kg.transition)return 0===Bk&&(Bk=yc()),Bk;a=C;if(0!==a)return a;a=window.event;a=void 0===a?16:jd(a.type);return a}function gi(a,b,c,d){if(50<yk)throw yk=0,zk=null,Error(p(185));Ac(a,c,d);if(0===(K&2)||a!==Q)a===Q&&(0===(K&2)&&(qk|=c),4===T&&Ck(a,Z)),Dk(a,d),1===c&&0===K&&0===(b.mode&1)&&(Gj=B()+500,fg&&jg())}
function Dk(a,b){var c=a.callbackNode;wc(a,b);var d=uc(a,a===Q?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?ig(Ek.bind(null,a)):hg(Ek.bind(null,a)),Jf(function(){0===(K&6)&&jg()}),c=null;else{switch(Dc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc}c=Fk(c,Gk.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}
function Gk(a,b){Ak=-1;Bk=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(Hk()&&a.callbackNode!==c)return null;var d=uc(a,a===Q?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Ik(a,d);else{b=d;var e=K;K|=2;var f=Jk();if(Q!==a||Z!==b)uk=null,Gj=B()+500,Kk(a,b);do try{Lk();break}catch(h){Mk(a,h)}while(1);$g();mk.current=f;K=e;null!==Y?b=0:(Q=null,Z=0,b=T)}if(0!==b){2===b&&(e=xc(a),0!==e&&(d=e,b=Nk(a,e)));if(1===b)throw c=pk,Kk(a,0),Ck(a,d),Dk(a,B()),c;if(6===b)Ck(a,d);
else{e=a.current.alternate;if(0===(d&30)&&!Ok(e)&&(b=Ik(a,d),2===b&&(f=xc(a),0!==f&&(d=f,b=Nk(a,f))),1===b))throw c=pk,Kk(a,0),Ck(a,d),Dk(a,B()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Pk(a,tk,uk);break;case 3:Ck(a,d);if((d&130023424)===d&&(b=fk+500-B(),10<b)){if(0!==uc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){R();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Ff(Pk.bind(null,a,tk,uk),b);break}Pk(a,tk,uk);break;case 4:Ck(a,d);if((d&4194240)===
d)break;b=a.eventTimes;for(e=-1;0<d;){var g=31-oc(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10<d){a.timeoutHandle=Ff(Pk.bind(null,a,tk,uk),d);break}Pk(a,tk,uk);break;case 5:Pk(a,tk,uk);break;default:throw Error(p(329));}}}Dk(a,B());return a.callbackNode===c?Gk.bind(null,a):null}
function Nk(a,b){var c=sk;a.current.memoizedState.isDehydrated&&(Kk(a,b).flags|=256);a=Ik(a,b);2!==a&&(b=tk,tk=c,null!==b&&Fj(b));return a}function Fj(a){null===tk?tk=a:tk.push.apply(tk,a)}
function Ok(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!He(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}
function Ck(a,b){b&=~rk;b&=~qk;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-oc(b),d=1<<c;a[c]=-1;b&=~d}}function Ek(a){if(0!==(K&6))throw Error(p(327));Hk();var b=uc(a,0);if(0===(b&1))return Dk(a,B()),null;var c=Ik(a,b);if(0!==a.tag&&2===c){var d=xc(a);0!==d&&(b=d,c=Nk(a,d))}if(1===c)throw c=pk,Kk(a,0),Ck(a,b),Dk(a,B()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Pk(a,tk,uk);Dk(a,B());return null}
function Qk(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(Gj=B()+500,fg&&jg())}}function Rk(a){null!==wk&&0===wk.tag&&0===(K&6)&&Hk();var b=K;K|=1;var c=ok.transition,d=C;try{if(ok.transition=null,C=1,a)return a()}finally{C=d,ok.transition=c,K=b,0===(K&6)&&jg()}}function Hj(){fj=ej.current;E(ej)}
function Kk(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Gf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;wg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&$f();break;case 3:zh();E(Wf);E(H);Eh();break;case 5:Bh(d);break;case 4:zh();break;case 13:E(L);break;case 19:E(L);break;case 10:ah(d.type._context);break;case 22:case 23:Hj()}c=c.return}Q=a;Y=a=Pg(a.current,null);Z=fj=b;T=0;pk=null;rk=qk=rh=0;tk=sk=null;if(null!==fh){for(b=
0;b<fh.length;b++)if(c=fh[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}fh=null}return a}
function Mk(a,b){do{var c=Y;try{$g();Fh.current=Rh;if(Ih){for(var d=M.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Ih=!1}Hh=0;O=N=M=null;Jh=!1;Kh=0;nk.current=null;if(null===c||null===c.return){T=1;pk=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=Z;h.flags|=32768;if(null!==k&&"object"===typeof k&&"function"===typeof k.then){var l=k,m=h,q=m.tag;if(0===(m.mode&1)&&(0===q||11===q||15===q)){var r=m.alternate;r?(m.updateQueue=r.updateQueue,m.memoizedState=r.memoizedState,
m.lanes=r.lanes):(m.updateQueue=null,m.memoizedState=null)}var y=Ui(g);if(null!==y){y.flags&=-257;Vi(y,g,h,f,b);y.mode&1&&Si(f,l,b);b=y;k=l;var n=b.updateQueue;if(null===n){var t=new Set;t.add(k);b.updateQueue=t}else n.add(k);break a}else{if(0===(b&1)){Si(f,l,b);tj();break a}k=Error(p(426))}}else if(I&&h.mode&1){var J=Ui(g);if(null!==J){0===(J.flags&65536)&&(J.flags|=256);Vi(J,g,h,f,b);Jg(Ji(k,h));break a}}f=k=Ji(k,h);4!==T&&(T=2);null===sk?sk=[f]:sk.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;
b&=-b;f.lanes|=b;var x=Ni(f,k,b);ph(f,x);break a;case 1:h=k;var w=f.type,u=f.stateNode;if(0===(f.flags&128)&&("function"===typeof w.getDerivedStateFromError||null!==u&&"function"===typeof u.componentDidCatch&&(null===Ri||!Ri.has(u)))){f.flags|=65536;b&=-b;f.lanes|=b;var F=Qi(f,h,b);ph(f,F);break a}}f=f.return}while(null!==f)}Sk(c)}catch(na){b=na;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function Jk(){var a=mk.current;mk.current=Rh;return null===a?Rh:a}
function tj(){if(0===T||3===T||2===T)T=4;null===Q||0===(rh&268435455)&&0===(qk&268435455)||Ck(Q,Z)}function Ik(a,b){var c=K;K|=2;var d=Jk();if(Q!==a||Z!==b)uk=null,Kk(a,b);do try{Tk();break}catch(e){Mk(a,e)}while(1);$g();K=c;mk.current=d;if(null!==Y)throw Error(p(261));Q=null;Z=0;return T}function Tk(){for(;null!==Y;)Uk(Y)}function Lk(){for(;null!==Y&&!cc();)Uk(Y)}function Uk(a){var b=Vk(a.alternate,a,fj);a.memoizedProps=a.pendingProps;null===b?Sk(a):Y=b;nk.current=null}
function Sk(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=Ej(c,b,fj),null!==c){Y=c;return}}else{c=Ij(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{T=6;Y=null;return}}b=b.sibling;if(null!==b){Y=b;return}Y=b=a}while(null!==b);0===T&&(T=5)}function Pk(a,b,c){var d=C,e=ok.transition;try{ok.transition=null,C=1,Wk(a,b,c,d)}finally{ok.transition=e,C=d}return null}
function Wk(a,b,c,d){do Hk();while(null!==wk);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Bc(a,f);a===Q&&(Y=Q=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||vk||(vk=!0,Fk(hc,function(){Hk();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=ok.transition;ok.transition=null;
var g=C;C=1;var h=K;K|=4;nk.current=null;Oj(a,c);dk(c,a);Oe(Df);dd=!!Cf;Df=Cf=null;a.current=c;hk(c,a,e);dc();K=h;C=g;ok.transition=f}else a.current=c;vk&&(vk=!1,wk=a,xk=e);f=a.pendingLanes;0===f&&(Ri=null);mc(c.stateNode,d);Dk(a,B());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Oi)throw Oi=!1,a=Pi,Pi=null,a;0!==(xk&1)&&0!==a.tag&&Hk();f=a.pendingLanes;0!==(f&1)?a===zk?yk++:(yk=0,zk=a):yk=0;jg();return null}
function Hk(){if(null!==wk){var a=Dc(xk),b=ok.transition,c=C;try{ok.transition=null;C=16>a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(V=l;null!==V;){var m=V;switch(m.tag){case 0:case 11:case 15:Pj(8,m,f)}var q=m.child;if(null!==q)q.return=m,V=q;else for(;null!==V;){m=V;var r=m.sibling,y=m.return;Sj(m);if(m===
l){V=null;break}if(null!==r){r.return=y;V=r;break}V=y}}}var n=f.alternate;if(null!==n){var t=n.child;if(null!==t){n.child=null;do{var J=t.sibling;t.sibling=null;t=J}while(null!==t)}}V=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,V=g;else b:for(;null!==V;){f=V;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Pj(9,f,f.return)}var x=f.sibling;if(null!==x){x.return=f.return;V=x;break b}V=f.return}}var w=a.current;for(V=w;null!==V;){g=V;var u=g.child;if(0!==(g.subtreeFlags&2064)&&null!==
u)u.return=g,V=u;else b:for(g=w;null!==V;){h=V;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Qj(9,h)}}catch(na){W(h,h.return,na)}if(h===g){V=null;break b}var F=h.sibling;if(null!==F){F.return=h.return;V=F;break b}V=h.return}}K=e;jg();if(lc&&"function"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a)}catch(na){}d=!0}return d}finally{C=c,ok.transition=b}}return!1}function Xk(a,b,c){b=Ji(c,b);b=Ni(a,b,1);a=nh(a,b,1);b=R();null!==a&&(Ac(a,1,b),Dk(a,b))}
function W(a,b,c){if(3===a.tag)Xk(a,a,c);else for(;null!==b;){if(3===b.tag){Xk(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Ri||!Ri.has(d))){a=Ji(c,a);a=Qi(b,a,1);b=nh(b,a,1);a=R();null!==b&&(Ac(b,1,a),Dk(b,a));break}}b=b.return}}
function Ti(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=R();a.pingedLanes|=a.suspendedLanes&c;Q===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>B()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}
function bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;
Vk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=
null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,
d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=
f,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),
gj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;
g=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,
c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),
b.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}
function $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}
function Zk(a){if("function"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}
function Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};
c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}
function Rg(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)aj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;
break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}
function Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=
null}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:wa,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}
function dl(a){if(!a)return Vf;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(Zf(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(Zf(c))return bg(a,c,b)}return b}
function el(a,b,c,d,e,f,g,h,k){a=bl(c,d,!0,a,e,f,g,h,k);a.context=dl(null);c=a.current;d=R();e=yi(c);f=mh(d,e);f.callback=void 0!==b&&null!==b?b:null;nh(c,f,e);a.current.lanes=e;Ac(a,e,d);Dk(a,d);return a}function fl(a,b,c,d){var e=b.current,f=R(),g=yi(e);c=dl(c);null===b.context?b.context=c:b.pendingContext=c;b=mh(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=nh(e,b,g);null!==a&&(gi(a,e,g,f),oh(a,e,g));return g}
function gl(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function hl(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function il(a,b){hl(a,b);(a=a.alternate)&&hl(a,b)}function jl(){return null}var kl="function"===typeof reportError?reportError:function(a){console.error(a)};function ll(a){this._internalRoot=a}
ml.prototype.render=ll.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));fl(a,b,null,null)};ml.prototype.unmount=ll.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;Rk(function(){fl(null,a,null,null)});b[uf]=null}};function ml(a){this._internalRoot=a}
ml.prototype.unstable_scheduleHydration=function(a){if(a){var b=Hc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Qc.length&&0!==b&&b<Qc[c].priority;c++);Qc.splice(c,0,a);0===c&&Vc(a)}};function nl(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function ol(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function pl(){}
function ql(a,b,c,d,e){if(e){if("function"===typeof d){var f=d;d=function(){var a=gl(g);f.call(a)}}var g=el(b,d,a,0,null,!1,!1,"",pl);a._reactRootContainer=g;a[uf]=g.current;sf(8===a.nodeType?a.parentNode:a);Rk();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=gl(k);h.call(a)}}var k=bl(a,0,!1,null,null,!1,!1,"",pl);a._reactRootContainer=k;a[uf]=k.current;sf(8===a.nodeType?a.parentNode:a);Rk(function(){fl(b,k,c,d)});return k}
function rl(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===typeof e){var h=e;e=function(){var a=gl(g);h.call(a)}}fl(b,g,a,e)}else g=ql(c,b,a,e,d);return gl(g)}Ec=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=tc(b.pendingLanes);0!==c&&(Cc(b,c|1),Dk(b,B()),0===(K&6)&&(Gj=B()+500,jg()))}break;case 13:Rk(function(){var b=ih(a,1);if(null!==b){var c=R();gi(b,a,1,c)}}),il(a,1)}};
Fc=function(a){if(13===a.tag){var b=ih(a,134217728);if(null!==b){var c=R();gi(b,a,134217728,c)}il(a,134217728)}};Gc=function(a){if(13===a.tag){var b=yi(a),c=ih(a,b);if(null!==c){var d=R();gi(c,a,b,d)}il(a,b)}};Hc=function(){return C};Ic=function(a,b){var c=C;try{return C=a,b()}finally{C=c}};
yb=function(a,b,c){switch(b){case "input":bb(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);bb(d,e)}}}break;case "textarea":ib(a,c);break;case "select":b=c.value,null!=b&&fb(a,!!c.multiple,b,!1)}};Gb=Qk;Hb=Rk;
var sl={usingClientEntryPoint:!1,Events:[Cb,ue,Db,Eb,Fb,Qk]},tl={findFiberByHostInstance:Wc,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"};
var ul={bundleType:tl.bundleType,version:tl.version,rendererPackageName:tl.rendererPackageName,rendererConfig:tl.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ua.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:tl.findFiberByHostInstance||
jl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var vl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!vl.isDisabled&&vl.supportsFiber)try{kc=vl.inject(ul),lc=vl}catch(a){}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=sl;
exports.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!nl(b))throw Error(p(200));return cl(a,b,null,c)};exports.createRoot=function(a,b){if(!nl(a))throw Error(p(299));var c=!1,d="",e=kl;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=bl(a,1,!1,null,null,c,!1,d,e);a[uf]=b.current;sf(8===a.nodeType?a.parentNode:a);return new ll(b)};
exports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(",");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a){return Rk(a)};exports.hydrate=function(a,b,c){if(!ol(b))throw Error(p(200));return rl(null,a,b,!0,c)};
exports.hydrateRoot=function(a,b,c){if(!nl(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=!1,f="",g=kl;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=el(b,null,a,1,null!=c?c:null,e,!1,f,g);a[uf]=b.current;sf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,
e);return new ml(b)};exports.render=function(a,b,c){if(!ol(b))throw Error(p(200));return rl(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!ol(a))throw Error(p(40));return a._reactRootContainer?(Rk(function(){rl(null,null,a,!1,function(){a._reactRootContainer=null;a[uf]=null})}),!0):!1};exports.unstable_batchedUpdates=Qk;
exports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!ol(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return rl(a,b,c,!1,d)};exports.version="18.3.1-next-f1338f8080-20240426";
/**
 * @license React
 * react-dom.profiling.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

          'use strict';

/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
}
          /*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
'use strict';var aa=require("react"),ba=require("scheduler");function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+"Capture",b)}
function ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a])}
var ia=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,la=
{},ma={};function na(a){if(ja.call(ma,a))return!0;if(ja.call(la,a))return!1;if(ka.test(a))return ma[a]=!0;la[a]=!0;return!1}function oa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}
function pa(a,b,c,d){if(null===b||"undefined"===typeof b||oa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function qa(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var t={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){t[a]=new qa(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];t[b]=new qa(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){t[a]=new qa(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){t[a]=new qa(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){t[a]=new qa(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){t[a]=new qa(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){t[a]=new qa(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){t[a]=new qa(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){t[a]=new qa(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\-:]([a-z])/g;function ta(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra,
ta);t[b]=new qa(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,ta);t[b]=new qa(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,ta);t[b]=new qa(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){t[a]=new qa(a,1,!1,a.toLowerCase(),null,!1,!1)});
t.xlinkHref=new qa("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){t[a]=new qa(a,1,!1,a.toLowerCase(),null,!0,!0)});
function ua(a,b,c,d){var e=t.hasOwnProperty(b)?t[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])pa(b,c,e,d)&&(c=null),d||null===e?na(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}
var va=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,wa=Symbol.for("react.element"),xa=Symbol.for("react.portal"),ya=Symbol.for("react.fragment"),za=Symbol.for("react.strict_mode"),Aa=Symbol.for("react.profiler"),Ba=Symbol.for("react.provider"),Ca=Symbol.for("react.context"),Da=Symbol.for("react.forward_ref"),Ea=Symbol.for("react.suspense"),Fa=Symbol.for("react.suspense_list"),Ga=Symbol.for("react.memo"),Ha=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");
var Ia=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var Ja=Symbol.iterator;function Ka(a){if(null===a||"object"!==typeof a)return null;a=Ja&&a[Ja]||a["@@iterator"];return"function"===typeof a?a:null}var u=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\n( *(at )?)/);La=b&&b[1]||""}return"\n"+La+a}var Na=!1;
function Oa(a,b){if(!a||Na)return"";Na=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(l){var d=l}Reflect.construct(a,[],b)}else{try{b.call()}catch(l){d=l}a.call(b.prototype)}else{try{throw Error();}catch(l){d=l}a()}}catch(l){if(l&&d&&"string"===typeof l.stack){for(var e=l.stack.split("\n"),
f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?Ma(a):""}
function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return""}}
function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return"Fragment";case xa:return"Portal";case Aa:return"Profiler";case za:return"StrictMode";case Ea:return"Suspense";case Fa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||"Context")+".Consumer";case Ba:return(a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}
function Ra(a){var b=a.type;switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return"Offscreen";
case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}}
function Ta(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}
function Ya(a,b){var c=b.checked;return u({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function $a(a,b){b=b.checked;null!=b&&ua(a,"checked",b,!1)}
function ab(a,b){$a(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?bb(a,b.type,c):b.hasOwnProperty("defaultValue")&&bb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}
function cb(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}
function bb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var db=Array.isArray;
function eb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}
function fb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return u({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function gb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(db(c)){if(1<c.length)throw Error(p(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:Sa(c)}}
function hb(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function ib(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}function jb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}
function kb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?jb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var mb,nb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{mb=mb||document.createElement("div");mb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});
function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}
var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,
zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"}
function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var tb=u({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});
function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}}
function vb(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;
function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(){}var Ib=!1;function Jb(a,b,c){if(Ib)return a(b,c);Ib=!0;try{return Gb(a,b,c)}finally{if(Ib=!1,null!==zb||null!==Ab)Hb(),Fb()}}
function Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==
typeof c)throw Error(p(231,b,typeof c));return c}var Lb=!1;if(ia)try{var Mb={};Object.defineProperty(Mb,"passive",{get:function(){Lb=!0}});window.addEventListener("test",Mb,Mb);window.removeEventListener("test",Mb,Mb)}catch(a){Lb=!1}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(n){this.onError(n)}}var Ob=!1,Pb=null,Qb=!1,Rb=null,Sb={onError:function(a){Ob=!0;Pb=a}};function Tb(a,b,c,d,e,f,g,h,k){Ob=!1;Pb=null;Nb.apply(Sb,arguments)}
function Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=!1;Pb=null}else throw Error(p(198));Qb||(Qb=!0,Rb=l)}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}
function Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===
c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling}return null}
var ac=ba.unstable_scheduleCallback,bc=ba.unstable_cancelCallback,cc=ba.unstable_shouldYield,dc=ba.unstable_requestPaint,A=ba.unstable_now,ec=ba.unstable_getCurrentPriorityLevel,fc=ba.unstable_ImmediatePriority,gc=ba.unstable_UserBlockingPriority,hc=ba.unstable_NormalPriority,ic=ba.unstable_LowPriority,jc=ba.unstable_IdlePriority,kc=null,lc=null,B=null,mc="undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__;
function nc(a,b){if(lc&&"function"===typeof lc.onCommitFiberRoot)try{var c=128===(a.current.flags&128);switch(b){case 1:var d=fc;break;case 4:d=gc;break;case 16:d=hc;break;case 536870912:d=jc;break;default:d=hc}lc.onCommitFiberRoot(kc,a,d,c)}catch(e){}}function oc(a){B=a}function pc(){for(var a=new Map,b=1,c=0;31>c;c++){var d=qc(b);a.set(b,d);b*=2}return a}function rc(){null!==B&&"function"===typeof B.markCommitStopped&&B.markCommitStopped()}
function sc(a){null!==B&&"function"===typeof B.markComponentRenderStarted&&B.markComponentRenderStarted(a)}function tc(){null!==B&&"function"===typeof B.markComponentRenderStopped&&B.markComponentRenderStopped()}function uc(a){null!==B&&"function"===typeof B.markComponentLayoutEffectUnmountStarted&&B.markComponentLayoutEffectUnmountStarted(a)}function vc(){null!==B&&"function"===typeof B.markComponentLayoutEffectUnmountStopped&&B.markComponentLayoutEffectUnmountStopped()}
function wc(a){null!==B&&"function"===typeof B.markRenderStarted&&B.markRenderStarted(a)}function xc(){null!==B&&"function"===typeof B.markRenderStopped&&B.markRenderStopped()}function yc(a,b){null!==B&&"function"===typeof B.markStateUpdateScheduled&&B.markStateUpdateScheduled(a,b)}var Ac=Math.clz32?Math.clz32:zc,Bc=Math.log,Cc=Math.LN2;function zc(a){a>>>=0;return 0===a?32:31-(Bc(a)/Cc|0)|0}
function qc(a){if(a&1)return"Sync";if(a&2)return"InputContinuousHydration";if(a&4)return"InputContinuous";if(a&8)return"DefaultHydration";if(a&16)return"Default";if(a&32)return"TransitionHydration";if(a&4194240)return"Transition";if(a&130023424)return"Retry";if(a&134217728)return"SelectiveHydration";if(a&268435456)return"IdleHydration";if(a&536870912)return"Idle";if(a&1073741824)return"Offscreen"}var Dc=64,Ec=4194304;
function Fc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;
default:return a}}function Gc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=Fc(h):(f&=g,0!==f&&(d=Fc(f)))}else g=c&~e,0!==g?d=Fc(g):0!==f&&(d=Fc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-Ac(b),e=1<<c,d|=a[c],b&=~e;return d}
function Hc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}
function Ic(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-Ac(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=Hc(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function Jc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function Kc(){var a=Dc;Dc<<=1;0===(Dc&4194240)&&(Dc=64);return a}function Lc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}
function Mc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-Ac(b);a[b]=c}function Nc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-Ac(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}
function Oc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-Ac(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}function Pc(a,b,c){if(mc)for(a=a.pendingUpdatersLaneMap;0<c;){var d=31-Ac(c),e=1<<d;a[d].add(b);c&=~e}}function Qc(a,b){if(mc)for(var c=a.pendingUpdatersLaneMap,d=a.memoizedUpdaters;0<b;){var e=31-Ac(b);a=1<<e;e=c[e];0<e.size&&(e.forEach(function(a){var b=a.alternate;null!==b&&d.has(b)||d.add(a)}),e.clear());b&=~a}}var E=0;
function Rc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Sc,Tc,Uc,Vc,Wc,Xc=!1,Yc=[],Zc=null,$c=null,ad=null,bd=new Map,cd=new Map,dd=[],ed="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
function fd(a,b){switch(a){case "focusin":case "focusout":Zc=null;break;case "dragenter":case "dragleave":$c=null;break;case "mouseover":case "mouseout":ad=null;break;case "pointerover":case "pointerout":bd.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":cd.delete(b.pointerId)}}
function gd(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Tc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}
function hd(a,b,c,d,e){switch(b){case "focusin":return Zc=gd(Zc,a,b,c,d,e),!0;case "dragenter":return $c=gd($c,a,b,c,d,e),!0;case "mouseover":return ad=gd(ad,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;bd.set(f,gd(bd.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,cd.set(f,gd(cd.get(f)||null,a,b,c,d,e)),!0}return!1}
function id(a){var b=jd(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Wc(a.priority,function(){Uc(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}
function kd(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=ld(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null}else return b=Cb(c),null!==b&&Tc(b),a.blockedOn=c,!1;b.shift()}return!0}function md(a,b,c){kd(a)&&c.delete(b)}function nd(){Xc=!1;null!==Zc&&kd(Zc)&&(Zc=null);null!==$c&&kd($c)&&($c=null);null!==ad&&kd(ad)&&(ad=null);bd.forEach(md);cd.forEach(md)}
function od(a,b){a.blockedOn===b&&(a.blockedOn=null,Xc||(Xc=!0,ba.unstable_scheduleCallback(ba.unstable_NormalPriority,nd)))}
function pd(a){function b(b){return od(b,a)}if(0<Yc.length){od(Yc[0],a);for(var c=1;c<Yc.length;c++){var d=Yc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Zc&&od(Zc,a);null!==$c&&od($c,a);null!==ad&&od(ad,a);bd.forEach(b);cd.forEach(b);for(c=0;c<dd.length;c++)d=dd[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<dd.length&&(c=dd[0],null===c.blockedOn);)id(c),null===c.blockedOn&&dd.shift()}var qd=va.ReactCurrentBatchConfig,rd=!0;
function sd(a,b,c,d){var e=E,f=qd.transition;qd.transition=null;try{E=1,td(a,b,c,d)}finally{E=e,qd.transition=f}}function ud(a,b,c,d){var e=E,f=qd.transition;qd.transition=null;try{E=4,td(a,b,c,d)}finally{E=e,qd.transition=f}}
function td(a,b,c,d){if(rd){var e=ld(a,b,c,d);if(null===e)vd(a,b,d,wd,c),fd(a,d);else if(hd(e,a,b,c,d))d.stopPropagation();else if(fd(a,d),b&4&&-1<ed.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Sc(f);f=ld(a,b,c,d);null===f&&vd(a,b,d,wd,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else vd(a,b,d,null,c)}}var wd=null;
function ld(a,b,c,d){wd=null;a=xb(d);a=jd(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);wd=a;return null}
function xd(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;
case "message":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var yd=null,zd=null,Ad=null;function Bd(){if(Ad)return Ad;var a,b=zd,c=b.length,d,e="value"in yd?yd.value:yd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return Ad=e.slice(a,1<d?1-d:void 0)}
function Cd(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function Dd(){return!0}function Ed(){return!1}
function Fd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?Dd:Ed;this.isPropagationStopped=Ed;return this}u(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&
(a.returnValue=!1),this.isDefaultPrevented=Dd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=Dd)},persist:function(){},isPersistent:Dd});return b}
var Gd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Hd=Fd(Gd),Id=u({},Gd,{view:0,detail:0}),Jd=Fd(Id),Kd,Ld,Md,Od=u({},Id,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Nd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in
a)return a.movementX;a!==Md&&(Md&&"mousemove"===a.type?(Kd=a.screenX-Md.screenX,Ld=a.screenY-Md.screenY):Ld=Kd=0,Md=a);return Kd},movementY:function(a){return"movementY"in a?a.movementY:Ld}}),Pd=Fd(Od),Qd=u({},Od,{dataTransfer:0}),Rd=Fd(Qd),Sd=u({},Id,{relatedTarget:0}),Td=Fd(Sd),Ud=u({},Gd,{animationName:0,elapsedTime:0,pseudoElement:0}),Vd=Fd(Ud),Wd=u({},Gd,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),Xd=Fd(Wd),Yd=u({},Gd,{data:0}),Zd=Fd(Yd),$d={Esc:"Escape",
Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ae={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",
119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},be={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ce(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=be[a])?!!b[a]:!1}function Nd(){return ce}
var de=u({},Id,{key:function(a){if(a.key){var b=$d[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=Cd(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?ae[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Nd,charCode:function(a){return"keypress"===a.type?Cd(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
a.type?Cd(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),ee=Fd(de),fe=u({},Od,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),ge=Fd(fe),he=u({},Id,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Nd}),ie=Fd(he),je=u({},Gd,{propertyName:0,elapsedTime:0,pseudoElement:0}),ke=Fd(je),le=u({},Od,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},
deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),me=Fd(le),ne=[9,13,27,32],oe=ia&&"CompositionEvent"in window,pe=null;ia&&"documentMode"in document&&(pe=document.documentMode);var qe=ia&&"TextEvent"in window&&!pe,re=ia&&(!oe||pe&&8<pe&&11>=pe),se=String.fromCharCode(32),te=!1;
function ue(a,b){switch(a){case "keyup":return-1!==ne.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function ve(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var we=!1;function xe(a,b){switch(a){case "compositionend":return ve(b);case "keypress":if(32!==b.which)return null;te=!0;return se;case "textInput":return a=b.data,a===se&&te?null:a;default:return null}}
function ye(a,b){if(we)return"compositionend"===a||!oe&&ue(a,b)?(a=Bd(),Ad=zd=yd=null,we=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return re&&"ko"!==b.locale?null:b.data;default:return null}}
var ze={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ae(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!ze[a.type]:"textarea"===b?!0:!1}function Be(a,b,c,d){Eb(d);b=Ce(b,"onChange");0<b.length&&(c=new Hd("onChange","change",null,c,d),a.push({event:c,listeners:b}))}var De=null,Ee=null;function Fe(a){Ge(a,0)}function He(a){var b=Ie(a);if(Wa(b))return a}
function Je(a,b){if("change"===a)return b}var Ke=!1;if(ia){var Le;if(ia){var Me="oninput"in document;if(!Me){var Ne=document.createElement("div");Ne.setAttribute("oninput","return;");Me="function"===typeof Ne.oninput}Le=Me}else Le=!1;Ke=Le&&(!document.documentMode||9<document.documentMode)}function Oe(){De&&(De.detachEvent("onpropertychange",Pe),Ee=De=null)}function Pe(a){if("value"===a.propertyName&&He(Ee)){var b=[];Be(b,Ee,a,xb(a));Jb(Fe,b)}}
function Qe(a,b,c){"focusin"===a?(Oe(),De=b,Ee=c,De.attachEvent("onpropertychange",Pe)):"focusout"===a&&Oe()}function Re(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return He(Ee)}function Se(a,b){if("click"===a)return He(b)}function Te(a,b){if("input"===a||"change"===a)return He(b)}function Ue(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var Ve="function"===typeof Object.is?Object.is:Ue;
function We(a,b){if(Ve(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!Ve(a[e],b[e]))return!1}return!0}function Xe(a){for(;a&&a.firstChild;)a=a.firstChild;return a}
function Ye(a,b){var c=Xe(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Xe(c)}}function Ze(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Ze(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}
function $e(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function af(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}
function bf(a){var b=$e(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Ze(c.ownerDocument.documentElement,c)){if(null!==d&&af(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ye(c,f);var g=Ye(c,
d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}
var cf=ia&&"documentMode"in document&&11>=document.documentMode,df=null,ef=null,ff=null,gf=!1;
function hf(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;gf||null==df||df!==Xa(d)||(d=df,"selectionStart"in d&&af(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),ff&&We(ff,d)||(ff=d,d=Ce(ef,"onSelect"),0<d.length&&(b=new Hd("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=df)))}
function jf(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var kf={animationend:jf("Animation","AnimationEnd"),animationiteration:jf("Animation","AnimationIteration"),animationstart:jf("Animation","AnimationStart"),transitionend:jf("Transition","TransitionEnd")},lf={},mf={};
ia&&(mf=document.createElement("div").style,"AnimationEvent"in window||(delete kf.animationend.animation,delete kf.animationiteration.animation,delete kf.animationstart.animation),"TransitionEvent"in window||delete kf.transitionend.transition);function nf(a){if(lf[a])return lf[a];if(!kf[a])return a;var b=kf[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in mf)return lf[a]=b[c];return a}var of=nf("animationend"),pf=nf("animationiteration"),qf=nf("animationstart"),rf=nf("transitionend"),sf=new Map,tf="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
function uf(a,b){sf.set(a,b);fa(b,[a])}for(var vf=0;vf<tf.length;vf++){var wf=tf[vf],xf=wf.toLowerCase(),yf=wf[0].toUpperCase()+wf.slice(1);uf(xf,"on"+yf)}uf(of,"onAnimationEnd");uf(pf,"onAnimationIteration");uf(qf,"onAnimationStart");uf("dblclick","onDoubleClick");uf("focusin","onFocus");uf("focusout","onBlur");uf(rf,"onTransitionEnd");ha("onMouseEnter",["mouseout","mouseover"]);ha("onMouseLeave",["mouseout","mouseover"]);ha("onPointerEnter",["pointerout","pointerover"]);
ha("onPointerLeave",["pointerout","pointerover"]);fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));fa("onBeforeInput",["compositionend","keypress","textInput","paste"]);fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));
fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var zf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Af=new Set("cancel close invalid load scroll toggle".split(" ").concat(zf));
function Bf(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null}
function Ge(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;Bf(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;Bf(e,h,l);f=k}}}if(Qb)throw a=Rb,Qb=!1,Rb=null,a;}
function F(a,b){var c=b[Cf];void 0===c&&(c=b[Cf]=new Set);var d=a+"__bubble";c.has(d)||(Df(b,a,2,!1),c.add(d))}function Ef(a,b,c){var d=0;b&&(d|=4);Df(c,a,d,b)}var Ff="_reactListening"+Math.random().toString(36).slice(2);function Gf(a){if(!a[Ff]){a[Ff]=!0;da.forEach(function(b){"selectionchange"!==b&&(Af.has(b)||Ef(b,!1,a),Ef(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[Ff]||(b[Ff]=!0,Ef("selectionchange",!1,b))}}
function Df(a,b,c,d){switch(xd(b)){case 1:var e=sd;break;case 4:e=ud;break;default:e=td}c=e.bind(null,b,c,a);e=void 0;!Lb||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}
function vd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=jd(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Jb(function(){var d=f,e=xb(c),g=[];
a:{var h=sf.get(a);if(void 0!==h){var k=Hd,m=a;switch(a){case "keypress":if(0===Cd(c))break a;case "keydown":case "keyup":k=ee;break;case "focusin":m="focus";k=Td;break;case "focusout":m="blur";k=Td;break;case "beforeblur":case "afterblur":k=Td;break;case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=Pd;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=
Rd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=ie;break;case of:case pf:case qf:k=Vd;break;case rf:k=ke;break;case "scroll":k=Jd;break;case "wheel":k=me;break;case "copy":case "cut":case "paste":k=Xd;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=ge}var w=0!==(b&4),C=!w&&"scroll"===a,x=w?null!==h?h+"Capture":null:h;w=[];for(var y=d,v;null!==
y;){v=y;var D=v.stateNode;5===v.tag&&null!==D&&(v=D,null!==x&&(D=Kb(y,x),null!=D&&w.push(Hf(y,D,v))));if(C)break;y=y.return}0<w.length&&(h=new k(h,m,null,c,e),g.push({event:h,listeners:w}))}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===a;k="mouseout"===a||"pointerout"===a;if(h&&c!==wb&&(m=c.relatedTarget||c.fromElement)&&(jd(m)||m[If]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(m=c.relatedTarget||c.toElement,k=d,m=m?jd(m):null,null!==
m&&(C=Vb(m),m!==C||5!==m.tag&&6!==m.tag))m=null}else k=null,m=d;if(k!==m){w=Pd;D="onMouseLeave";x="onMouseEnter";y="mouse";if("pointerout"===a||"pointerover"===a)w=ge,D="onPointerLeave",x="onPointerEnter",y="pointer";C=null==k?h:Ie(k);v=null==m?h:Ie(m);h=new w(D,y+"leave",k,c,e);h.target=C;h.relatedTarget=v;D=null;jd(e)===d&&(w=new w(x,y+"enter",m,c,e),w.target=v,w.relatedTarget=C,D=w);C=D;if(k&&m)b:{w=k;x=m;y=0;for(v=w;v;v=Jf(v))y++;v=0;for(D=x;D;D=Jf(D))v++;for(;0<y-v;)w=Jf(w),y--;for(;0<v-y;)x=
Jf(x),v--;for(;y--;){if(w===x||null!==x&&w===x.alternate)break b;w=Jf(w);x=Jf(x)}w=null}else w=null;null!==k&&Kf(g,h,k,w,!1);null!==m&&null!==C&&Kf(g,C,m,w,!0)}}}a:{h=d?Ie(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===k&&"file"===h.type)var ca=Je;else if(Ae(h))if(Ke)ca=Te;else{ca=Re;var R=Qe}else(k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(ca=Se);if(ca&&(ca=ca(a,d))){Be(g,ca,c,e);break a}R&&R(a,h,d);"focusout"===a&&(R=h._wrapperState)&&
R.controlled&&"number"===h.type&&bb(h,"number",h.value)}R=d?Ie(d):window;switch(a){case "focusin":if(Ae(R)||"true"===R.contentEditable)df=R,ef=d,ff=null;break;case "focusout":ff=ef=df=null;break;case "mousedown":gf=!0;break;case "contextmenu":case "mouseup":case "dragend":gf=!1;hf(g,c,e);break;case "selectionchange":if(cf)break;case "keydown":case "keyup":hf(g,c,e)}var sa;if(oe)b:{switch(a){case "compositionstart":var V="onCompositionStart";break b;case "compositionend":V="onCompositionEnd";break b;
case "compositionupdate":V="onCompositionUpdate";break b}V=void 0}else we?ue(a,c)&&(V="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(V="onCompositionStart");V&&(re&&"ko"!==c.locale&&(we||"onCompositionStart"!==V?"onCompositionEnd"===V&&we&&(sa=Bd()):(yd=e,zd="value"in yd?yd.value:yd.textContent,we=!0)),R=Ce(d,V),0<R.length&&(V=new Zd(V,a,null,c,e),g.push({event:V,listeners:R}),sa?V.data=sa:(sa=ve(c),null!==sa&&(V.data=sa))));if(sa=qe?xe(a,c):ye(a,c))d=Ce(d,"onBeforeInput"),0<d.length&&(e=new Zd("onBeforeInput",
"beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=sa)}Ge(g,b)})}function Hf(a,b,c){return{instance:a,listener:b,currentTarget:c}}function Ce(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(Hf(a,f,e)),f=Kb(a,b),null!=f&&d.push(Hf(a,f,e)));a=a.return}return d}function Jf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}
function Kf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(Hf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(Hf(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}var Lf=/\r\n?/g,Mf=/\u0000|\uFFFD/g;function Nf(a){return("string"===typeof a?a:""+a).replace(Lf,"\n").replace(Mf,"")}function Of(a,b,c){b=Nf(b);if(Nf(a)!==b&&c)throw Error(p(425));}function Pf(){}
var Qf=null,Rf=null;function Sf(a,b){return"textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}
var Tf="function"===typeof setTimeout?setTimeout:void 0,Uf="function"===typeof clearTimeout?clearTimeout:void 0,Vf="function"===typeof Promise?Promise:void 0,Xf="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof Vf?function(a){return Vf.resolve(null).then(a).catch(Wf)}:Tf;function Wf(a){setTimeout(function(){throw a;})}
function Yf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,"/$"===c){if(0===d){a.removeChild(e);pd(b);return}d--}else"$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e}while(c);pd(b)}function Zf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}
function $f(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--}else"/$"===c&&b++}a=a.previousSibling}return null}var ag=Math.random().toString(36).slice(2),bg="__reactFiber$"+ag,cg="__reactProps$"+ag,If="__reactContainer$"+ag,Cf="__reactEvents$"+ag,dg="__reactListeners$"+ag,eg="__reactHandles$"+ag;
function jd(a){var b=a[bg];if(b)return b;for(var c=a.parentNode;c;){if(b=c[If]||c[bg]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=$f(a);null!==a;){if(c=a[bg])return c;a=$f(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[bg]||a[If];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Ie(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[cg]||null}var fg=[],gg=-1;function hg(a){return{current:a}}
function G(a){0>gg||(a.current=fg[gg],fg[gg]=null,gg--)}function H(a,b){gg++;fg[gg]=a.current;a.current=b}var ig={},I=hg(ig),jg=hg(!1),kg=ig;function lg(a,b){var c=a.type.contextTypes;if(!c)return ig;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}
function mg(a){a=a.childContextTypes;return null!==a&&void 0!==a}function ng(){G(jg);G(I)}function og(a,b,c){if(I.current!==ig)throw Error(p(168));H(I,b);H(jg,c)}function pg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return u({},c,d)}
function qg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||ig;kg=I.current;H(I,a);H(jg,jg.current);return!0}function rg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=pg(a,b,kg),d.__reactInternalMemoizedMergedChildContext=a,G(jg),G(I),H(I,a)):G(jg);H(jg,c)}var sg=null,tg=!1,ug=!1;function vg(a){null===sg?sg=[a]:sg.push(a)}function wg(a){tg=!0;vg(a)}
function xg(){if(!ug&&null!==sg){ug=!0;var a=0,b=E;try{var c=sg;for(E=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}sg=null;tg=!1}catch(e){throw null!==sg&&(sg=sg.slice(a+1)),ac(fc,xg),e;}finally{E=b,ug=!1}}return null}var yg=[],zg=0,Ag=null,Bg=0,Cg=[],Dg=0,Eg=null,Fg=1,Gg="";function Hg(a,b){yg[zg++]=Bg;yg[zg++]=Ag;Ag=a;Bg=b}
function Ig(a,b,c){Cg[Dg++]=Fg;Cg[Dg++]=Gg;Cg[Dg++]=Eg;Eg=a;var d=Fg;a=Gg;var e=32-Ac(d)-1;d&=~(1<<e);c+=1;var f=32-Ac(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;Fg=1<<32-Ac(b)+e|c<<e|d;Gg=f+a}else Fg=1<<f|c<<e|d,Gg=a}function Jg(a){null!==a.return&&(Hg(a,1),Ig(a,1,0))}function Kg(a){for(;a===Ag;)Ag=yg[--zg],yg[zg]=null,Bg=yg[--zg],yg[zg]=null;for(;a===Eg;)Eg=Cg[--Dg],Cg[Dg]=null,Gg=Cg[--Dg],Cg[Dg]=null,Fg=Cg[--Dg],Cg[Dg]=null}var Lg=null,Mg=null,J=!1,Ng=null;
function Og(a,b){var c=Pg(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}
function Qg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,Lg=a,Mg=Zf(b.firstChild),!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,Lg=a,Mg=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==Eg?{id:Fg,overflow:Gg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Pg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,Lg=a,Mg=
null,!0):!1;default:return!1}}function Rg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Sg(a){if(J){var b=Mg;if(b){var c=b;if(!Qg(a,b)){if(Rg(a))throw Error(p(418));b=Zf(c.nextSibling);var d=Lg;b&&Qg(a,b)?Og(d,c):(a.flags=a.flags&-4097|2,J=!1,Lg=a)}}else{if(Rg(a))throw Error(p(418));a.flags=a.flags&-4097|2;J=!1;Lg=a}}}function Tg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;Lg=a}
function Ug(a){if(a!==Lg)return!1;if(!J)return Tg(a),J=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!Sf(a.type,a.memoizedProps));if(b&&(b=Mg)){if(Rg(a))throw Vg(),Error(p(418));for(;b;)Og(a,b),b=Zf(b.nextSibling)}Tg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){Mg=Zf(a.nextSibling);break a}b--}else"$"!==c&&"$!"!==c&&"$?"!==c||b++}a=a.nextSibling}Mg=
null}}else Mg=Lg?Zf(a.stateNode.nextSibling):null;return!0}function Vg(){for(var a=Mg;a;)a=Zf(a.nextSibling)}function Wg(){Mg=Lg=null;J=!1}function Xg(a){null===Ng?Ng=[a]:Ng.push(a)}var Yg=va.ReactCurrentBatchConfig;
function Zg(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode}if(!d)throw Error(p(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if("string"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}
function $g(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function ah(a){var b=a._init;return b(a._payload)}
function bh(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=ch(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&
null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=dh(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return n(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ha&&ah(f)===b.type))return d=e(b,c.props),d.ref=Zg(a,b,c),d.return=a,d;d=eh(c.type,c.key,c.props,null,a.mode,d);d.ref=Zg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||
b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=fh(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function n(a,b,c,d,f){if(null===b||7!==b.tag)return b=gh(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if("string"===typeof b&&""!==b||"number"===typeof b)return b=dh(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case wa:return c=eh(b.type,b.key,b.props,null,a.mode,c),
c.ref=Zg(a,null,b),c.return=a,c;case xa:return b=fh(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(db(b)||Ka(b))return b=gh(b,a.mode,c,null),b.return=a,b;$g(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case wa:return c.key===e?k(a,b,c,d):null;case xa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,
b,e(c._payload),d)}if(db(c)||Ka(c))return null!==e?null:n(a,b,c,d,null);$g(a,c)}return null}function z(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case wa:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case xa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return z(a,b,c,f(d._payload),e)}if(db(d)||Ka(d))return a=a.get(c)||null,n(b,a,d,e,null);$g(b,d)}return null}
function m(e,g,h,k){for(var l=null,v=null,n=g,m=g=0,y=null;null!==n&&m<h.length;m++){n.index>m?(y=n,n=null):y=n.sibling;var x=r(e,n,h[m],k);if(null===x){null===n&&(n=y);break}a&&n&&null===x.alternate&&b(e,n);g=f(x,g,m);null===v?l=x:v.sibling=x;v=x;n=y}if(m===h.length)return c(e,n),J&&Hg(e,m),l;if(null===n){for(;m<h.length;m++)n=q(e,h[m],k),null!==n&&(g=f(n,g,m),null===v?l=n:v.sibling=n,v=n);J&&Hg(e,m);return l}for(n=d(e,n);m<h.length;m++)y=z(n,e,m,h[m],k),null!==y&&(a&&null!==y.alternate&&n.delete(null===
y.key?m:y.key),g=f(y,g,m),null===v?l=y:v.sibling=y,v=y);a&&n.forEach(function(a){return b(e,a)});J&&Hg(e,m);return l}function w(e,g,h,k){var l=Ka(h);if("function"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var n=l=null,m=g,v=g=0,y=null,x=h.next();null!==m&&!x.done;v++,x=h.next()){m.index>v?(y=m,m=null):y=m.sibling;var w=r(e,m,x.value,k);if(null===w){null===m&&(m=y);break}a&&m&&null===w.alternate&&b(e,m);g=f(w,g,v);null===n?l=w:n.sibling=w;n=w;m=y}if(x.done)return c(e,
m),J&&Hg(e,v),l;if(null===m){for(;!x.done;v++,x=h.next())x=q(e,x.value,k),null!==x&&(g=f(x,g,v),null===n?l=x:n.sibling=x,n=x);J&&Hg(e,v);return l}for(m=d(e,m);!x.done;v++,x=h.next())x=z(m,e,v,x.value,k),null!==x&&(a&&null!==x.alternate&&m.delete(null===x.key?v:x.key),g=f(x,g,v),null===n?l=x:n.sibling=x,n=x);a&&m.forEach(function(a){return b(e,a)});J&&Hg(e,v);return l}function C(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case wa:a:{for(var k=
f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&ah(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Zg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=gh(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=eh(f.type,f.key,f.props,null,a.mode,h),h.ref=Zg(a,d,f),h.return=a,a=h)}return g(a);case xa:a:{for(l=f.key;null!==
d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=fh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,C(a,d,l(f._payload),h)}if(db(f))return m(a,d,f,h);if(Ka(f))return w(a,d,f,h);$g(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):
(c(a,d),d=dh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return C}var hh=bh(!0),ih=bh(!1),jh=hg(null),kh=null,lh=null,mh=null;function nh(){mh=lh=kh=null}function oh(a){var b=jh.current;G(jh);a._currentValue=b}function ph(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}
function qh(a,b){kh=a;mh=lh=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(rh=!0),a.firstContext=null)}function sh(a){var b=a._currentValue;if(mh!==a)if(a={context:a,memoizedValue:b,next:null},null===lh){if(null===kh)throw Error(p(308));lh=a;kh.dependencies={lanes:0,firstContext:a}}else lh=lh.next=a;return b}var th=null;function uh(a){null===th?th=[a]:th.push(a)}
function vh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,uh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return wh(a,d)}function wh(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var xh=!1;function yh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}
function zh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Ah(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}
function Bh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return wh(a,c)}e=d.interleaved;null===e?(b.next=b,uh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return wh(a,c)}function Ch(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Oc(a,c)}}
function Dh(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=
b;c.lastBaseUpdate=b}
function Eh(a,b,c,d){var e=a.updateQueue;xh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var n=a.alternate;null!==n&&(n=n.updateQueue,h=n.lastBaseUpdate,h!==g&&(null===h?n.firstBaseUpdate=l:h.next=l,n.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;n=l=k=null;h=f;do{var r=h.lane,z=h.eventTime;if((d&r)===r){null!==n&&(n=n.next={eventTime:z,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,
next:null});a:{var m=a,w=h;r=b;z=c;switch(w.tag){case 1:m=w.payload;if("function"===typeof m){q=m.call(z,q,r);break a}q=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:m=w.payload;r="function"===typeof m?m.call(z,q,r):m;if(null===r||void 0===r)break a;q=u({},q,r);break a;case 2:xh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else z={eventTime:z,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===n?(l=n=z,k=q):n=n.next=z,g|=r;
h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===n&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=n;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);Fh|=g;a.lanes=g;a.memoizedState=q}}
function Gh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(p(191,e));e.call(d)}}}var Hh={},Ih=hg(Hh),Jh=hg(Hh),Kh=hg(Hh);function Lh(a){if(a===Hh)throw Error(p(174));return a}
function Mh(a,b){H(Kh,b);H(Jh,a);H(Ih,Hh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:kb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=kb(b,a)}G(Ih);H(Ih,b)}function Nh(){G(Ih);G(Jh);G(Kh)}function Oh(a){Lh(Kh.current);var b=Lh(Ih.current);var c=kb(b,a.type);b!==c&&(H(Jh,a),H(Ih,c))}function Ph(a){Jh.current===a&&(G(Ih),G(Jh))}var L=hg(0);
function Qh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Rh=[];
function Sh(){for(var a=0;a<Rh.length;a++)Rh[a]._workInProgressVersionPrimary=null;Rh.length=0}var Th=va.ReactCurrentDispatcher,Uh=va.ReactCurrentBatchConfig,Vh=0,M=null,N=null,O=null,Wh=!1,Xh=!1,Yh=0,Zh=0;function P(){throw Error(p(321));}function $h(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!Ve(a[c],b[c]))return!1;return!0}
function ai(a,b,c,d,e,f){Vh=f;M=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Th.current=null===a||null===a.memoizedState?bi:ci;a=c(d,e);if(Xh){f=0;do{Xh=!1;Yh=0;if(25<=f)throw Error(p(301));f+=1;O=N=null;b.updateQueue=null;Th.current=di;a=c(d,e)}while(Xh)}Th.current=ei;b=null!==N&&null!==N.next;Vh=0;O=N=M=null;Wh=!1;if(b)throw Error(p(300));return a}function fi(){var a=0!==Yh;Yh=0;return a}
function gi(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===O?M.memoizedState=O=a:O=O.next=a;return O}function hi(){if(null===N){var a=M.alternate;a=null!==a?a.memoizedState:null}else a=N.next;var b=null===O?M.memoizedState:O.next;if(null!==b)O=b,N=a;else{if(null===a)throw Error(p(310));N=a;a={memoizedState:N.memoizedState,baseState:N.baseState,baseQueue:N.baseQueue,queue:N.queue,next:null};null===O?M.memoizedState=O=a:O=O.next=a}return O}
function ii(a,b){return"function"===typeof b?b(a):b}
function ji(a){var b=hi(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=N,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var n=l.lane;if((Vh&n)===n)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else{var q={lane:n,action:l.action,hasEagerState:l.hasEagerState,
eagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;M.lanes|=n;Fh|=n}l=l.next}while(null!==l&&l!==f);null===k?g=d:k.next=h;Ve(d,b.memoizedState)||(rh=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=e.lane,M.lanes|=f,Fh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}
function ki(a){var b=hi(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);Ve(f,b.memoizedState)||(rh=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function li(){}
function mi(a,b){var c=M,d=hi(),e=b(),f=!Ve(d.memoizedState,e);f&&(d.memoizedState=e,rh=!0);d=d.queue;ni(oi.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==O&&O.memoizedState.tag&1){c.flags|=2048;pi(9,qi.bind(null,c,d,e,b),void 0,null);if(null===Q)throw Error(p(349));0!==(Vh&30)||ri(c,b,e)}return e}function ri(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}
function qi(a,b,c,d){b.value=c;b.getSnapshot=d;si(b)&&ti(a)}function oi(a,b,c){return c(function(){si(b)&&ti(a)})}function si(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!Ve(a,c)}catch(d){return!0}}function ti(a){var b=wh(a,1);null!==b&&ui(b,a,1,-1)}
function vi(a){var b=gi();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ii,lastRenderedState:a};b.queue=a;a=a.dispatch=wi.bind(null,M,a);return[b.memoizedState,a]}
function pi(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function xi(){return hi().memoizedState}function Ai(a,b,c,d){var e=gi();M.flags|=a;e.memoizedState=pi(1|b,c,void 0,void 0===d?null:d)}
function Bi(a,b,c,d){var e=hi();d=void 0===d?null:d;var f=void 0;if(null!==N){var g=N.memoizedState;f=g.destroy;if(null!==d&&$h(d,g.deps)){e.memoizedState=pi(b,c,f,d);return}}M.flags|=a;e.memoizedState=pi(1|b,c,f,d)}function Ci(a,b){return Ai(8390656,8,a,b)}function ni(a,b){return Bi(2048,8,a,b)}function Di(a,b){return Bi(4,2,a,b)}function Ei(a,b){return Bi(4,4,a,b)}
function Fi(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function Gi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Bi(4,4,Fi.bind(null,b,a),c)}function Hi(){}function Ii(a,b){var c=hi();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&$h(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function Ji(a,b){var c=hi();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&$h(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Ki(a,b,c){if(0===(Vh&21))return a.baseState&&(a.baseState=!1,rh=!0),a.memoizedState=c;Ve(c,b)||(c=Kc(),M.lanes|=c,Fh|=c,a.baseState=!0);return b}function Li(a,b){var c=E;E=0!==c&&4>c?c:4;a(!0);var d=Uh.transition;Uh.transition={};try{a(!1),b()}finally{E=c,Uh.transition=d}}function Mi(){return hi().memoizedState}
function Ni(a,b,c){var d=Oi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Pi(a))Qi(b,c);else if(c=vh(a,b,c,d),null!==c){var e=Ri();ui(c,a,d,e);Si(c,b,d)}yc(a,d)}
function wi(a,b,c){var d=Oi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Pi(a))Qi(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Ve(h,g)){var k=b.interleaved;null===k?(e.next=e,uh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=vh(a,b,e,d);null!==c&&(e=Ri(),ui(c,a,d,e),Si(c,b,d))}yc(a,d)}
function Pi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Qi(a,b){Xh=Wh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Si(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Oc(a,c)}}
var ei={readContext:sh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},bi={readContext:sh,useCallback:function(a,b){gi().memoizedState=[a,void 0===b?null:b];return a},useContext:sh,useEffect:Ci,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Ai(4194308,
4,Fi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Ai(4194308,4,a,b)},useInsertionEffect:function(a,b){return Ai(4,2,a,b)},useMemo:function(a,b){var c=gi();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=gi();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Ni.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=
gi();a={current:a};return b.memoizedState=a},useState:vi,useDebugValue:Hi,useDeferredValue:function(a){return gi().memoizedState=a},useTransition:function(){var a=vi(!1),b=a[0];a=Li.bind(null,a[1]);gi().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=gi();if(J){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Vh&30)||ri(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;Ci(oi.bind(null,d,
f,a),[a]);d.flags|=2048;pi(9,qi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=gi(),b=Q.identifierPrefix;if(J){var c=Gg;var d=Fg;c=(d&~(1<<32-Ac(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Yh++;0<c&&(b+="H"+c.toString(32));b+=":"}else c=Zh++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:!1},ci={readContext:sh,useCallback:Ii,useContext:sh,useEffect:ni,useImperativeHandle:Gi,useInsertionEffect:Di,useLayoutEffect:Ei,useMemo:Ji,useReducer:ji,useRef:xi,useState:function(){return ji(ii)},
useDebugValue:Hi,useDeferredValue:function(a){var b=hi();return Ki(b,N.memoizedState,a)},useTransition:function(){var a=ji(ii)[0],b=hi().memoizedState;return[a,b]},useMutableSource:li,useSyncExternalStore:mi,useId:Mi,unstable_isNewReconciler:!1},di={readContext:sh,useCallback:Ii,useContext:sh,useEffect:ni,useImperativeHandle:Gi,useInsertionEffect:Di,useLayoutEffect:Ei,useMemo:Ji,useReducer:ki,useRef:xi,useState:function(){return ki(ii)},useDebugValue:Hi,useDeferredValue:function(a){var b=hi();return null===
N?b.memoizedState=a:Ki(b,N.memoizedState,a)},useTransition:function(){var a=ki(ii)[0],b=hi().memoizedState;return[a,b]},useMutableSource:li,useSyncExternalStore:mi,useId:Mi,unstable_isNewReconciler:!1},Ti=ba.unstable_now,Ui=0,Vi=-1,Wi=-1,Xi=-1,Yi=!1,Zi=!1;function $i(a,b){if(0<=Wi){var c=Ti()-Wi;a.actualDuration+=c;b&&(a.selfBaseDuration=c);Wi=-1}}
function aj(a){if(0<=Vi){var b=Ti()-Vi;Vi=-1;for(a=a.return;null!==a;){switch(a.tag){case 3:a.stateNode.effectDuration+=b;return;case 12:a.stateNode.effectDuration+=b;return}a=a.return}}}function bj(a){if(0<=Xi){var b=Ti()-Xi;Xi=-1;for(a=a.return;null!==a;){switch(a.tag){case 3:a=a.stateNode;null!==a&&(a.passiveEffectDuration+=b);return;case 12:a=a.stateNode;null!==a&&(a.passiveEffectDuration+=b);return}a=a.return}}}function cj(){Vi=Ti()}
function dj(a){for(var b=a.child;b;)a.actualDuration+=b.actualDuration,b=b.sibling}function ej(a,b){if(a&&a.defaultProps){b=u({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}function fj(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:u({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}
var gj={isMounted:function(a){return(a=a._reactInternals)?Vb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=Ri(),e=Oi(a),f=Ah(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=Bh(a,f,e);null!==b&&(ui(b,a,e,d),Ch(b,a,e));yc(a,e)},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=Ri(),e=Oi(a),f=Ah(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=Bh(a,f,e);null!==b&&(ui(b,a,e,d),Ch(b,a,e));yc(a,e)},enqueueForceUpdate:function(a,b){a=a._reactInternals;
var c=Ri(),d=Oi(a),e=Ah(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=Bh(a,e,d);null!==b&&(ui(b,a,d,c),Ch(b,a,d));null!==B&&"function"===typeof B.markForceUpdateScheduled&&B.markForceUpdateScheduled(a,d)}};function hj(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!We(c,d)||!We(e,f):!0}
function ij(a,b,c){var d=!1,e=ig;var f=b.contextType;"object"===typeof f&&null!==f?f=sh(f):(e=mg(b)?kg:I.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?lg(a,e):ig);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=gj;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function jj(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&gj.enqueueReplaceState(b,b.state,null)}
function kj(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs={};yh(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=sh(f):(f=mg(b)?kg:I.current,e.context=lg(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(fj(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,
"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&gj.enqueueReplaceState(e,e.state,null),Eh(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308)}function lj(a,b){try{var c="",d=b;do c+=Pa(d),d=d.return;while(d);var e=c}catch(f){e="\nError generating stack: "+f.message+"\n"+f.stack}return{value:a,source:b,stack:e,digest:null}}
function mj(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}function nj(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var oj="function"===typeof WeakMap?WeakMap:Map;function pj(a,b,c){c=Ah(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){qj||(qj=!0,rj=d);nj(a,b)};return c}
function sj(a,b,c){c=Ah(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){nj(a,b)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){nj(a,b);"function"!==typeof d&&(null===tj?tj=new Set([this]):tj.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}
function uj(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new oj;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),d=vj.bind(null,a,b,c),mc&&wj(a,c),b.then(d,d))}function xj(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}
function yj(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=Ah(-1,1),b.tag=2,Bh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var zj=va.ReactCurrentOwner,rh=!1;function Aj(a,b,c,d){b.child=null===a?ih(b,null,c,d):hh(b,a.child,c,d)}
function Bj(a,b,c,d,e){c=c.render;var f=b.ref;qh(b,e);sc(b);d=ai(a,b,c,d,f,e);c=fi();tc();if(null!==a&&!rh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Cj(a,b,e);J&&c&&Jg(b);b.flags|=1;Aj(a,b,d,e);return b.child}
function Dj(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!Ej(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,Fj(a,b,f,d,e);a=eh(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:We;if(c(g,d)&&a.ref===b.ref)return Cj(a,b,e)}b.flags|=1;a=ch(f,d);a.ref=b.ref;a.return=b;return b.child=a}
function Fj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(We(f,d)&&a.ref===b.ref)if(rh=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(rh=!0);else return b.lanes=a.lanes,Cj(a,b,e)}return Gj(a,b,c,d,e)}
function Hj(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},H(Ij,Jj),Jj|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,H(Ij,Jj),Jj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;H(Ij,Jj);Jj|=d}else null!==
f?(d=f.baseLanes|c,b.memoizedState=null):d=c,H(Ij,Jj),Jj|=d;Aj(a,b,e,c);return b.child}function Kj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function Gj(a,b,c,d,e){var f=mg(c)?kg:I.current;f=lg(b,f);qh(b,e);sc(b);c=ai(a,b,c,d,f,e);d=fi();tc();if(null!==a&&!rh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Cj(a,b,e);J&&d&&Jg(b);b.flags|=1;Aj(a,b,c,e);return b.child}
function Lj(a,b,c,d,e){if(mg(c)){var f=!0;qg(b)}else f=!1;qh(b,e);if(null===b.stateNode)Mj(a,b),ij(b,c,d),kj(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=sh(l):(l=mg(c)?kg:I.current,l=lg(b,l));var n=c.getDerivedStateFromProps,q="function"===typeof n||"function"===typeof g.getSnapshotBeforeUpdate;q||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||
(h!==d||k!==l)&&jj(b,g,d,l);xh=!1;var r=b.memoizedState;g.state=r;Eh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||jg.current||xh?("function"===typeof n&&(fj(b,c,n,d),k=b.memoizedState),(h=xh||hj(b,c,h,d,r,k,l))?(q||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):
("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;zh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:ej(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=sh(k):(k=mg(c)?kg:I.current,k=lg(b,k));var z=c.getDerivedStateFromProps;(n="function"===typeof z||"function"===typeof g.getSnapshotBeforeUpdate)||
"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&jj(b,g,d,k);xh=!1;r=b.memoizedState;g.state=r;Eh(b,d,g,e);var m=b.memoizedState;h!==q||r!==m||jg.current||xh?("function"===typeof z&&(fj(b,c,z,d),m=b.memoizedState),(l=xh||hj(b,c,l,d,r,m,k)||!1)?(n||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,m,k),"function"===typeof g.UNSAFE_componentWillUpdate&&
g.UNSAFE_componentWillUpdate(d,m,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=m),g.props=d,g.state=m,g.context=k,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===
a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return Nj(a,b,c,d,f,e)}
function Nj(a,b,c,d,e,f){Kj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&rg(b,c,!1),Cj(a,b,f);d=b.stateNode;zj.current=b;if(g&&"function"!==typeof c.getDerivedStateFromError){var h=null;Wi=-1}else sc(b),h=d.render(),tc();b.flags|=1;null!==a&&g?(g=h,b.child=hh(b,a.child,null,f),b.child=hh(b,null,g,f)):Aj(a,b,h,f);b.memoizedState=d.state;e&&rg(b,c,!0);return b.child}
function Oj(a){var b=a.stateNode;b.pendingContext?og(a,b.pendingContext,b.pendingContext!==b.context):b.context&&og(a,b.context,!1);Mh(a,b.containerInfo)}function Rj(a,b,c,d,e){Wg();Xg(e);b.flags|=256;Aj(a,b,c,d);return b.child}var Sj={dehydrated:null,treeContext:null,retryLane:0};function Tj(a){return{baseLanes:a,cachePool:null,transitions:null}}
function Uj(a,b,c){var d=b.pendingProps,e=L.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;H(L,e&1);if(null===a){Sg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=
g,b.mode&2&&(f.actualDuration=0,f.actualStartTime=-1,f.selfBaseDuration=0,f.treeBaseDuration=0)):f=Vj(g,d,0,null),a=gh(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=Tj(c),b.memoizedState=Sj,a):Wj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return Xj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.mode&2&&(d.actualDuration=
0,d.actualStartTime=-1,d.selfBaseDuration=e.selfBaseDuration,d.treeBaseDuration=e.treeBaseDuration),b.deletions=null):(d=ch(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=ch(h,f):(f=gh(f,g,c,null),f.flags|=2);f.return=b;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?Tj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=Sj;return d}f=a.child;a=f.sibling;d=ch(f,{mode:"visible",
children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}function Wj(a,b){b=Vj({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function Yj(a,b,c,d){null!==d&&Xg(d);hh(b,a.child,null,c);a=Wj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}
function Xj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=mj(Error(p(422))),Yj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=Vj({mode:"visible",children:d.children},e,0,null);f=gh(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&hh(b,a.child,null,g);b.child.memoizedState=Tj(g);b.memoizedState=Sj;return f}if(0===(b.mode&1))return Yj(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;
if(d)var h=d.dgst;d=h;f=Error(p(419));d=mj(f,d,void 0);return Yj(a,b,g,d)}h=0!==(g&a.childLanes);if(rh||h){d=Q;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;
0!==e&&e!==f.retryLane&&(f.retryLane=e,wh(a,e),ui(d,a,e,-1))}Zj();d=mj(Error(p(421)));return Yj(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=ak.bind(null,a),e._reactRetry=b,null;a=f.treeContext;Mg=Zf(e.nextSibling);Lg=b;J=!0;Ng=null;null!==a&&(Cg[Dg++]=Fg,Cg[Dg++]=Gg,Cg[Dg++]=Eg,Fg=a.id,Gg=a.overflow,Eg=b);b=Wj(b,d.children);b.flags|=4096;return b}function bk(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);ph(a.return,b,c)}
function ck(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}
function dk(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Aj(a,b,d.children,c);d=L.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&bk(a,c,b);else if(19===a.tag)bk(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}H(L,d);if(0===(b.mode&1))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Qh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);ck(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Qh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}ck(b,!0,c,null,f);break;case "together":ck(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}
function Mj(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function Cj(a,b,c){null!==a&&(b.dependencies=a.dependencies);Wi=-1;Fh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=ch(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=ch(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}
function ek(a,b,c){switch(b.tag){case 3:Oj(b);Wg();break;case 5:Oh(b);break;case 1:mg(b.type)&&qg(b);break;case 4:Mh(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;H(jh,d._currentValue);d._currentValue=e;break;case 12:0!==(c&b.childLanes)&&(b.flags|=4);d=b.stateNode;d.effectDuration=0;d.passiveEffectDuration=0;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return H(L,L.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return Uj(a,
b,c);H(L,L.current&1);a=Cj(a,b,c);return null!==a?a.sibling:null}H(L,L.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return dk(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);H(L,L.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,Hj(a,b,c)}return Cj(a,b,c)}var fk,gk,hk,ik;
fk=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};gk=function(){};
hk=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;Lh(Ih.current);var f=null;switch(c){case "input":e=Ya(a,e);d=Ya(a,d);f=[];break;case "select":e=u({},e,{value:void 0});d=u({},d,{value:void 0});f=[];break;case "textarea":e=fb(a,e);d=fb(a,d);f=[];break;default:"function"!==typeof e.onClick&&"function"===typeof d.onClick&&(a.onclick=Pf)}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if("style"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&
(c||(c={}),c[g]="")}else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,
c)),c=k;else"dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(f=f||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(ea.hasOwnProperty(l)?(null!=k&&"onScroll"===l&&F("scroll",a),f||h===k||(f=[])):(f=f||[]).push(l,k))}c&&(f=f||[]).push("style",c);var l=f;if(b.updateQueue=l)b.flags|=4}};ik=function(a,b,c,d){c!==d&&(b.flags|=4)};
function jk(a,b){if(!J)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}
function S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)if(0!==(a.mode&2)){for(var e=a.selfBaseDuration,f=a.child;null!==f;)c|=f.lanes|f.childLanes,d|=f.subtreeFlags&14680064,d|=f.flags&14680064,e+=f.treeBaseDuration,f=f.sibling;a.treeBaseDuration=e}else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else if(0!==(a.mode&2)){e=a.actualDuration;f=a.selfBaseDuration;for(var g=a.child;null!==g;)c|=g.lanes|
g.childLanes,d|=g.subtreeFlags,d|=g.flags,e+=g.actualDuration,f+=g.treeBaseDuration,g=g.sibling;a.actualDuration=e;a.treeBaseDuration=f}else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}
function kk(a,b,c){var d=b.pendingProps;Kg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return mg(b.type)&&ng(),S(b),null;case 3:d=b.stateNode;Nh();G(jg);G(I);Sh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Ug(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==Ng&&(lk(Ng),Ng=null));gk(a,b);S(b);return null;case 5:Ph(b);var e=Lh(Kh.current);
c=b.type;if(null!==a&&null!=b.stateNode)hk(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=Lh(Ih.current);if(Ug(b)){d=b.stateNode;a=b.type;c=b.memoizedProps;d[bg]=b;d[cg]=c;var f=0!==(b.mode&1);switch(a){case "dialog":F("cancel",d);F("close",d);break;case "iframe":case "object":case "embed":F("load",d);break;case "video":case "audio":for(e=0;e<zf.length;e++)F(zf[e],d);break;case "source":F("error",d);break;case "img":case "image":case "link":F("error",
d);F("load",d);break;case "details":F("toggle",d);break;case "input":Za(d,c);F("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!c.multiple};F("invalid",d);break;case "textarea":gb(d,c),F("invalid",d)}ub(a,c);e=null;for(var g in c)if(c.hasOwnProperty(g)){var h=c[g];"children"===g?"string"===typeof h?d.textContent!==h&&(!0!==c.suppressHydrationWarning&&Of(d.textContent,h,f),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(!0!==c.suppressHydrationWarning&&Of(d.textContent,
h,f),e=["children",""+h]):ea.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&F("scroll",d)}switch(a){case "input":Va(d);cb(d,c,!0);break;case "textarea":Va(d);ib(d);break;case "select":case "option":break;default:"function"===typeof c.onClick&&(d.onclick=Pf)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===a&&(a=jb(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):
"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[bg]=b;a[cg]=d;fk(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":F("cancel",a);F("close",a);e=d;break;case "iframe":case "object":case "embed":F("load",a);e=d;break;case "video":case "audio":for(e=0;e<zf.length;e++)F(zf[e],a);e=d;break;case "source":F("error",a);e=d;break;case "img":case "image":case "link":F("error",
a);F("load",a);e=d;break;case "details":F("toggle",a);e=d;break;case "input":Za(a,d);e=Ya(a,d);F("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=u({},d,{value:void 0});F("invalid",a);break;case "textarea":gb(a,d);e=fb(a,d);F("invalid",a);break;default:e=d}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];"style"===f?sb(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):"children"===f?"string"===typeof k?("textarea"!==
c||""!==k)&&ob(a,k):"number"===typeof k&&ob(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(ea.hasOwnProperty(f)?null!=k&&"onScroll"===f&&F("scroll",a):null!=k&&ua(a,f,k,g))}switch(c){case "input":Va(a);cb(a,d,!1);break;case "textarea":Va(a);ib(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Sa(d.value));break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?eb(a,!!d.multiple,f,!1):null!=d.defaultValue&&eb(a,!!d.multiple,d.defaultValue,
!0);break;default:"function"===typeof e.onClick&&(a.onclick=Pf)}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}S(b);return null;case 6:if(a&&null!=b.stateNode)ik(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===b.stateNode)throw Error(p(166));a=Lh(Kh.current);Lh(Ih.current);if(Ug(b)){d=b.stateNode;a=b.memoizedProps;d[bg]=b;if(c=d.nodeValue!==a)if(f=
Lg,null!==f)switch(f.tag){case 3:Of(d.nodeValue,a,0!==(f.mode&1));break;case 5:!0!==f.memoizedProps.suppressHydrationWarning&&Of(d.nodeValue,a,0!==(f.mode&1))}c&&(b.flags|=4)}else d=(9===a.nodeType?a:a.ownerDocument).createTextNode(d),d[bg]=b,b.stateNode=d}S(b);return null;case 13:G(L);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(J&&null!==Mg&&0!==(b.mode&1)&&0===(b.flags&128))Vg(),Wg(),b.flags|=98560,f=!1;else if(f=Ug(b),null!==d&&null!==d.dehydrated){if(null===
a){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[bg]=b;S(b);0!==(b.mode&2)&&null!==d&&(f=b.child,null!==f&&(b.treeBaseDuration-=f.treeBaseDuration))}else Wg(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4,S(b),0!==(b.mode&2)&&null!==d&&(f=b.child,null!==f&&(b.treeBaseDuration-=f.treeBaseDuration));f=!1}else null!==Ng&&(lk(Ng),Ng=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,0!==(b.mode&2)&&dj(b),b;d=
null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(L.current&1)?0===T&&(T=3):Zj()));null!==b.updateQueue&&(b.flags|=4);S(b);0!==(b.mode&2)&&d&&(d=b.child,null!==d&&(b.treeBaseDuration-=d.treeBaseDuration));return null;case 4:return Nh(),gk(a,b),null===a&&Gf(b.stateNode.containerInfo),S(b),null;case 10:return oh(b.type._context),S(b),null;case 17:return mg(b.type)&&ng(),S(b),null;case 19:G(L);f=b.memoizedState;if(null===f)return S(b),null;d=0!==
(b.flags&128);g=f.rendering;if(null===g)if(d)jk(f,!1);else{if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Qh(a);if(null!==g){b.flags|=128;jk(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(a=b.child;null!==a;)c=a,g=d,c.flags&=14680066,f=c.alternate,null===f?(c.childLanes=0,c.lanes=g,c.child=null,c.subtreeFlags=0,c.memoizedProps=null,c.memoizedState=null,c.updateQueue=null,c.dependencies=null,c.stateNode=null,c.selfBaseDuration=0,c.treeBaseDuration=
0):(c.childLanes=f.childLanes,c.lanes=f.lanes,c.child=f.child,c.subtreeFlags=0,c.deletions=null,c.memoizedProps=f.memoizedProps,c.memoizedState=f.memoizedState,c.updateQueue=f.updateQueue,c.type=f.type,g=f.dependencies,c.dependencies=null===g?null:{lanes:g.lanes,firstContext:g.firstContext},c.selfBaseDuration=f.selfBaseDuration,c.treeBaseDuration=f.treeBaseDuration),a=a.sibling;H(L,L.current&1|2);return b.child}a=a.sibling}null!==f.tail&&A()>mk&&(b.flags|=128,d=!0,jk(f,!1),b.lanes=4194304)}else{if(!d)if(a=
Qh(g),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),jk(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!J)return S(b),null}else 2*A()-f.renderingStartTime>mk&&1073741824!==c&&(b.flags|=128,d=!0,jk(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(a=f.last,null!==a?a.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=b,f.tail=b.sibling,f.renderingStartTime=A(),b.sibling=null,a=L.current,H(L,d?a&1|2:a&1),b;S(b);
return null;case 22:case 23:return nk(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Jj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}
function ok(a,b){Kg(b);switch(b.tag){case 1:return mg(b.type)&&ng(),a=b.flags,a&65536?(b.flags=a&-65537|128,0!==(b.mode&2)&&dj(b),b):null;case 3:return Nh(),G(jg),G(I),Sh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Ph(b),null;case 13:G(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Wg()}a=b.flags;return a&65536?(b.flags=a&-65537|128,0!==(b.mode&2)&&dj(b),b):null;case 19:return G(L),null;case 4:return Nh(),null;
case 10:return oh(b.type._context),null;case 22:case 23:return nk(),null;case 24:return null;default:return null}}var pk=!1,qk=!1,rk="function"===typeof WeakSet?WeakSet:Set,U=null,sk=null,tk=null;function uk(a,b){b.props=a.memoizedProps;b.state=a.memoizedState;if(a.mode&2)try{cj(),b.componentWillUnmount()}finally{aj(a)}else b.componentWillUnmount()}
function vk(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{if(a.mode&2)try{cj(),c(null)}finally{aj(a)}else c(null)}catch(d){W(a,b,d)}else c.current=null}function wk(a,b,c){try{c()}catch(d){W(a,b,d)}}var xk=!1;
function yk(a,b){Qf=rd;a=$e();if(af(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(D){c=null;break a}var g=0,h=-1,k=-1,l=0,n=0,q=a,r=null;b:for(;;){for(var z;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=
q.nodeValue.length);if(null===(z=q.firstChild))break;r=q;q=z}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++n===d&&(k=g);if(null!==(z=q.nextSibling))break;q=r;r=q.parentNode}q=z}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Rf={focusedElem:a,selectionRange:c};rd=!1;for(U=b;null!==U;)if(b=U,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,U=a;else for(;null!==U;){b=U;try{var m=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;
case 1:if(null!==m){var w=m.memoizedProps,C=m.memoizedState,x=b.stateNode,y=x.getSnapshotBeforeUpdate(b.elementType===b.type?w:ej(b.type,w),C);x.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var v=b.stateNode.containerInfo;1===v.nodeType?v.textContent="":9===v.nodeType&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(D){W(b,b.return,D)}a=b.sibling;if(null!==a){a.return=b.return;U=a;break}U=b.return}m=xk;xk=!1;return m}
function zk(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&(0!==(a&8)?null!==B&&"function"===typeof B.markComponentPassiveEffectUnmountStarted&&B.markComponentPassiveEffectUnmountStarted(b):0!==(a&4)&&uc(b),wk(b,c,f),0!==(a&8)?null!==B&&"function"===typeof B.markComponentPassiveEffectUnmountStopped&&B.markComponentPassiveEffectUnmountStopped():0!==(a&4)&&vc())}e=e.next}while(e!==d)}}
function Ak(a,b){var c=b.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do{if((d.tag&a)===a){0!==(a&8)?null!==B&&"function"===typeof B.markComponentPassiveEffectMountStarted&&B.markComponentPassiveEffectMountStarted(b):0!==(a&4)&&null!==B&&"function"===typeof B.markComponentLayoutEffectMountStarted&&B.markComponentLayoutEffectMountStarted(b);var e=d.create;d.destroy=e();0!==(a&8)?null!==B&&"function"===typeof B.markComponentPassiveEffectMountStopped&&B.markComponentPassiveEffectMountStopped():
0!==(a&4)&&null!==B&&"function"===typeof B.markComponentLayoutEffectMountStopped&&B.markComponentLayoutEffectMountStopped()}d=d.next}while(d!==c)}}function Bk(a){var b=a.ref;if(null!==b){var c=a.stateNode;if("function"===typeof b)if(a.mode&2)try{cj(),b(c)}finally{aj(a)}else b(c);else b.current=c}}
function Ck(a){var b=a.alternate;null!==b&&(a.alternate=null,Ck(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[bg],delete b[cg],delete b[Cf],delete b[dg],delete b[eg]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Dk(a){return 5===a.tag||3===a.tag||4===a.tag}
function Ek(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Dk(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}
function Fk(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Pf));else if(4!==d&&(a=a.child,null!==a))for(Fk(a,b,c),a=a.sibling;null!==a;)Fk(a,b,c),a=a.sibling}
function Gk(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Gk(a,b,c),a=a.sibling;null!==a;)Gk(a,b,c),a=a.sibling}var X=null,Hk=!1;function Ik(a,b,c){for(c=c.child;null!==c;)Jk(a,b,c),c=c.sibling}
function Jk(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:qk||vk(c,b);case 6:var d=X,e=Hk;X=null;Ik(a,b,c);X=d;Hk=e;null!==X&&(Hk?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Hk?(a=X,c=c.stateNode,8===a.nodeType?Yf(a.parentNode,c):1===a.nodeType&&Yf(a,c),pd(a)):Yf(X,c.stateNode));break;case 4:d=X;e=Hk;X=c.stateNode.containerInfo;Hk=!0;
Ik(a,b,c);X=d;Hk=e;break;case 0:case 11:case 14:case 15:if(!qk&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?wk(c,b,g):0!==(f&4)&&(uc(c),c.mode&2?(cj(),wk(c,b,g),aj(c)):wk(c,b,g),vc()));e=e.next}while(e!==d)}Ik(a,b,c);break;case 1:if(!qk&&(vk(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{uk(c,d)}catch(h){W(c,b,h)}Ik(a,b,c);break;case 21:Ik(a,b,c);break;case 22:c.mode&1?(qk=(d=qk)||null!==c.memoizedState,
Ik(a,b,c),qk=d):Ik(a,b,c);break;default:Ik(a,b,c)}}function Kk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new rk);b.forEach(function(b){var d=Lk.bind(null,a,b);if(!c.has(b)){c.add(b);if(mc)if(null!==sk&&null!==tk)wj(tk,sk);else throw Error(p(413));b.then(d,d)}})}}function Mk(a,b,c){sk=c;tk=a;Nk(b,a);tk=sk=null}
function Ok(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Hk=!1;break a;case 3:X=h.stateNode.containerInfo;Hk=!0;break a;case 4:X=h.stateNode.containerInfo;Hk=!0;break a}h=h.return}if(null===X)throw Error(p(160));Jk(f,g,e);X=null;Hk=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(l){W(e,b,l)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)Nk(b,a),b=b.sibling}
function Nk(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:Ok(b,a);Pk(a);if(d&4){try{zk(3,a,a.return),Ak(3,a)}catch(m){W(a,a.return,m)}if(a.mode&2){try{cj(),zk(5,a,a.return)}catch(m){W(a,a.return,m)}aj(a)}else try{zk(5,a,a.return)}catch(m){W(a,a.return,m)}}break;case 1:Ok(b,a);Pk(a);d&512&&null!==c&&vk(c,c.return);break;case 5:Ok(b,a);Pk(a);d&512&&null!==c&&vk(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,"")}catch(m){W(a,a.return,m)}}if(d&4&&(e=a.stateNode,
null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&$a(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var n=k[g],q=k[g+1];"style"===n?sb(e,q):"dangerouslySetInnerHTML"===n?nb(e,q):"children"===n?ob(e,q):ua(e,n,q,l)}switch(h){case "input":ab(e,f);break;case "textarea":hb(e,f);break;case "select":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var z=f.value;
null!=z?eb(e,!!f.multiple,z,!1):r!==!!f.multiple&&(null!=f.defaultValue?eb(e,!!f.multiple,f.defaultValue,!0):eb(e,!!f.multiple,f.multiple?[]:"",!1))}e[cg]=f}catch(m){W(a,a.return,m)}}break;case 6:Ok(b,a);Pk(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(m){W(a,a.return,m)}}break;case 3:Ok(b,a);Pk(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{pd(b.containerInfo)}catch(m){W(a,a.return,m)}break;case 4:Ok(b,a);Pk(a);break;case 13:Ok(b,
a);Pk(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||null!==e.alternate&&null!==e.alternate.memoizedState||(Qk=A()));d&4&&Kk(a);break;case 22:n=null!==c&&null!==c.memoizedState;a.mode&1?(qk=(l=qk)||n,Ok(b,a),qk=l):Ok(b,a);Pk(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!n&&0!==(a.mode&1))for(U=a,n=a.child;null!==n;){for(q=U=n;null!==U;){r=U;z=r.child;switch(r.tag){case 0:case 11:case 14:case 15:if(r.mode&2)try{cj(),zk(4,r,r.return)}finally{aj(r)}else zk(4,
r,r.return);break;case 1:vk(r,r.return);d=r.stateNode;if("function"===typeof d.componentWillUnmount){c=r;b=r.return;try{uk(c,d)}catch(m){W(c,b,m)}}break;case 5:vk(r,r.return);break;case 22:if(null!==r.memoizedState){Rk(q);continue}}null!==z?(z.return=r,U=z):Rk(q)}n=n.sibling}a:for(n=null,q=a;;){if(5===q.tag){if(null===n){n=q;try{e=q.stateNode,l?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==
k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=rb("display",g))}catch(m){W(a,a.return,m)}}}else if(6===q.tag){if(null===n)try{q.stateNode.nodeValue=l?"":q.memoizedProps}catch(m){W(a,a.return,m)}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;n===q&&(n=null);q=q.return}n===q&&(n=null);q.sibling.return=q.return;q=q.sibling}}break;
case 19:Ok(b,a);Pk(a);d&4&&Kk(a);break;case 21:break;default:Ok(b,a),Pk(a)}}function Pk(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Dk(c)){var d=c;break a}c=c.return}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,""),d.flags&=-33);var f=Ek(a);Gk(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Ek(a);Fk(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}
function Sk(a,b,c){sk=c;tk=b;U=a;Tk(a,b,c);tk=sk=null}
function Tk(a,b,c){for(var d=0!==(a.mode&1);null!==U;){var e=U,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||pk;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||qk;h=pk;var l=qk;pk=g;if((qk=k)&&!l)for(U=e;null!==U;)g=U,k=g.child,22===g.tag&&null!==g.memoizedState?Uk(e):null!==k?(k.return=g,U=k):Uk(e);for(;null!==f;)U=f,Tk(f,b,c),f=f.sibling;U=e;pk=h;qk=l}Vk(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,U=f):Vk(a,b,c)}}
function Vk(a){for(;null!==U;){var b=U;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:if(!qk)if(b.mode&2)try{cj(),Ak(5,b)}finally{aj(b)}else Ak(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!qk)if(null===c)if(b.mode&2)try{cj(),d.componentDidMount()}finally{aj(b)}else d.componentDidMount();else{var e=b.elementType===b.type?c.memoizedProps:ej(b.type,c.memoizedProps),f=c.memoizedState;if(b.mode&2)try{cj(),d.componentDidUpdate(e,f,d.__reactInternalSnapshotBeforeUpdate)}finally{aj(b)}else d.componentDidUpdate(e,
f,d.__reactInternalSnapshotBeforeUpdate)}var g=b.updateQueue;null!==g&&Gh(b,g,d);break;case 3:var h=b.updateQueue;if(null!==h){var k=null;if(null!==b.child)switch(b.child.tag){case 5:k=b.child.stateNode;break;case 1:k=b.child.stateNode}Gh(b,h,k)}break;case 5:var l=b.stateNode;if(null===c&&b.flags&4){k=l;var n=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":n.autoFocus&&k.focus();break;case "img":n.src&&(k.src=n.src)}}break;case 6:break;case 4:break;case 12:var q=
b.memoizedProps,r=q.onCommit,z=q.onRender,m=b.stateNode.effectDuration;k=Ui;c=null===c?"mount":"update";Yi&&(c="nested-update");"function"===typeof z&&z(b.memoizedProps.id,c,b.actualDuration,b.treeBaseDuration,b.actualStartTime,k);"function"===typeof r&&r(b.memoizedProps.id,c,m,k);Wk(b);var w=b.return;a:for(;null!==w;){switch(w.tag){case 3:w.stateNode.effectDuration+=m;break a;case 12:w.stateNode.effectDuration+=m;break a}w=w.return}break;case 13:if(null===b.memoizedState){var C=b.alternate;if(null!==
C){var x=C.memoizedState;if(null!==x){var y=x.dehydrated;null!==y&&pd(y)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(p(163));}qk||b.flags&512&&Bk(b)}catch(v){W(b,b.return,v)}}if(b===a){U=null;break}k=b.sibling;if(null!==k){k.return=b.return;U=k;break}U=b.return}}function Rk(a){for(;null!==U;){var b=U;if(b===a){U=null;break}var c=b.sibling;if(null!==c){c.return=b.return;U=c;break}U=b.return}}
function Uk(a){for(;null!==U;){var b=U;try{switch(b.tag){case 0:case 11:case 15:if(b.mode&2)try{cj();var c=b.return;try{Ak(4,b)}catch(l){W(b,c,l)}}finally{aj(b)}else{var d=b.return;try{Ak(4,b)}catch(l){W(b,d,l)}}break;case 1:var e=b.stateNode;if("function"===typeof e.componentDidMount){var f=b.return;try{e.componentDidMount()}catch(l){W(b,f,l)}}var g=b.return;try{Bk(b)}catch(l){W(b,g,l)}break;case 5:var h=b.return;try{Bk(b)}catch(l){W(b,h,l)}}}catch(l){W(b,b.return,l)}if(b===a){U=null;break}var k=
b.sibling;if(null!==k){k.return=b.return;U=k;break}U=b.return}}var Xk=Math.ceil,Yk=va.ReactCurrentDispatcher,Zk=va.ReactCurrentOwner,$k=va.ReactCurrentBatchConfig,K=0,Q=null,Y=null,Z=0,Jj=0,Ij=hg(0),T=0,al=null,Fh=0,bl=0,cl=0,dl=null,el=null,Qk=0,mk=Infinity,fl=null,qj=!1,rj=null,tj=null,gl=!1,hl=null,il=0,jl=[],kl=0,ll=null,ml=-1,nl=0;function Ri(){return 0!==(K&6)?A():-1!==ml?ml:ml=A()}
function Oi(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Yg.transition)return 0===nl&&(nl=Kc()),nl;a=E;if(0!==a)return a;a=window.event;a=void 0===a?16:xd(a.type);return a}function ui(a,b,c,d){if(50<kl)throw kl=0,ll=null,Error(p(185));Mc(a,c,d);if(0===(K&2)||a!==Q)mc&&Pc(a,b,c),a===Q&&(0===(K&2)&&(bl|=c),4===T&&ol(a,Z)),pl(a,d),1===c&&0===K&&0===(b.mode&1)&&(mk=A()+500,tg&&xg())}
function pl(a,b){var c=a.callbackNode;Ic(a,b);var d=Gc(a,a===Q?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?wg(ql.bind(null,a)):vg(ql.bind(null,a)),Xf(function(){0===(K&6)&&xg()}),c=null;else{switch(Rc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc}c=rl(c,sl.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}
function sl(a,b){Zi=Yi=!1;ml=-1;nl=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(tl()&&a.callbackNode!==c)return null;var d=Gc(a,a===Q?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=ul(a,d);else{b=d;var e=K;K|=2;var f=vl();if(Q!==a||Z!==b){if(mc){var g=a.memoizedUpdaters;0<g.size&&(wj(a,Z),g.clear());Qc(a,b)}fl=null;mk=A()+500;wl(a,b)}wc(b);do try{xl();break}catch(h){yl(a,h)}while(1);nh();Yk.current=f;K=e;null!==Y?(null!==B&&"function"===typeof B.markRenderYielded&&
B.markRenderYielded(),b=0):(xc(),Q=null,Z=0,b=T)}if(0!==b){2===b&&(e=Jc(a),0!==e&&(d=e,b=zl(a,e)));if(1===b)throw c=al,wl(a,0),ol(a,d),pl(a,A()),c;if(6===b)ol(a,d);else{e=a.current.alternate;if(0===(d&30)&&!Al(e)&&(b=ul(a,d),2===b&&(f=Jc(a),0!==f&&(d=f,b=zl(a,f))),1===b))throw c=al,wl(a,0),ol(a,d),pl(a,A()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Cl(a,el,fl);break;case 3:ol(a,d);if((d&130023424)===d&&(b=Qk+500-A(),10<b)){if(0!==Gc(a,0))break;e=a.suspendedLanes;
if((e&d)!==d){Ri();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Tf(Cl.bind(null,a,el,fl),b);break}Cl(a,el,fl);break;case 4:ol(a,d);if((d&4194240)===d)break;b=a.eventTimes;for(e=-1;0<d;)g=31-Ac(d),f=1<<g,g=b[g],g>e&&(e=g),d&=~f;d=e;d=A()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*Xk(d/1960))-d;if(10<d){a.timeoutHandle=Tf(Cl.bind(null,a,el,fl),d);break}Cl(a,el,fl);break;case 5:Cl(a,el,fl);break;default:throw Error(p(329));}}}pl(a,A());return a.callbackNode===
c?sl.bind(null,a):null}function zl(a,b){var c=dl;a.current.memoizedState.isDehydrated&&(wl(a,b).flags|=256);a=ul(a,b);2!==a&&(b=el,el=c,null!==b&&lk(b));return a}function lk(a){null===el?el=a:el.push.apply(el,a)}
function Al(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!Ve(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}
function ol(a,b){b&=~cl;b&=~bl;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-Ac(b),d=1<<c;a[c]=-1;b&=~d}}function ql(a){Yi=Zi;Zi=!1;if(0!==(K&6))throw Error(p(327));tl();var b=Gc(a,0);if(0===(b&1))return pl(a,A()),null;var c=ul(a,b);if(0!==a.tag&&2===c){var d=Jc(a);0!==d&&(b=d,c=zl(a,d))}if(1===c)throw c=al,wl(a,0),ol(a,b),pl(a,A()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Cl(a,el,fl);pl(a,A());return null}
function Dl(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(mk=A()+500,tg&&xg())}}function El(a){null!==hl&&0===hl.tag&&0===(K&6)&&tl();var b=K;K|=1;var c=$k.transition,d=E;try{if($k.transition=null,E=1,a)return a()}finally{E=d,$k.transition=c,K=b,0===(K&6)&&xg()}}function nk(){Jj=Ij.current;G(Ij)}
function wl(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Uf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;Kg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&ng();break;case 3:Nh();G(jg);G(I);Sh();break;case 5:Ph(d);break;case 4:Nh();break;case 13:G(L);break;case 19:G(L);break;case 10:oh(d.type._context);break;case 22:case 23:nk()}c=c.return}Q=a;Y=a=ch(a.current,null);Z=Jj=b;T=0;al=null;cl=bl=Fh=0;el=dl=null;if(null!==th){for(b=
0;b<th.length;b++)if(c=th[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}th=null}return a}
function yl(a,b){do{var c=Y;try{nh();Th.current=ei;if(Wh){for(var d=M.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Wh=!1}Vh=0;O=N=M=null;Xh=!1;Yh=0;Zk.current=null;if(null===c||null===c.return){T=1;al=b;Y=null;break}c.mode&2&&$i(c,!0);tc();if(null!==b&&"object"===typeof b&&"function"===typeof b.then){var f=b;null!==B&&"function"===typeof B.markComponentSuspended&&B.markComponentSuspended(c,f,Z)}else null!==B&&"function"===typeof B.markComponentErrored&&B.markComponentErrored(c,
b,Z);a:{var g=a,h=c.return,k=c;f=b;b=Z;k.flags|=32768;mc&&wj(g,b);if(null!==f&&"object"===typeof f&&"function"===typeof f.then){var l=f,n=k,q=n.tag;if(0===(n.mode&1)&&(0===q||11===q||15===q)){var r=n.alternate;r?(n.updateQueue=r.updateQueue,n.memoizedState=r.memoizedState,n.lanes=r.lanes):(n.updateQueue=null,n.memoizedState=null)}var z=xj(h);if(null!==z){z.flags&=-257;yj(z,h,k,g,b);z.mode&1&&uj(g,l,b);b=z;f=l;var m=b.updateQueue;if(null===m){var w=new Set;w.add(f);b.updateQueue=w}else m.add(f);break a}else{if(0===
(b&1)){uj(g,l,b);Zj();break a}f=Error(p(426))}}else if(J&&k.mode&1){var C=xj(h);if(null!==C){0===(C.flags&65536)&&(C.flags|=256);yj(C,h,k,g,b);Xg(lj(f,k));break a}}g=f=lj(f,k);4!==T&&(T=2);null===dl?dl=[g]:dl.push(g);g=h;do{switch(g.tag){case 3:g.flags|=65536;b&=-b;g.lanes|=b;var x=pj(g,f,b);Dh(g,x);break a;case 1:k=f;var y=g.type,v=g.stateNode;if(0===(g.flags&128)&&("function"===typeof y.getDerivedStateFromError||null!==v&&"function"===typeof v.componentDidCatch&&(null===tj||!tj.has(v)))){g.flags|=
65536;b&=-b;g.lanes|=b;var D=sj(g,k,b);Dh(g,D);break a}}g=g.return}while(null!==g)}Fl(c)}catch(ca){b=ca;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function vl(){var a=Yk.current;Yk.current=ei;return null===a?ei:a}function Zj(){if(0===T||3===T||2===T)T=4;null===Q||0===(Fh&268435455)&&0===(bl&268435455)||ol(Q,Z)}
function ul(a,b){var c=K;K|=2;var d=vl();if(Q!==a||Z!==b){if(mc){var e=a.memoizedUpdaters;0<e.size&&(wj(a,Z),e.clear());Qc(a,b)}fl=null;wl(a,b)}wc(b);do try{Gl();break}catch(f){yl(a,f)}while(1);nh();K=c;Yk.current=d;if(null!==Y)throw Error(p(261));xc();Q=null;Z=0;return T}function Gl(){for(;null!==Y;)Hl(Y)}function xl(){for(;null!==Y&&!cc();)Hl(Y)}
function Hl(a){var b=a.alternate;0!==(a.mode&2)?(Wi=Ti(),0>a.actualStartTime&&(a.actualStartTime=Ti()),b=Il(b,a,Jj),$i(a,!0)):b=Il(b,a,Jj);a.memoizedProps=a.pendingProps;null===b?Fl(a):Y=b;Zk.current=null}
function Fl(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(0===(b.mode&2))c=kk(c,b,Jj);else{var d=b;Wi=Ti();0>d.actualStartTime&&(d.actualStartTime=Ti());c=kk(c,b,Jj);$i(b,!1)}if(null!==c){Y=c;return}}else{c=ok(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(0!==(b.mode&2)){$i(b,!1);c=b.actualDuration;for(d=b.child;null!==d;)c+=d.actualDuration,d=d.sibling;b.actualDuration=c}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{T=6;Y=null;return}}b=b.sibling;if(null!==
b){Y=b;return}Y=b=a}while(null!==b);0===T&&(T=5)}function Cl(a,b,c){var d=E,e=$k.transition;try{$k.transition=null,E=1,Jl(a,b,c,d)}finally{$k.transition=e,E=d}return null}
function Jl(a,b,c,d){do tl();while(null!==hl);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;null!==B&&"function"===typeof B.markCommitStarted&&B.markCommitStarted(e);if(null===c)return rc(),null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Nc(a,f);a===Q&&(Y=Q=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||gl||(gl=!0,rl(hc,function(){tl();return null}));f=0!==(c.flags&
15990);if(0!==(c.subtreeFlags&15990)||f){f=$k.transition;$k.transition=null;var g=E;E=1;var h=K;K|=4;Zk.current=null;yk(a,c);Ui=Ti();Mk(a,c,e);bf(Rf);rd=!!Qf;Rf=Qf=null;a.current=c;null!==B&&"function"===typeof B.markLayoutEffectsStarted&&B.markLayoutEffectsStarted(e);Sk(c,a,e);null!==B&&"function"===typeof B.markLayoutEffectsStopped&&B.markLayoutEffectsStopped();dc();K=h;E=g;$k.transition=f}else a.current=c,Ui=Ti();gl&&(gl=!1,hl=a,il=e);f=a.pendingLanes;0===f&&(tj=null);nc(c.stateNode,d);mc&&a.memoizedUpdaters.clear();
pl(a,A());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(qj)throw qj=!1,a=rj,rj=null,a;0!==(il&1)&&0!==a.tag&&tl();f=a.pendingLanes;0!==(f&1)?(Zi=!0,a===ll?kl++:(kl=0,ll=a)):kl=0;xg();rc();return null}
function tl(){if(null!==hl){var a=Rc(il),b=$k.transition,c=E;try{$k.transition=null;E=16>a?16:a;if(null===hl)var d=!1;else{a=hl;var e=il;hl=null;il=0;if(0!==(K&6))throw Error(p(331));null!==B&&"function"===typeof B.markPassiveEffectsStarted&&B.markPassiveEffectsStarted(e);e=K;K|=4;for(U=a.current;null!==U;){var f=U,g=f.child;if(0!==(U.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(U=l;null!==U;){var n=U,q=n;switch(q.tag){case 0:case 11:case 15:q.mode&2?(Xi=Ti(),
zk(8,q,f),bj(q)):zk(8,q,f)}var r=n.child;if(null!==r)r.return=n,U=r;else for(;null!==U;){n=U;var z=n.sibling,m=n.return;Ck(n);if(n===l){U=null;break}if(null!==z){z.return=m;U=z;break}U=m}}}var w=f.alternate;if(null!==w){var C=w.child;if(null!==C){w.child=null;do{var x=C.sibling;C.sibling=null;C=x}while(null!==C)}}U=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,U=g;else b:for(;null!==U;){f=U;if(0!==(f.flags&2048))switch(k=f,k.tag){case 0:case 11:case 15:k.mode&2?(Xi=Ti(),zk(9,k,k.return),bj(k)):
zk(9,k,k.return)}var y=f.sibling;if(null!==y){y.return=f.return;U=y;break b}U=f.return}}var v=a.current;for(U=v;null!==U;){g=U;var D=g.child;if(0!==(g.subtreeFlags&2064)&&null!==D)D.return=g,U=D;else b:for(g=v;null!==U;){h=U;if(0!==(h.flags&2048))try{switch(l=h,l.tag){case 0:case 11:case 15:if(l.mode&2){Xi=Ti();try{Ak(9,l)}finally{bj(l)}}else Ak(9,l)}}catch(Pj){W(h,h.return,Pj)}if(h===g){U=null;break b}var ca=h.sibling;if(null!==ca){ca.return=h.return;U=ca;break b}U=h.return}}v=jl;jl=[];for(D=0;D<
v.length;D++){var R=v[D];if(0!==(R.flags&4))switch(R.tag){case 12:var sa=R.stateNode.passiveEffectDuration,V=R.memoizedProps,Bl=V.id,yi=V.onPostCommit;ca=Ui;var zi=null===R.alternate?"mount":"update";Yi&&(zi="nested-update");"function"===typeof yi&&yi(Bl,zi,sa,ca);var lb=R.return;b:for(;null!==lb;){switch(lb.tag){case 3:lb.stateNode.passiveEffectDuration+=sa;break b;case 12:lb.stateNode.passiveEffectDuration+=sa;break b}lb=lb.return}}}null!==B&&"function"===typeof B.markPassiveEffectsStopped&&B.markPassiveEffectsStopped();
K=e;xg();if(lc&&"function"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a)}catch(Pj){}var Qj=a.current.stateNode;Qj.effectDuration=0;Qj.passiveEffectDuration=0;d=!0}return d}finally{E=c,$k.transition=b}}return!1}function Wk(a){jl.push(a);gl||(gl=!0,rl(hc,function(){tl();return null}))}function Kl(a,b,c){b=lj(c,b);b=pj(a,b,1);a=Bh(a,b,1);b=Ri();null!==a&&(Mc(a,1,b),pl(a,b))}
function W(a,b,c){if(3===a.tag)Kl(a,a,c);else for(;null!==b;){if(3===b.tag){Kl(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===tj||!tj.has(d))){a=lj(c,a);a=sj(b,a,1);b=Bh(b,a,1);a=Ri();null!==b&&(Mc(b,1,a),pl(b,a));break}}b=b.return}}
function vj(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=Ri();a.pingedLanes|=a.suspendedLanes&c;Q===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>A()-Qk?wl(a,0):cl|=c);pl(a,b)}function Ll(a,b){0===b&&(0===(a.mode&1)?b=1:(b=Ec,Ec<<=1,0===(Ec&130023424)&&(Ec=4194304)));var c=Ri();a=wh(a,b);null!==a&&(Mc(a,b,c),pl(a,c))}function ak(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Ll(a,c)}
function Lk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Ll(a,c)}var Il;
Il=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||jg.current)rh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return rh=!1,ek(a,b,c);rh=0!==(a.flags&131072)?!0:!1}else rh=!1,J&&0!==(b.flags&1048576)&&Ig(b,Bg,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;Mj(a,b);a=b.pendingProps;var e=lg(b,I.current);qh(b,c);sc(b);e=ai(null,b,d,a,e,c);var f=fi();tc();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=
null,mg(d)?(f=!0,qg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,yh(b),e.updater=gj,b.stateNode=e,e._reactInternals=b,kj(b,d,a,c),b=Nj(null,b,d,!0,f,c)):(b.tag=0,J&&f&&Jg(b),Aj(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{Mj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Ml(d);a=ej(d,a);switch(e){case 0:b=Gj(null,b,d,a,c);break a;case 1:b=Lj(null,b,d,a,c);break a;case 11:b=Bj(null,b,d,a,c);break a;case 14:b=Dj(null,b,d,ej(d.type,a),c);break a}throw Error(p(306,
d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ej(d,e),Gj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ej(d,e),Lj(a,b,d,e,c);case 3:a:{Oj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;zh(a,b);Eh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=
f,b.memoizedState=f,b.flags&256){e=lj(Error(p(423)),b);b=Rj(a,b,d,c,e);break a}else if(d!==e){e=lj(Error(p(424)),b);b=Rj(a,b,d,c,e);break a}else for(Mg=Zf(b.stateNode.containerInfo.firstChild),Lg=b,J=!0,Ng=null,c=ih(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Wg();if(d===e){b=Cj(a,b,c);break a}Aj(a,b,d,c)}b=b.child}return b;case 5:return Oh(b),null===a&&Sg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Sf(d,e)?g=null:null!==f&&Sf(d,f)&&(b.flags|=32),
Kj(a,b),Aj(a,b,g,c),b.child;case 6:return null===a&&Sg(b),null;case 13:return Uj(a,b,c);case 4:return Mh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=hh(b,null,d,c):Aj(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ej(d,e),Bj(a,b,d,e,c);case 7:return Aj(a,b,b.pendingProps,c),b.child;case 8:return Aj(a,b,b.pendingProps.children,c),b.child;case 12:return b.flags|=4,d=b.stateNode,d.effectDuration=0,d.passiveEffectDuration=0,Aj(a,b,b.pendingProps.children,
c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;H(jh,d._currentValue);d._currentValue=g;if(null!==f)if(Ve(f.value,g)){if(f.children===e.children&&!jg.current){b=Cj(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=Ah(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var n=l.pending;null===n?k.next=k:(k.next=n.next,n.next=
k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);ph(f.return,c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);ph(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Aj(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,
d=b.pendingProps.children,qh(b,c),e=sh(e),sc(b),d=d(e),tc(),b.flags|=1,Aj(a,b,d,c),b.child;case 14:return d=b.type,e=ej(d,b.pendingProps),e=ej(d.type,e),Dj(a,b,d,e,c);case 15:return Fj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ej(d,e),Mj(a,b),b.tag=1,mg(d)?(a=!0,qg(b)):a=!1,qh(b,c),ij(b,d,e),kj(b,d,e,c),Nj(null,b,d,!0,a,c);case 19:return dk(a,b,c);case 22:return Hj(a,b,c)}throw Error(p(156,b.tag));};
function wj(a,b){mc&&a.memoizedUpdaters.forEach(function(c){Pc(a,c,b)})}function rl(a,b){return ac(a,b)}
function Nl(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;this.actualDuration=0;this.actualStartTime=-1;this.treeBaseDuration=this.selfBaseDuration=0}function Pg(a,b,c,d){return new Nl(a,b,c,d)}
function Ej(a){a=a.prototype;return!(!a||!a.isReactComponent)}function Ml(a){if("function"===typeof a)return Ej(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}
function ch(a,b){var c=a.alternate;null===c?(c=Pg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null,c.actualDuration=0,c.actualStartTime=-1);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:
{lanes:b.lanes,firstContext:b.firstContext};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;c.selfBaseDuration=a.selfBaseDuration;c.treeBaseDuration=a.treeBaseDuration;return c}
function eh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Ej(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return gh(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Pg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a.stateNode={effectDuration:0,passiveEffectDuration:0},a;case Ea:return a=Pg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Pg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return Vj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=
10;break a;case Ca:g=9;break a;case Da:g=11;break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Pg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function gh(a,b,c,d){a=Pg(7,a,d,b);a.lanes=c;return a}function Vj(a,b,c,d){a=Pg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function dh(a,b,c){a=Pg(6,a,null,b);a.lanes=c;return a}
function fh(a,b,c){b=Pg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function Ol(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=Lc(0);this.expirationTimes=Lc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Lc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=
null;this.passiveEffectDuration=this.effectDuration=0;this.memoizedUpdaters=new Set;a=this.pendingUpdatersLaneMap=[];for(b=0;31>b;b++)a.push(new Set)}function Pl(a,b,c,d,e,f,g,h,k){a=new Ol(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;mc&&(b|=2);f=Pg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};yh(f);return a}
function Ql(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:xa,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}
function Rl(a){if(!a)return ig;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(mg(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(mg(c))return pg(a,c,b)}return b}
function Sl(a,b,c,d,e,f,g,h,k){a=Pl(c,d,!0,a,e,f,g,h,k);a.context=Rl(null);c=a.current;d=Ri();e=Oi(c);f=Ah(d,e);f.callback=void 0!==b&&null!==b?b:null;Bh(c,f,e);a.current.lanes=e;Mc(a,e,d);pl(a,d);return a}
function Tl(a,b,c,d){var e=b.current,f=Ri(),g=Oi(e);null!==B&&"function"===typeof B.markRenderScheduled&&B.markRenderScheduled(g);c=Rl(c);null===b.context?b.context=c:b.pendingContext=c;b=Ah(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=Bh(e,b,g);null!==a&&(ui(a,e,g,f),Ch(a,e,g));return g}function Ul(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}
function Vl(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function Wl(a,b){Vl(a,b);(a=a.alternate)&&Vl(a,b)}function Xl(){return null}var Yl="function"===typeof reportError?reportError:function(a){console.error(a)};function Zl(a){this._internalRoot=a}$l.prototype.render=Zl.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));Tl(a,b,null,null)};
$l.prototype.unmount=Zl.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;El(function(){Tl(null,a,null,null)});b[If]=null}};function $l(a){this._internalRoot=a}$l.prototype.unstable_scheduleHydration=function(a){if(a){var b=Vc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<dd.length&&0!==b&&b<dd[c].priority;c++);dd.splice(c,0,a);0===c&&id(a)}};function am(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}
function bm(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function cm(){}
function dm(a,b,c,d,e){if(e){if("function"===typeof d){var f=d;d=function(){var a=Ul(g);f.call(a)}}var g=Sl(b,d,a,0,null,!1,!1,"",cm);a._reactRootContainer=g;a[If]=g.current;Gf(8===a.nodeType?a.parentNode:a);El();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=Ul(k);h.call(a)}}var k=Pl(a,0,!1,null,null,!1,!1,"",cm);a._reactRootContainer=k;a[If]=k.current;Gf(8===a.nodeType?a.parentNode:a);El(function(){Tl(b,k,c,d)});return k}
function em(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===typeof e){var h=e;e=function(){var a=Ul(g);h.call(a)}}Tl(b,g,a,e)}else g=dm(c,b,a,e,d);return Ul(g)}Sc=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=Fc(b.pendingLanes);0!==c&&(Oc(b,c|1),pl(b,A()),0===(K&6)&&(mk=A()+500,xg()))}break;case 13:El(function(){var b=wh(a,1);if(null!==b){var c=Ri();ui(b,a,1,c)}}),Wl(a,1)}};
Tc=function(a){if(13===a.tag){var b=wh(a,134217728);if(null!==b){var c=Ri();ui(b,a,134217728,c)}Wl(a,134217728)}};Uc=function(a){if(13===a.tag){var b=Oi(a),c=wh(a,b);if(null!==c){var d=Ri();ui(c,a,b,d)}Wl(a,b)}};Vc=function(){return E};Wc=function(a,b){var c=E;try{return E=a,b()}finally{E=c}};
yb=function(a,b,c){switch(b){case "input":ab(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);ab(d,e)}}}break;case "textarea":hb(a,c);break;case "select":b=c.value,null!=b&&eb(a,!!c.multiple,b,!1)}};Gb=Dl;Hb=El;
var fm={usingClientEntryPoint:!1,Events:[Cb,Ie,Db,Eb,Fb,Dl]},gm={findFiberByHostInstance:jd,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"};
(function(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{a=u({},a,{getLaneLabelMap:pc,injectProfilingHooks:oc}),kc=b.inject(a),lc=b}catch(c){}return b.checkDCE?!0:!1})({bundleType:gm.bundleType,version:gm.version,rendererPackageName:gm.rendererPackageName,rendererConfig:gm.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,
overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:va.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:gm.findFiberByHostInstance||Xl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"});
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=fm;exports.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!am(b))throw Error(p(200));return Ql(a,b,null,c)};
exports.createRoot=function(a,b){if(!am(a))throw Error(p(299));var c=!1,d="",e=Yl;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=Pl(a,1,!1,null,null,c,!1,d,e);a[If]=b.current;Gf(8===a.nodeType?a.parentNode:a);return new Zl(b)};
exports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(",");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a){return El(a)};exports.hydrate=function(a,b,c){if(!bm(b))throw Error(p(200));return em(null,a,b,!0,c)};
exports.hydrateRoot=function(a,b,c){if(!am(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=!1,f="",g=Yl;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=Sl(b,null,a,1,null!=c?c:null,e,!1,f,g);a[If]=b.current;Gf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,
e);return new $l(b)};exports.render=function(a,b,c){if(!bm(b))throw Error(p(200));return em(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!bm(a))throw Error(p(40));return a._reactRootContainer?(El(function(){em(null,null,a,!1,function(){a._reactRootContainer=null;a[If]=null})}),!0):!1};exports.unstable_batchedUpdates=Dl;
exports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!bm(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return em(a,b,c,!1,d)};exports.version="18.3.1-next-f1338f8080-20240426";

          /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
        
MIT License

Copyright (c) React Training LLC 2015-2019
Copyright (c) Remix Software Inc. 2020-2021
Copyright (c) Shopify Inc. 2022-2023

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
  "name": "react-router",
  "version": "6.30.6",
  "description": "Declarative routing for React",
  "repository": {
    "type": "git",
    "url": "https://github.com/remix-run/react-router",
    "directory": "packages/react-router"
  },
  "license": "MIT",
  "author": "Remix Software <hello@remix.run>",
  "sideEffects": false,
  "main": "./dist/main.js",
  "unpkg": "./dist/umd/react-router.production.min.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "dependencies": {
    "@remix-run/router": "1.23.4"
  },
  "devDependencies": {
    "react": "^18.2.0",
    "react-router-dom": "6.30.6"
  },
  "peerDependencies": {
    "react": ">=16.8"
  },
  "files": [
    "dist/",
    "CHANGELOG.md",
    "LICENSE.md",
    "README.md"
  ],
  "engines": {
    "node": ">=14.0.0"
  }
}/**
 * React Router v6.30.6
 *
 * 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
 */
import * as React from 'react';
import { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';
export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, replace, resolvePath } from '@remix-run/router';

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}

// Create react-specific types from the agnostic types in @remix-run/router to
// export from react-router

const DataRouterContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  DataRouterContext.displayName = "DataRouter";
}
const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  DataRouterStateContext.displayName = "DataRouterState";
}
const AwaitContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  AwaitContext.displayName = "Await";
}

/**
 * A Navigator is a "location changer"; it's how you get to different locations.
 *
 * Every history instance conforms to the Navigator interface, but the
 * distinction is useful primarily when it comes to the low-level `<Router>` API
 * where both the location and a navigator must be provided separately in order
 * to avoid "tearing" that may occur in a suspense-enabled app if the action
 * and/or location were to be read directly from the history instance.
 */

const NavigationContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  NavigationContext.displayName = "Navigation";
}
const LocationContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  LocationContext.displayName = "Location";
}
const RouteContext = /*#__PURE__*/React.createContext({
  outlet: null,
  matches: [],
  isDataRoute: false
});
if (process.env.NODE_ENV !== "production") {
  RouteContext.displayName = "Route";
}
const RouteErrorContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
  RouteErrorContext.displayName = "RouteError";
}

/**
 * Returns the full href for the given "to" value. This is useful for building
 * custom links that are also accessible and preserve right-click behavior.
 *
 * @see https://reactrouter.com/v6/hooks/use-href
 */
function useHref(to, _temp) {
  let {
    relative
  } = _temp === void 0 ? {} : _temp;
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  "useHref() may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  let {
    basename,
    navigator
  } = React.useContext(NavigationContext);
  let {
    hash,
    pathname,
    search
  } = useResolvedPath(to, {
    relative
  });
  let joinedPathname = pathname;

  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the href.  If this is a root navigation, then just use the raw
  // basename which allows the basename to have full control over the presence
  // of a trailing slash on root links
  if (basename !== "/") {
    joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  }
  return navigator.createHref({
    pathname: joinedPathname,
    search,
    hash
  });
}

/**
 * Returns true if this component is a descendant of a `<Router>`.
 *
 * @see https://reactrouter.com/v6/hooks/use-in-router-context
 */
function useInRouterContext() {
  return React.useContext(LocationContext) != null;
}

/**
 * Returns the current location object, which represents the current URL in web
 * browsers.
 *
 * Note: If you're using this it may mean you're doing some of your own
 * "routing" in your app, and we'd like to know what your use case is. We may
 * be able to provide something higher-level to better suit your needs.
 *
 * @see https://reactrouter.com/v6/hooks/use-location
 */
function useLocation() {
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  "useLocation() may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  return React.useContext(LocationContext).location;
}

/**
 * Returns the current navigation action which describes how the router came to
 * the current location, either by a pop, push, or replace on the history stack.
 *
 * @see https://reactrouter.com/v6/hooks/use-navigation-type
 */
function useNavigationType() {
  return React.useContext(LocationContext).navigationType;
}

/**
 * Returns a PathMatch object if the given pattern matches the current URL.
 * This is useful for components that need to know "active" state, e.g.
 * `<NavLink>`.
 *
 * @see https://reactrouter.com/v6/hooks/use-match
 */
function useMatch(pattern) {
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  "useMatch() may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  let {
    pathname
  } = useLocation();
  return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);
}

/**
 * The interface for the navigate() function returned from useNavigate().
 */

const navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.";

// Mute warnings for calls to useNavigate in SSR environments
function useIsomorphicLayoutEffect(cb) {
  let isStatic = React.useContext(NavigationContext).static;
  if (!isStatic) {
    // We should be able to get rid of this once react 18.3 is released
    // See: https://github.com/facebook/react/pull/26395
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(cb);
  }
}

/**
 * Returns an imperative method for changing the location. Used by `<Link>`s, but
 * may also be used by other elements to change the location.
 *
 * @see https://reactrouter.com/v6/hooks/use-navigate
 */
function useNavigate() {
  let {
    isDataRoute
  } = React.useContext(RouteContext);
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  "useNavigate() may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  let dataRouterContext = React.useContext(DataRouterContext);
  let {
    basename,
    future,
    navigator
  } = React.useContext(NavigationContext);
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  let activeRef = React.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = React.useCallback(function (to, options) {
    if (options === void 0) {
      options = {};
    }
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;

    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our history listener yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      navigator.go(to);
      return;
    }
    let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");

    // If we're operating within a basename, prepend it to the pathname prior
    // to handing off to history (but only if we're not in a data router,
    // otherwise it'll prepend the basename inside of the router).
    // If this is a root navigation, then we navigate to the raw basename
    // which allows the basename to have full control over the presence of a
    // trailing slash on root links
    if (dataRouterContext == null && basename !== "/") {
      path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
    }
    (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
  return navigate;
}
const OutletContext = /*#__PURE__*/React.createContext(null);

/**
 * Returns the context (if provided) for the child route at this level of the route
 * hierarchy.
 * @see https://reactrouter.com/v6/hooks/use-outlet-context
 */
function useOutletContext() {
  return React.useContext(OutletContext);
}

/**
 * Returns the element for the child route at this level of the route
 * hierarchy. Used internally by `<Outlet>` to render child routes.
 *
 * @see https://reactrouter.com/v6/hooks/use-outlet
 */
function useOutlet(context) {
  let outlet = React.useContext(RouteContext).outlet;
  if (outlet) {
    return /*#__PURE__*/React.createElement(OutletContext.Provider, {
      value: context
    }, outlet);
  }
  return outlet;
}

/**
 * Returns an object of key/value pairs of the dynamic params from the current
 * URL that were matched by the route path.
 *
 * @see https://reactrouter.com/v6/hooks/use-params
 */
function useParams() {
  let {
    matches
  } = React.useContext(RouteContext);
  let routeMatch = matches[matches.length - 1];
  return routeMatch ? routeMatch.params : {};
}

/**
 * Resolves the pathname of the given `to` value against the current location.
 *
 * @see https://reactrouter.com/v6/hooks/use-resolved-path
 */
function useResolvedPath(to, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    future
  } = React.useContext(NavigationContext);
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}

/**
 * Returns the element of the route that matched the current location, prepared
 * with the correct context to render the remainder of the route tree. Route
 * elements in the tree must render an `<Outlet>` to render their child route's
 * element.
 *
 * @see https://reactrouter.com/v6/hooks/use-routes
 */
function useRoutes(routes, locationArg) {
  return useRoutesImpl(routes, locationArg);
}

// Internal implementation with accept optional param for RouterProvider usage
function useRoutesImpl(routes, locationArg, dataRouterState, future) {
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  "useRoutes() may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  let {
    navigator
  } = React.useContext(NavigationContext);
  let {
    matches: parentMatches
  } = React.useContext(RouteContext);
  let routeMatch = parentMatches[parentMatches.length - 1];
  let parentParams = routeMatch ? routeMatch.params : {};
  let parentPathname = routeMatch ? routeMatch.pathname : "/";
  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  let parentRoute = routeMatch && routeMatch.route;
  if (process.env.NODE_ENV !== "production") {
    // You won't get a warning about 2 different <Routes> under a <Route>
    // without a trailing *, but this is a best-effort warning anyway since we
    // cannot even give the warning unless they land at the parent route.
    //
    // Example:
    //
    // <Routes>
    //   {/* This route path MUST end with /* because otherwise
    //       it will never match /blog/post/123 */}
    //   <Route path="blog" element={<Blog />} />
    //   <Route path="blog/feed" element={<BlogFeed />} />
    // </Routes>
    //
    // function Blog() {
    //   return (
    //     <Routes>
    //       <Route path="post/:id" element={<Post />} />
    //     </Routes>
    //   );
    // }
    let parentPath = parentRoute && parentRoute.path || "";
    warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
  }
  let locationFromContext = useLocation();
  let location;
  if (locationArg) {
    var _parsedLocationArg$pa;
    let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
    !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop.")) : UNSAFE_invariant(false) : void 0;
    location = parsedLocationArg;
  } else {
    location = locationFromContext;
  }
  let pathname = location.pathname || "/";
  let remainingPathname = pathname;
  if (parentPathnameBase !== "/") {
    // Determine the remaining pathname by removing the # of URL segments the
    // parentPathnameBase has, instead of removing based on character count.
    // This is because we can't guarantee that incoming/outgoing encodings/
    // decodings will match exactly.
    // We decode paths before matching on a per-segment basis with
    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they
    // match what `window.location.pathname` would reflect.  Those don't 100%
    // align when it comes to encoded URI characters such as % and &.
    //
    // So we may end up with:
    //   pathname:           "/descendant/a%25b/match"
    //   parentPathnameBase: "/descendant/a%b"
    //
    // And the direct substring removal approach won't work :/
    let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
    let segments = pathname.replace(/^\//, "").split("/");
    remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  }
  let matches = matchRoutes(routes, {
    pathname: remainingPathname
  });
  if (process.env.NODE_ENV !== "production") {
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") : void 0;
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" " + "does not have an element or Component. This means it will render an <Outlet /> with a " + "null value by default resulting in an \"empty\" page.") : void 0;
  }
  let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
    params: Object.assign({}, parentParams, match.params),
    pathname: joinPaths([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
    pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
  })), parentMatches, dataRouterState, future);

  // When a user passes in a `locationArg`, the associated routes need to
  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
  // to use the scoped location instead of the global location.
  if (locationArg && renderedMatches) {
    return /*#__PURE__*/React.createElement(LocationContext.Provider, {
      value: {
        location: _extends({
          pathname: "/",
          search: "",
          hash: "",
          state: null,
          key: "default"
        }, location),
        navigationType: Action.Pop
      }
    }, renderedMatches);
  }
  return renderedMatches;
}
function DefaultErrorComponent() {
  let error = useRouteError();
  let message = isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
  let stack = error instanceof Error ? error.stack : null;
  let lightgrey = "rgba(200,200,200, 0.5)";
  let preStyles = {
    padding: "0.5rem",
    backgroundColor: lightgrey
  };
  let codeStyles = {
    padding: "2px 4px",
    backgroundColor: lightgrey
  };
  let devInfo = null;
  if (process.env.NODE_ENV !== "production") {
    console.error("Error handled by React Router default ErrorBoundary:", error);
    devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /*#__PURE__*/React.createElement("code", {
      style: codeStyles
    }, "ErrorBoundary"), " or", " ", /*#__PURE__*/React.createElement("code", {
      style: codeStyles
    }, "errorElement"), " prop on your route."));
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React.createElement("h3", {
    style: {
      fontStyle: "italic"
    }
  }, message), stack ? /*#__PURE__*/React.createElement("pre", {
    style: preStyles
  }, stack) : null, devInfo);
}
const defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);
class RenderErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: props.location,
      revalidation: props.revalidation,
      error: props.error
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error: error
    };
  }
  static getDerivedStateFromProps(props, state) {
    // When we get into an error state, the user will likely click "back" to the
    // previous page that didn't have an error. Because this wraps the entire
    // application, that will have no effect--the error page continues to display.
    // This gives us a mechanism to recover from the error when the location changes.
    //
    // Whether we're in an error state or not, we update the location in state
    // so that when we are in an error state, it gets reset when a new location
    // comes in and the user recovers from the error.
    if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
      return {
        error: props.error,
        location: props.location,
        revalidation: props.revalidation
      };
    }

    // If we're not changing locations, preserve the location but still surface
    // any new errors that may come through. We retain the existing error, we do
    // this because the error provided from the app state may be cleared without
    // the location changing.
    return {
      error: props.error !== undefined ? props.error : state.error,
      location: state.location,
      revalidation: props.revalidation || state.revalidation
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("React Router caught the following error during render", error, errorInfo);
  }
  render() {
    return this.state.error !== undefined ? /*#__PURE__*/React.createElement(RouteContext.Provider, {
      value: this.props.routeContext
    }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
      value: this.state.error,
      children: this.props.component
    })) : this.props.children;
  }
}
function RenderedRoute(_ref) {
  let {
    routeContext,
    match,
    children
  } = _ref;
  let dataRouterContext = React.useContext(DataRouterContext);

  // Track how deep we got in our render pass to emulate SSR componentDidCatch
  // in a DataStaticRouter
  if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  }
  return /*#__PURE__*/React.createElement(RouteContext.Provider, {
    value: routeContext
  }, children);
}
function _renderMatches(matches, parentMatches, dataRouterState, future) {
  var _dataRouterState;
  if (parentMatches === void 0) {
    parentMatches = [];
  }
  if (dataRouterState === void 0) {
    dataRouterState = null;
  }
  if (future === void 0) {
    future = null;
  }
  if (matches == null) {
    var _future;
    if (!dataRouterState) {
      return null;
    }
    if (dataRouterState.errors) {
      // Don't bail if we have data router errors so we can render them in the
      // boundary.  Use the pre-matched (or shimmed) matches
      matches = dataRouterState.matches;
    } else if ((_future = future) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
      // Don't bail if we're initializing with partial hydration and we have
      // router matches.  That means we're actively running `patchRoutesOnNavigation`
      // so we should render down the partial matches to the appropriate
      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it
      // only impacts the root matches for `RouterProvider` and no descendant
      // `<Routes>`
      matches = dataRouterState.matches;
    } else {
      return null;
    }
  }
  let renderedMatches = matches;

  // If we have data errors, trim matches to the highest error boundary
  let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;
  if (errors != null) {
    let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== undefined);
    !(errorIndex >= 0) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "Could not find a matching route for errors on route IDs: " + Object.keys(errors).join(",")) : UNSAFE_invariant(false) : void 0;
    renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  }

  // If we're in a partial hydration mode, detect if we need to render down to
  // a given HydrateFallback while we load the rest of the hydration data
  let renderFallback = false;
  let fallbackIndex = -1;
  if (dataRouterState && future && future.v7_partialHydration) {
    for (let i = 0; i < renderedMatches.length; i++) {
      let match = renderedMatches[i];
      // Track the deepest fallback up until the first route without data
      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
        fallbackIndex = i;
      }
      if (match.route.id) {
        let {
          loaderData,
          errors
        } = dataRouterState;
        let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);
        if (match.route.lazy || needsToRunLoader) {
          // We found the first route that's not ready to render (waiting on
          // lazy, or has a loader that hasn't run yet).  Flag that we need to
          // render a fallback and render up until the appropriate fallback
          renderFallback = true;
          if (fallbackIndex >= 0) {
            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
          } else {
            renderedMatches = [renderedMatches[0]];
          }
          break;
        }
      }
    }
  }
  return renderedMatches.reduceRight((outlet, match, index) => {
    // Only data routers handle errors/fallbacks
    let error;
    let shouldRenderHydrateFallback = false;
    let errorElement = null;
    let hydrateFallbackElement = null;
    if (dataRouterState) {
      error = errors && match.route.id ? errors[match.route.id] : undefined;
      errorElement = match.route.errorElement || defaultErrorElement;
      if (renderFallback) {
        if (fallbackIndex < 0 && index === 0) {
          warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = null;
        } else if (fallbackIndex === index) {
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = match.route.hydrateFallbackElement || null;
        }
      }
    }
    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
    let getChildren = () => {
      let children;
      if (error) {
        children = errorElement;
      } else if (shouldRenderHydrateFallback) {
        children = hydrateFallbackElement;
      } else if (match.route.Component) {
        // Note: This is a de-optimized path since React won't re-use the
        // ReactElement since it's identity changes with each new
        // React.createElement call.  We keep this so folks can use
        // `<Route Component={...}>` in `<Routes>` but generally `Component`
        // usage is only advised in `RouterProvider` when we can convert it to
        // `element` ahead of time.
        children = /*#__PURE__*/React.createElement(match.route.Component, null);
      } else if (match.route.element) {
        children = match.route.element;
      } else {
        children = outlet;
      }
      return /*#__PURE__*/React.createElement(RenderedRoute, {
        match: match,
        routeContext: {
          outlet,
          matches,
          isDataRoute: dataRouterState != null
        },
        children: children
      });
    };
    // Only wrap in an error boundary within data router usages when we have an
    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to
    // an ancestor ErrorBoundary/errorElement
    return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
      location: dataRouterState.location,
      revalidation: dataRouterState.revalidation,
      component: errorElement,
      error: error,
      children: getChildren(),
      routeContext: {
        outlet: null,
        matches,
        isDataRoute: true
      }
    }) : getChildren();
  }, null);
}
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
  DataRouterHook["UseBlocker"] = "useBlocker";
  DataRouterHook["UseRevalidator"] = "useRevalidator";
  DataRouterHook["UseNavigateStable"] = "useNavigate";
  return DataRouterHook;
}(DataRouterHook || {});
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
  DataRouterStateHook["UseBlocker"] = "useBlocker";
  DataRouterStateHook["UseLoaderData"] = "useLoaderData";
  DataRouterStateHook["UseActionData"] = "useActionData";
  DataRouterStateHook["UseRouteError"] = "useRouteError";
  DataRouterStateHook["UseNavigation"] = "useNavigation";
  DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
  DataRouterStateHook["UseMatches"] = "useMatches";
  DataRouterStateHook["UseRevalidator"] = "useRevalidator";
  DataRouterStateHook["UseNavigateStable"] = "useNavigate";
  DataRouterStateHook["UseRouteId"] = "useRouteId";
  return DataRouterStateHook;
}(DataRouterStateHook || {});
function getDataRouterConsoleError(hookName) {
  return hookName + " must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
  let ctx = React.useContext(DataRouterContext);
  !ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = React.useContext(DataRouterStateContext);
  !state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  return state;
}
function useRouteContext(hookName) {
  let route = React.useContext(RouteContext);
  !route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  return route;
}

// Internal version with hookName-aware debugging
function useCurrentRouteId(hookName) {
  let route = useRouteContext(hookName);
  let thisRoute = route.matches[route.matches.length - 1];
  !thisRoute.route.id ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : UNSAFE_invariant(false) : void 0;
  return thisRoute.route.id;
}

/**
 * Returns the ID for the nearest contextual route
 */
function useRouteId() {
  return useCurrentRouteId(DataRouterStateHook.UseRouteId);
}

/**
 * Returns the current navigation, defaulting to an "idle" navigation when
 * no navigation is in progress
 */
function useNavigation() {
  let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  return state.navigation;
}

/**
 * Returns a revalidate function for manually triggering revalidation, as well
 * as the current state of any manual revalidations
 */
function useRevalidator() {
  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  return React.useMemo(() => ({
    revalidate: dataRouterContext.router.revalidate,
    state: state.revalidation
  }), [dataRouterContext.router.revalidate, state.revalidation]);
}

/**
 * Returns the active route matches, useful for accessing loaderData for
 * parent/child routes or the route "handle" property
 */
function useMatches() {
  let {
    matches,
    loaderData
  } = useDataRouterState(DataRouterStateHook.UseMatches);
  return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
}

/**
 * Returns the loader data for the nearest ancestor Route loader
 */
function useLoaderData() {
  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  if (state.errors && state.errors[routeId] != null) {
    console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
    return undefined;
  }
  return state.loaderData[routeId];
}

/**
 * Returns the loaderData for the given routeId
 */
function useRouteLoaderData(routeId) {
  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  return state.loaderData[routeId];
}

/**
 * Returns the action data for the nearest ancestor Route action
 */
function useActionData() {
  let state = useDataRouterState(DataRouterStateHook.UseActionData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  return state.actionData ? state.actionData[routeId] : undefined;
}

/**
 * Returns the nearest ancestor Route error, which could be a loader/action
 * error or a render error.  This is intended to be called from your
 * ErrorBoundary/errorElement to display a proper error message.
 */
function useRouteError() {
  var _state$errors;
  let error = React.useContext(RouteErrorContext);
  let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);

  // If this was a render error, we put it in a RouteError context inside
  // of RenderErrorBoundary
  if (error !== undefined) {
    return error;
  }

  // Otherwise look for errors from our data router state
  return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
}

/**
 * Returns the happy-path data from the nearest ancestor `<Await />` value
 */
function useAsyncValue() {
  let value = React.useContext(AwaitContext);
  return value == null ? void 0 : value._data;
}

/**
 * Returns the error from the nearest ancestor `<Await />` value
 */
function useAsyncError() {
  let value = React.useContext(AwaitContext);
  return value == null ? void 0 : value._error;
}
let blockerId = 0;

/**
 * Allow the application to block navigations within the SPA and present the
 * user a confirmation dialog to confirm the navigation.  Mostly used to avoid
 * using half-filled form data.  This does not handle hard-reloads or
 * cross-origin navigations.
 */
function useBlocker(shouldBlock) {
  let {
    router,
    basename
  } = useDataRouterContext(DataRouterHook.UseBlocker);
  let state = useDataRouterState(DataRouterStateHook.UseBlocker);
  let [blockerKey, setBlockerKey] = React.useState("");
  let blockerFunction = React.useCallback(arg => {
    if (typeof shouldBlock !== "function") {
      return !!shouldBlock;
    }
    if (basename === "/") {
      return shouldBlock(arg);
    }

    // If they provided us a function and we've got an active basename, strip
    // it from the locations we expose to the user to match the behavior of
    // useLocation
    let {
      currentLocation,
      nextLocation,
      historyAction
    } = arg;
    return shouldBlock({
      currentLocation: _extends({}, currentLocation, {
        pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
      }),
      nextLocation: _extends({}, nextLocation, {
        pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
      }),
      historyAction
    });
  }, [basename, shouldBlock]);

  // This effect is in charge of blocker key assignment and deletion (which is
  // tightly coupled to the key)
  React.useEffect(() => {
    let key = String(++blockerId);
    setBlockerKey(key);
    return () => router.deleteBlocker(key);
  }, [router]);

  // This effect handles assigning the blockerFunction.  This is to handle
  // unstable blocker function identities, and happens only after the prior
  // effect so we don't get an orphaned blockerFunction in the router with a
  // key of "".  Until then we just have the IDLE_BLOCKER.
  React.useEffect(() => {
    if (blockerKey !== "") {
      router.getBlocker(blockerKey, blockerFunction);
    }
  }, [router, blockerKey, blockerFunction]);

  // Prefer the blocker from `state` not `router.state` since DataRouterContext
  // is memoized so this ensures we update on blocker state updates
  return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
}

/**
 * Stable version of useNavigate that is used when we are in the context of
 * a RouterProvider.
 */
function useNavigateStable() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseNavigateStable);
  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
  let activeRef = React.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = React.useCallback(function (to, options) {
    if (options === void 0) {
      options = {};
    }
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;

    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our router subscriber yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      router.navigate(to);
    } else {
      router.navigate(to, _extends({
        fromRouteId: id
      }, options));
    }
  }, [router, id]);
  return navigate;
}
const alreadyWarned$1 = {};
function warningOnce(key, cond, message) {
  if (!cond && !alreadyWarned$1[key]) {
    alreadyWarned$1[key] = true;
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, message) : void 0;
  }
}

const alreadyWarned = {};
function warnOnce(key, message) {
  if (process.env.NODE_ENV !== "production" && !alreadyWarned[message]) {
    alreadyWarned[message] = true;
    console.warn(message);
  }
}
const logDeprecation = (flag, msg, link) => warnOnce(flag, "\u26A0\uFE0F React Router Future Flag Warning: " + msg + ". " + ("You can use the `" + flag + "` future flag to opt-in early. ") + ("For more information, see " + link + "."));
function logV6DeprecationWarnings(renderFuture, routerFuture) {
  if ((renderFuture == null ? void 0 : renderFuture.v7_startTransition) === undefined) {
    logDeprecation("v7_startTransition", "React Router will begin wrapping state updates in `React.startTransition` in v7", "https://reactrouter.com/v6/upgrading/future#v7_starttransition");
  }
  if ((renderFuture == null ? void 0 : renderFuture.v7_relativeSplatPath) === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {
    logDeprecation("v7_relativeSplatPath", "Relative route resolution within Splat routes is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath");
  }
  if (routerFuture) {
    if (routerFuture.v7_fetcherPersist === undefined) {
      logDeprecation("v7_fetcherPersist", "The persistence behavior of fetchers is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist");
    }
    if (routerFuture.v7_normalizeFormMethod === undefined) {
      logDeprecation("v7_normalizeFormMethod", "Casing of `formMethod` fields is being normalized to uppercase in v7", "https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod");
    }
    if (routerFuture.v7_partialHydration === undefined) {
      logDeprecation("v7_partialHydration", "`RouterProvider` hydration behavior is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_partialhydration");
    }
    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {
      logDeprecation("v7_skipActionErrorRevalidation", "The revalidation behavior after 4xx/5xx `action` responses is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation");
    }
  }
}

/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];

/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider(_ref) {
  let {
    fallbackElement,
    router,
    future
  } = _ref;
  let [state, setStateImpl] = React.useState(router.state);
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    if (v7_startTransition && startTransitionImpl) {
      startTransitionImpl(() => setStateImpl(newState));
    } else {
      setStateImpl(newState);
    }
  }, [setStateImpl, v7_startTransition]);

  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  React.useEffect(() => {
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);
  React.useEffect(() => logV6DeprecationWarnings(future, router.future), [router, future]);

  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  }) : fallbackElement))), null);
}
function DataRoutes(_ref2) {
  let {
    routes,
    future,
    state
  } = _ref2;
  return useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` that stores all entries in memory.
 *
 * @see https://reactrouter.com/v6/router-components/memory-router
 */
function MemoryRouter(_ref3) {
  let {
    basename,
    children,
    initialEntries,
    initialIndex,
    future
  } = _ref3;
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createMemoryHistory({
      initialEntries,
      initialIndex,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * Changes the current location.
 *
 * Note: This API is mostly useful in React.Component subclasses that are not
 * able to use hooks. In functional components, we recommend you use the
 * `useNavigate` hook instead.
 *
 * @see https://reactrouter.com/v6/components/navigate
 */
function Navigate(_ref4) {
  let {
    to,
    replace,
    state,
    relative
  } = _ref4;
  !useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
  // the router loaded. We can help them understand how to avoid that.
  "<Navigate> may be used only in the context of a <Router> component.") : UNSAFE_invariant(false) : void 0;
  let {
    future,
    static: isStatic
  } = React.useContext(NavigationContext);
  process.env.NODE_ENV !== "production" ? UNSAFE_warning(!isStatic, "<Navigate> must not be used on the initial render in a <StaticRouter>. " + "This is a no-op, but you should modify your code so the <Navigate> is " + "only ever rendered in response to some user interaction or state change.") : void 0;
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let navigate = useNavigate();

  // Resolve the path outside of the effect so that when effects run twice in
  // StrictMode they navigate to the same place
  let path = resolveTo(to, UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
  let jsonPath = JSON.stringify(path);
  React.useEffect(() => navigate(JSON.parse(jsonPath), {
    replace,
    state,
    relative
  }), [navigate, jsonPath, relative, replace, state]);
  return null;
}
/**
 * Renders the child route's element, if there is one.
 *
 * @see https://reactrouter.com/v6/components/outlet
 */
function Outlet(props) {
  return useOutlet(props.context);
}
/**
 * Declares an element that should be rendered at a certain URL path.
 *
 * @see https://reactrouter.com/v6/components/route
 */
function Route(_props) {
  process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.") : UNSAFE_invariant(false) ;
}
/**
 * Provides location context for the rest of the app.
 *
 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
 * router that is more specific to your environment such as a `<BrowserRouter>`
 * in web browsers or a `<StaticRouter>` for server rendering.
 *
 * @see https://reactrouter.com/v6/router-components/router
 */
function Router(_ref5) {
  let {
    basename: basenameProp = "/",
    children = null,
    location: locationProp,
    navigationType = Action.Pop,
    navigator,
    static: staticProp = false,
    future
  } = _ref5;
  !!useInRouterContext() ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : UNSAFE_invariant(false) : void 0;

  // Preserve trailing slashes on basename, so we can let the user control
  // the enforcement of trailing slashes throughout the app
  let basename = basenameProp.replace(/^\/*/, "/");
  let navigationContext = React.useMemo(() => ({
    basename,
    navigator,
    static: staticProp,
    future: _extends({
      v7_relativeSplatPath: false
    }, future)
  }), [basename, future, navigator, staticProp]);
  if (typeof locationProp === "string") {
    locationProp = parsePath(locationProp);
  }
  let {
    pathname = "/",
    search = "",
    hash = "",
    state = null,
    key = "default"
  } = locationProp;
  let locationContext = React.useMemo(() => {
    let trailingPathname = stripBasename(pathname, basename);
    if (trailingPathname == null) {
      return null;
    }
    return {
      location: {
        pathname: trailingPathname,
        search,
        hash,
        state,
        key
      },
      navigationType
    };
  }, [basename, pathname, search, hash, state, key, navigationType]);
  process.env.NODE_ENV !== "production" ? UNSAFE_warning(locationContext != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") : void 0;
  if (locationContext == null) {
    return null;
  }
  return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
    value: navigationContext
  }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
    children: children,
    value: locationContext
  }));
}
/**
 * A container for a nested tree of `<Route>` elements that renders the branch
 * that best matches the current location.
 *
 * @see https://reactrouter.com/v6/components/routes
 */
function Routes(_ref6) {
  let {
    children,
    location
  } = _ref6;
  return useRoutes(createRoutesFromChildren(children), location);
}
/**
 * Component to use for rendering lazily loaded data from returning defer()
 * in a loader function
 */
function Await(_ref7) {
  let {
    children,
    errorElement,
    resolve
  } = _ref7;
  return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
    resolve: resolve,
    errorElement: errorElement
  }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
}
var AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {
  AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
  AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
  AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
  return AwaitRenderStatus;
}(AwaitRenderStatus || {});
const neverSettledPromise = new Promise(() => {});
class AwaitErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("<Await> caught the following error during render", error, errorInfo);
  }
  render() {
    let {
      children,
      errorElement,
      resolve
    } = this.props;
    let promise = null;
    let status = AwaitRenderStatus.pending;
    if (!(resolve instanceof Promise)) {
      // Didn't get a promise - provide as a resolved promise
      status = AwaitRenderStatus.success;
      promise = Promise.resolve();
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_data", {
        get: () => resolve
      });
    } else if (this.state.error) {
      // Caught a render error, provide it as a rejected promise
      status = AwaitRenderStatus.error;
      let renderError = this.state.error;
      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_error", {
        get: () => renderError
      });
    } else if (resolve._tracked) {
      // Already tracked promise - check contents
      promise = resolve;
      status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
    } else {
      // Raw (untracked) promise - track it
      status = AwaitRenderStatus.pending;
      Object.defineProperty(resolve, "_tracked", {
        get: () => true
      });
      promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
        get: () => data
      }), error => Object.defineProperty(resolve, "_error", {
        get: () => error
      }));
    }
    if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
      // Freeze the UI by throwing a never resolved promise
      throw neverSettledPromise;
    }
    if (status === AwaitRenderStatus.error && !errorElement) {
      // No errorElement, throw to the nearest route-level error boundary
      throw promise._error;
    }
    if (status === AwaitRenderStatus.error) {
      // Render via our errorElement
      return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
        value: promise,
        children: errorElement
      });
    }
    if (status === AwaitRenderStatus.success) {
      // Render children with resolved value
      return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
        value: promise,
        children: children
      });
    }

    // Throw to the suspense boundary
    throw promise;
  }
}

/**
 * @private
 * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
 */
function ResolveAwait(_ref8) {
  let {
    children
  } = _ref8;
  let data = useAsyncValue();
  let toRender = typeof children === "function" ? children(data) : children;
  return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
}

///////////////////////////////////////////////////////////////////////////////
// UTILS
///////////////////////////////////////////////////////////////////////////////

/**
 * Creates a route config from a React "children" object, which is usually
 * either a `<Route>` element or an array of them. Used internally by
 * `<Routes>` to create a route config from its children.
 *
 * @see https://reactrouter.com/v6/utils/create-routes-from-children
 */
function createRoutesFromChildren(children, parentPath) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  let routes = [];
  React.Children.forEach(children, (element, index) => {
    if (! /*#__PURE__*/React.isValidElement(element)) {
      // Ignore non-elements. This allows people to more easily inline
      // conditionals in their route config.
      return;
    }
    let treePath = [...parentPath, index];
    if (element.type === React.Fragment) {
      // Transparently support React.Fragment and its children.
      routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
      return;
    }
    !(element.type === Route) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "[" + (typeof element.type === "string" ? element.type : element.type.name) + "] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>") : UNSAFE_invariant(false) : void 0;
    !(!element.props.index || !element.props.children) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "An index route cannot have child routes.") : UNSAFE_invariant(false) : void 0;
    let route = {
      id: element.props.id || treePath.join("-"),
      caseSensitive: element.props.caseSensitive,
      element: element.props.element,
      Component: element.props.Component,
      index: element.props.index,
      path: element.props.path,
      loader: element.props.loader,
      action: element.props.action,
      errorElement: element.props.errorElement,
      ErrorBoundary: element.props.ErrorBoundary,
      hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
      shouldRevalidate: element.props.shouldRevalidate,
      handle: element.props.handle,
      lazy: element.props.lazy
    };
    if (element.props.children) {
      route.children = createRoutesFromChildren(element.props.children, treePath);
    }
    routes.push(route);
  });
  return routes;
}

/**
 * Renders the result of `matchRoutes()` into a React element.
 */
function renderMatches(matches) {
  return _renderMatches(matches);
}

function mapRouteProperties(route) {
  let updates = {
    // Note: this check also occurs in createRoutesFromChildren so update
    // there if you change this -- please and thank you!
    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  };
  if (route.Component) {
    if (process.env.NODE_ENV !== "production") {
      if (route.element) {
        process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") : void 0;
      }
    }
    Object.assign(updates, {
      element: /*#__PURE__*/React.createElement(route.Component),
      Component: undefined
    });
  }
  if (route.HydrateFallback) {
    if (process.env.NODE_ENV !== "production") {
      if (route.hydrateFallbackElement) {
        process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - " + "`HydrateFallback` will be used.") : void 0;
      }
    }
    Object.assign(updates, {
      hydrateFallbackElement: /*#__PURE__*/React.createElement(route.HydrateFallback),
      HydrateFallback: undefined
    });
  }
  if (route.ErrorBoundary) {
    if (process.env.NODE_ENV !== "production") {
      if (route.errorElement) {
        process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") : void 0;
      }
    }
    Object.assign(updates, {
      errorElement: /*#__PURE__*/React.createElement(route.ErrorBoundary),
      ErrorBoundary: undefined
    });
  }
  return updates;
}
function createMemoryRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createMemoryHistory({
      initialEntries: opts == null ? void 0 : opts.initialEntries,
      initialIndex: opts == null ? void 0 : opts.initialIndex
    }),
    hydrationData: opts == null ? void 0 : opts.hydrationData,
    routes,
    mapRouteProperties,
    dataStrategy: opts == null ? void 0 : opts.dataStrategy,
    patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation
  }).initialize();
}

export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sources":["../lib/context.ts","../lib/hooks.tsx","../lib/deprecations.ts","../lib/components.tsx","../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>ðŸ’¿ Hey developer ðŸ‘‹</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (__DEV__ && !alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `âš ï¸� React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (renderFuture?.v7_startTransition === undefined) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    renderFuture?.v7_relativeSplatPath === undefined &&\n    (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (routerFuture.v7_fetcherPersist === undefined) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (routerFuture.v7_normalizeFormMethod === undefined) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (routerFuture.v7_partialHydration === undefined) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n","import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n"],"names":["DataRouterContext","React","createContext","process","env","NODE_ENV","displayName","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useHref","to","_temp","relative","useInRouterContext","invariant","basename","navigator","useContext","hash","pathname","search","useResolvedPath","joinedPathname","joinPaths","createHref","useLocation","location","useNavigationType","navigationType","useMatch","pattern","useMemo","matchPath","decodePath","navigateEffectWarning","useIsomorphicLayoutEffect","cb","isStatic","static","useLayoutEffect","useNavigate","useNavigateStable","useNavigateUnstable","dataRouterContext","future","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","activeRef","useRef","current","navigate","useCallback","options","warning","go","path","resolveTo","parse","replace","push","state","OutletContext","useOutletContext","useOutlet","context","createElement","Provider","value","useParams","routeMatch","length","params","_temp2","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathname","parentPathnameBase","pathnameBase","parentRoute","route","parentPath","warningOnce","endsWith","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","segments","slice","join","matchRoutes","element","undefined","Component","lazy","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","_extends","key","NavigationType","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","lightgrey","preStyles","padding","backgroundColor","codeStyles","devInfo","console","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","constructor","props","revalidation","getDerivedStateFromError","getDerivedStateFromProps","componentDidCatch","errorInfo","render","routeContext","children","component","RenderedRoute","_ref","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","id","_dataRouterState","_future","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","keys","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","reduceRight","index","shouldRenderHydrateFallback","concat","getChildren","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","useDataRouterState","useRouteContext","useCurrentRouteId","thisRoute","useRouteId","UseRouteId","useNavigation","UseNavigation","navigation","useRevalidator","UseRevalidator","revalidate","router","useMatches","UseMatches","convertRouteMatchToUiMatch","useLoaderData","UseLoaderData","routeId","useRouteLoaderData","UseRouteLoaderData","useActionData","UseActionData","actionData","_state$errors","UseRouteError","useAsyncValue","_data","useAsyncError","_error","blockerId","useBlocker","shouldBlock","UseBlocker","blockerKey","setBlockerKey","useState","blockerFunction","arg","currentLocation","nextLocation","historyAction","stripBasename","useEffect","String","deleteBlocker","getBlocker","blockers","has","get","IDLE_BLOCKER","UseNavigateStable","fromRouteId","alreadyWarned","cond","warnOnce","warn","logDeprecation","flag","msg","link","logV6DeprecationWarnings","renderFuture","routerFuture","v7_startTransition","v7_fetcherPersist","v7_normalizeFormMethod","v7_skipActionErrorRevalidation","START_TRANSITION","startTransitionImpl","RouterProvider","fallbackElement","setStateImpl","setState","newState","subscribe","n","opts","preventScrollReset","Router","DataRoutes","_ref2","MemoryRouter","_ref3","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","action","listen","Navigate","_ref4","jsonPath","Outlet","Route","_props","_ref5","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","_ref6","createRoutesFromChildren","Await","_ref7","resolve","AwaitErrorBoundary","ResolveAwait","AwaitRenderStatus","neverSettledPromise","Promise","promise","pending","success","defineProperty","renderError","reject","catch","_tracked","then","data","AbortedDeferredError","_ref8","toRender","Children","forEach","isValidElement","treePath","type","apply","name","caseSensitive","hasErrorBoundary","shouldRevalidate","handle","renderMatches","mapRouteProperties","updates","createMemoryRouter","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgBA;AACA;;AA+DO,MAAMA,iBAAiB,gBAC5BC,KAAK,CAACC,aAAa,CAAiC,IAAI,EAAC;AAC3D,IAAAC,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAa,YAAA,EAAA;EACXL,iBAAiB,CAACM,WAAW,GAAG,YAAY,CAAA;AAC9C,CAAA;AAEO,MAAMC,sBAAsB,gBAAGN,KAAK,CAACC,aAAa,CAEvD,IAAI,EAAC;AACP,IAAAC,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAa,YAAA,EAAA;EACXE,sBAAsB,CAACD,WAAW,GAAG,iBAAiB,CAAA;AACxD,CAAA;AAEO,MAAME,YAAY,gBAAGP,KAAK,CAACC,aAAa,CAAwB,IAAI,CAAC,CAAA;AAC5E,IAAAC,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAa,YAAA,EAAA;EACXG,YAAY,CAACF,WAAW,GAAG,OAAO,CAAA;AACpC,CAAA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAmBO,MAAMG,iBAAiB,gBAAGR,KAAK,CAACC,aAAa,CAClD,IACF,EAAC;AAED,IAAAC,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAa,YAAA,EAAA;EACXI,iBAAiB,CAACH,WAAW,GAAG,YAAY,CAAA;AAC9C,CAAA;AAOO,MAAMI,eAAe,gBAAGT,KAAK,CAACC,aAAa,CAChD,IACF,EAAC;AAED,IAAAC,OAAA,CAAAC,GAAA,CAAAC,QAAA,KAAa,YAAA,EAAA;EACXK,eAAe,CAACJ,WAAW,GAAG,UAAU,CAAA;AAC1C,CAAA;MAQaK,YAAY,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A,CAAAA,GAAAA,IAAI,CAAEsE,YAAY;AAChCC,IAAAA,uBAAuB,EAAEvE,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEuE,uBAAAA;AACjC,GAAC,CAAC,CAACC,UAAU,EAAE,CAAA;AACjB;;;;"}/**
 * React Router v6.30.6
 *
 * 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
 */
'use strict';

/* eslint-env node */

if (process.env.NODE_ENV === "production") {
  module.exports = require("./umd/react-router.production.min.js");
} else {
  module.exports = require("./umd/react-router.development.js");
}
/**
 * React Router v6.30.6
 *
 * 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
 */
import * as React from 'react';
import { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';
export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, replace, resolvePath } from '@remix-run/router';

const DataRouterContext = /*#__PURE__*/React.createContext(null);
{
  DataRouterContext.displayName = "DataRouter";
}
const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
{
  DataRouterStateContext.displayName = "DataRouterState";
}
const AwaitContext = /*#__PURE__*/React.createContext(null);
{
  AwaitContext.displayName = "Await";
}
const NavigationContext = /*#__PURE__*/React.createContext(null);
{
  NavigationContext.displayName = "Navigation";
}
const LocationContext = /*#__PURE__*/React.createContext(null);
{
  LocationContext.displayName = "Location";
}
const RouteContext = /*#__PURE__*/React.createContext({
  outlet: null,
  matches: [],
  isDataRoute: false
});
{
  RouteContext.displayName = "Route";
}
const RouteErrorContext = /*#__PURE__*/React.createContext(null);
{
  RouteErrorContext.displayName = "RouteError";
}

/**
 * Returns the full href for the given "to" value. This is useful for building
 * custom links that are also accessible and preserve right-click behavior.
 *
 * @see https://reactrouter.com/v6/hooks/use-href
 */
function useHref(to, {
  relative
} = {}) {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  `useHref() may be used only in the context of a <Router> component.`)  : void 0;
  let {
    basename,
    navigator
  } = React.useContext(NavigationContext);
  let {
    hash,
    pathname,
    search
  } = useResolvedPath(to, {
    relative
  });
  let joinedPathname = pathname;
  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the href.  If this is a root navigation, then just use the raw
  // basename which allows the basename to have full control over the presence
  // of a trailing slash on root links
  if (basename !== "/") {
    joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  }
  return navigator.createHref({
    pathname: joinedPathname,
    search,
    hash
  });
}
/**
 * Returns true if this component is a descendant of a `<Router>`.
 *
 * @see https://reactrouter.com/v6/hooks/use-in-router-context
 */
function useInRouterContext() {
  return React.useContext(LocationContext) != null;
}
/**
 * Returns the current location object, which represents the current URL in web
 * browsers.
 *
 * Note: If you're using this it may mean you're doing some of your own
 * "routing" in your app, and we'd like to know what your use case is. We may
 * be able to provide something higher-level to better suit your needs.
 *
 * @see https://reactrouter.com/v6/hooks/use-location
 */
function useLocation() {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  `useLocation() may be used only in the context of a <Router> component.`)  : void 0;
  return React.useContext(LocationContext).location;
}
/**
 * Returns the current navigation action which describes how the router came to
 * the current location, either by a pop, push, or replace on the history stack.
 *
 * @see https://reactrouter.com/v6/hooks/use-navigation-type
 */
function useNavigationType() {
  return React.useContext(LocationContext).navigationType;
}
/**
 * Returns a PathMatch object if the given pattern matches the current URL.
 * This is useful for components that need to know "active" state, e.g.
 * `<NavLink>`.
 *
 * @see https://reactrouter.com/v6/hooks/use-match
 */
function useMatch(pattern) {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  `useMatch() may be used only in the context of a <Router> component.`)  : void 0;
  let {
    pathname
  } = useLocation();
  return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);
}
const navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`;
// Mute warnings for calls to useNavigate in SSR environments
function useIsomorphicLayoutEffect(cb) {
  let isStatic = React.useContext(NavigationContext).static;
  if (!isStatic) {
    // We should be able to get rid of this once react 18.3 is released
    // See: https://github.com/facebook/react/pull/26395
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(cb);
  }
}
/**
 * Returns an imperative method for changing the location. Used by `<Link>`s, but
 * may also be used by other elements to change the location.
 *
 * @see https://reactrouter.com/v6/hooks/use-navigate
 */
function useNavigate() {
  let {
    isDataRoute
  } = React.useContext(RouteContext);
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  `useNavigate() may be used only in the context of a <Router> component.`)  : void 0;
  let dataRouterContext = React.useContext(DataRouterContext);
  let {
    basename,
    future,
    navigator
  } = React.useContext(NavigationContext);
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  let activeRef = React.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = React.useCallback((to, options = {}) => {
    UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our history listener yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      navigator.go(to);
      return;
    }
    let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
    // If we're operating within a basename, prepend it to the pathname prior
    // to handing off to history (but only if we're not in a data router,
    // otherwise it'll prepend the basename inside of the router).
    // If this is a root navigation, then we navigate to the raw basename
    // which allows the basename to have full control over the presence of a
    // trailing slash on root links
    if (dataRouterContext == null && basename !== "/") {
      path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
    }
    (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
  return navigate;
}
const OutletContext = /*#__PURE__*/React.createContext(null);
/**
 * Returns the context (if provided) for the child route at this level of the route
 * hierarchy.
 * @see https://reactrouter.com/v6/hooks/use-outlet-context
 */
function useOutletContext() {
  return React.useContext(OutletContext);
}
/**
 * Returns the element for the child route at this level of the route
 * hierarchy. Used internally by `<Outlet>` to render child routes.
 *
 * @see https://reactrouter.com/v6/hooks/use-outlet
 */
function useOutlet(context) {
  let outlet = React.useContext(RouteContext).outlet;
  if (outlet) {
    return /*#__PURE__*/React.createElement(OutletContext.Provider, {
      value: context
    }, outlet);
  }
  return outlet;
}
/**
 * Returns an object of key/value pairs of the dynamic params from the current
 * URL that were matched by the route path.
 *
 * @see https://reactrouter.com/v6/hooks/use-params
 */
function useParams() {
  let {
    matches
  } = React.useContext(RouteContext);
  let routeMatch = matches[matches.length - 1];
  return routeMatch ? routeMatch.params : {};
}
/**
 * Resolves the pathname of the given `to` value against the current location.
 *
 * @see https://reactrouter.com/v6/hooks/use-resolved-path
 */
function useResolvedPath(to, {
  relative
} = {}) {
  let {
    future
  } = React.useContext(NavigationContext);
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}
/**
 * Returns the element of the route that matched the current location, prepared
 * with the correct context to render the remainder of the route tree. Route
 * elements in the tree must render an `<Outlet>` to render their child route's
 * element.
 *
 * @see https://reactrouter.com/v6/hooks/use-routes
 */
function useRoutes(routes, locationArg) {
  return useRoutesImpl(routes, locationArg);
}
// Internal implementation with accept optional param for RouterProvider usage
function useRoutesImpl(routes, locationArg, dataRouterState, future) {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of the
  // router loaded. We can help them understand how to avoid that.
  `useRoutes() may be used only in the context of a <Router> component.`)  : void 0;
  let {
    navigator
  } = React.useContext(NavigationContext);
  let {
    matches: parentMatches
  } = React.useContext(RouteContext);
  let routeMatch = parentMatches[parentMatches.length - 1];
  let parentParams = routeMatch ? routeMatch.params : {};
  let parentPathname = routeMatch ? routeMatch.pathname : "/";
  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  let parentRoute = routeMatch && routeMatch.route;
  {
    // You won't get a warning about 2 different <Routes> under a <Route>
    // without a trailing *, but this is a best-effort warning anyway since we
    // cannot even give the warning unless they land at the parent route.
    //
    // Example:
    //
    // <Routes>
    //   {/* This route path MUST end with /* because otherwise
    //       it will never match /blog/post/123 */}
    //   <Route path="blog" element={<Blog />} />
    //   <Route path="blog/feed" element={<BlogFeed />} />
    // </Routes>
    //
    // function Blog() {
    //   return (
    //     <Routes>
    //       <Route path="post/:id" element={<Post />} />
    //     </Routes>
    //   );
    // }
    let parentPath = parentRoute && parentRoute.path || "";
    warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), `You rendered descendant <Routes> (or called \`useRoutes()\`) at ` + `"${parentPathname}" (under <Route path="${parentPath}">) but the ` + `parent route path has no trailing "*". This means if you navigate ` + `deeper, the parent won't match anymore and therefore the child ` + `routes will never render.\n\n` + `Please change the parent <Route path="${parentPath}"> to <Route ` + `path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`);
  }
  let locationFromContext = useLocation();
  let location;
  if (locationArg) {
    let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
    !(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase)) ? UNSAFE_invariant(false, `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, ` + `the location pathname must begin with the portion of the URL pathname that was ` + `matched by all parent routes. The current pathname base is "${parentPathnameBase}" ` + `but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`)  : void 0;
    location = parsedLocationArg;
  } else {
    location = locationFromContext;
  }
  let pathname = location.pathname || "/";
  let remainingPathname = pathname;
  if (parentPathnameBase !== "/") {
    // Determine the remaining pathname by removing the # of URL segments the
    // parentPathnameBase has, instead of removing based on character count.
    // This is because we can't guarantee that incoming/outgoing encodings/
    // decodings will match exactly.
    // We decode paths before matching on a per-segment basis with
    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they
    // match what `window.location.pathname` would reflect.  Those don't 100%
    // align when it comes to encoded URI characters such as % and &.
    //
    // So we may end up with:
    //   pathname:           "/descendant/a%25b/match"
    //   parentPathnameBase: "/descendant/a%b"
    //
    // And the direct substring removal approach won't work :/
    let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
    let segments = pathname.replace(/^\//, "").split("/");
    remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  }
  let matches = matchRoutes(routes, {
    pathname: remainingPathname
  });
  {
    UNSAFE_warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
    UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" ` + `does not have an element or Component. This means it will render an <Outlet /> with a ` + `null value by default resulting in an "empty" page.`) ;
  }
  let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
    params: Object.assign({}, parentParams, match.params),
    pathname: joinPaths([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
    pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
  })), parentMatches, dataRouterState, future);
  // When a user passes in a `locationArg`, the associated routes need to
  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
  // to use the scoped location instead of the global location.
  if (locationArg && renderedMatches) {
    return /*#__PURE__*/React.createElement(LocationContext.Provider, {
      value: {
        location: {
          pathname: "/",
          search: "",
          hash: "",
          state: null,
          key: "default",
          ...location
        },
        navigationType: Action.Pop
      }
    }, renderedMatches);
  }
  return renderedMatches;
}
function DefaultErrorComponent() {
  let error = useRouteError();
  let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
  let stack = error instanceof Error ? error.stack : null;
  let lightgrey = "rgba(200,200,200, 0.5)";
  let preStyles = {
    padding: "0.5rem",
    backgroundColor: lightgrey
  };
  let codeStyles = {
    padding: "2px 4px",
    backgroundColor: lightgrey
  };
  let devInfo = null;
  {
    console.error("Error handled by React Router default ErrorBoundary:", error);
    devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /*#__PURE__*/React.createElement("code", {
      style: codeStyles
    }, "ErrorBoundary"), " or", " ", /*#__PURE__*/React.createElement("code", {
      style: codeStyles
    }, "errorElement"), " prop on your route."));
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React.createElement("h3", {
    style: {
      fontStyle: "italic"
    }
  }, message), stack ? /*#__PURE__*/React.createElement("pre", {
    style: preStyles
  }, stack) : null, devInfo);
}
const defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);
class RenderErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: props.location,
      revalidation: props.revalidation,
      error: props.error
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error: error
    };
  }
  static getDerivedStateFromProps(props, state) {
    // When we get into an error state, the user will likely click "back" to the
    // previous page that didn't have an error. Because this wraps the entire
    // application, that will have no effect--the error page continues to display.
    // This gives us a mechanism to recover from the error when the location changes.
    //
    // Whether we're in an error state or not, we update the location in state
    // so that when we are in an error state, it gets reset when a new location
    // comes in and the user recovers from the error.
    if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
      return {
        error: props.error,
        location: props.location,
        revalidation: props.revalidation
      };
    }
    // If we're not changing locations, preserve the location but still surface
    // any new errors that may come through. We retain the existing error, we do
    // this because the error provided from the app state may be cleared without
    // the location changing.
    return {
      error: props.error !== undefined ? props.error : state.error,
      location: state.location,
      revalidation: props.revalidation || state.revalidation
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("React Router caught the following error during render", error, errorInfo);
  }
  render() {
    return this.state.error !== undefined ? (/*#__PURE__*/React.createElement(RouteContext.Provider, {
      value: this.props.routeContext
    }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
      value: this.state.error,
      children: this.props.component
    }))) : this.props.children;
  }
}
function RenderedRoute({
  routeContext,
  match,
  children
}) {
  let dataRouterContext = React.useContext(DataRouterContext);
  // Track how deep we got in our render pass to emulate SSR componentDidCatch
  // in a DataStaticRouter
  if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  }
  return /*#__PURE__*/React.createElement(RouteContext.Provider, {
    value: routeContext
  }, children);
}
function _renderMatches(matches, parentMatches = [], dataRouterState = null, future = null) {
  if (matches == null) {
    if (!dataRouterState) {
      return null;
    }
    if (dataRouterState.errors) {
      // Don't bail if we have data router errors so we can render them in the
      // boundary.  Use the pre-matched (or shimmed) matches
      matches = dataRouterState.matches;
    } else if (future?.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
      // Don't bail if we're initializing with partial hydration and we have
      // router matches.  That means we're actively running `patchRoutesOnNavigation`
      // so we should render down the partial matches to the appropriate
      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it
      // only impacts the root matches for `RouterProvider` and no descendant
      // `<Routes>`
      matches = dataRouterState.matches;
    } else {
      return null;
    }
  }
  let renderedMatches = matches;
  // If we have data errors, trim matches to the highest error boundary
  let errors = dataRouterState?.errors;
  if (errors != null) {
    let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id] !== undefined);
    !(errorIndex >= 0) ? UNSAFE_invariant(false, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`)  : void 0;
    renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  }
  // If we're in a partial hydration mode, detect if we need to render down to
  // a given HydrateFallback while we load the rest of the hydration data
  let renderFallback = false;
  let fallbackIndex = -1;
  if (dataRouterState && future && future.v7_partialHydration) {
    for (let i = 0; i < renderedMatches.length; i++) {
      let match = renderedMatches[i];
      // Track the deepest fallback up until the first route without data
      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
        fallbackIndex = i;
      }
      if (match.route.id) {
        let {
          loaderData,
          errors: _errors
        } = dataRouterState;
        let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!_errors || _errors[match.route.id] === undefined);
        if (match.route.lazy || needsToRunLoader) {
          // We found the first route that's not ready to render (waiting on
          // lazy, or has a loader that hasn't run yet).  Flag that we need to
          // render a fallback and render up until the appropriate fallback
          renderFallback = true;
          if (fallbackIndex >= 0) {
            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
          } else {
            renderedMatches = [renderedMatches[0]];
          }
          break;
        }
      }
    }
  }
  return renderedMatches.reduceRight((outlet, match, index) => {
    // Only data routers handle errors/fallbacks
    let error;
    let shouldRenderHydrateFallback = false;
    let errorElement = null;
    let hydrateFallbackElement = null;
    if (dataRouterState) {
      error = errors && match.route.id ? errors[match.route.id] : undefined;
      errorElement = match.route.errorElement || defaultErrorElement;
      if (renderFallback) {
        if (fallbackIndex < 0 && index === 0) {
          warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = null;
        } else if (fallbackIndex === index) {
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = match.route.hydrateFallbackElement || null;
        }
      }
    }
    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
    let getChildren = () => {
      let children;
      if (error) {
        children = errorElement;
      } else if (shouldRenderHydrateFallback) {
        children = hydrateFallbackElement;
      } else if (match.route.Component) {
        // Note: This is a de-optimized path since React won't re-use the
        // ReactElement since it's identity changes with each new
        // React.createElement call.  We keep this so folks can use
        // `<Route Component={...}>` in `<Routes>` but generally `Component`
        // usage is only advised in `RouterProvider` when we can convert it to
        // `element` ahead of time.
        children = /*#__PURE__*/React.createElement(match.route.Component, null);
      } else if (match.route.element) {
        children = match.route.element;
      } else {
        children = outlet;
      }
      return /*#__PURE__*/React.createElement(RenderedRoute, {
        match: match,
        routeContext: {
          outlet,
          matches,
          isDataRoute: dataRouterState != null
        },
        children: children
      });
    };
    // Only wrap in an error boundary within data router usages when we have an
    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to
    // an ancestor ErrorBoundary/errorElement
    return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (/*#__PURE__*/React.createElement(RenderErrorBoundary, {
      location: dataRouterState.location,
      revalidation: dataRouterState.revalidation,
      component: errorElement,
      error: error,
      children: getChildren(),
      routeContext: {
        outlet: null,
        matches,
        isDataRoute: true
      }
    })) : getChildren();
  }, null);
}
var DataRouterHook;
(function (DataRouterHook) {
  DataRouterHook["UseBlocker"] = "useBlocker";
  DataRouterHook["UseRevalidator"] = "useRevalidator";
  DataRouterHook["UseNavigateStable"] = "useNavigate";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
  DataRouterStateHook["UseBlocker"] = "useBlocker";
  DataRouterStateHook["UseLoaderData"] = "useLoaderData";
  DataRouterStateHook["UseActionData"] = "useActionData";
  DataRouterStateHook["UseRouteError"] = "useRouteError";
  DataRouterStateHook["UseNavigation"] = "useNavigation";
  DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
  DataRouterStateHook["UseMatches"] = "useMatches";
  DataRouterStateHook["UseRevalidator"] = "useRevalidator";
  DataRouterStateHook["UseNavigateStable"] = "useNavigate";
  DataRouterStateHook["UseRouteId"] = "useRouteId";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function getDataRouterConsoleError(hookName) {
  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
  let ctx = React.useContext(DataRouterContext);
  !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = React.useContext(DataRouterStateContext);
  !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
  return state;
}
function useRouteContext(hookName) {
  let route = React.useContext(RouteContext);
  !route ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
  return route;
}
// Internal version with hookName-aware debugging
function useCurrentRouteId(hookName) {
  let route = useRouteContext(hookName);
  let thisRoute = route.matches[route.matches.length - 1];
  !thisRoute.route.id ? UNSAFE_invariant(false, `${hookName} can only be used on routes that contain a unique "id"`)  : void 0;
  return thisRoute.route.id;
}
/**
 * Returns the ID for the nearest contextual route
 */
function useRouteId() {
  return useCurrentRouteId(DataRouterStateHook.UseRouteId);
}
/**
 * Returns the current navigation, defaulting to an "idle" navigation when
 * no navigation is in progress
 */
function useNavigation() {
  let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  return state.navigation;
}
/**
 * Returns a revalidate function for manually triggering revalidation, as well
 * as the current state of any manual revalidations
 */
function useRevalidator() {
  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  return React.useMemo(() => ({
    revalidate: dataRouterContext.router.revalidate,
    state: state.revalidation
  }), [dataRouterContext.router.revalidate, state.revalidation]);
}
/**
 * Returns the active route matches, useful for accessing loaderData for
 * parent/child routes or the route "handle" property
 */
function useMatches() {
  let {
    matches,
    loaderData
  } = useDataRouterState(DataRouterStateHook.UseMatches);
  return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
}
/**
 * Returns the loader data for the nearest ancestor Route loader
 */
function useLoaderData() {
  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  if (state.errors && state.errors[routeId] != null) {
    console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
    return undefined;
  }
  return state.loaderData[routeId];
}
/**
 * Returns the loaderData for the given routeId
 */
function useRouteLoaderData(routeId) {
  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  return state.loaderData[routeId];
}
/**
 * Returns the action data for the nearest ancestor Route action
 */
function useActionData() {
  let state = useDataRouterState(DataRouterStateHook.UseActionData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  return state.actionData ? state.actionData[routeId] : undefined;
}
/**
 * Returns the nearest ancestor Route error, which could be a loader/action
 * error or a render error.  This is intended to be called from your
 * ErrorBoundary/errorElement to display a proper error message.
 */
function useRouteError() {
  let error = React.useContext(RouteErrorContext);
  let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
  // If this was a render error, we put it in a RouteError context inside
  // of RenderErrorBoundary
  if (error !== undefined) {
    return error;
  }
  // Otherwise look for errors from our data router state
  return state.errors?.[routeId];
}
/**
 * Returns the happy-path data from the nearest ancestor `<Await />` value
 */
function useAsyncValue() {
  let value = React.useContext(AwaitContext);
  return value?._data;
}
/**
 * Returns the error from the nearest ancestor `<Await />` value
 */
function useAsyncError() {
  let value = React.useContext(AwaitContext);
  return value?._error;
}
let blockerId = 0;
/**
 * Allow the application to block navigations within the SPA and present the
 * user a confirmation dialog to confirm the navigation.  Mostly used to avoid
 * using half-filled form data.  This does not handle hard-reloads or
 * cross-origin navigations.
 */
function useBlocker(shouldBlock) {
  let {
    router,
    basename
  } = useDataRouterContext(DataRouterHook.UseBlocker);
  let state = useDataRouterState(DataRouterStateHook.UseBlocker);
  let [blockerKey, setBlockerKey] = React.useState("");
  let blockerFunction = React.useCallback(arg => {
    if (typeof shouldBlock !== "function") {
      return !!shouldBlock;
    }
    if (basename === "/") {
      return shouldBlock(arg);
    }
    // If they provided us a function and we've got an active basename, strip
    // it from the locations we expose to the user to match the behavior of
    // useLocation
    let {
      currentLocation,
      nextLocation,
      historyAction
    } = arg;
    return shouldBlock({
      currentLocation: {
        ...currentLocation,
        pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
      },
      nextLocation: {
        ...nextLocation,
        pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
      },
      historyAction
    });
  }, [basename, shouldBlock]);
  // This effect is in charge of blocker key assignment and deletion (which is
  // tightly coupled to the key)
  React.useEffect(() => {
    let key = String(++blockerId);
    setBlockerKey(key);
    return () => router.deleteBlocker(key);
  }, [router]);
  // This effect handles assigning the blockerFunction.  This is to handle
  // unstable blocker function identities, and happens only after the prior
  // effect so we don't get an orphaned blockerFunction in the router with a
  // key of "".  Until then we just have the IDLE_BLOCKER.
  React.useEffect(() => {
    if (blockerKey !== "") {
      router.getBlocker(blockerKey, blockerFunction);
    }
  }, [router, blockerKey, blockerFunction]);
  // Prefer the blocker from `state` not `router.state` since DataRouterContext
  // is memoized so this ensures we update on blocker state updates
  return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
}
/**
 * Stable version of useNavigate that is used when we are in the context of
 * a RouterProvider.
 */
function useNavigateStable() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseNavigateStable);
  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
  let activeRef = React.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = React.useCallback((to, options = {}) => {
    UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our router subscriber yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      router.navigate(to);
    } else {
      router.navigate(to, {
        fromRouteId: id,
        ...options
      });
    }
  }, [router, id]);
  return navigate;
}
const alreadyWarned$1 = {};
function warningOnce(key, cond, message) {
  if (!cond && !alreadyWarned$1[key]) {
    alreadyWarned$1[key] = true;
    UNSAFE_warning(false, message) ;
  }
}

const alreadyWarned = {};
function warnOnce(key, message) {
  if (!alreadyWarned[message]) {
    alreadyWarned[message] = true;
    console.warn(message);
  }
}
const logDeprecation = (flag, msg, link) => warnOnce(flag, `âš ï¸� React Router Future Flag Warning: ${msg}. ` + `You can use the \`${flag}\` future flag to opt-in early. ` + `For more information, see ${link}.`);
function logV6DeprecationWarnings(renderFuture, routerFuture) {
  if (renderFuture?.v7_startTransition === undefined) {
    logDeprecation("v7_startTransition", "React Router will begin wrapping state updates in `React.startTransition` in v7", "https://reactrouter.com/v6/upgrading/future#v7_starttransition");
  }
  if (renderFuture?.v7_relativeSplatPath === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {
    logDeprecation("v7_relativeSplatPath", "Relative route resolution within Splat routes is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath");
  }
  if (routerFuture) {
    if (routerFuture.v7_fetcherPersist === undefined) {
      logDeprecation("v7_fetcherPersist", "The persistence behavior of fetchers is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist");
    }
    if (routerFuture.v7_normalizeFormMethod === undefined) {
      logDeprecation("v7_normalizeFormMethod", "Casing of `formMethod` fields is being normalized to uppercase in v7", "https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod");
    }
    if (routerFuture.v7_partialHydration === undefined) {
      logDeprecation("v7_partialHydration", "`RouterProvider` hydration behavior is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_partialhydration");
    }
    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {
      logDeprecation("v7_skipActionErrorRevalidation", "The revalidation behavior after 4xx/5xx `action` responses is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation");
    }
  }
}

/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider({
  fallbackElement,
  router,
  future
}) {
  let [state, setStateImpl] = React.useState(router.state);
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    if (v7_startTransition && startTransitionImpl) {
      startTransitionImpl(() => setStateImpl(newState));
    } else {
      setStateImpl(newState);
    }
  }, [setStateImpl, v7_startTransition]);
  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  React.useEffect(() => {
    UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts?.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts?.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);
  React.useEffect(() => logV6DeprecationWarnings(future, router.future), [router, future]);
  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, state.initialized || router.future.v7_partialHydration ? (/*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  })) : fallbackElement))), null);
}
function DataRoutes({
  routes,
  future,
  state
}) {
  return useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` that stores all entries in memory.
 *
 * @see https://reactrouter.com/v6/router-components/memory-router
 */
function MemoryRouter({
  basename,
  children,
  initialEntries,
  initialIndex,
  future
}) {
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createMemoryHistory({
      initialEntries,
      initialIndex,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * Changes the current location.
 *
 * Note: This API is mostly useful in React.Component subclasses that are not
 * able to use hooks. In functional components, we recommend you use the
 * `useNavigate` hook instead.
 *
 * @see https://reactrouter.com/v6/components/navigate
 */
function Navigate({
  to,
  replace,
  state,
  relative
}) {
  !useInRouterContext() ? UNSAFE_invariant(false,
  // TODO: This error is probably because they somehow have 2 versions of
  // the router loaded. We can help them understand how to avoid that.
  `<Navigate> may be used only in the context of a <Router> component.`)  : void 0;
  let {
    future,
    static: isStatic
  } = React.useContext(NavigationContext);
  UNSAFE_warning(!isStatic, `<Navigate> must not be used on the initial render in a <StaticRouter>. ` + `This is a no-op, but you should modify your code so the <Navigate> is ` + `only ever rendered in response to some user interaction or state change.`) ;
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let navigate = useNavigate();
  // Resolve the path outside of the effect so that when effects run twice in
  // StrictMode they navigate to the same place
  let path = resolveTo(to, UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
  let jsonPath = JSON.stringify(path);
  React.useEffect(() => navigate(JSON.parse(jsonPath), {
    replace,
    state,
    relative
  }), [navigate, jsonPath, relative, replace, state]);
  return null;
}
/**
 * Renders the child route's element, if there is one.
 *
 * @see https://reactrouter.com/v6/components/outlet
 */
function Outlet(props) {
  return useOutlet(props.context);
}
/**
 * Declares an element that should be rendered at a certain URL path.
 *
 * @see https://reactrouter.com/v6/components/route
 */
function Route(_props) {
  UNSAFE_invariant(false, `A <Route> is only ever to be used as the child of <Routes> element, ` + `never rendered directly. Please wrap your <Route> in a <Routes>.`)  ;
}
/**
 * Provides location context for the rest of the app.
 *
 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
 * router that is more specific to your environment such as a `<BrowserRouter>`
 * in web browsers or a `<StaticRouter>` for server rendering.
 *
 * @see https://reactrouter.com/v6/router-components/router
 */
function Router({
  basename: basenameProp = "/",
  children = null,
  location: locationProp,
  navigationType = Action.Pop,
  navigator,
  static: staticProp = false,
  future
}) {
  !!useInRouterContext() ? UNSAFE_invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`)  : void 0;
  // Preserve trailing slashes on basename, so we can let the user control
  // the enforcement of trailing slashes throughout the app
  let basename = basenameProp.replace(/^\/*/, "/");
  let navigationContext = React.useMemo(() => ({
    basename,
    navigator,
    static: staticProp,
    future: {
      v7_relativeSplatPath: false,
      ...future
    }
  }), [basename, future, navigator, staticProp]);
  if (typeof locationProp === "string") {
    locationProp = parsePath(locationProp);
  }
  let {
    pathname = "/",
    search = "",
    hash = "",
    state = null,
    key = "default"
  } = locationProp;
  let locationContext = React.useMemo(() => {
    let trailingPathname = stripBasename(pathname, basename);
    if (trailingPathname == null) {
      return null;
    }
    return {
      location: {
        pathname: trailingPathname,
        search,
        hash,
        state,
        key
      },
      navigationType
    };
  }, [basename, pathname, search, hash, state, key, navigationType]);
  UNSAFE_warning(locationContext != null, `<Router basename="${basename}"> is not able to match the URL ` + `"${pathname}${search}${hash}" because it does not start with the ` + `basename, so the <Router> won't render anything.`) ;
  if (locationContext == null) {
    return null;
  }
  return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
    value: navigationContext
  }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
    children: children,
    value: locationContext
  }));
}
/**
 * A container for a nested tree of `<Route>` elements that renders the branch
 * that best matches the current location.
 *
 * @see https://reactrouter.com/v6/components/routes
 */
function Routes({
  children,
  location
}) {
  return useRoutes(createRoutesFromChildren(children), location);
}
/**
 * Component to use for rendering lazily loaded data from returning defer()
 * in a loader function
 */
function Await({
  children,
  errorElement,
  resolve
}) {
  return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
    resolve: resolve,
    errorElement: errorElement
  }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
}
var AwaitRenderStatus;
(function (AwaitRenderStatus) {
  AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
  AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
  AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
})(AwaitRenderStatus || (AwaitRenderStatus = {}));
const neverSettledPromise = new Promise(() => {});
class AwaitErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("<Await> caught the following error during render", error, errorInfo);
  }
  render() {
    let {
      children,
      errorElement,
      resolve
    } = this.props;
    let promise = null;
    let status = AwaitRenderStatus.pending;
    if (!(resolve instanceof Promise)) {
      // Didn't get a promise - provide as a resolved promise
      status = AwaitRenderStatus.success;
      promise = Promise.resolve();
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_data", {
        get: () => resolve
      });
    } else if (this.state.error) {
      // Caught a render error, provide it as a rejected promise
      status = AwaitRenderStatus.error;
      let renderError = this.state.error;
      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_error", {
        get: () => renderError
      });
    } else if (resolve._tracked) {
      // Already tracked promise - check contents
      promise = resolve;
      status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
    } else {
      // Raw (untracked) promise - track it
      status = AwaitRenderStatus.pending;
      Object.defineProperty(resolve, "_tracked", {
        get: () => true
      });
      promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
        get: () => data
      }), error => Object.defineProperty(resolve, "_error", {
        get: () => error
      }));
    }
    if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
      // Freeze the UI by throwing a never resolved promise
      throw neverSettledPromise;
    }
    if (status === AwaitRenderStatus.error && !errorElement) {
      // No errorElement, throw to the nearest route-level error boundary
      throw promise._error;
    }
    if (status === AwaitRenderStatus.error) {
      // Render via our errorElement
      return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
        value: promise,
        children: errorElement
      });
    }
    if (status === AwaitRenderStatus.success) {
      // Render children with resolved value
      return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
        value: promise,
        children: children
      });
    }
    // Throw to the suspense boundary
    throw promise;
  }
}
/**
 * @private
 * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
 */
function ResolveAwait({
  children
}) {
  let data = useAsyncValue();
  let toRender = typeof children === "function" ? children(data) : children;
  return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
}
///////////////////////////////////////////////////////////////////////////////
// UTILS
///////////////////////////////////////////////////////////////////////////////
/**
 * Creates a route config from a React "children" object, which is usually
 * either a `<Route>` element or an array of them. Used internally by
 * `<Routes>` to create a route config from its children.
 *
 * @see https://reactrouter.com/v6/utils/create-routes-from-children
 */
function createRoutesFromChildren(children, parentPath = []) {
  let routes = [];
  React.Children.forEach(children, (element, index) => {
    if (! /*#__PURE__*/React.isValidElement(element)) {
      // Ignore non-elements. This allows people to more easily inline
      // conditionals in their route config.
      return;
    }
    let treePath = [...parentPath, index];
    if (element.type === React.Fragment) {
      // Transparently support React.Fragment and its children.
      routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
      return;
    }
    !(element.type === Route) ? UNSAFE_invariant(false, `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`)  : void 0;
    !(!element.props.index || !element.props.children) ? UNSAFE_invariant(false, "An index route cannot have child routes.")  : void 0;
    let route = {
      id: element.props.id || treePath.join("-"),
      caseSensitive: element.props.caseSensitive,
      element: element.props.element,
      Component: element.props.Component,
      index: element.props.index,
      path: element.props.path,
      loader: element.props.loader,
      action: element.props.action,
      errorElement: element.props.errorElement,
      ErrorBoundary: element.props.ErrorBoundary,
      hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
      shouldRevalidate: element.props.shouldRevalidate,
      handle: element.props.handle,
      lazy: element.props.lazy
    };
    if (element.props.children) {
      route.children = createRoutesFromChildren(element.props.children, treePath);
    }
    routes.push(route);
  });
  return routes;
}
/**
 * Renders the result of `matchRoutes()` into a React element.
 */
function renderMatches(matches) {
  return _renderMatches(matches);
}

function mapRouteProperties(route) {
  let updates = {
    // Note: this check also occurs in createRoutesFromChildren so update
    // there if you change this -- please and thank you!
    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  };
  if (route.Component) {
    {
      if (route.element) {
        UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
      }
    }
    Object.assign(updates, {
      element: /*#__PURE__*/React.createElement(route.Component),
      Component: undefined
    });
  }
  if (route.HydrateFallback) {
    {
      if (route.hydrateFallbackElement) {
        UNSAFE_warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - " + "`HydrateFallback` will be used.") ;
      }
    }
    Object.assign(updates, {
      hydrateFallbackElement: /*#__PURE__*/React.createElement(route.HydrateFallback),
      HydrateFallback: undefined
    });
  }
  if (route.ErrorBoundary) {
    {
      if (route.errorElement) {
        UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
      }
    }
    Object.assign(updates, {
      errorElement: /*#__PURE__*/React.createElement(route.ErrorBoundary),
      ErrorBoundary: undefined
    });
  }
  return updates;
}
function createMemoryRouter(routes, opts) {
  return createRouter({
    basename: opts?.basename,
    future: {
      ...opts?.future,
      v7_prependBasename: true
    },
    history: createMemoryHistory({
      initialEntries: opts?.initialEntries,
      initialIndex: opts?.initialIndex
    }),
    hydrationData: opts?.hydrationData,
    routes,
    mapRouteProperties,
    dataStrategy: opts?.dataStrategy,
    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation
  }).initialize();
}

export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
//# sourceMappingURL=react-router.development.js.map
{"version":3,"file":"react-router.development.js","sources":["../lib/context.ts","../lib/hooks.tsx","../lib/deprecations.ts","../lib/components.tsx","../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>ðŸ’¿ Hey developer ðŸ‘‹</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (__DEV__ && !alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `âš ï¸� React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (renderFuture?.v7_startTransition === undefined) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    renderFuture?.v7_relativeSplatPath === undefined &&\n    (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (routerFuture.v7_fetcherPersist === undefined) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (routerFuture.v7_normalizeFormMethod === undefined) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (routerFuture.v7_partialHydration === undefined) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n","import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n"],"names":["DataRouterContext","React","createContext","displayName","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useHref","to","relative","useInRouterContext","invariant","basename","navigator","useContext","hash","pathname","search","useResolvedPath","joinedPathname","joinPaths","createHref","useLocation","location","useNavigationType","navigationType","useMatch","pattern","useMemo","matchPath","decodePath","navigateEffectWarning","useIsomorphicLayoutEffect","cb","isStatic","static","useLayoutEffect","useNavigate","useNavigateStable","useNavigateUnstable","dataRouterContext","future","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","activeRef","useRef","current","navigate","useCallback","options","process","warning","go","path","resolveTo","parse","replace","push","state","OutletContext","useOutletContext","useOutlet","context","createElement","Provider","value","useParams","routeMatch","length","params","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathname","parentPathnameBase","pathnameBase","parentRoute","route","parentPath","warningOnce","endsWith","locationFromContext","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","segments","slice","join","matchRoutes","element","undefined","Component","lazy","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","key","NavigationType","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","lightgrey","preStyles","padding","backgroundColor","codeStyles","devInfo","console","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","constructor","props","revalidation","getDerivedStateFromError","getDerivedStateFromProps","componentDidCatch","errorInfo","render","routeContext","children","component","RenderedRoute","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","id","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","keys","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","reduceRight","index","shouldRenderHydrateFallback","concat","getChildren","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","useDataRouterState","useRouteContext","useCurrentRouteId","thisRoute","useRouteId","UseRouteId","useNavigation","UseNavigation","navigation","useRevalidator","UseRevalidator","revalidate","router","useMatches","UseMatches","convertRouteMatchToUiMatch","useLoaderData","UseLoaderData","routeId","useRouteLoaderData","UseRouteLoaderData","useActionData","UseActionData","actionData","UseRouteError","useAsyncValue","_data","useAsyncError","_error","blockerId","useBlocker","shouldBlock","UseBlocker","blockerKey","setBlockerKey","useState","blockerFunction","arg","currentLocation","nextLocation","historyAction","stripBasename","useEffect","String","deleteBlocker","getBlocker","blockers","has","get","IDLE_BLOCKER","UseNavigateStable","fromRouteId","alreadyWarned","cond","warnOnce","warn","logDeprecation","flag","msg","link","logV6DeprecationWarnings","renderFuture","routerFuture","v7_startTransition","v7_fetcherPersist","v7_normalizeFormMethod","v7_skipActionErrorRevalidation","START_TRANSITION","startTransitionImpl","RouterProvider","fallbackElement","setStateImpl","setState","newState","subscribe","n","opts","preventScrollReset","Router","DataRoutes","MemoryRouter","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","action","listen","Navigate","jsonPath","Outlet","Route","_props","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","createRoutesFromChildren","Await","resolve","AwaitErrorBoundary","ResolveAwait","AwaitRenderStatus","neverSettledPromise","Promise","promise","pending","success","defineProperty","renderError","reject","catch","_tracked","then","data","AbortedDeferredError","toRender","Children","forEach","isValidElement","treePath","type","apply","name","caseSensitive","hasErrorBoundary","shouldRevalidate","handle","renderMatches","mapRouteProperties","updates","createMemoryRouter","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize"],"mappings":";;;;;;;;;;;;;;AAgFO,MAAMA,iBAAiB,gBAC5BC,KAAK,CAACC,aAAa,CAAiC,IAAI,EAAC;AAC9C;EACXF,iBAAiB,CAACG,WAAW,GAAG,YAAY,CAAA;AAC7C,CAAA;AAEM,MAAMC,sBAAsB,gBAAGH,KAAK,CAACC,aAAa,CAEvD,IAAI,EAAC;AACM;EACXE,sBAAsB,CAACD,WAAW,GAAG,iBAAiB,CAAA;AACvD,CAAA;AAEM,MAAME,YAAY,gBAAGJ,KAAK,CAACC,aAAa,CAAwB,IAAI,CAAC,CAAA;AAC/D;EACXG,YAAY,CAACF,WAAW,GAAG,OAAO,CAAA;AACnC,CAAA;AAsCM,MAAMG,iBAAiB,gBAAGL,KAAK,CAACC,aAAa,CAClD,IAAK,EACN;AAEY;EACXI,iBAAiB,CAACH,WAAW,GAAG,YAAY,CAAA;AAC7C,CAAA;AAOM,MAAMI,eAAe,gBAAGN,KAAK,CAACC,aAAa,CA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AmB,CAAC;MAC3BH,cAAc,EAAEL,IAAI,EAAEK,cAAc;MACpCC,YAAY,EAAEN,IAAI,EAAEM,YAAAA;KACrB,CAAC;IACFwD,aAAa,EAAE9D,IAAI,EAAE8D,aAAa;IAClCnP,MAAM;IACN8O,kBAAkB;IAClBM,YAAY,EAAE/D,IAAI,EAAE+D,YAAY;IAChCC,uBAAuB,EAAEhE,IAAI,EAAEgE,uBAAAA;GAChC,CAAC,CAACC,UAAU,EAAE,CAAA;AACjB;;;;"}/**
 * React Router v6.30.6
 *
 * 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
 */
import*as e from"react";import{UNSAFE_invariant as t,joinPaths as r,matchPath as n,UNSAFE_decodePath as a,UNSAFE_getResolveToMatches as o,resolveTo as i,parsePath as l,matchRoutes as u,Action as s,UNSAFE_convertRouteMatchToUiMatch as c,stripBasename as d,IDLE_BLOCKER as p,isRouteErrorResponse as m,createMemoryHistory as h,AbortedDeferredError as f,createRouter as v}from"@remix-run/router";export{AbortedDeferredError,Action as NavigationType,createPath,defer,generatePath,isRouteErrorResponse,json,matchPath,matchRoutes,parsePath,redirect,redirectDocument,replace,resolvePath}from"@remix-run/router";const E=e.createContext(null),g=e.createContext(null),y=e.createContext(null),x=e.createContext(null),C=e.createContext(null),b=e.createContext({outlet:null,matches:[],isDataRoute:!1}),R=e.createContext(null);function S(n,{relative:a}={}){_()||t(!1);let{basename:o,navigator:i}=e.useContext(x),{hash:l,pathname:u,search:s}=A(n,{relative:a}),c=u;return"/"!==o&&(c="/"===u?o:r([o,u])),i.createHref({pathname:c,search:s,hash:l})}function _(){return null!=e.useContext(C)}function P(){return _()||t(!1),e.useContext(C).location}function U(){return e.useContext(C).navigationType}function k(r){_()||t(!1);let{pathname:o}=P();return e.useMemo(()=>n(r,a(o)),[o,r])}function D(t){e.useContext(x).static||e.useLayoutEffect(t)}function N(){let{isDataRoute:n}=e.useContext(b);return n?function(){let{router:t}=V(J.UseNavigateStable),r=Y($.UseNavigateStable),n=e.useRef(!1);return D(()=>{n.current=!0}),e.useCallback((e,a={})=>{n.current&&("number"==typeof e?t.navigate(e):t.navigate(e,{fromRouteId:r,...a}))},[t,r])}():function(){_()||t(!1);let n=e.useContext(E),{basename:a,future:l,navigator:u}=e.useContext(x),{matches:s}=e.useContext(b),{pathname:c}=P(),d=JSON.stringify(o(s,l.v7_relativeSplatPath)),p=e.useRef(!1);return D(()=>{p.current=!0}),e.useCallback((e,t={})=>{if(!p.current)return;if("number"==typeof e)return void u.go(e);let o=i(e,JSON.parse(d),c,"path"===t.relative);null==n&&"/"!==a&&(o.pathname="/"===o.pathname?a:r([a,o.pathname])),(t.replace?u.replace:u.push)(o,t.state,t)},[a,u,d,c,n])}()}const B=e.createContext(null);function F(){return e.useContext(B)}function L(t){let r=e.useContext(b).outlet;return r?e.createElement(B.Provider,{value:t},r):r}function O(){let{matches:t}=e.useContext(b),r=t[t.length-1];return r?r.params:{}}function A(t,{relative:r}={}){let{future:n}=e.useContext(x),{matches:a}=e.useContext(b),{pathname:l}=P(),u=JSON.stringify(o(a,n.v7_relativeSplatPath));return e.useMemo(()=>i(t,JSON.parse(u),l,"path"===r),[t,u,l,r])}function j(e,t){return I(e,t)}function I(n,a,o,i){_()||t(!1);let{navigator:c}=e.useContext(x),{matches:d}=e.useContext(b),p=d[d.length-1],m=p?p.params:{};!p||p.pathname;let h=p?p.pathnameBase:"/";p&&p.route;let f,v=P();if(a){let e="string"==typeof a?l(a):a;"/"===h||e.pathname?.startsWith(h)||t(!1),f=e}else f=v;let E=f.pathname||"/",g=E;if("/"!==h){let e=h.replace(/^\//,"").split("/");g="/"+E.replace(/^\//,"").split("/").slice(e.length).join("/")}let y=u(n,{pathname:g}),R=z(y&&y.map(e=>Object.assign({},e,{params:Object.assign({},m,e.params),pathname:r([h,c.encodeLocation?c.encodeLocation(e.pathname).pathname:e.pathname]),pathnameBase:"/"===e.pathnameBase?h:r([h,c.encodeLocation?c.encodeLocation(e.pathnameBase).pathname:e.pathnameBase])})),d,o,i);return a&&R?e.createElement(C.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...f},navigationType:s.Pop}},R):R}function M(){let t=te(),r=m(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return e.createElement(e.Fragment,null,e.createElement("h2",null,"Unexpected Application Error!"),e.createElement("h3",{style:{fontStyle:"italic"}},r),n?e.createElement("pre",{style:a},n):null,null)}const H=e.createElement(M,null);class T extends e.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||"idle"!==t.revalidation&&"idle"===e.revalidation?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:void 0!==e.error?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return void 0!==this.state.error?e.createElement(b.Provider,{value:this.props.routeContext},e.createElement(R.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function w({routeContext:t,match:r,children:n}){let a=e.useContext(E);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),e.createElement(b.Provider,{value:t},n)}function z(r,n=[],a=null,o=null){if(null==r){if(!a)return null;if(a.errors)r=a.matches;else{if(!(o?.v7_partialHydration&&0===n.length&&!a.initialized&&a.matches.length>0))return null;r=a.matches}}let i=r,l=a?.errors;if(null!=l){let e=i.findIndex(e=>e.route.id&&void 0!==l?.[e.route.id]);e>=0||t(!1),i=i.slice(0,Math.min(i.length,e+1))}let u=!1,s=-1;if(a&&o&&o.v7_partialHydration)for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:r}=a,n=t.route.loader&&void 0===e[t.route.id]&&(!r||void 0===r[t.route.id]);if(t.route.lazy||n){u=!0,i=s>=0?i.slice(0,s+1):[i[0]];break}}}return i.reduceRight((t,r,o)=>{let c,d=!1,p=null,m=null;var h;a&&(c=l&&r.route.id?l[r.route.id]:void 0,p=r.route.errorElement||H,u&&(s<0&&0===o?(h="route-fallback",!1||ie[h]||(ie[h]=!0),d=!0,m=null):s===o&&(d=!0,m=r.route.hydrateFallbackElement||null)));let f=n.concat(i.slice(0,o+1)),v=()=>{let n;return n=c?p:d?m:r.route.Component?e.createElement(r.route.Component,null):r.route.element?r.route.element:t,e.createElement(w,{match:r,routeContext:{outlet:t,matches:f,isDataRoute:null!=a},children:n})};return a&&(r.route.ErrorBoundary||r.route.errorElement||0===o)?e.createElement(T,{location:a.location,revalidation:a.revalidation,component:p,error:c,children:v(),routeContext:{outlet:null,matches:f,isDataRoute:!0}}):v()},null)}var J=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(J||{}),$=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}($||{});function V(r){let n=e.useContext(E);return n||t(!1),n}function W(r){let n=e.useContext(g);return n||t(!1),n}function Y(r){let n=function(){let r=e.useContext(b);return r||t(!1),r}(),a=n.matches[n.matches.length-1];return a.route.id||t(!1),a.route.id}function q(){return Y($.UseRouteId)}function G(){return W($.UseNavigation).navigation}function K(){let t=V(J.UseRevalidator),r=W($.UseRevalidator);return e.useMemo(()=>({revalidate:t.router.revalidate,state:r.revalidation}),[t.router.revalidate,r.revalidation])}function Q(){let{matches:t,loaderData:r}=W($.UseMatches);return e.useMemo(()=>t.map(e=>c(e,r)),[t,r])}function X(){let e=W($.UseLoaderData),t=Y($.UseLoaderData);if(!e.errors||null==e.errors[t])return e.loaderData[t];console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${t})`)}function Z(e){return W($.UseRouteLoaderData).loaderData[e]}function ee(){let e=W($.UseActionData),t=Y($.UseLoaderData);return e.actionData?e.actionData[t]:void 0}function te(){let t=e.useContext(R),r=W($.UseRouteError),n=Y($.UseRouteError);return void 0!==t?t:r.errors?.[n]}function re(){let t=e.useContext(y);return t?._data}function ne(){let t=e.useContext(y);return t?._error}let ae=0;function oe(t){let{router:r,basename:n}=V(J.UseBlocker),a=W($.UseBlocker),[o,i]=e.useState(""),l=e.useCallback(e=>{if("function"!=typeof t)return!!t;if("/"===n)return t(e);let{currentLocation:r,nextLocation:a,historyAction:o}=e;return t({currentLocation:{...r,pathname:d(r.pathname,n)||r.pathname},nextLocation:{...a,pathname:d(a.pathname,n)||a.pathname},historyAction:o})},[n,t]);return e.useEffect(()=>{let e=String(++ae);return i(e),()=>r.deleteBlocker(e)},[r]),e.useEffect(()=>{""!==o&&r.getBlocker(o,l)},[r,o,l]),o&&a.blockers.has(o)?a.blockers.get(o):p}const ie={};function le(e,t){void 0===e?.v7_relativeSplatPath&&(!t||t.v7_relativeSplatPath),t&&(t.v7_fetcherPersist,t.v7_normalizeFormMethod,t.v7_partialHydration,t.v7_skipActionErrorRevalidation)}const ue=e.startTransition;function se({fallbackElement:t,router:r,future:n}){let[a,o]=e.useState(r.state),{v7_startTransition:i}=n||{},l=e.useCallback(e=>{i&&ue?ue(()=>o(e)):o(e)},[o,i]);e.useLayoutEffect(()=>r.subscribe(l),[r,l]),e.useEffect(()=>{},[]);let u=e.useMemo(()=>({createHref:r.createHref,encodeLocation:r.encodeLocation,go:e=>r.navigate(e),push:(e,t,n)=>r.navigate(e,{state:t,preventScrollReset:n?.preventScrollReset}),replace:(e,t,n)=>r.navigate(e,{replace:!0,state:t,preventScrollReset:n?.preventScrollReset})}),[r]),s=r.basename||"/",c=e.useMemo(()=>({router:r,navigator:u,static:!1,basename:s}),[r,u,s]);return e.useEffect(()=>le(n,r.future),[r,n]),e.createElement(e.Fragment,null,e.createElement(E.Provider,{value:c},e.createElement(g.Provider,{value:a},e.createElement(fe,{basename:s,location:a.location,navigationType:a.historyAction,navigator:u,future:{v7_relativeSplatPath:r.future.v7_relativeSplatPath}},a.initialized||r.future.v7_partialHydration?e.createElement(ce,{routes:r.routes,future:r.future,state:a}):t))),null)}function ce({routes:e,future:t,state:r}){return I(e,void 0,r,t)}function de({basename:t,children:r,initialEntries:n,initialIndex:a,future:o}){let i=e.useRef();null==i.current&&(i.current=h({initialEntries:n,initialIndex:a,v5Compat:!0}));let l=i.current,[u,s]=e.useState({action:l.action,location:l.location}),{v7_startTransition:c}=o||{},d=e.useCallback(e=>{c&&ue?ue(()=>s(e)):s(e)},[s,c]);return e.useLayoutEffect(()=>l.listen(d),[l,d]),e.useEffect(()=>le(o),[o]),e.createElement(fe,{basename:t,children:r,location:u.location,navigationType:u.action,navigator:l,future:o})}function pe({to:r,replace:n,state:a,relative:l}){_()||t(!1);let{future:u,static:s}=e.useContext(x),{matches:c}=e.useContext(b),{pathname:d}=P(),p=N(),m=i(r,o(c,u.v7_relativeSplatPath),d,"path"===l),h=JSON.stringify(m);return e.useEffect(()=>p(JSON.parse(h),{replace:n,state:a,relative:l}),[p,h,l,n,a]),null}function me(e){return L(e.context)}function he(e){t(!1)}function fe({basename:r="/",children:n=null,location:a,navigationType:o=s.Pop,navigator:i,static:u=!1,future:c}){_()&&t(!1);let p=r.replace(/^\/*/,"/"),m=e.useMemo(()=>({basename:p,navigator:i,static:u,future:{v7_relativeSplatPath:!1,...c}}),[p,c,i,u]);"string"==typeof a&&(a=l(a));let{pathname:h="/",search:f="",hash:v="",state:E=null,key:g="default"}=a,y=e.useMemo(()=>{let e=d(h,p);return null==e?null:{location:{pathname:e,search:f,hash:v,state:E,key:g},navigationType:o}},[p,h,f,v,E,g,o]);return null==y?null:e.createElement(x.Provider,{value:m},e.createElement(C.Provider,{children:n,value:y}))}function ve({children:e,location:t}){return j(be(e),t)}function Ee({children:t,errorElement:r,resolve:n}){return e.createElement(xe,{resolve:n,errorElement:r},e.createElement(Ce,null,t))}var ge=function(e){return e[e.pending=0]="pending",e[e.success=1]="success",e[e.error=2]="error",e}(ge||{});const ye=new Promise(()=>{});class xe extends e.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("<Await> caught the following error during render",e,t)}render(){let{children:t,errorElement:r,resolve:n}=this.props,a=null,o=ge.pending;if(n instanceof Promise)if(this.state.error){o=ge.error;let e=this.state.error;a=Promise.reject().catch(()=>{}),Object.defineProperty(a,"_tracked",{get:()=>!0}),Object.defineProperty(a,"_error",{get:()=>e})}else n._tracked?(a=n,o="_error"in a?ge.error:"_data"in a?ge.success:ge.pending):(o=ge.pending,Object.defineProperty(n,"_tracked",{get:()=>!0}),a=n.then(e=>Object.defineProperty(n,"_data",{get:()=>e}),e=>Object.defineProperty(n,"_error",{get:()=>e})));else o=ge.success,a=Promise.resolve(),Object.defineProperty(a,"_tracked",{get:()=>!0}),Object.defineProperty(a,"_data",{get:()=>n});if(o===ge.error&&a._error instanceof f)throw ye;if(o===ge.error&&!r)throw a._error;if(o===ge.error)return e.createElement(y.Provider,{value:a,children:r});if(o===ge.success)return e.createElement(y.Provider,{value:a,children:t});throw a}}function Ce({children:t}){let r=re(),n="function"==typeof t?t(r):t;return e.createElement(e.Fragment,null,n)}function be(r,n=[]){let a=[];return e.Children.forEach(r,(r,o)=>{if(!e.isValidElement(r))return;let i=[...n,o];if(r.type===e.Fragment)return void a.push.apply(a,be(r.props.children,i));r.type!==he&&t(!1),r.props.index&&r.props.children&&t(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:null!=r.props.ErrorBoundary||null!=r.props.errorElement,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=be(r.props.children,i)),a.push(l)}),a}function Re(e){return z(e)}function Se(t){let r={hasErrorBoundary:null!=t.ErrorBoundary||null!=t.errorElement};return t.Component&&Object.assign(r,{element:e.createElement(t.Component),Component:void 0}),t.HydrateFallback&&Object.assign(r,{hydrateFallbackElement:e.createElement(t.HydrateFallback),HydrateFallback:void 0}),t.ErrorBoundary&&Object.assign(r,{errorElement:e.createElement(t.ErrorBoundary),ErrorBoundary:void 0}),r}function _e(e,t){return v({basename:t?.basename,future:{...t?.future,v7_prependBasename:!0},history:h({initialEntries:t?.initialEntries,initialIndex:t?.initialIndex}),hydrationData:t?.hydrationData,routes:e,mapRouteProperties:Se,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation}).initialize()}export{Ee as Await,de as MemoryRouter,pe as Navigate,me as Outlet,he as Route,fe as Router,se as RouterProvider,ve as Routes,E as UNSAFE_DataRouterContext,g as UNSAFE_DataRouterStateContext,C as UNSAFE_LocationContext,x as UNSAFE_NavigationContext,b as UNSAFE_RouteContext,le as UNSAFE_logV6DeprecationWarnings,Se as UNSAFE_mapRouteProperties,q as UNSAFE_useRouteId,I as UNSAFE_useRoutesImpl,_e as createMemoryRouter,be as createRoutesFromChildren,be as createRoutesFromElements,Re as renderMatches,ee as useActionData,ne as useAsyncError,re as useAsyncValue,oe as useBlocker,S as useHref,_ as useInRouterContext,X as useLoaderData,P as useLocation,k as useMatch,Q as useMatches,N as useNavigate,G as useNavigation,U as useNavigationType,L as useOutlet,F as useOutletContext,O as useParams,A as useResolvedPath,K as useRevalidator,te as useRouteError,Z as useRouteLoaderData,j as useRoutes};
//# sourceMappingURL=react-router.production.min.js.map
{"version":3,"file":"react-router.production.min.js","sources":["../lib/context.ts","../lib/hooks.tsx","../lib/deprecations.ts","../lib/components.tsx","../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>ðŸ’¿ Hey developer ðŸ‘‹</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (__DEV__ && !alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `âš ï¸� React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (renderFuture?.v7_startTransition === undefined) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    renderFuture?.v7_relativeSplatPath === undefined &&\n    (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (routerFuture.v7_fetcherPersist === undefined) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (routerFuture.v7_normalizeFormMethod === undefined) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (routerFuture.v7_partialHydration === undefined) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n","import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n"],"names":["DataRouterContext","React","createContext","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useHref","to","relative","useInRouterContext","invariant","basename","navigator","useContext","hash","pathname","search","useResolvedPath","joinedPathname","joinPaths","createHref","useLocation","location","useNavigationType","navigationType","useMatch","pattern","useMemo","matchPath","decodePath","useIsomorphicLayoutEffect","cb","static","useLayoutEffect","useNavigate","router","useDataRouterContext","DataRouterHook","UseNavigateStable","id","useCurrentRouteId","DataRouterStateHook","activeRef","useRef","current","useCallback","options","navigate","fromRouteId","useNavigateStable","dataRouterContext","future","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","go","path","resolveTo","parse","replace","push","state","useNavigateUnstable","OutletContext","useOutletContext","useOutlet","context","createElement","Provider","value","useParams","routeMatch","length","params","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathnameBase","pathnameBase","route","locationFromContext","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","slice","join","matchRoutes","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","key","NavigationType","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","preStyles","padding","backgroundColor","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","Component","constructor","props","super","this","revalidation","getDerivedStateFromError","getDerivedStateFromProps","undefined","componentDidCatch","errorInfo","console","render","routeContext","children","component","RenderedRoute","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","lazy","reduceRight","index","shouldRenderHydrateFallback","alreadyWarned","concat","getChildren","element","hookName","ctx","useDataRouterState","useRouteContext","thisRoute","useRouteId","UseRouteId","useNavigation","UseNavigation","navigation","useRevalidator","UseRevalidator","revalidate","useMatches","UseMatches","convertRouteMatchToUiMatch","useLoaderData","UseLoaderData","routeId","useRouteLoaderData","UseRouteLoaderData","useActionData","UseActionData","actionData","UseRouteError","useAsyncValue","_data","useAsyncError","_error","blockerId","useBlocker","shouldBlock","UseBlocker","blockerKey","setBlockerKey","useState","blockerFunction","arg","currentLocation","nextLocation","historyAction","stripBasename","useEffect","String","deleteBlocker","getBlocker","blockers","has","get","IDLE_BLOCKER","logV6DeprecationWarnings","renderFuture","routerFuture","v7_fetcherPersist","v7_normalizeFormMethod","v7_skipActionErrorRevalidation","startTransitionImpl","RouterProvider","fallbackElement","setStateImpl","v7_startTransition","setState","newState","subscribe","n","opts","preventScrollReset","Router","DataRoutes","MemoryRouter","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","action","listen","Navigate","isStatic","jsonPath","Outlet","Route","_props","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","createRoutesFromChildren","Await","resolve","AwaitErrorBoundary","ResolveAwait","AwaitRenderStatus","neverSettledPromise","Promise","promise","pending","renderError","reject","catch","defineProperty","_tracked","success","then","data","AbortedDeferredError","toRender","parentPath","Children","forEach","isValidElement","treePath","type","apply","caseSensitive","hasErrorBoundary","shouldRevalidate","handle","renderMatches","mapRouteProperties","updates","createMemoryRouter","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize"],"mappings":";;;;;;;;;;2lBAgFO,MAAMA,EACXC,EAAMC,cAA8C,MAKzCC,EAAyBF,EAAMC,cAE1C,MAKWE,EAAeH,EAAMC,cAAqC,MAyC1DG,EAAoBJ,EAAMC,cACrC,MAYWI,EAAkBL,EAAMC,cACnC,MAaWK,EAAeN,EAAMC,cAAkC,CAClEM,OAAQ,KACRC,QAAS,GACTC,aAAa,IAOFC,EAAoBV,EAAMC,cAAmB,MCnHnD,SAASU,EACdC,GACAC,SAAEA,GAAiD,IAGjDC,KADFC,GAAS,GAOT,IAAIC,SAAEA,EAAQC,UAAEA,GAAcjB,EAAMkB,WAAWd,IAC3Ce,KAAEA,EAAIC,SAAEA,EAAQC,OAAEA,GAAWC,EAAgBV,EAAI,CAAEC,aAEnDU,EAAiBH,EAWrB,MALiB,MAAbJ,IACFO,EACe,MAAbH,EAAm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AAgE,CAGlEL,iBAAyC,MAAvB1M,EAAMyD,eAA+C,MAAtBzD,EAAMwD,cAmDzD,OAhDIxD,EAAMsC,WAURvB,OAAOC,OAAO+L,EAAS,CACrB7H,QAAS7K,EAAM2E,cAAcgB,EAAMsC,WACnCA,eAAWQ,IAIX9C,EAAMsE,iBAURvD,OAAOC,OAAO+L,EAAS,CACrBxI,uBAAwBlK,EAAM2E,cAAcgB,EAAMsE,iBAClDA,qBAAiBxB,IAIjB9C,EAAMyD,eAUR1C,OAAOC,OAAO+L,EAAS,CACrBvJ,aAAcnJ,EAAM2E,cAAcgB,EAAMyD,eACxCA,mBAAeX,IAIZiK,CACT,CAEO,SAASC,GACdxN,EACA4J,GAUA,OAAO6D,EAAa,CAClB5R,SAAU+N,GAAM/N,SAChBwC,OAAQ,IACHuL,GAAMvL,OACTqP,oBAAoB,GAEtBpD,QAASF,EAAoB,CAC3BH,eAAgBL,GAAMK,eACtBC,aAAcN,GAAMM,eAEtByD,cAAe/D,GAAM+D,cACrB3N,SACAsN,sBACAM,aAAchE,GAAMgE,aACpBC,wBAAyBjE,GAAMiE,0BAC9BC,YACL"}/**
 * React Router v6.30.6
 *
 * 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
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@remix-run/router')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', '@remix-run/router'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.React, global.RemixRouter));
})(this, (function (exports, React, router) { 'use strict';

  function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
      Object.keys(e).forEach(function (k) {
        if (k !== 'default') {
          var d = Object.getOwnPropertyDescriptor(e, k);
          Object.defineProperty(n, k, d.get ? d : {
            enumerable: true,
            get: function () { return e[k]; }
          });
        }
      });
    }
    n["default"] = e;
    return Object.freeze(n);
  }

  var React__namespace = /*#__PURE__*/_interopNamespace(React);

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }

  // Create react-specific types from the agnostic types in @remix-run/router to
  // export from react-router

  const DataRouterContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    DataRouterContext.displayName = "DataRouter";
  }
  const DataRouterStateContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    DataRouterStateContext.displayName = "DataRouterState";
  }
  const AwaitContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    AwaitContext.displayName = "Await";
  }

  /**
   * A Navigator is a "location changer"; it's how you get to different locations.
   *
   * Every history instance conforms to the Navigator interface, but the
   * distinction is useful primarily when it comes to the low-level `<Router>` API
   * where both the location and a navigator must be provided separately in order
   * to avoid "tearing" that may occur in a suspense-enabled app if the action
   * and/or location were to be read directly from the history instance.
   */

  const NavigationContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    NavigationContext.displayName = "Navigation";
  }
  const LocationContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    LocationContext.displayName = "Location";
  }
  const RouteContext = /*#__PURE__*/React__namespace.createContext({
    outlet: null,
    matches: [],
    isDataRoute: false
  });
  {
    RouteContext.displayName = "Route";
  }
  const RouteErrorContext = /*#__PURE__*/React__namespace.createContext(null);
  {
    RouteErrorContext.displayName = "RouteError";
  }

  /**
   * Returns the full href for the given "to" value. This is useful for building
   * custom links that are also accessible and preserve right-click behavior.
   *
   * @see https://reactrouter.com/v6/hooks/use-href
   */
  function useHref(to, _temp) {
    let {
      relative
    } = _temp === void 0 ? {} : _temp;
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    "useHref() may be used only in the context of a <Router> component.")  : void 0;
    let {
      basename,
      navigator
    } = React__namespace.useContext(NavigationContext);
    let {
      hash,
      pathname,
      search
    } = useResolvedPath(to, {
      relative
    });
    let joinedPathname = pathname;

    // If we're operating within a basename, prepend it to the pathname prior
    // to creating the href.  If this is a root navigation, then just use the raw
    // basename which allows the basename to have full control over the presence
    // of a trailing slash on root links
    if (basename !== "/") {
      joinedPathname = pathname === "/" ? basename : router.joinPaths([basename, pathname]);
    }
    return navigator.createHref({
      pathname: joinedPathname,
      search,
      hash
    });
  }

  /**
   * Returns true if this component is a descendant of a `<Router>`.
   *
   * @see https://reactrouter.com/v6/hooks/use-in-router-context
   */
  function useInRouterContext() {
    return React__namespace.useContext(LocationContext) != null;
  }

  /**
   * Returns the current location object, which represents the current URL in web
   * browsers.
   *
   * Note: If you're using this it may mean you're doing some of your own
   * "routing" in your app, and we'd like to know what your use case is. We may
   * be able to provide something higher-level to better suit your needs.
   *
   * @see https://reactrouter.com/v6/hooks/use-location
   */
  function useLocation() {
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    "useLocation() may be used only in the context of a <Router> component.")  : void 0;
    return React__namespace.useContext(LocationContext).location;
  }

  /**
   * Returns the current navigation action which describes how the router came to
   * the current location, either by a pop, push, or replace on the history stack.
   *
   * @see https://reactrouter.com/v6/hooks/use-navigation-type
   */
  function useNavigationType() {
    return React__namespace.useContext(LocationContext).navigationType;
  }

  /**
   * Returns a PathMatch object if the given pattern matches the current URL.
   * This is useful for components that need to know "active" state, e.g.
   * `<NavLink>`.
   *
   * @see https://reactrouter.com/v6/hooks/use-match
   */
  function useMatch(pattern) {
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    "useMatch() may be used only in the context of a <Router> component.")  : void 0;
    let {
      pathname
    } = useLocation();
    return React__namespace.useMemo(() => router.matchPath(pattern, router.UNSAFE_decodePath(pathname)), [pathname, pattern]);
  }

  /**
   * The interface for the navigate() function returned from useNavigate().
   */

  const navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.";

  // Mute warnings for calls to useNavigate in SSR environments
  function useIsomorphicLayoutEffect(cb) {
    let isStatic = React__namespace.useContext(NavigationContext).static;
    if (!isStatic) {
      // We should be able to get rid of this once react 18.3 is released
      // See: https://github.com/facebook/react/pull/26395
      // eslint-disable-next-line react-hooks/rules-of-hooks
      React__namespace.useLayoutEffect(cb);
    }
  }

  /**
   * Returns an imperative method for changing the location. Used by `<Link>`s, but
   * may also be used by other elements to change the location.
   *
   * @see https://reactrouter.com/v6/hooks/use-navigate
   */
  function useNavigate() {
    let {
      isDataRoute
    } = React__namespace.useContext(RouteContext);
    // Conditional usage is OK here because the usage of a data router is static
    // eslint-disable-next-line react-hooks/rules-of-hooks
    return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  }
  function useNavigateUnstable() {
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    "useNavigate() may be used only in the context of a <Router> component.")  : void 0;
    let dataRouterContext = React__namespace.useContext(DataRouterContext);
    let {
      basename,
      future,
      navigator
    } = React__namespace.useContext(NavigationContext);
    let {
      matches
    } = React__namespace.useContext(RouteContext);
    let {
      pathname: locationPathname
    } = useLocation();
    let routePathnamesJson = JSON.stringify(router.UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
    let activeRef = React__namespace.useRef(false);
    useIsomorphicLayoutEffect(() => {
      activeRef.current = true;
    });
    let navigate = React__namespace.useCallback(function (to, options) {
      if (options === void 0) {
        options = {};
      }
      router.UNSAFE_warning(activeRef.current, navigateEffectWarning) ;

      // Short circuit here since if this happens on first render the navigate
      // is useless because we haven't wired up our history listener yet
      if (!activeRef.current) return;
      if (typeof to === "number") {
        navigator.go(to);
        return;
      }
      let path = router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");

      // If we're operating within a basename, prepend it to the pathname prior
      // to handing off to history (but only if we're not in a data router,
      // otherwise it'll prepend the basename inside of the router).
      // If this is a root navigation, then we navigate to the raw basename
      // which allows the basename to have full control over the presence of a
      // trailing slash on root links
      if (dataRouterContext == null && basename !== "/") {
        path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
      }
      (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
    }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
    return navigate;
  }
  const OutletContext = /*#__PURE__*/React__namespace.createContext(null);

  /**
   * Returns the context (if provided) for the child route at this level of the route
   * hierarchy.
   * @see https://reactrouter.com/v6/hooks/use-outlet-context
   */
  function useOutletContext() {
    return React__namespace.useContext(OutletContext);
  }

  /**
   * Returns the element for the child route at this level of the route
   * hierarchy. Used internally by `<Outlet>` to render child routes.
   *
   * @see https://reactrouter.com/v6/hooks/use-outlet
   */
  function useOutlet(context) {
    let outlet = React__namespace.useContext(RouteContext).outlet;
    if (outlet) {
      return /*#__PURE__*/React__namespace.createElement(OutletContext.Provider, {
        value: context
      }, outlet);
    }
    return outlet;
  }

  /**
   * Returns an object of key/value pairs of the dynamic params from the current
   * URL that were matched by the route path.
   *
   * @see https://reactrouter.com/v6/hooks/use-params
   */
  function useParams() {
    let {
      matches
    } = React__namespace.useContext(RouteContext);
    let routeMatch = matches[matches.length - 1];
    return routeMatch ? routeMatch.params : {};
  }

  /**
   * Resolves the pathname of the given `to` value against the current location.
   *
   * @see https://reactrouter.com/v6/hooks/use-resolved-path
   */
  function useResolvedPath(to, _temp2) {
    let {
      relative
    } = _temp2 === void 0 ? {} : _temp2;
    let {
      future
    } = React__namespace.useContext(NavigationContext);
    let {
      matches
    } = React__namespace.useContext(RouteContext);
    let {
      pathname: locationPathname
    } = useLocation();
    let routePathnamesJson = JSON.stringify(router.UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
    return React__namespace.useMemo(() => router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
  }

  /**
   * Returns the element of the route that matched the current location, prepared
   * with the correct context to render the remainder of the route tree. Route
   * elements in the tree must render an `<Outlet>` to render their child route's
   * element.
   *
   * @see https://reactrouter.com/v6/hooks/use-routes
   */
  function useRoutes(routes, locationArg) {
    return useRoutesImpl(routes, locationArg);
  }

  // Internal implementation with accept optional param for RouterProvider usage
  function useRoutesImpl(routes, locationArg, dataRouterState, future) {
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    "useRoutes() may be used only in the context of a <Router> component.")  : void 0;
    let {
      navigator
    } = React__namespace.useContext(NavigationContext);
    let {
      matches: parentMatches
    } = React__namespace.useContext(RouteContext);
    let routeMatch = parentMatches[parentMatches.length - 1];
    let parentParams = routeMatch ? routeMatch.params : {};
    let parentPathname = routeMatch ? routeMatch.pathname : "/";
    let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
    let parentRoute = routeMatch && routeMatch.route;
    {
      // You won't get a warning about 2 different <Routes> under a <Route>
      // without a trailing *, but this is a best-effort warning anyway since we
      // cannot even give the warning unless they land at the parent route.
      //
      // Example:
      //
      // <Routes>
      //   {/* This route path MUST end with /* because otherwise
      //       it will never match /blog/post/123 */}
      //   <Route path="blog" element={<Blog />} />
      //   <Route path="blog/feed" element={<BlogFeed />} />
      // </Routes>
      //
      // function Blog() {
      //   return (
      //     <Routes>
      //       <Route path="post/:id" element={<Post />} />
      //     </Routes>
      //   );
      // }
      let parentPath = parentRoute && parentRoute.path || "";
      warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
    }
    let locationFromContext = useLocation();
    let location;
    if (locationArg) {
      var _parsedLocationArg$pa;
      let parsedLocationArg = typeof locationArg === "string" ? router.parsePath(locationArg) : locationArg;
      !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? router.UNSAFE_invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop."))  : void 0;
      location = parsedLocationArg;
    } else {
      location = locationFromContext;
    }
    let pathname = location.pathname || "/";
    let remainingPathname = pathname;
    if (parentPathnameBase !== "/") {
      // Determine the remaining pathname by removing the # of URL segments the
      // parentPathnameBase has, instead of removing based on character count.
      // This is because we can't guarantee that incoming/outgoing encodings/
      // decodings will match exactly.
      // We decode paths before matching on a per-segment basis with
      // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they
      // match what `window.location.pathname` would reflect.  Those don't 100%
      // align when it comes to encoded URI characters such as % and &.
      //
      // So we may end up with:
      //   pathname:           "/descendant/a%25b/match"
      //   parentPathnameBase: "/descendant/a%b"
      //
      // And the direct substring removal approach won't work :/
      let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
      let segments = pathname.replace(/^\//, "").split("/");
      remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
    }
    let matches = router.matchRoutes(routes, {
      pathname: remainingPathname
    });
    {
      router.UNSAFE_warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") ;
      router.UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" " + "does not have an element or Component. This means it will render an <Outlet /> with a " + "null value by default resulting in an \"empty\" page.") ;
    }
    let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
      params: Object.assign({}, parentParams, match.params),
      pathname: router.joinPaths([parentPathnameBase,
      // Re-encode pathnames that were decoded inside matchRoutes
      navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
      pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : router.joinPaths([parentPathnameBase,
      // Re-encode pathnames that were decoded inside matchRoutes
      navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
    })), parentMatches, dataRouterState, future);

    // When a user passes in a `locationArg`, the associated routes need to
    // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
    // to use the scoped location instead of the global location.
    if (locationArg && renderedMatches) {
      return /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
        value: {
          location: _extends({
            pathname: "/",
            search: "",
            hash: "",
            state: null,
            key: "default"
          }, location),
          navigationType: router.Action.Pop
        }
      }, renderedMatches);
    }
    return renderedMatches;
  }
  function DefaultErrorComponent() {
    let error = useRouteError();
    let message = router.isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
    let stack = error instanceof Error ? error.stack : null;
    let lightgrey = "rgba(200,200,200, 0.5)";
    let preStyles = {
      padding: "0.5rem",
      backgroundColor: lightgrey
    };
    let codeStyles = {
      padding: "2px 4px",
      backgroundColor: lightgrey
    };
    let devInfo = null;
    {
      console.error("Error handled by React Router default ErrorBoundary:", error);
      devInfo = /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React__namespace.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /*#__PURE__*/React__namespace.createElement("code", {
        style: codeStyles
      }, "ErrorBoundary"), " or", " ", /*#__PURE__*/React__namespace.createElement("code", {
        style: codeStyles
      }, "errorElement"), " prop on your route."));
    }
    return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React__namespace.createElement("h3", {
      style: {
        fontStyle: "italic"
      }
    }, message), stack ? /*#__PURE__*/React__namespace.createElement("pre", {
      style: preStyles
    }, stack) : null, devInfo);
  }
  const defaultErrorElement = /*#__PURE__*/React__namespace.createElement(DefaultErrorComponent, null);
  class RenderErrorBoundary extends React__namespace.Component {
    constructor(props) {
      super(props);
      this.state = {
        location: props.location,
        revalidation: props.revalidation,
        error: props.error
      };
    }
    static getDerivedStateFromError(error) {
      return {
        error: error
      };
    }
    static getDerivedStateFromProps(props, state) {
      // When we get into an error state, the user will likely click "back" to the
      // previous page that didn't have an error. Because this wraps the entire
      // application, that will have no effect--the error page continues to display.
      // This gives us a mechanism to recover from the error when the location changes.
      //
      // Whether we're in an error state or not, we update the location in state
      // so that when we are in an error state, it gets reset when a new location
      // comes in and the user recovers from the error.
      if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
        return {
          error: props.error,
          location: props.location,
          revalidation: props.revalidation
        };
      }

      // If we're not changing locations, preserve the location but still surface
      // any new errors that may come through. We retain the existing error, we do
      // this because the error provided from the app state may be cleared without
      // the location changing.
      return {
        error: props.error !== undefined ? props.error : state.error,
        location: state.location,
        revalidation: props.revalidation || state.revalidation
      };
    }
    componentDidCatch(error, errorInfo) {
      console.error("React Router caught the following error during render", error, errorInfo);
    }
    render() {
      return this.state.error !== undefined ? /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
        value: this.props.routeContext
      }, /*#__PURE__*/React__namespace.createElement(RouteErrorContext.Provider, {
        value: this.state.error,
        children: this.props.component
      })) : this.props.children;
    }
  }
  function RenderedRoute(_ref) {
    let {
      routeContext,
      match,
      children
    } = _ref;
    let dataRouterContext = React__namespace.useContext(DataRouterContext);

    // Track how deep we got in our render pass to emulate SSR componentDidCatch
    // in a DataStaticRouter
    if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
      dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
    }
    return /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
      value: routeContext
    }, children);
  }
  function _renderMatches(matches, parentMatches, dataRouterState, future) {
    var _dataRouterState;
    if (parentMatches === void 0) {
      parentMatches = [];
    }
    if (dataRouterState === void 0) {
      dataRouterState = null;
    }
    if (future === void 0) {
      future = null;
    }
    if (matches == null) {
      var _future;
      if (!dataRouterState) {
        return null;
      }
      if (dataRouterState.errors) {
        // Don't bail if we have data router errors so we can render them in the
        // boundary.  Use the pre-matched (or shimmed) matches
        matches = dataRouterState.matches;
      } else if ((_future = future) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
        // Don't bail if we're initializing with partial hydration and we have
        // router matches.  That means we're actively running `patchRoutesOnNavigation`
        // so we should render down the partial matches to the appropriate
        // `HydrateFallback`.  We only do this if `parentMatches` is empty so it
        // only impacts the root matches for `RouterProvider` and no descendant
        // `<Routes>`
        matches = dataRouterState.matches;
      } else {
        return null;
      }
    }
    let renderedMatches = matches;

    // If we have data errors, trim matches to the highest error boundary
    let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;
    if (errors != null) {
      let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== undefined);
      !(errorIndex >= 0) ? router.UNSAFE_invariant(false, "Could not find a matching route for errors on route IDs: " + Object.keys(errors).join(","))  : void 0;
      renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
    }

    // If we're in a partial hydration mode, detect if we need to render down to
    // a given HydrateFallback while we load the rest of the hydration data
    let renderFallback = false;
    let fallbackIndex = -1;
    if (dataRouterState && future && future.v7_partialHydration) {
      for (let i = 0; i < renderedMatches.length; i++) {
        let match = renderedMatches[i];
        // Track the deepest fallback up until the first route without data
        if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
          fallbackIndex = i;
        }
        if (match.route.id) {
          let {
            loaderData,
            errors
          } = dataRouterState;
          let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);
          if (match.route.lazy || needsToRunLoader) {
            // We found the first route that's not ready to render (waiting on
            // lazy, or has a loader that hasn't run yet).  Flag that we need to
            // render a fallback and render up until the appropriate fallback
            renderFallback = true;
            if (fallbackIndex >= 0) {
              renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
            } else {
              renderedMatches = [renderedMatches[0]];
            }
            break;
          }
        }
      }
    }
    return renderedMatches.reduceRight((outlet, match, index) => {
      // Only data routers handle errors/fallbacks
      let error;
      let shouldRenderHydrateFallback = false;
      let errorElement = null;
      let hydrateFallbackElement = null;
      if (dataRouterState) {
        error = errors && match.route.id ? errors[match.route.id] : undefined;
        errorElement = match.route.errorElement || defaultErrorElement;
        if (renderFallback) {
          if (fallbackIndex < 0 && index === 0) {
            warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
            shouldRenderHydrateFallback = true;
            hydrateFallbackElement = null;
          } else if (fallbackIndex === index) {
            shouldRenderHydrateFallback = true;
            hydrateFallbackElement = match.route.hydrateFallbackElement || null;
          }
        }
      }
      let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
      let getChildren = () => {
        let children;
        if (error) {
          children = errorElement;
        } else if (shouldRenderHydrateFallback) {
          children = hydrateFallbackElement;
        } else if (match.route.Component) {
          // Note: This is a de-optimized path since React won't re-use the
          // ReactElement since it's identity changes with each new
          // React.createElement call.  We keep this so folks can use
          // `<Route Component={...}>` in `<Routes>` but generally `Component`
          // usage is only advised in `RouterProvider` when we can convert it to
          // `element` ahead of time.
          children = /*#__PURE__*/React__namespace.createElement(match.route.Component, null);
        } else if (match.route.element) {
          children = match.route.element;
        } else {
          children = outlet;
        }
        return /*#__PURE__*/React__namespace.createElement(RenderedRoute, {
          match: match,
          routeContext: {
            outlet,
            matches,
            isDataRoute: dataRouterState != null
          },
          children: children
        });
      };
      // Only wrap in an error boundary within data router usages when we have an
      // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to
      // an ancestor ErrorBoundary/errorElement
      return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React__namespace.createElement(RenderErrorBoundary, {
        location: dataRouterState.location,
        revalidation: dataRouterState.revalidation,
        component: errorElement,
        error: error,
        children: getChildren(),
        routeContext: {
          outlet: null,
          matches,
          isDataRoute: true
        }
      }) : getChildren();
    }, null);
  }
  var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
    DataRouterHook["UseBlocker"] = "useBlocker";
    DataRouterHook["UseRevalidator"] = "useRevalidator";
    DataRouterHook["UseNavigateStable"] = "useNavigate";
    return DataRouterHook;
  }(DataRouterHook || {});
  var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
    DataRouterStateHook["UseBlocker"] = "useBlocker";
    DataRouterStateHook["UseLoaderData"] = "useLoaderData";
    DataRouterStateHook["UseActionData"] = "useActionData";
    DataRouterStateHook["UseRouteError"] = "useRouteError";
    DataRouterStateHook["UseNavigation"] = "useNavigation";
    DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
    DataRouterStateHook["UseMatches"] = "useMatches";
    DataRouterStateHook["UseRevalidator"] = "useRevalidator";
    DataRouterStateHook["UseNavigateStable"] = "useNavigate";
    DataRouterStateHook["UseRouteId"] = "useRouteId";
    return DataRouterStateHook;
  }(DataRouterStateHook || {});
  function getDataRouterConsoleError(hookName) {
    return hookName + " must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.";
  }
  function useDataRouterContext(hookName) {
    let ctx = React__namespace.useContext(DataRouterContext);
    !ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
    return ctx;
  }
  function useDataRouterState(hookName) {
    let state = React__namespace.useContext(DataRouterStateContext);
    !state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
    return state;
  }
  function useRouteContext(hookName) {
    let route = React__namespace.useContext(RouteContext);
    !route ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
    return route;
  }

  // Internal version with hookName-aware debugging
  function useCurrentRouteId(hookName) {
    let route = useRouteContext(hookName);
    let thisRoute = route.matches[route.matches.length - 1];
    !thisRoute.route.id ? router.UNSAFE_invariant(false, hookName + " can only be used on routes that contain a unique \"id\"")  : void 0;
    return thisRoute.route.id;
  }

  /**
   * Returns the ID for the nearest contextual route
   */
  function useRouteId() {
    return useCurrentRouteId(DataRouterStateHook.UseRouteId);
  }

  /**
   * Returns the current navigation, defaulting to an "idle" navigation when
   * no navigation is in progress
   */
  function useNavigation() {
    let state = useDataRouterState(DataRouterStateHook.UseNavigation);
    return state.navigation;
  }

  /**
   * Returns a revalidate function for manually triggering revalidation, as well
   * as the current state of any manual revalidations
   */
  function useRevalidator() {
    let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
    let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
    return React__namespace.useMemo(() => ({
      revalidate: dataRouterContext.router.revalidate,
      state: state.revalidation
    }), [dataRouterContext.router.revalidate, state.revalidation]);
  }

  /**
   * Returns the active route matches, useful for accessing loaderData for
   * parent/child routes or the route "handle" property
   */
  function useMatches() {
    let {
      matches,
      loaderData
    } = useDataRouterState(DataRouterStateHook.UseMatches);
    return React__namespace.useMemo(() => matches.map(m => router.UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
  }

  /**
   * Returns the loader data for the nearest ancestor Route loader
   */
  function useLoaderData() {
    let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
    let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
    if (state.errors && state.errors[routeId] != null) {
      console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
      return undefined;
    }
    return state.loaderData[routeId];
  }

  /**
   * Returns the loaderData for the given routeId
   */
  function useRouteLoaderData(routeId) {
    let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
    return state.loaderData[routeId];
  }

  /**
   * Returns the action data for the nearest ancestor Route action
   */
  function useActionData() {
    let state = useDataRouterState(DataRouterStateHook.UseActionData);
    let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
    return state.actionData ? state.actionData[routeId] : undefined;
  }

  /**
   * Returns the nearest ancestor Route error, which could be a loader/action
   * error or a render error.  This is intended to be called from your
   * ErrorBoundary/errorElement to display a proper error message.
   */
  function useRouteError() {
    var _state$errors;
    let error = React__namespace.useContext(RouteErrorContext);
    let state = useDataRouterState(DataRouterStateHook.UseRouteError);
    let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);

    // If this was a render error, we put it in a RouteError context inside
    // of RenderErrorBoundary
    if (error !== undefined) {
      return error;
    }

    // Otherwise look for errors from our data router state
    return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
  }

  /**
   * Returns the happy-path data from the nearest ancestor `<Await />` value
   */
  function useAsyncValue() {
    let value = React__namespace.useContext(AwaitContext);
    return value == null ? void 0 : value._data;
  }

  /**
   * Returns the error from the nearest ancestor `<Await />` value
   */
  function useAsyncError() {
    let value = React__namespace.useContext(AwaitContext);
    return value == null ? void 0 : value._error;
  }
  let blockerId = 0;

  /**
   * Allow the application to block navigations within the SPA and present the
   * user a confirmation dialog to confirm the navigation.  Mostly used to avoid
   * using half-filled form data.  This does not handle hard-reloads or
   * cross-origin navigations.
   */
  function useBlocker(shouldBlock) {
    let {
      router: router$1,
      basename
    } = useDataRouterContext(DataRouterHook.UseBlocker);
    let state = useDataRouterState(DataRouterStateHook.UseBlocker);
    let [blockerKey, setBlockerKey] = React__namespace.useState("");
    let blockerFunction = React__namespace.useCallback(arg => {
      if (typeof shouldBlock !== "function") {
        return !!shouldBlock;
      }
      if (basename === "/") {
        return shouldBlock(arg);
      }

      // If they provided us a function and we've got an active basename, strip
      // it from the locations we expose to the user to match the behavior of
      // useLocation
      let {
        currentLocation,
        nextLocation,
        historyAction
      } = arg;
      return shouldBlock({
        currentLocation: _extends({}, currentLocation, {
          pathname: router.stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
        }),
        nextLocation: _extends({}, nextLocation, {
          pathname: router.stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
        }),
        historyAction
      });
    }, [basename, shouldBlock]);

    // This effect is in charge of blocker key assignment and deletion (which is
    // tightly coupled to the key)
    React__namespace.useEffect(() => {
      let key = String(++blockerId);
      setBlockerKey(key);
      return () => router$1.deleteBlocker(key);
    }, [router$1]);

    // This effect handles assigning the blockerFunction.  This is to handle
    // unstable blocker function identities, and happens only after the prior
    // effect so we don't get an orphaned blockerFunction in the router with a
    // key of "".  Until then we just have the IDLE_BLOCKER.
    React__namespace.useEffect(() => {
      if (blockerKey !== "") {
        router$1.getBlocker(blockerKey, blockerFunction);
      }
    }, [router$1, blockerKey, blockerFunction]);

    // Prefer the blocker from `state` not `router.state` since DataRouterContext
    // is memoized so this ensures we update on blocker state updates
    return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : router.IDLE_BLOCKER;
  }

  /**
   * Stable version of useNavigate that is used when we are in the context of
   * a RouterProvider.
   */
  function useNavigateStable() {
    let {
      router: router$1
    } = useDataRouterContext(DataRouterHook.UseNavigateStable);
    let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
    let activeRef = React__namespace.useRef(false);
    useIsomorphicLayoutEffect(() => {
      activeRef.current = true;
    });
    let navigate = React__namespace.useCallback(function (to, options) {
      if (options === void 0) {
        options = {};
      }
      router.UNSAFE_warning(activeRef.current, navigateEffectWarning) ;

      // Short circuit here since if this happens on first render the navigate
      // is useless because we haven't wired up our router subscriber yet
      if (!activeRef.current) return;
      if (typeof to === "number") {
        router$1.navigate(to);
      } else {
        router$1.navigate(to, _extends({
          fromRouteId: id
        }, options));
      }
    }, [router$1, id]);
    return navigate;
  }
  const alreadyWarned$1 = {};
  function warningOnce(key, cond, message) {
    if (!cond && !alreadyWarned$1[key]) {
      alreadyWarned$1[key] = true;
      router.UNSAFE_warning(false, message) ;
    }
  }

  const alreadyWarned = {};
  function warnOnce(key, message) {
    if (!alreadyWarned[message]) {
      alreadyWarned[message] = true;
      console.warn(message);
    }
  }
  const logDeprecation = (flag, msg, link) => warnOnce(flag, "\u26A0\uFE0F React Router Future Flag Warning: " + msg + ". " + ("You can use the `" + flag + "` future flag to opt-in early. ") + ("For more information, see " + link + "."));
  function logV6DeprecationWarnings(renderFuture, routerFuture) {
    if ((renderFuture == null ? void 0 : renderFuture.v7_startTransition) === undefined) {
      logDeprecation("v7_startTransition", "React Router will begin wrapping state updates in `React.startTransition` in v7", "https://reactrouter.com/v6/upgrading/future#v7_starttransition");
    }
    if ((renderFuture == null ? void 0 : renderFuture.v7_relativeSplatPath) === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {
      logDeprecation("v7_relativeSplatPath", "Relative route resolution within Splat routes is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath");
    }
    if (routerFuture) {
      if (routerFuture.v7_fetcherPersist === undefined) {
        logDeprecation("v7_fetcherPersist", "The persistence behavior of fetchers is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist");
      }
      if (routerFuture.v7_normalizeFormMethod === undefined) {
        logDeprecation("v7_normalizeFormMethod", "Casing of `formMethod` fields is being normalized to uppercase in v7", "https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod");
      }
      if (routerFuture.v7_partialHydration === undefined) {
        logDeprecation("v7_partialHydration", "`RouterProvider` hydration behavior is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_partialhydration");
      }
      if (routerFuture.v7_skipActionErrorRevalidation === undefined) {
        logDeprecation("v7_skipActionErrorRevalidation", "The revalidation behavior after 4xx/5xx `action` responses is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation");
      }
    }
  }

  /**
    Webpack + React 17 fails to compile on any of the following because webpack
    complains that `startTransition` doesn't exist in `React`:
    * import { startTransition } from "react"
    * import * as React from from "react";
      "startTransition" in React ? React.startTransition(() => setState()) : setState()
    * import * as React from from "react";
      "startTransition" in React ? React["startTransition"](() => setState()) : setState()

    Moving it to a constant such as the following solves the Webpack/React 17 issue:
    * import * as React from from "react";
      const START_TRANSITION = "startTransition";
      START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

    However, that introduces webpack/terser minification issues in production builds
    in React 18 where minification/obfuscation ends up removing the call of
    React.startTransition entirely from the first half of the ternary.  Grabbing
    this exported reference once up front resolves that issue.

    See https://github.com/remix-run/react-router/issues/10579
  */
  const START_TRANSITION = "startTransition";
  const startTransitionImpl = React__namespace[START_TRANSITION];

  /**
   * Given a Remix Router instance, render the appropriate UI
   */
  function RouterProvider(_ref) {
    let {
      fallbackElement,
      router: router$1,
      future
    } = _ref;
    let [state, setStateImpl] = React__namespace.useState(router$1.state);
    let {
      v7_startTransition
    } = future || {};
    let setState = React__namespace.useCallback(newState => {
      if (v7_startTransition && startTransitionImpl) {
        startTransitionImpl(() => setStateImpl(newState));
      } else {
        setStateImpl(newState);
      }
    }, [setStateImpl, v7_startTransition]);

    // Need to use a layout effect here so we are subscribed early enough to
    // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
    React__namespace.useLayoutEffect(() => router$1.subscribe(setState), [router$1, setState]);
    React__namespace.useEffect(() => {
      router.UNSAFE_warning(fallbackElement == null || !router$1.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
      // Only log this once on initial mount
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    let navigator = React__namespace.useMemo(() => {
      return {
        createHref: router$1.createHref,
        encodeLocation: router$1.encodeLocation,
        go: n => router$1.navigate(n),
        push: (to, state, opts) => router$1.navigate(to, {
          state,
          preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
        }),
        replace: (to, state, opts) => router$1.navigate(to, {
          replace: true,
          state,
          preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
        })
      };
    }, [router$1]);
    let basename = router$1.basename || "/";
    let dataRouterContext = React__namespace.useMemo(() => ({
      router: router$1,
      navigator,
      static: false,
      basename
    }), [router$1, navigator, basename]);
    React__namespace.useEffect(() => logV6DeprecationWarnings(future, router$1.future), [router$1, future]);

    // The fragment and {null} here are important!  We need them to keep React 18's
    // useId happy when we are server-rendering since we may have a <script> here
    // containing the hydrated server-side staticContext (from StaticRouterProvider).
    // useId relies on the component tree structure to generate deterministic id's
    // so we need to ensure it remains the same on the client even though
    // we don't need the <script> tag
    return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
      value: dataRouterContext
    }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
      value: state
    }, /*#__PURE__*/React__namespace.createElement(Router, {
      basename: basename,
      location: state.location,
      navigationType: state.historyAction,
      navigator: navigator,
      future: {
        v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
      }
    }, state.initialized || router$1.future.v7_partialHydration ? /*#__PURE__*/React__namespace.createElement(DataRoutes, {
      routes: router$1.routes,
      future: router$1.future,
      state: state
    }) : fallbackElement))), null);
  }
  function DataRoutes(_ref2) {
    let {
      routes,
      future,
      state
    } = _ref2;
    return useRoutesImpl(routes, undefined, state, future);
  }
  /**
   * A `<Router>` that stores all entries in memory.
   *
   * @see https://reactrouter.com/v6/router-components/memory-router
   */
  function MemoryRouter(_ref3) {
    let {
      basename,
      children,
      initialEntries,
      initialIndex,
      future
    } = _ref3;
    let historyRef = React__namespace.useRef();
    if (historyRef.current == null) {
      historyRef.current = router.createMemoryHistory({
        initialEntries,
        initialIndex,
        v5Compat: true
      });
    }
    let history = historyRef.current;
    let [state, setStateImpl] = React__namespace.useState({
      action: history.action,
      location: history.location
    });
    let {
      v7_startTransition
    } = future || {};
    let setState = React__namespace.useCallback(newState => {
      v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
    }, [setStateImpl, v7_startTransition]);
    React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
    React__namespace.useEffect(() => logV6DeprecationWarnings(future), [future]);
    return /*#__PURE__*/React__namespace.createElement(Router, {
      basename: basename,
      children: children,
      location: state.location,
      navigationType: state.action,
      navigator: history,
      future: future
    });
  }
  /**
   * Changes the current location.
   *
   * Note: This API is mostly useful in React.Component subclasses that are not
   * able to use hooks. In functional components, we recommend you use the
   * `useNavigate` hook instead.
   *
   * @see https://reactrouter.com/v6/components/navigate
   */
  function Navigate(_ref4) {
    let {
      to,
      replace,
      state,
      relative
    } = _ref4;
    !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
    // the router loaded. We can help them understand how to avoid that.
    "<Navigate> may be used only in the context of a <Router> component.")  : void 0;
    let {
      future,
      static: isStatic
    } = React__namespace.useContext(NavigationContext);
    router.UNSAFE_warning(!isStatic, "<Navigate> must not be used on the initial render in a <StaticRouter>. " + "This is a no-op, but you should modify your code so the <Navigate> is " + "only ever rendered in response to some user interaction or state change.") ;
    let {
      matches
    } = React__namespace.useContext(RouteContext);
    let {
      pathname: locationPathname
    } = useLocation();
    let navigate = useNavigate();

    // Resolve the path outside of the effect so that when effects run twice in
    // StrictMode they navigate to the same place
    let path = router.resolveTo(to, router.UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
    let jsonPath = JSON.stringify(path);
    React__namespace.useEffect(() => navigate(JSON.parse(jsonPath), {
      replace,
      state,
      relative
    }), [navigate, jsonPath, relative, replace, state]);
    return null;
  }
  /**
   * Renders the child route's element, if there is one.
   *
   * @see https://reactrouter.com/v6/components/outlet
   */
  function Outlet(props) {
    return useOutlet(props.context);
  }
  /**
   * Declares an element that should be rendered at a certain URL path.
   *
   * @see https://reactrouter.com/v6/components/route
   */
  function Route(_props) {
    router.UNSAFE_invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.")  ;
  }
  /**
   * Provides location context for the rest of the app.
   *
   * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
   * router that is more specific to your environment such as a `<BrowserRouter>`
   * in web browsers or a `<StaticRouter>` for server rendering.
   *
   * @see https://reactrouter.com/v6/router-components/router
   */
  function Router(_ref5) {
    let {
      basename: basenameProp = "/",
      children = null,
      location: locationProp,
      navigationType = router.Action.Pop,
      navigator,
      static: staticProp = false,
      future
    } = _ref5;
    !!useInRouterContext() ? router.UNSAFE_invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.")  : void 0;

    // Preserve trailing slashes on basename, so we can let the user control
    // the enforcement of trailing slashes throughout the app
    let basename = basenameProp.replace(/^\/*/, "/");
    let navigationContext = React__namespace.useMemo(() => ({
      basename,
      navigator,
      static: staticProp,
      future: _extends({
        v7_relativeSplatPath: false
      }, future)
    }), [basename, future, navigator, staticProp]);
    if (typeof locationProp === "string") {
      locationProp = router.parsePath(locationProp);
    }
    let {
      pathname = "/",
      search = "",
      hash = "",
      state = null,
      key = "default"
    } = locationProp;
    let locationContext = React__namespace.useMemo(() => {
      let trailingPathname = router.stripBasename(pathname, basename);
      if (trailingPathname == null) {
        return null;
      }
      return {
        location: {
          pathname: trailingPathname,
          search,
          hash,
          state,
          key
        },
        navigationType
      };
    }, [basename, pathname, search, hash, state, key, navigationType]);
    router.UNSAFE_warning(locationContext != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") ;
    if (locationContext == null) {
      return null;
    }
    return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
      value: navigationContext
    }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
      children: children,
      value: locationContext
    }));
  }
  /**
   * A container for a nested tree of `<Route>` elements that renders the branch
   * that best matches the current location.
   *
   * @see https://reactrouter.com/v6/components/routes
   */
  function Routes(_ref6) {
    let {
      children,
      location
    } = _ref6;
    return useRoutes(createRoutesFromChildren(children), location);
  }
  /**
   * Component to use for rendering lazily loaded data from returning defer()
   * in a loader function
   */
  function Await(_ref7) {
    let {
      children,
      errorElement,
      resolve
    } = _ref7;
    return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
      resolve: resolve,
      errorElement: errorElement
    }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
  }
  var AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {
    AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
    AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
    AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
    return AwaitRenderStatus;
  }(AwaitRenderStatus || {});
  const neverSettledPromise = new Promise(() => {});
  class AwaitErrorBoundary extends React__namespace.Component {
    constructor(props) {
      super(props);
      this.state = {
        error: null
      };
    }
    static getDerivedStateFromError(error) {
      return {
        error
      };
    }
    componentDidCatch(error, errorInfo) {
      console.error("<Await> caught the following error during render", error, errorInfo);
    }
    render() {
      let {
        children,
        errorElement,
        resolve
      } = this.props;
      let promise = null;
      let status = AwaitRenderStatus.pending;
      if (!(resolve instanceof Promise)) {
        // Didn't get a promise - provide as a resolved promise
        status = AwaitRenderStatus.success;
        promise = Promise.resolve();
        Object.defineProperty(promise, "_tracked", {
          get: () => true
        });
        Object.defineProperty(promise, "_data", {
          get: () => resolve
        });
      } else if (this.state.error) {
        // Caught a render error, provide it as a rejected promise
        status = AwaitRenderStatus.error;
        let renderError = this.state.error;
        promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
        Object.defineProperty(promise, "_tracked", {
          get: () => true
        });
        Object.defineProperty(promise, "_error", {
          get: () => renderError
        });
      } else if (resolve._tracked) {
        // Already tracked promise - check contents
        promise = resolve;
        status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
      } else {
        // Raw (untracked) promise - track it
        status = AwaitRenderStatus.pending;
        Object.defineProperty(resolve, "_tracked", {
          get: () => true
        });
        promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
          get: () => data
        }), error => Object.defineProperty(resolve, "_error", {
          get: () => error
        }));
      }
      if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
        // Freeze the UI by throwing a never resolved promise
        throw neverSettledPromise;
      }
      if (status === AwaitRenderStatus.error && !errorElement) {
        // No errorElement, throw to the nearest route-level error boundary
        throw promise._error;
      }
      if (status === AwaitRenderStatus.error) {
        // Render via our errorElement
        return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
          value: promise,
          children: errorElement
        });
      }
      if (status === AwaitRenderStatus.success) {
        // Render children with resolved value
        return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
          value: promise,
          children: children
        });
      }

      // Throw to the suspense boundary
      throw promise;
    }
  }

  /**
   * @private
   * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
   */
  function ResolveAwait(_ref8) {
    let {
      children
    } = _ref8;
    let data = useAsyncValue();
    let toRender = typeof children === "function" ? children(data) : children;
    return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
  }

  ///////////////////////////////////////////////////////////////////////////////
  // UTILS
  ///////////////////////////////////////////////////////////////////////////////

  /**
   * Creates a route config from a React "children" object, which is usually
   * either a `<Route>` element or an array of them. Used internally by
   * `<Routes>` to create a route config from its children.
   *
   * @see https://reactrouter.com/v6/utils/create-routes-from-children
   */
  function createRoutesFromChildren(children, parentPath) {
    if (parentPath === void 0) {
      parentPath = [];
    }
    let routes = [];
    React__namespace.Children.forEach(children, (element, index) => {
      if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
        // Ignore non-elements. This allows people to more easily inline
        // conditionals in their route config.
        return;
      }
      let treePath = [...parentPath, index];
      if (element.type === React__namespace.Fragment) {
        // Transparently support React.Fragment and its children.
        routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
        return;
      }
      !(element.type === Route) ? router.UNSAFE_invariant(false, "[" + (typeof element.type === "string" ? element.type : element.type.name) + "] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>")  : void 0;
      !(!element.props.index || !element.props.children) ? router.UNSAFE_invariant(false, "An index route cannot have child routes.")  : void 0;
      let route = {
        id: element.props.id || treePath.join("-"),
        caseSensitive: element.props.caseSensitive,
        element: element.props.element,
        Component: element.props.Component,
        index: element.props.index,
        path: element.props.path,
        loader: element.props.loader,
        action: element.props.action,
        errorElement: element.props.errorElement,
        ErrorBoundary: element.props.ErrorBoundary,
        hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
        shouldRevalidate: element.props.shouldRevalidate,
        handle: element.props.handle,
        lazy: element.props.lazy
      };
      if (element.props.children) {
        route.children = createRoutesFromChildren(element.props.children, treePath);
      }
      routes.push(route);
    });
    return routes;
  }

  /**
   * Renders the result of `matchRoutes()` into a React element.
   */
  function renderMatches(matches) {
    return _renderMatches(matches);
  }

  function mapRouteProperties(route) {
    let updates = {
      // Note: this check also occurs in createRoutesFromChildren so update
      // there if you change this -- please and thank you!
      hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
    };
    if (route.Component) {
      {
        if (route.element) {
          router.UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
        }
      }
      Object.assign(updates, {
        element: /*#__PURE__*/React__namespace.createElement(route.Component),
        Component: undefined
      });
    }
    if (route.HydrateFallback) {
      {
        if (route.hydrateFallbackElement) {
          router.UNSAFE_warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - " + "`HydrateFallback` will be used.") ;
        }
      }
      Object.assign(updates, {
        hydrateFallbackElement: /*#__PURE__*/React__namespace.createElement(route.HydrateFallback),
        HydrateFallback: undefined
      });
    }
    if (route.ErrorBoundary) {
      {
        if (route.errorElement) {
          router.UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
        }
      }
      Object.assign(updates, {
        errorElement: /*#__PURE__*/React__namespace.createElement(route.ErrorBoundary),
        ErrorBoundary: undefined
      });
    }
    return updates;
  }
  function createMemoryRouter(routes, opts) {
    return router.createRouter({
      basename: opts == null ? void 0 : opts.basename,
      future: _extends({}, opts == null ? void 0 : opts.future, {
        v7_prependBasename: true
      }),
      history: router.createMemoryHistory({
        initialEntries: opts == null ? void 0 : opts.initialEntries,
        initialIndex: opts == null ? void 0 : opts.initialIndex
      }),
      hydrationData: opts == null ? void 0 : opts.hydrationData,
      routes,
      mapRouteProperties,
      dataStrategy: opts == null ? void 0 : opts.dataStrategy,
      patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation
    }).initialize();
  }

  Object.defineProperty(exports, 'AbortedDeferredError', {
    enumerable: true,
    get: function () { return router.AbortedDeferredError; }
  });
  Object.defineProperty(exports, 'NavigationType', {
    enumerable: true,
    get: function () { return router.Action; }
  });
  Object.defineProperty(exports, 'createPath', {
    enumerable: true,
    get: function () { return router.createPath; }
  });
  Object.defineProperty(exports, 'defer', {
    enumerable: true,
    get: function () { return router.defer; }
  });
  Object.defineProperty(exports, 'generatePath', {
    enumerable: true,
    get: function () { return router.generatePath; }
  });
  Object.defineProperty(exports, 'isRouteErrorResponse', {
    enumerable: true,
    get: function () { return router.isRouteErrorResponse; }
  });
  Object.defineProperty(exports, 'json', {
    enumerable: true,
    get: function () { return router.json; }
  });
  Object.defineProperty(exports, 'matchPath', {
    enumerable: true,
    get: function () { return router.matchPath; }
  });
  Object.defineProperty(exports, 'matchRoutes', {
    enumerable: true,
    get: function () { return router.matchRoutes; }
  });
  Object.defineProperty(exports, 'parsePath', {
    enumerable: true,
    get: function () { return router.parsePath; }
  });
  Object.defineProperty(exports, 'redirect', {
    enumerable: true,
    get: function () { return router.redirect; }
  });
  Object.defineProperty(exports, 'redirectDocument', {
    enumerable: true,
    get: function () { return router.redirectDocument; }
  });
  Object.defineProperty(exports, 'replace', {
    enumerable: true,
    get: function () { return router.replace; }
  });
  Object.defineProperty(exports, 'resolvePath', {
    enumerable: true,
    get: function () { return router.resolvePath; }
  });
  exports.Await = Await;
  exports.MemoryRouter = MemoryRouter;
  exports.Navigate = Navigate;
  exports.Outlet = Outlet;
  exports.Route = Route;
  exports.Router = Router;
  exports.RouterProvider = RouterProvider;
  exports.Routes = Routes;
  exports.UNSAFE_DataRouterContext = DataRouterContext;
  exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
  exports.UNSAFE_LocationContext = LocationContext;
  exports.UNSAFE_NavigationContext = NavigationContext;
  exports.UNSAFE_RouteContext = RouteContext;
  exports.UNSAFE_logV6DeprecationWarnings = logV6DeprecationWarnings;
  exports.UNSAFE_mapRouteProperties = mapRouteProperties;
  exports.UNSAFE_useRouteId = useRouteId;
  exports.UNSAFE_useRoutesImpl = useRoutesImpl;
  exports.createMemoryRouter = createMemoryRouter;
  exports.createRoutesFromChildren = createRoutesFromChildren;
  exports.createRoutesFromElements = createRoutesFromChildren;
  exports.renderMatches = renderMatches;
  exports.useActionData = useActionData;
  exports.useAsyncError = useAsyncError;
  exports.useAsyncValue = useAsyncValue;
  exports.useBlocker = useBlocker;
  exports.useHref = useHref;
  exports.useInRouterContext = useInRouterContext;
  exports.useLoaderData = useLoaderData;
  exports.useLocation = useLocation;
  exports.useMatch = useMatch;
  exports.useMatches = useMatches;
  exports.useNavigate = useNavigate;
  exports.useNavigation = useNavigation;
  exports.useNavigationType = useNavigationType;
  exports.useOutlet = useOutlet;
  exports.useOutletContext = useOutletContext;
  exports.useParams = useParams;
  exports.useResolvedPath = useResolvedPath;
  exports.useRevalidator = useRevalidator;
  exports.useRouteError = useRouteError;
  exports.useRouteLoaderData = useRouteLoaderData;
  exports.useRoutes = useRoutes;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=react-router.development.js.map
{"version":3,"file":"react-router.development.js","sources":["../../lib/context.ts","../../lib/hooks.tsx","../../lib/deprecations.ts","../../lib/components.tsx","../../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>ðŸ’¿ Hey developer ðŸ‘‹</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (__DEV__ && !alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `âš ï¸� React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (renderFuture?.v7_startTransition === undefined) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    renderFuture?.v7_relativeSplatPath === undefined &&\n    (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (routerFuture.v7_fetcherPersist === undefined) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (routerFuture.v7_normalizeFormMethod === undefined) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (routerFuture.v7_partialHydration === undefined) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n","import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n"],"names":["DataRouterContext","React","createContext","displayName","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useHref","to","_temp","relative","useInRouterContext","invariant","basename","navigator","useContext","hash","pathname","search","useResolvedPath","joinedPathname","joinPaths","createHref","useLocation","location","useNavigationType","navigationType","useMatch","pattern","useMemo","matchPath","decodePath","navigateEffectWarning","useIsomorphicLayoutEffect","cb","isStatic","static","useLayoutEffect","useNavigate","useNavigateStable","useNavigateUnstable","dataRouterContext","future","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","activeRef","useRef","current","navigate","useCallback","options","process","warning","go","path","resolveTo","parse","replace","push","state","OutletContext","useOutletContext","useOutlet","context","createElement","Provider","value","useParams","routeMatch","length","params","_temp2","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathname","parentPathnameBase","pathnameBase","parentRoute","route","parentPath","warningOnce","endsWith","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","segments","slice","join","matchRoutes","element","undefined","Component","lazy","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","_extends","key","NavigationType","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","lightgrey","preStyles","padding","backgroundColor","codeStyles","devInfo","console","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","constructor","props","revalidation","getDerivedStateFromError","getDerivedStateFromProps","componentDidCatch","errorInfo","render","routeContext","children","component","RenderedRoute","_ref","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","id","_dataRouterState","_future","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","keys","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","reduceRight","index","shouldRenderHydrateFallback","concat","getChildren","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","useDataRouterState","useRouteContext","useCurrentRouteId","thisRoute","useRouteId","UseRouteId","useNavigation","UseNavigation","navigation","useRevalidator","UseRevalidator","revalidate","router","useMatches","UseMatches","convertRouteMatchToUiMatch","useLoaderData","UseLoaderData","routeId","useRouteLoaderData","UseRouteLoaderData","useActionData","UseActionData","actionData","_state$errors","UseRouteError","useAsyncValue","_data","useAsyncError","_error","blockerId","useBlocker","shouldBlock","UseBlocker","blockerKey","setBlockerKey","useState","blockerFunction","arg","currentLocation","nextLocation","historyAction","stripBasename","useEffect","String","deleteBlocker","getBlocker","blockers","has","get","IDLE_BLOCKER","UseNavigateStable","fromRouteId","alreadyWarned","cond","warnOnce","warn","logDeprecation","flag","msg","link","logV6DeprecationWarnings","renderFuture","routerFuture","v7_startTransition","v7_fetcherPersist","v7_normalizeFormMethod","v7_skipActionErrorRevalidation","START_TRANSITION","startTransitionImpl","RouterProvider","fallbackElement","setStateImpl","setState","newState","subscribe","n","opts","preventScrollReset","Router","DataRoutes","_ref2","MemoryRouter","_ref3","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","action","listen","Navigate","_ref4","jsonPath","Outlet","Route","_props","_ref5","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","_ref6","createRoutesFromChildren","Await","_ref7","resolve","AwaitErrorBoundary","ResolveAwait","AwaitRenderStatus","neverSettledPromise","Promise","promise","pending","success","defineProperty","renderError","reject","catch","_tracked","then","data","AbortedDeferredError","_ref8","toRender","Children","forEach","isValidElement","treePath","type","apply","name","caseSensitive","hasErrorBoundary","shouldRevalidate","handle","renderMatches","mapRouteProperties","updates","createMemoryRouter","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgBA;EACA;;AA+DO,QAAMA,iBAAiB,gBAC5BC,gBAAK,CAACC,aAAa,CAAiC,IAAI,EAAC;EAC9C;IACXF,iBAAiB,CAACG,WAAW,GAAG,YAAY,CAAA;EAC9C,CAAA;AAEO,QAAMC,sBAAsB,gBAAGH,gBAAK,CAACC,a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AAI,CAAE3P,QAAQ;EACxB6B,IAAAA,MAAM,EAAAwE,QAAA,CAAA,EAAA,EACDsJ,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAE9N,MAAM,EAAA;EACfkS,MAAAA,kBAAkB,EAAE,IAAA;OACrB,CAAA;MACDxD,OAAO,EAAEF,0BAAmB,CAAC;EAC3BH,MAAAA,cAAc,EAAEP,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEO,cAAc;EACpCC,MAAAA,YAAY,EAAER,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEQ,YAAAA;EACtB,KAAC,CAAC;EACF6D,IAAAA,aAAa,EAAErE,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEqE,aAAa;MAClChQ,MAAM;MACN2P,kBAAkB;EAClBM,IAAAA,YAAY,EAAEtE,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEsE,YAAY;EAChCC,IAAAA,uBAAuB,EAAEvE,IAAI,IAAJA,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,IAAI,CAAEuE,uBAAAA;EACjC,GAAC,CAAC,CAACC,UAAU,EAAE,CAAA;EACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}/**
 * React Router v6.30.6
 *
 * 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
 */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouter={},e.React,e.RemixRouter)}(this,function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var a=n(t);function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o.apply(null,arguments)}const i=a.createContext(null),u=a.createContext(null),l=a.createContext(null),s=a.createContext(null),c=a.createContext(null),d=a.createContext({outlet:null,matches:[],isDataRoute:!1}),p=a.createContext(null);function f(){return null!=a.useContext(c)}function v(){return f()||r.UNSAFE_invariant(!1),a.useContext(c).location}function m(e){a.useContext(s).static||a.useLayoutEffect(e)}function h(){let{isDataRoute:e}=a.useContext(d);return e?function(){let{router:e}=A(U.UseNavigateStable),t=F(N.UseNavigateStable),r=a.useRef(!1);m(()=>{r.current=!0});let n=a.useCallback(function(n,a){void 0===a&&(a={}),r.current&&("number"==typeof n?e.navigate(n):e.navigate(n,o({fromRouteId:t},a)))},[e,t]);return n}():function(){f()||r.UNSAFE_invariant(!1);let e=a.useContext(i),{basename:t,future:n,navigator:o}=a.useContext(s),{matches:u}=a.useContext(d),{pathname:l}=v(),c=JSON.stringify(r.UNSAFE_getResolveToMatches(u,n.v7_relativeSplatPath)),p=a.useRef(!1);return m(()=>{p.current=!0}),a.useCallback(function(n,a){if(void 0===a&&(a={}),!p.current)return;if("number"==typeof n)return void o.go(n);let i=r.resolveTo(n,JSON.parse(c),l,"path"===a.relative);null==e&&"/"!==t&&(i.pathname="/"===i.pathname?t:r.joinPaths([t,i.pathname])),(a.replace?o.replace:o.push)(i,a.state,a)},[t,o,c,l,e])}()}const E=a.createContext(null);function g(e){let t=a.useContext(d).outlet;return t?a.createElement(E.Provider,{value:e},t):t}function y(e,t){let{relative:n}=void 0===t?{}:t,{future:o}=a.useContext(s),{matches:i}=a.useContext(d),{pathname:u}=v(),l=JSON.stringify(r.UNSAFE_getResolveToMatches(i,o.v7_relativeSplatPath));return a.useMemo(()=>r.resolveTo(e,JSON.parse(l),u,"path"===n),[e,l,u,n])}function b(e,t){return R(e,t)}function R(e,t,n,i){f()||r.UNSAFE_invariant(!1);let{navigator:u}=a.useContext(s),{matches:l}=a.useContext(d),p=l[l.length-1],m=p?p.params:{};!p||p.pathname;let h=p?p.pathnameBase:"/";p&&p.route;let E,g=v();if(t){var y;let e="string"==typeof t?r.parsePath(t):t;"/"===h||(null==(y=e.pathname)?void 0:y.startsWith(h))||r.UNSAFE_invariant(!1),E=e}else E=g;let b=E.pathname||"/",R=b;if("/"!==h){let e=h.replace(/^\//,"").split("/");R="/"+b.replace(/^\//,"").split("/").slice(e.length).join("/")}let P=r.matchRoutes(e,{pathname:R}),_=S(P&&P.map(e=>Object.assign({},e,{params:Object.assign({},m,e.params),pathname:r.joinPaths([h,u.encodeLocation?u.encodeLocation(e.pathname).pathname:e.pathname]),pathnameBase:"/"===e.pathnameBase?h:r.joinPaths([h,u.encodeLocation?u.encodeLocation(e.pathnameBase).pathname:e.pathnameBase])})),l,n,i);return t&&_?a.createElement(c.Provider,{value:{location:o({pathname:"/",search:"",hash:"",state:null,key:"default"},E),navigationType:r.Action.Pop}},_):_}function P(){let e=j(),t=r.isRouteErrorResponse(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return a.createElement(a.Fragment,null,a.createElement("h2",null,"Unexpected Application Error!"),a.createElement("h3",{style:{fontStyle:"italic"}},t),n?a.createElement("pre",{style:o},n):null,null)}const _=a.createElement(P,null);class x extends a.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||"idle"!==t.revalidation&&"idle"===e.revalidation?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:void 0!==e.error?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return void 0!==this.state.error?a.createElement(d.Provider,{value:this.props.routeContext},a.createElement(p.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function C(e){let{routeContext:t,match:r,children:n}=e,o=a.useContext(i);return o&&o.static&&o.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=r.route.id),a.createElement(d.Provider,{value:t},n)}function S(e,t,n,o){var i;if(void 0===t&&(t=[]),void 0===n&&(n=null),void 0===o&&(o=null),null==e){var u;if(!n)return null;if(n.errors)e=n.matches;else{if(!(null!=(u=o)&&u.v7_partialHydration&&0===t.length&&!n.initialized&&n.matches.length>0))return null;e=n.matches}}let l=e,s=null==(i=n)?void 0:i.errors;if(null!=s){let e=l.findIndex(e=>e.route.id&&void 0!==(null==s?void 0:s[e.route.id]));e>=0||r.UNSAFE_invariant(!1),l=l.slice(0,Math.min(l.length,e+1))}let c=!1,d=-1;if(n&&o&&o.v7_partialHydration)for(let e=0;e<l.length;e++){let t=l[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(d=e),t.route.id){let{loaderData:e,errors:r}=n,a=t.route.loader&&void 0===e[t.route.id]&&(!r||void 0===r[t.route.id]);if(t.route.lazy||a){c=!0,l=d>=0?l.slice(0,d+1):[l[0]];break}}}return l.reduceRight((e,r,o)=>{let i,u=!1,p=null,f=null;var v;n&&(i=s&&r.route.id?s[r.route.id]:void 0,p=r.route.errorElement||_,c&&(d<0&&0===o?(v="route-fallback",!1||B[v]||(B[v]=!0),u=!0,f=null):d===o&&(u=!0,f=r.route.hydrateFallbackElement||null)));let m=t.concat(l.slice(0,o+1)),h=()=>{let t;return t=i?p:u?f:r.route.Component?a.createElement(r.route.Component,null):r.route.element?r.route.element:e,a.createElement(C,{match:r,routeContext:{outlet:e,matches:m,isDataRoute:null!=n},children:t})};return n&&(r.route.ErrorBoundary||r.route.errorElement||0===o)?a.createElement(x,{location:n.location,revalidation:n.revalidation,component:p,error:i,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0}}):h()},null)}var U=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(U||{}),N=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(N||{});function A(e){let t=a.useContext(i);return t||r.UNSAFE_invariant(!1),t}function O(e){let t=a.useContext(u);return t||r.UNSAFE_invariant(!1),t}function F(e){let t=function(){let e=a.useContext(d);return e||r.UNSAFE_invariant(!1),e}(),n=t.matches[t.matches.length-1];return n.route.id||r.UNSAFE_invariant(!1),n.route.id}function j(){var e;let t=a.useContext(p),r=O(N.UseRouteError),n=F(N.UseRouteError);return void 0!==t?t:null==(e=r.errors)?void 0:e[n]}function D(){let e=a.useContext(l);return null==e?void 0:e._data}let k=0;const B={};function L(e,t){null==e||e.v7_startTransition,void 0===(null==e?void 0:e.v7_relativeSplatPath)&&(!t||t.v7_relativeSplatPath),t&&(t.v7_fetcherPersist,t.v7_normalizeFormMethod,t.v7_partialHydration,t.v7_skipActionErrorRevalidation)}const M=a.startTransition;function T(e){let{routes:t,future:r,state:n}=e;return R(t,void 0,n,r)}function I(e){r.UNSAFE_invariant(!1)}function H(e){let{basename:t="/",children:n=null,location:i,navigationType:u=r.Action.Pop,navigator:l,static:d=!1,future:p}=e;f()&&r.UNSAFE_invariant(!1);let v=t.replace(/^\/*/,"/"),m=a.useMemo(()=>({basename:v,navigator:l,static:d,future:o({v7_relativeSplatPath:!1},p)}),[v,p,l,d]);"string"==typeof i&&(i=r.parsePath(i));let{pathname:h="/",search:E="",hash:g="",state:y=null,key:b="default"}=i,R=a.useMemo(()=>{let e=r.stripBasename(h,v);return null==e?null:{location:{pathname:e,search:E,hash:g,state:y,key:b},navigationType:u}},[v,h,E,g,y,b,u]);return null==R?null:a.createElement(s.Provider,{value:m},a.createElement(c.Provider,{children:n,value:R}))}var w=function(e){return e[e.pending=0]="pending",e[e.success=1]="success",e[e.error=2]="error",e}(w||{});const z=new Promise(()=>{});class J extends a.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("<Await> caught the following error during render",e,t)}render(){let{children:e,errorElement:t,resolve:n}=this.props,o=null,i=w.pending;if(n instanceof Promise)if(this.state.error){i=w.error;let e=this.state.error;o=Promise.reject().catch(()=>{}),Object.defineProperty(o,"_tracked",{get:()=>!0}),Object.defineProperty(o,"_error",{get:()=>e})}else n._tracked?(o=n,i="_error"in o?w.error:"_data"in o?w.success:w.pending):(i=w.pending,Object.defineProperty(n,"_tracked",{get:()=>!0}),o=n.then(e=>Object.defineProperty(n,"_data",{get:()=>e}),e=>Object.defineProperty(n,"_error",{get:()=>e})));else i=w.success,o=Promise.resolve(),Object.defineProperty(o,"_tracked",{get:()=>!0}),Object.defineProperty(o,"_data",{get:()=>n});if(i===w.error&&o._error instanceof r.AbortedDeferredError)throw z;if(i===w.error&&!t)throw o._error;if(i===w.error)return a.createElement(l.Provider,{value:o,children:t});if(i===w.success)return a.createElement(l.Provider,{value:o,children:e});throw o}}function V(e){let{children:t}=e,r=D(),n="function"==typeof t?t(r):t;return a.createElement(a.Fragment,null,n)}function q(e,t){void 0===t&&(t=[]);let n=[];return a.Children.forEach(e,(e,o)=>{if(!a.isValidElement(e))return;let i=[...t,o];if(e.type===a.Fragment)return void n.push.apply(n,q(e.props.children,i));e.type!==I&&r.UNSAFE_invariant(!1),e.props.index&&e.props.children&&r.UNSAFE_invariant(!1);let u={id:e.props.id||i.join("-"),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,loader:e.props.loader,action:e.props.action,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:null!=e.props.ErrorBoundary||null!=e.props.errorElement,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(u.children=q(e.props.children,i)),n.push(u)}),n}function W(e){let t={hasErrorBoundary:null!=e.ErrorBoundary||null!=e.errorElement};return e.Component&&Object.assign(t,{element:a.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:a.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:a.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.Action}}),Object.defineProperty(e,"createPath",{enumerable:!0,get:function(){return r.createPath}}),Object.defineProperty(e,"defer",{enumerable:!0,get:function(){return r.defer}}),Object.defineProperty(e,"generatePath",{enumerable:!0,get:function(){return r.generatePath}}),Object.defineProperty(e,"isRouteErrorResponse",{enumerable:!0,get:function(){return r.isRouteErrorResponse}}),Object.defineProperty(e,"json",{enumerable:!0,get:function(){return r.json}}),Object.defineProperty(e,"matchPath",{enumerable:!0,get:function(){return r.matchPath}}),Object.defineProperty(e,"matchRoutes",{enumerable:!0,get:function(){return r.matchRoutes}}),Object.defineProperty(e,"parsePath",{enumerable:!0,get:function(){return r.parsePath}}),Object.defineProperty(e,"redirect",{enumerable:!0,get:function(){return r.redirect}}),Object.defineProperty(e,"redirectDocument",{enumerable:!0,get:function(){return r.redirectDocument}}),Object.defineProperty(e,"replace",{enumerable:!0,get:function(){return r.replace}}),Object.defineProperty(e,"resolvePath",{enumerable:!0,get:function(){return r.resolvePath}}),e.Await=function(e){let{children:t,errorElement:r,resolve:n}=e;return a.createElement(J,{resolve:n,errorElement:r},a.createElement(V,null,t))},e.MemoryRouter=function(e){let{basename:t,children:n,initialEntries:o,initialIndex:i,future:u}=e,l=a.useRef();null==l.current&&(l.current=r.createMemoryHistory({initialEntries:o,initialIndex:i,v5Compat:!0}));let s=l.current,[c,d]=a.useState({action:s.action,location:s.location}),{v7_startTransition:p}=u||{},f=a.useCallback(e=>{p&&M?M(()=>d(e)):d(e)},[d,p]);return a.useLayoutEffect(()=>s.listen(f),[s,f]),a.useEffect(()=>L(u),[u]),a.createElement(H,{basename:t,children:n,location:c.location,navigationType:c.action,navigator:s,future:u})},e.Navigate=function(e){let{to:t,replace:n,state:o,relative:i}=e;f()||r.UNSAFE_invariant(!1);let{future:u,static:l}=a.useContext(s),{matches:c}=a.useContext(d),{pathname:p}=v(),m=h(),E=r.resolveTo(t,r.UNSAFE_getResolveToMatches(c,u.v7_relativeSplatPath),p,"path"===i),g=JSON.stringify(E);return a.useEffect(()=>m(JSON.parse(g),{replace:n,state:o,relative:i}),[m,g,i,n,o]),null},e.Outlet=function(e){return g(e.context)},e.Route=I,e.Router=H,e.RouterProvider=function(e){let{fallbackElement:t,router:r,future:n}=e,[o,l]=a.useState(r.state),{v7_startTransition:s}=n||{},c=a.useCallback(e=>{s&&M?M(()=>l(e)):l(e)},[l,s]);a.useLayoutEffect(()=>r.subscribe(c),[r,c]),a.useEffect(()=>{},[]);let d=a.useMemo(()=>({createHref:r.createHref,encodeLocation:r.encodeLocation,go:e=>r.navigate(e),push:(e,t,n)=>r.navigate(e,{state:t,preventScrollReset:null==n?void 0:n.preventScrollReset}),replace:(e,t,n)=>r.navigate(e,{replace:!0,state:t,preventScrollReset:null==n?void 0:n.preventScrollReset})}),[r]),p=r.basename||"/",f=a.useMemo(()=>({router:r,navigator:d,static:!1,basename:p}),[r,d,p]);return a.useEffect(()=>L(n,r.future),[r,n]),a.createElement(a.Fragment,null,a.createElement(i.Provider,{value:f},a.createElement(u.Provider,{value:o},a.createElement(H,{basename:p,location:o.location,navigationType:o.historyAction,navigator:d,future:{v7_relativeSplatPath:r.future.v7_relativeSplatPath}},o.initialized||r.future.v7_partialHydration?a.createElement(T,{routes:r.routes,future:r.future,state:o}):t))),null)},e.Routes=function(e){let{children:t,location:r}=e;return b(q(t),r)},e.UNSAFE_DataRouterContext=i,e.UNSAFE_DataRouterStateContext=u,e.UNSAFE_LocationContext=c,e.UNSAFE_NavigationContext=s,e.UNSAFE_RouteContext=d,e.UNSAFE_logV6DeprecationWarnings=L,e.UNSAFE_mapRouteProperties=W,e.UNSAFE_useRouteId=function(){return F(N.UseRouteId)},e.UNSAFE_useRoutesImpl=R,e.createMemoryRouter=function(e,t){return r.createRouter({basename:null==t?void 0:t.basename,future:o({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:r.createMemoryHistory({initialEntries:null==t?void 0:t.initialEntries,initialIndex:null==t?void 0:t.initialIndex}),hydrationData:null==t?void 0:t.hydrationData,routes:e,mapRouteProperties:W,dataStrategy:null==t?void 0:t.dataStrategy,patchRoutesOnNavigation:null==t?void 0:t.patchRoutesOnNavigation}).initialize()},e.createRoutesFromChildren=q,e.createRoutesFromElements=q,e.renderMatches=function(e){return S(e)},e.useActionData=function(){let e=O(N.UseActionData),t=F(N.UseLoaderData);return e.actionData?e.actionData[t]:void 0},e.useAsyncError=function(){let e=a.useContext(l);return null==e?void 0:e._error},e.useAsyncValue=D,e.useBlocker=function(e){let{router:t,basename:n}=A(U.UseBlocker),i=O(N.UseBlocker),[u,l]=a.useState(""),s=a.useCallback(t=>{if("function"!=typeof e)return!!e;if("/"===n)return e(t);let{currentLocation:a,nextLocation:i,historyAction:u}=t;return e({currentLocation:o({},a,{pathname:r.stripBasename(a.pathname,n)||a.pathname}),nextLocation:o({},i,{pathname:r.stripBasename(i.pathname,n)||i.pathname}),historyAction:u})},[n,e]);return a.useEffect(()=>{let e=String(++k);return l(e),()=>t.deleteBlocker(e)},[t]),a.useEffect(()=>{""!==u&&t.getBlocker(u,s)},[t,u,s]),u&&i.blockers.has(u)?i.blockers.get(u):r.IDLE_BLOCKER},e.useHref=function(e,t){let{relative:n}=void 0===t?{}:t;f()||r.UNSAFE_invariant(!1);let{basename:o,navigator:i}=a.useContext(s),{hash:u,pathname:l,search:c}=y(e,{relative:n}),d=l;return"/"!==o&&(d="/"===l?o:r.joinPaths([o,l])),i.createHref({pathname:d,search:c,hash:u})},e.useInRouterContext=f,e.useLoaderData=function(){let e=O(N.UseLoaderData),t=F(N.UseLoaderData);if(!e.errors||null==e.errors[t])return e.loaderData[t];console.error("You cannot `useLoaderData` in an errorElement (routeId: "+t+")")},e.useLocation=v,e.useMatch=function(e){f()||r.UNSAFE_invariant(!1);let{pathname:t}=v();return a.useMemo(()=>r.matchPath(e,r.UNSAFE_decodePath(t)),[t,e])},e.useMatches=function(){let{matches:e,loaderData:t}=O(N.UseMatches);return a.useMemo(()=>e.map(e=>r.UNSAFE_convertRouteMatchToUiMatch(e,t)),[e,t])},e.useNavigate=h,e.useNavigation=function(){return O(N.UseNavigation).navigation},e.useNavigationType=function(){return a.useContext(c).navigationType},e.useOutlet=g,e.useOutletContext=function(){return a.useContext(E)},e.useParams=function(){let{matches:e}=a.useContext(d),t=e[e.length-1];return t?t.params:{}},e.useResolvedPath=y,e.useRevalidator=function(){let e=A(U.UseRevalidator),t=O(N.UseRevalidator);return a.useMemo(()=>({revalidate:e.router.revalidate,state:t.revalidation}),[e.router.revalidate,t.revalidation])},e.useRouteError=j,e.useRouteLoaderData=function(e){return O(N.UseRouteLoaderData).loaderData[e]},e.useRoutes=b,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=react-router.production.min.js.map
{"version":3,"file":"react-router.production.min.js","sources":["../../lib/context.ts","../../lib/hooks.tsx","../../lib/deprecations.ts","../../lib/components.tsx","../../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>ðŸ’¿ Hey developer ðŸ‘‹</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (__DEV__ && !alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `âš ï¸� React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (renderFuture?.v7_startTransition === undefined) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    renderFuture?.v7_relativeSplatPath === undefined &&\n    (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (routerFuture.v7_fetcherPersist === undefined) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (routerFuture.v7_normalizeFormMethod === undefined) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (routerFuture.v7_partialHydration === undefined) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n","import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n"],"names":["DataRouterContext","React","createContext","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useInRouterContext","useContext","useLocation","invariant","location","useIsomorphicLayoutEffect","cb","static","useLayoutEffect","useNavigate","router","useDataRouterContext","DataRouterHook","UseNavigateStable","id","useCurrentRouteId","DataRouterStateHook","activeRef","useRef","current","navigate","useCallback","to","options","_extends","fromRouteId","useNavigateStable","dataRouterContext","basename","future","navigator","pathname","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","go","path","resolveTo","parse","relative","joinPaths","replace","push","state","useNavigateUnstable","OutletContext","useOutlet","context","createElement","Provider","value","useResolvedPath","_temp2","useMemo","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","routeMatch","length","parentParams","params","parentPathnameBase","pathnameBase","route","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","slice","join","matchRoutes","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","search","hash","key","navigationType","NavigationType","Action","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","preStyles","padding","backgroundColor","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","Component","constructor","props","super","this","revalidation","getDerivedStateFromError","getDerivedStateFromProps","undefined","componentDidCatch","errorInfo","console","render","routeContext","children","component","RenderedRoute","_ref","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState","_future","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","UNSAFE_invariant","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","lazy","reduceRight","index","shouldRenderHydrateFallback","alreadyWarned","concat","getChildren","element","hookName","ctx","useDataRouterState","useRouteContext","thisRoute","_state$errors","UseRouteError","routeId","useAsyncValue","_data","blockerId","logV6DeprecationWarnings","renderFuture","routerFuture","v7_startTransition","v7_fetcherPersist","v7_normalizeFormMethod","v7_skipActionErrorRevalidation","startTransitionImpl","DataRoutes","_ref2","Route","_props","Router","_ref5","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","stripBasename","AwaitRenderStatus","neverSettledPromise","Promise","AwaitErrorBoundary","resolve","promise","pending","renderError","reject","catch","defineProperty","get","_tracked","success","then","data","_error","AbortedDeferredError","ResolveAwait","_ref8","toRender","createRoutesFromChildren","parentPath","Children","forEach","isValidElement","treePath","type","apply","caseSensitive","action","hasErrorBoundary","shouldRevalidate","handle","mapRouteProperties","updates","_ref7","_ref3","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","setStateImpl","useState","setState","newState","listen","useEffect","_ref4","isStatic","UNSAFE_getResolveToMatches","jsonPath","fallbackElement","subscribe","createHref","n","opts","preventScrollReset","historyAction","_ref6","UseRouteId","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize","UseActionData","UseLoaderData","actionData","shouldBlock","UseBlocker","blockerKey","setBlockerKey","blockerFunction","arg","currentLocation","nextLocation","String","deleteBlocker","getBlocker","blockers","has","IDLE_BLOCKER","_temp","joinedPathname","pattern","matchPath","decodePath","UseMatches","convertRouteMatchToUiMatch","UseNavigation","navigation","UseRevalidator","revalidate","UseRouteLoaderData"],"mappings":";;;;;;;;;;s1BAgFO,MAAMA,EACXC,EAAMC,cAA8C,MAKzCC,EAAyBF,EAAMC,cAE1C,MAKWE,EAAeH,EAAMC,cAAqC,MAyC1DG,EAAoBJ,EAAMC,cACrC,MAYWI,EAAkBL,EAAMC,cACnC,MAaWK,EAAeN,EAAMC,cAAkC,CAClEM,OAAQ,KACRC,QAAS,GACTC,aAAa,IAOFC,EAAoBV,EAAMC,cAAmB,MClFnD,SAASU,IACd,OAA4C,MAArCX,EAAMY,WAAWP,EAC1B,CAYO,SAASQ,IAQd,OANEF,KADFG,EAAAA,kBAAS,GAOFd,EAAMY,WAAWP,GAAiBU,QAC3C,CAkDA,SAASC,EACPC,GAEejB,EAAMY,WAAWR,GAAmBc,QAKjDlB,EAAMmB,gBAAgBF,EAE1B,CAQO,SAASG,IACd,IAAIX,YAAEA,GAAgBT,EAAMY,WAAWN,GAGvC,OAAOG,EAq4BT,WACE,IAAIY,OAAEA,GAAWC,EAAqBC,EAAeC,mBACjDC,EAAKC,EAAkBC,EAAoBH,mBAE3CI,EAAY5B,EAAM6B,QAAO,GAC7Bb,EAA0B,KACx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BO,WAKL,IAAInD,QAAEA,GAAYR,EAAMY,WAAWN,GAC/BoE,EAAalE,EAAQA,EAAQmE,OAAS,GAC1C,OAAOD,EAAcA,EAAWG,OAAiB,EACnD,uCAumBO,WACL,IAAIvC,EAAoBhB,EAAqBC,EAAeoR,gBACxDlP,EAAQqH,EAAmBnJ,EAAoBgR,gBACnD,OAAO3S,EAAMmE,QACX,KAAO,CACLyO,WAAYtQ,EAAkBjB,OAAOuR,WACrCnP,MAAOA,EAAMuE,eAEf,CAAC1F,EAAkBjB,OAAOuR,WAAYnP,EAAMuE,cAEhD,yCAmCO,SAA4BmD,GAEjC,OADYL,EAAmBnJ,EAAoBkR,oBACtC5I,WAAWkB,EAC1B"}MIT License

Copyright (c) React Training LLC 2015-2019
Copyright (c) Remix Software Inc. 2020-2021
Copyright (c) Shopify Inc. 2022-2023

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
  "name": "react-router-dom",
  "version": "6.30.6",
  "description": "Declarative routing for React web applications",
  "repository": {
    "type": "git",
    "url": "https://github.com/remix-run/react-router",
    "directory": "packages/react-router-dom"
  },
  "license": "MIT",
  "author": "Remix Software <hello@remix.run>",
  "sideEffects": false,
  "main": "./dist/main.js",
  "unpkg": "./dist/umd/react-router-dom.production.min.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "dependencies": {
    "react-router": "6.30.6",
    "@remix-run/router": "1.23.4"
  },
  "devDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "peerDependencies": {
    "react": ">=16.8",
    "react-dom": ">=16.8"
  },
  "files": [
    "dist/",
    "CHANGELOG.md",
    "LICENSE.md",
    "README.md",
    "server.d.ts",
    "server.js",
    "server.mjs"
  ],
  "engines": {
    "node": ">=14.0.0"
  }
}'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var router = require('@remix-run/router');
var reactRouter = require('react-router');
var reactRouterDom = require('react-router-dom');

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var React__namespace = /*#__PURE__*/_interopNamespace(React);

/**
 * A `<Router>` that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouter({
  basename,
  children,
  location: locationProp = "/",
  future
}) {
  if (typeof locationProp === "string") {
    locationProp = reactRouterDom.parsePath(locationProp);
  }
  let action = router.Action.Pop;
  let location = {
    pathname: locationProp.pathname || "/",
    search: locationProp.search || "",
    hash: locationProp.hash || "",
    state: locationProp.state != null ? locationProp.state : null,
    key: locationProp.key || "default"
  };
  let staticNavigator = getStatelessNavigator();
  return /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
    basename: basename,
    children: children,
    location: location,
    navigationType: action,
    navigator: staticNavigator,
    future: future,
    static: true
  });
}
/**
 * A Data Router that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouterProvider({
  context,
  router: router$1,
  hydrate = true,
  nonce
}) {
  !(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.UNSAFE_invariant(false) : void 0;
  let dataRouterContext = {
    router: router$1,
    navigator: getStatelessNavigator(),
    static: true,
    staticContext: context,
    basename: context.basename || "/"
  };
  let fetchersContext = new Map();
  let hydrateScript = "";
  if (hydrate !== false) {
    let data = {
      loaderData: context.loaderData,
      actionData: context.actionData,
      errors: serializeErrors(context.errors)
    };
    // Use JSON.parse here instead of embedding a raw JS object here to speed
    // up parsing on the client.  Dual-stringify is needed to ensure all quotes
    // are properly escaped in the resulting string.  See:
    //   https://v8.dev/blog/cost-of-javascript-2019#json
    let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
    hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  }
  let {
    state
  } = dataRouterContext.router;
  return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_FetchersContext.Provider, {
    value: fetchersContext
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_ViewTransitionContext.Provider, {
    value: {
      isTransitioning: false
    }
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
    basename: dataRouterContext.basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: dataRouterContext.navigator,
    static: dataRouterContext.static,
    future: {
      v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
    }
  }, /*#__PURE__*/React__namespace.createElement(DataRoutes, {
    routes: router$1.routes,
    future: router$1.future,
    state: state
  })))))), hydrateScript ? (/*#__PURE__*/React__namespace.createElement("script", {
    suppressHydrationWarning: true,
    nonce: nonce,
    dangerouslySetInnerHTML: {
      __html: hydrateScript
    }
  })) : null);
}
function DataRoutes({
  routes,
  future,
  state
}) {
  return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
function serializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // deserializeErrors in react-router-dom/index.tsx :)
    if (router.isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      // Do not serialize stack traces from SSR for security reasons
      serialized[key] = {
        message: val.message,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.
        ...(val.name !== "Error" ? {
          __subType: val.name
        } : {})
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
function getStatelessNavigator() {
  return {
    createHref,
    encodeLocation,
    push(to) {
      throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
    },
    replace(to) {
      throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
    },
    go(delta) {
      throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
    },
    back() {
      throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
    },
    forward() {
      throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
    }
  };
}
function createStaticHandler(routes, opts) {
  return router.createStaticHandler(routes, {
    ...opts,
    mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties
  });
}
function createStaticRouter(routes, context, opts = {}) {
  let manifest = {};
  let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest);
  // Because our context matches may be from a framework-agnostic set of
  // routes passed to createStaticHandler(), we update them here with our
  // newly created/enhanced data routes
  let matches = context.matches.map(match => {
    let route = manifest[match.route.id] || match.route;
    return {
      ...match,
      route
    };
  });
  let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
  return {
    get basename() {
      return context.basename;
    },
    get future() {
      return {
        v7_fetcherPersist: false,
        v7_normalizeFormMethod: false,
        v7_partialHydration: opts.future?.v7_partialHydration === true,
        v7_prependBasename: false,
        v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true,
        v7_skipActionErrorRevalidation: false
      };
    },
    get state() {
      return {
        historyAction: router.Action.Pop,
        location: context.location,
        matches,
        loaderData: context.loaderData,
        actionData: context.actionData,
        errors: context.errors,
        initialized: true,
        navigation: router.IDLE_NAVIGATION,
        restoreScrollPosition: null,
        preventScrollReset: false,
        revalidation: "idle",
        fetchers: new Map(),
        blockers: new Map()
      };
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return undefined;
    },
    initialize() {
      throw msg("initialize");
    },
    subscribe() {
      throw msg("subscribe");
    },
    enableScrollRestoration() {
      throw msg("enableScrollRestoration");
    },
    navigate() {
      throw msg("navigate");
    },
    fetch() {
      throw msg("fetch");
    },
    revalidate() {
      throw msg("revalidate");
    },
    createHref,
    encodeLocation,
    getFetcher() {
      return router.IDLE_FETCHER;
    },
    deleteFetcher() {
      throw msg("deleteFetcher");
    },
    dispose() {
      throw msg("dispose");
    },
    getBlocker() {
      return router.IDLE_BLOCKER;
    },
    deleteBlocker() {
      throw msg("deleteBlocker");
    },
    patchRoutes() {
      throw msg("patchRoutes");
    },
    _internalFetchControllers: new Map(),
    _internalActiveDeferreds: new Map(),
    _internalSetRoutes() {
      throw msg("_internalSetRoutes");
    }
  };
}
function createHref(to) {
  return typeof to === "string" ? to : reactRouterDom.createPath(to);
}
function encodeLocation(to) {
  let href = typeof to === "string" ? to : reactRouterDom.createPath(to);
  // Treating this as a full URL will strip any trailing spaces so we need to
  // pre-encode them since they might be part of a matching splat param from
  // an ancestor route
  href = href.replace(/ $/, "%20");
  let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
  return {
    pathname: encoded.pathname,
    search: encoded.search,
    hash: encoded.hash
  };
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function htmlEscape(str) {
  return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]);
}

exports.StaticRouter = StaticRouter;
exports.StaticRouterProvider = StaticRouterProvider;
exports.createStaticHandler = createStaticHandler;
exports.createStaticRouter = createStaticRouter;
import * as React from 'react';
import { Action, UNSAFE_invariant, isRouteErrorResponse, createStaticHandler as createStaticHandler$1, UNSAFE_convertRoutesToDataRoutes, IDLE_NAVIGATION, IDLE_FETCHER, IDLE_BLOCKER } from '@remix-run/router';
import { UNSAFE_useRoutesImpl, UNSAFE_mapRouteProperties } from 'react-router';
import { parsePath, Router, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_FetchersContext, UNSAFE_ViewTransitionContext, createPath } from 'react-router-dom';

/**
 * A `<Router>` that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouter({
  basename,
  children,
  location: locationProp = "/",
  future
}) {
  if (typeof locationProp === "string") {
    locationProp = parsePath(locationProp);
  }
  let action = Action.Pop;
  let location = {
    pathname: locationProp.pathname || "/",
    search: locationProp.search || "",
    hash: locationProp.hash || "",
    state: locationProp.state != null ? locationProp.state : null,
    key: locationProp.key || "default"
  };
  let staticNavigator = getStatelessNavigator();
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: location,
    navigationType: action,
    navigator: staticNavigator,
    future: future,
    static: true
  });
}
/**
 * A Data Router that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouterProvider({
  context,
  router,
  hydrate = true,
  nonce
}) {
  !(router && context) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : UNSAFE_invariant(false) : void 0;
  let dataRouterContext = {
    router,
    navigator: getStatelessNavigator(),
    static: true,
    staticContext: context,
    basename: context.basename || "/"
  };
  let fetchersContext = new Map();
  let hydrateScript = "";
  if (hydrate !== false) {
    let data = {
      loaderData: context.loaderData,
      actionData: context.actionData,
      errors: serializeErrors(context.errors)
    };
    // Use JSON.parse here instead of embedding a raw JS object here to speed
    // up parsing on the client.  Dual-stringify is needed to ensure all quotes
    // are properly escaped in the resulting string.  See:
    //   https://v8.dev/blog/cost-of-javascript-2019#json
    let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
    hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  }
  let {
    state
  } = dataRouterContext.router;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(UNSAFE_FetchersContext.Provider, {
    value: fetchersContext
  }, /*#__PURE__*/React.createElement(UNSAFE_ViewTransitionContext.Provider, {
    value: {
      isTransitioning: false
    }
  }, /*#__PURE__*/React.createElement(Router, {
    basename: dataRouterContext.basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: dataRouterContext.navigator,
    static: dataRouterContext.static,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, /*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  })))))), hydrateScript ? /*#__PURE__*/React.createElement("script", {
    suppressHydrationWarning: true,
    nonce: nonce,
    dangerouslySetInnerHTML: {
      __html: hydrateScript
    }
  }) : null);
}
function DataRoutes({
  routes,
  future,
  state
}) {
  return UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
function serializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // deserializeErrors in react-router-dom/index.tsx :)
    if (isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      // Do not serialize stack traces from SSR for security reasons
      serialized[key] = {
        message: val.message,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.
        ...(val.name !== "Error" ? {
          __subType: val.name
        } : {})
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
function getStatelessNavigator() {
  return {
    createHref,
    encodeLocation,
    push(to) {
      throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
    },
    replace(to) {
      throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
    },
    go(delta) {
      throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
    },
    back() {
      throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
    },
    forward() {
      throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
    }
  };
}
function createStaticHandler(routes, opts) {
  return createStaticHandler$1(routes, {
    ...opts,
    mapRouteProperties: UNSAFE_mapRouteProperties
  });
}
function createStaticRouter(routes, context, opts = {}) {
  let manifest = {};
  let dataRoutes = UNSAFE_convertRoutesToDataRoutes(routes, UNSAFE_mapRouteProperties, undefined, manifest);

  // Because our context matches may be from a framework-agnostic set of
  // routes passed to createStaticHandler(), we update them here with our
  // newly created/enhanced data routes
  let matches = context.matches.map(match => {
    let route = manifest[match.route.id] || match.route;
    return {
      ...match,
      route
    };
  });
  let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
  return {
    get basename() {
      return context.basename;
    },
    get future() {
      return {
        v7_fetcherPersist: false,
        v7_normalizeFormMethod: false,
        v7_partialHydration: opts.future?.v7_partialHydration === true,
        v7_prependBasename: false,
        v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true,
        v7_skipActionErrorRevalidation: false
      };
    },
    get state() {
      return {
        historyAction: Action.Pop,
        location: context.location,
        matches,
        loaderData: context.loaderData,
        actionData: context.actionData,
        errors: context.errors,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        restoreScrollPosition: null,
        preventScrollReset: false,
        revalidation: "idle",
        fetchers: new Map(),
        blockers: new Map()
      };
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return undefined;
    },
    initialize() {
      throw msg("initialize");
    },
    subscribe() {
      throw msg("subscribe");
    },
    enableScrollRestoration() {
      throw msg("enableScrollRestoration");
    },
    navigate() {
      throw msg("navigate");
    },
    fetch() {
      throw msg("fetch");
    },
    revalidate() {
      throw msg("revalidate");
    },
    createHref,
    encodeLocation,
    getFetcher() {
      return IDLE_FETCHER;
    },
    deleteFetcher() {
      throw msg("deleteFetcher");
    },
    dispose() {
      throw msg("dispose");
    },
    getBlocker() {
      return IDLE_BLOCKER;
    },
    deleteBlocker() {
      throw msg("deleteBlocker");
    },
    patchRoutes() {
      throw msg("patchRoutes");
    },
    _internalFetchControllers: new Map(),
    _internalActiveDeferreds: new Map(),
    _internalSetRoutes() {
      throw msg("_internalSetRoutes");
    }
  };
}
function createHref(to) {
  return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
  let href = typeof to === "string" ? to : createPath(to);
  // Treating this as a full URL will strip any trailing spaces so we need to
  // pre-encode them since they might be part of a matching splat param from
  // an ancestor route
  href = href.replace(/ $/, "%20");
  let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
  return {
    pathname: encoded.pathname,
    search: encoded.search,
    hash: encoded.hash
  };
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;

// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function htmlEscape(str) {
  return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]);
}

export { StaticRouter, StaticRouterProvider, createStaticHandler, createStaticRouter };
/**
 * React Router DOM v6.30.6
 *
 * 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
 */
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { UNSAFE_mapRouteProperties, UNSAFE_logV6DeprecationWarnings, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Router, UNSAFE_useRoutesImpl, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, useBlocker } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, replace, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, UNSAFE_ErrorResponseImpl, UNSAFE_invariant, joinPaths, IDLE_FETCHER, matchPath } from '@remix-run/router';
export { UNSAFE_ErrorResponseImpl } from '@remix-run/router';

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
function _objectWithoutPropertiesLoose(r, e) {
  if (null == r) return {};
  var t = {};
  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
    if (-1 !== e.indexOf(n)) continue;
    t[n] = r[n];
  }
  return t;
}

const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
  return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
  return event.button === 0 && (
  // Ignore everything but left clicks
  !target || target === "_self") &&
  // Let browser handle "target=_blank" etc.
  !isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
 * Creates a URLSearchParams object using the given initializer.
 *
 * This is identical to `new URLSearchParams(init)` except it also
 * supports arrays as values in the object form of the initializer
 * instead of just strings. This is convenient when you need multiple
 * values for a given key, but don't want to use an array initializer.
 *
 * For example, instead of:
 *
 *   let searchParams = new URLSearchParams([
 *     ['sort', 'name'],
 *     ['sort', 'price']
 *   ]);
 *
 * you can do:
 *
 *   let searchParams = createSearchParams({
 *     sort: ['name', 'price']
 *   });
 */
function createSearchParams(init) {
  if (init === void 0) {
    init = "";
  }
  return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
    let value = init[key];
    return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
  }, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  let searchParams = createSearchParams(locationSearch);
  if (defaultSearchParams) {
    // Use `defaultSearchParams.forEach(...)` here instead of iterating of
    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
    // web extensions. Relevant Bugzilla tickets:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
    defaultSearchParams.forEach((_, key) => {
      if (!searchParams.has(key)) {
        defaultSearchParams.getAll(key).forEach(value => {
          searchParams.append(key, value);
        });
      }
    });
  }
  return searchParams;
}
// One-time check for submitter support
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
  if (_formDataSupportsSubmitter === null) {
    try {
      new FormData(document.createElement("form"),
      // @ts-expect-error if FormData supports the submitter parameter, this will throw
      0);
      _formDataSupportsSubmitter = false;
    } catch (e) {
      _formDataSupportsSubmitter = true;
    }
  }
  return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
  if (encType != null && !supportedFormEncTypes.has(encType)) {
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) : void 0;
    return null;
  }
  return encType;
}
function getFormSubmissionInfo(target, basename) {
  let method;
  let action;
  let encType;
  let formData;
  let body;
  if (isFormElement(target)) {
    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(target);
  } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
    let form = target.form;
    if (form == null) {
      throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
    }
    // <button>/<input type="submit"> may override attributes of <form>
    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("formaction") || form.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
    // Build a FormData object populated from a form and submitter
    formData = new FormData(form, target);
    // If this browser doesn't support the `FormData(el, submitter)` format,
    // then tack on the submitter value at the end.  This is a lightweight
    // solution that is not 100% spec compliant.  For complete support in older
    // browsers, consider using the `formdata-submitter-polyfill` package
    if (!isFormDataSubmitterSupported()) {
      let {
        name,
        type,
        value
      } = target;
      if (type === "image") {
        let prefix = name ? name + "." : "";
        formData.append(prefix + "x", "0");
        formData.append(prefix + "y", "0");
      } else if (name) {
        formData.append(name, value);
      }
    }
  } else if (isHtmlElement(target)) {
    throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
  } else {
    method = defaultMethod;
    action = null;
    encType = defaultEncType;
    body = target;
  }
  // Send body for <Form encType="text/plain" so we encode it into text
  if (formData && encType === "text/plain") {
    body = formData;
    formData = undefined;
  }
  return {
    action,
    method: method.toLowerCase(),
    encType,
    formData,
    body
  };
}

const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"],
  _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"],
  _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
// HEY YOU! DON'T TOUCH THIS VARIABLE!
//
// It is replaced with the proper version at build time via a babel plugin in
// the rollup config.
//
// Export a global property onto the window for React Router detection by the
// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`
// to detect and properly classify live websites as being built with React Router:
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
const REACT_ROUTER_VERSION = "6";
try {
  window.__reactRouterVersion = REACT_ROUTER_VERSION;
} catch (e) {
  // no-op
}
function createBrowserRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createBrowserHistory({
      window: opts == null ? void 0 : opts.window
    }),
    hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    dataStrategy: opts == null ? void 0 : opts.dataStrategy,
    patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
    window: opts == null ? void 0 : opts.window
  }).initialize();
}
function createHashRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createHashHistory({
      window: opts == null ? void 0 : opts.window
    }),
    hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    dataStrategy: opts == null ? void 0 : opts.dataStrategy,
    patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
    window: opts == null ? void 0 : opts.window
  }).initialize();
}
function parseHydrationData() {
  var _window;
  let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
  if (state && state.errors) {
    state = _extends({}, state, {
      errors: deserializeErrors(state.errors)
    });
  }
  return state;
}
function deserializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // serializeErrors in react-router-dom/server.tsx :)
    if (val && val.__type === "RouteErrorResponse") {
      serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
    } else if (val && val.__type === "Error") {
      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
      if (val.__subType) {
        let ErrorConstructor = window[val.__subType];
        if (typeof ErrorConstructor === "function") {
          try {
            // @ts-expect-error
            let error = new ErrorConstructor(val.message);
            // Wipe away the client-side stack trace.  Nothing to fill it in with
            // because we don't serialize SSR stack traces for security reasons
            error.stack = "";
            serialized[key] = error;
          } catch (e) {
            // no-op - fall through and create a normal Error
          }
        }
      }
      if (serialized[key] == null) {
        let error = new Error(val.message);
        // Wipe away the client-side stack trace.  Nothing to fill it in with
        // because we don't serialize SSR stack traces for security reasons
        error.stack = "";
        serialized[key] = error;
      }
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
const ViewTransitionContext = /*#__PURE__*/React.createContext({
  isTransitioning: false
});
if (process.env.NODE_ENV !== "production") {
  ViewTransitionContext.displayName = "ViewTransition";
}
const FetchersContext = /*#__PURE__*/React.createContext(new Map());
if (process.env.NODE_ENV !== "production") {
  FetchersContext.displayName = "Fetchers";
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
const FLUSH_SYNC = "flushSync";
const flushSyncImpl = ReactDOM[FLUSH_SYNC];
const USE_ID = "useId";
const useIdImpl = React[USE_ID];
function startTransitionSafe(cb) {
  if (startTransitionImpl) {
    startTransitionImpl(cb);
  } else {
    cb();
  }
}
function flushSyncSafe(cb) {
  if (flushSyncImpl) {
    flushSyncImpl(cb);
  } else {
    cb();
  }
}
class Deferred {
  constructor() {
    this.status = "pending";
    this.promise = new Promise((resolve, reject) => {
      this.resolve = value => {
        if (this.status === "pending") {
          this.status = "resolved";
          resolve(value);
        }
      };
      this.reject = reason => {
        if (this.status === "pending") {
          this.status = "rejected";
          reject(reason);
        }
      };
    });
  }
}
/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider(_ref) {
  let {
    fallbackElement,
    router,
    future
  } = _ref;
  let [state, setStateImpl] = React.useState(router.state);
  let [pendingState, setPendingState] = React.useState();
  let [vtContext, setVtContext] = React.useState({
    isTransitioning: false
  });
  let [renderDfd, setRenderDfd] = React.useState();
  let [transition, setTransition] = React.useState();
  let [interruption, setInterruption] = React.useState();
  let fetcherData = React.useRef(new Map());
  let {
    v7_startTransition
  } = future || {};
  let optInStartTransition = React.useCallback(cb => {
    if (v7_startTransition) {
      startTransitionSafe(cb);
    } else {
      cb();
    }
  }, [v7_startTransition]);
  let setState = React.useCallback((newState, _ref2) => {
    let {
      deletedFetchers,
      flushSync: flushSync,
      viewTransitionOpts: viewTransitionOpts
    } = _ref2;
    newState.fetchers.forEach((fetcher, key) => {
      if (fetcher.data !== undefined) {
        fetcherData.current.set(key, fetcher.data);
      }
    });
    deletedFetchers.forEach(key => fetcherData.current.delete(key));
    let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function";
    // If this isn't a view transition or it's not available in this browser,
    // just update and be done with it
    if (!viewTransitionOpts || isViewTransitionUnavailable) {
      if (flushSync) {
        flushSyncSafe(() => setStateImpl(newState));
      } else {
        optInStartTransition(() => setStateImpl(newState));
      }
      return;
    }
    // flushSync + startViewTransition
    if (flushSync) {
      // Flush through the context to mark DOM elements as transition=ing
      flushSyncSafe(() => {
        // Cancel any pending transitions
        if (transition) {
          renderDfd && renderDfd.resolve();
          transition.skipTransition();
        }
        setVtContext({
          isTransitioning: true,
          flushSync: true,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      });
      // Update the DOM
      let t = router.window.document.startViewTransition(() => {
        flushSyncSafe(() => setStateImpl(newState));
      });
      // Clean up after the animation completes
      t.finished.finally(() => {
        flushSyncSafe(() => {
          setRenderDfd(undefined);
          setTransition(undefined);
          setPendingState(undefined);
          setVtContext({
            isTransitioning: false
          });
        });
      });
      flushSyncSafe(() => setTransition(t));
      return;
    }
    // startTransition + startViewTransition
    if (transition) {
      // Interrupting an in-progress transition, cancel and let everything flush
      // out, and then kick off a new transition from the interruption state
      renderDfd && renderDfd.resolve();
      transition.skipTransition();
      setInterruption({
        state: newState,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    } else {
      // Completed navigation update with opted-in view transitions, let 'er rip
      setPendingState(newState);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    }
  }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);
  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  // When we start a view transition, create a Deferred we can use for the
  // eventual "completed" render
  React.useEffect(() => {
    if (vtContext.isTransitioning && !vtContext.flushSync) {
      setRenderDfd(new Deferred());
    }
  }, [vtContext]);
  // Once the deferred is created, kick off startViewTransition() to update the
  // DOM and then wait on the Deferred to resolve (indicating the DOM update has
  // happened)
  React.useEffect(() => {
    if (renderDfd && pendingState && router.window) {
      let newState = pendingState;
      let renderPromise = renderDfd.promise;
      let transition = router.window.document.startViewTransition(async () => {
        optInStartTransition(() => setStateImpl(newState));
        await renderPromise;
      });
      transition.finished.finally(() => {
        setRenderDfd(undefined);
        setTransition(undefined);
        setPendingState(undefined);
        setVtContext({
          isTransitioning: false
        });
      });
      setTransition(transition);
    }
  }, [optInStartTransition, pendingState, renderDfd, router.window]);
  // When the new location finally renders and is committed to the DOM, this
  // effect will run to resolve the transition
  React.useEffect(() => {
    if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
      renderDfd.resolve();
    }
  }, [renderDfd, transition, state.location, pendingState]);
  // If we get interrupted with a new navigation during a transition, we skip
  // the active transition, let it cleanup, then kick it off again here
  React.useEffect(() => {
    if (!vtContext.isTransitioning && interruption) {
      setPendingState(interruption.state);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: interruption.currentLocation,
        nextLocation: interruption.nextLocation
      });
      setInterruption(undefined);
    }
  }, [vtContext.isTransitioning, interruption]);
  React.useEffect(() => {
    process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);
  let routerFuture = React.useMemo(() => ({
    v7_relativeSplatPath: router.future.v7_relativeSplatPath
  }), [router.future.v7_relativeSplatPath]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future, router.future), [future, router.future]);
  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
    value: fetcherData.current
  }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
    value: vtContext
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: routerFuture
  }, state.initialized || router.future.v7_partialHydration ? (/*#__PURE__*/React.createElement(MemoizedDataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  })) : fallbackElement))))), null);
}
// Memoize to avoid re-renders when updating `ViewTransitionContext`
const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes);
function DataRoutes(_ref3) {
  let {
    routes,
    future,
    state
  } = _ref3;
  return UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` for use in web browsers. Provides the cleanest URLs.
 */
function BrowserRouter(_ref4) {
  let {
    basename,
    children,
    future,
    window
  } = _ref4;
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` for use in web browsers. Stores the location in the hash
 * portion of the URL so it is not sent to the server.
 */
function HashRouter(_ref5) {
  let {
    basename,
    children,
    future,
    window
  } = _ref5;
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createHashHistory({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` that accepts a pre-instantiated history object. It's important
 * to note that using your own history object is highly discouraged and may add
 * two versions of the history library to your bundles unless you use the same
 * version of the history library that React Router uses internally.
 */
function HistoryRouter(_ref6) {
  let {
    basename,
    children,
    future,
    history
  } = _ref6;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
if (process.env.NODE_ENV !== "production") {
  HistoryRouter.displayName = "unstable_HistoryRouter";
}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
 * The public API for rendering a history-aware `<a>`.
 */
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref7, ref) {
  let {
      onClick,
      relative,
      reloadDocument,
      replace,
      state,
      target,
      to,
      preventScrollReset,
      viewTransition
    } = _ref7,
    rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  // Rendered into <a href> for absolute URLs
  let absoluteHref;
  let isExternal = false;
  if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
    // Render the absolute href server- and client-side
    absoluteHref = to;
    // Only check for external origins client-side
    if (isBrowser) {
      try {
        let currentUrl = new URL(window.location.href);
        let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
        let path = stripBasename(targetUrl.pathname, basename);
        if (targetUrl.origin === currentUrl.origin && path != null) {
          // Strip the protocol/origin/basename for same-origin absolute URLs
          to = path + targetUrl.search + targetUrl.hash;
        } else {
          isExternal = true;
        }
      } catch (e) {
        // We can't do external URL detection without a valid URL
        process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") : void 0;
      }
    }
  }
  // Rendered into <a href> for relative URLs
  let href = useHref(to, {
    relative
  });
  let internalOnClick = useLinkClickHandler(to, {
    replace,
    state,
    target,
    preventScrollReset,
    relative,
    viewTransition
  });
  function handleClick(event) {
    if (onClick) onClick(event);
    if (!event.defaultPrevented) {
      internalOnClick(event);
    }
  }
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    React.createElement("a", _extends({}, rest, {
      href: absoluteHref || href,
      onClick: isExternal || reloadDocument ? onClick : handleClick,
      ref: ref,
      target: target
    }))
  );
});
if (process.env.NODE_ENV !== "production") {
  Link.displayName = "Link";
}
/**
 * A `<Link>` wrapper that knows if it's "active" or not.
 */
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref8, ref) {
  let {
      "aria-current": ariaCurrentProp = "page",
      caseSensitive = false,
      className: classNameProp = "",
      end = false,
      style: styleProp,
      to,
      viewTransition,
      children
    } = _ref8,
    rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
  let path = useResolvedPath(to, {
    relative: rest.relative
  });
  let location = useLocation();
  let routerState = React.useContext(UNSAFE_DataRouterStateContext);
  let {
    navigator,
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let isTransitioning = routerState != null &&
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useViewTransitionState(path) && viewTransition === true;
  let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  let locationPathname = location.pathname;
  let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  if (!caseSensitive) {
    locationPathname = locationPathname.toLowerCase();
    nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
    toPathname = toPathname.toLowerCase();
  }
  if (nextLocationPathname && basename) {
    nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  }
  // If the `to` has a trailing slash, look at that exact spot.  Otherwise,
  // we're looking for a slash _after_ what's in `to`.  For example:
  //
  // <NavLink to="/users"> and <NavLink to="/users/">
  // both want to look for a / at index 6 to match URL `/users/matt`
  const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  let renderProps = {
    isActive,
    isPending,
    isTransitioning
  };
  let ariaCurrent = isActive ? ariaCurrentProp : undefined;
  let className;
  if (typeof classNameProp === "function") {
    className = classNameProp(renderProps);
  } else {
    // If the className prop is not a function, we use a default `active`
    // class for <NavLink />s that are active. In v5 `active` was the default
    // value for `activeClassName`, but we are removing that API and can still
    // use the old default behavior for a cleaner upgrade path and keep the
    // simple styling rules working as they currently do.
    className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  }
  let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
    "aria-current": ariaCurrent,
    className: className,
    ref: ref,
    style: style,
    to: to,
    viewTransition: viewTransition
  }), typeof children === "function" ? children(renderProps) : children);
});
if (process.env.NODE_ENV !== "production") {
  NavLink.displayName = "NavLink";
}
/**
 * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
 * that the interaction with the server is with `fetch` instead of new document
 * requests, allowing components to add nicer UX to the page as the form is
 * submitted and returns with data.
 */
const Form = /*#__PURE__*/React.forwardRef((_ref9, forwardedRef) => {
  let {
      fetcherKey,
      navigate,
      reloadDocument,
      replace,
      state,
      method = defaultMethod,
      action,
      onSubmit,
      relative,
      preventScrollReset,
      viewTransition
    } = _ref9,
    props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
  let submit = useSubmit();
  let formAction = useFormAction(action, {
    relative
  });
  let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  let submitHandler = event => {
    onSubmit && onSubmit(event);
    if (event.defaultPrevented) return;
    event.preventDefault();
    let submitter = event.nativeEvent.submitter;
    let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
    submit(submitter || event.currentTarget, {
      fetcherKey,
      method: submitMethod,
      navigate,
      replace,
      state,
      relative,
      preventScrollReset,
      viewTransition
    });
  };
  return /*#__PURE__*/React.createElement("form", _extends({
    ref: forwardedRef,
    method: formMethod,
    action: formAction,
    onSubmit: reloadDocument ? onSubmit : submitHandler
  }, props));
});
if (process.env.NODE_ENV !== "production") {
  Form.displayName = "Form";
}
/**
 * This component will emulate the browser's scroll restoration on location
 * changes.
 */
function ScrollRestoration(_ref0) {
  let {
    getKey,
    storageKey
  } = _ref0;
  useScrollRestoration({
    getKey,
    storageKey
  });
  return null;
}
if (process.env.NODE_ENV !== "production") {
  ScrollRestoration.displayName = "ScrollRestoration";
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook;
(function (DataRouterHook) {
  DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
  DataRouterHook["UseSubmit"] = "useSubmit";
  DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
  DataRouterHook["UseFetcher"] = "useFetcher";
  DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
  DataRouterStateHook["UseFetcher"] = "useFetcher";
  DataRouterStateHook["UseFetchers"] = "useFetchers";
  DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
// Internal hooks
function getDataRouterConsoleError(hookName) {
  return hookName + " must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
  let ctx = React.useContext(UNSAFE_DataRouterContext);
  !ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = React.useContext(UNSAFE_DataRouterStateContext);
  !state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  return state;
}
// External hooks
/**
 * Handles the click behavior for router `<Link>` components. This is useful if
 * you need to create custom `<Link>` components with the same click behavior we
 * use in our exported `<Link>`.
 */
function useLinkClickHandler(to, _temp) {
  let {
    target,
    replace: replaceProp,
    state,
    preventScrollReset,
    relative,
    viewTransition
  } = _temp === void 0 ? {} : _temp;
  let navigate = useNavigate();
  let location = useLocation();
  let path = useResolvedPath(to, {
    relative
  });
  return React.useCallback(event => {
    if (shouldProcessLinkClick(event, target)) {
      event.preventDefault();
      // If the URL hasn't changed, a regular <a> will do a replace instead of
      // a push, so do the same here unless the replace prop is explicitly set
      let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
      navigate(to, {
        replace,
        state,
        preventScrollReset,
        relative,
        viewTransition
      });
    }
  }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
}
/**
 * A convenient wrapper for reading and writing search parameters via the
 * URLSearchParams interface.
 */
function useSearchParams(defaultInit) {
  process.env.NODE_ENV !== "production" ? UNSAFE_warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params.") : void 0;
  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
  let hasSetSearchParamsRef = React.useRef(false);
  let location = useLocation();
  let searchParams = React.useMemo(() =>
  // Only merge in the defaults if we haven't yet called setSearchParams.
  // Once we call that we want those to take precedence, otherwise you can't
  // remove a param with setSearchParams({}) if it has an initial value
  getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
  let navigate = useNavigate();
  let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
    const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
    hasSetSearchParamsRef.current = true;
    navigate("?" + newSearchParams, navigateOptions);
  }, [navigate, searchParams]);
  return [searchParams, setSearchParams];
}
function validateClientSideSubmission() {
  if (typeof document === "undefined") {
    throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
  }
}
let fetcherId = 0;
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
/**
 * Returns a function that may be used to programmatically submit a form (or
 * some arbitrary data) to the server.
 */
function useSubmit() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseSubmit);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let currentRouteId = UNSAFE_useRouteId();
  return React.useCallback(function (target, options) {
    if (options === void 0) {
      options = {};
    }
    validateClientSideSubmission();
    let {
      action,
      method,
      encType,
      formData,
      body
    } = getFormSubmissionInfo(target, basename);
    if (options.navigate === false) {
      let key = options.fetcherKey || getUniqueFetcherId();
      router.fetch(key, currentRouteId, options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        flushSync: options.flushSync
      });
    } else {
      router.navigate(options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        replace: options.replace,
        state: options.state,
        fromRouteId: currentRouteId,
        flushSync: options.flushSync,
        viewTransition: options.viewTransition
      });
    }
  }, [router, basename, currentRouteId]);
}
// v7: Eventually we should deprecate this entirely in favor of using the
// router method directly?
function useFormAction(action, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let routeContext = React.useContext(UNSAFE_RouteContext);
  !routeContext ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
  let [match] = routeContext.matches.slice(-1);
  // Shallow clone path so we can modify it below, otherwise we modify the
  // object referenced by useMemo inside useResolvedPath
  let path = _extends({}, useResolvedPath(action ? action : ".", {
    relative
  }));
  // If no action was specified, browsers will persist current search params
  // when determining the path, so match that behavior
  // https://github.com/remix-run/remix/issues/927
  let location = useLocation();
  if (action == null) {
    // Safe to write to this directly here since if action was undefined, we
    // would have called useResolvedPath(".") which will never include a search
    path.search = location.search;
    // When grabbing search params from the URL, remove any included ?index param
    // since it might not apply to our contextual route.  We add it back based
    // on match.route.index below
    let params = new URLSearchParams(path.search);
    let indexValues = params.getAll("index");
    let hasNakedIndexParam = indexValues.some(v => v === "");
    if (hasNakedIndexParam) {
      params.delete("index");
      indexValues.filter(v => v).forEach(v => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? "?" + qs : "";
    }
  }
  if ((!action || action === ".") && match.route.index) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }
  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the form action.  If this is a root navigation, then just use
  // the raw basename which allows the basename to have full control over the
  // presence of a trailing slash on root actions
  if (basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
/**
 * Interacts with route loaders and actions without causing a navigation. Great
 * for any interaction that stays on the same page.
 */
function useFetcher(_temp3) {
  var _route$matches;
  let {
    key
  } = _temp3 === void 0 ? {} : _temp3;
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseFetcher);
  let state = useDataRouterState(DataRouterStateHook.UseFetcher);
  let fetcherData = React.useContext(FetchersContext);
  let route = React.useContext(UNSAFE_RouteContext);
  let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
  !fetcherData ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : UNSAFE_invariant(false) : void 0;
  !route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
  !(routeId != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : UNSAFE_invariant(false) : void 0;
  // Fetcher key handling
  // OK to call conditionally to feature detect `useId`
  // eslint-disable-next-line react-hooks/rules-of-hooks
  let defaultKey = useIdImpl ? useIdImpl() : "";
  let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
  if (key && key !== fetcherKey) {
    setFetcherKey(key);
  } else if (!fetcherKey) {
    // We will only fall through here when `useId` is not available
    setFetcherKey(getUniqueFetcherId());
  }
  // Registration/cleanup
  React.useEffect(() => {
    router.getFetcher(fetcherKey);
    return () => {
      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
      // will not delete immediately but instead queue up a delete after the
      // fetcher returns to an `idle` state
      router.deleteFetcher(fetcherKey);
    };
  }, [router, fetcherKey]);
  // Fetcher additions
  let load = React.useCallback((href, opts) => {
    !routeId ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : UNSAFE_invariant(false) : void 0;
    router.fetch(fetcherKey, routeId, href, opts);
  }, [fetcherKey, routeId, router]);
  let submitImpl = useSubmit();
  let submit = React.useCallback((target, opts) => {
    submitImpl(target, _extends({}, opts, {
      navigate: false,
      fetcherKey
    }));
  }, [fetcherKey, submitImpl]);
  let FetcherForm = React.useMemo(() => {
    let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
      return /*#__PURE__*/React.createElement(Form, _extends({}, props, {
        navigate: false,
        fetcherKey: fetcherKey,
        ref: ref
      }));
    });
    if (process.env.NODE_ENV !== "production") {
      FetcherForm.displayName = "fetcher.Form";
    }
    return FetcherForm;
  }, [fetcherKey]);
  // Exposed FetcherWithComponents
  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  let data = fetcherData.get(fetcherKey);
  let fetcherWithComponents = React.useMemo(() => _extends({
    Form: FetcherForm,
    submit,
    load
  }, fetcher, {
    data
  }), [FetcherForm, submit, load, fetcher, data]);
  return fetcherWithComponents;
}
/**
 * Provides all fetchers currently on the page. Useful for layouts and parent
 * routes that need to provide pending/optimistic UI regarding the fetch.
 */
function useFetchers() {
  let state = useDataRouterState(DataRouterStateHook.UseFetchers);
  return Array.from(state.fetchers.entries()).map(_ref1 => {
    let [key, fetcher] = _ref1;
    return _extends({}, fetcher, {
      key
    });
  });
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
 * When rendered inside a RouterProvider, will restore scroll positions on navigations
 */
function useScrollRestoration(_temp4) {
  let {
    getKey,
    storageKey
  } = _temp4 === void 0 ? {} : _temp4;
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
  let {
    restoreScrollPosition,
    preventScrollReset
  } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let location = useLocation();
  let matches = useMatches();
  let navigation = useNavigation();
  // Trigger manual scroll restoration while we're active
  React.useEffect(() => {
    window.history.scrollRestoration = "manual";
    return () => {
      window.history.scrollRestoration = "auto";
    };
  }, []);
  // Save positions on pagehide
  usePageHide(React.useCallback(() => {
    if (navigation.state === "idle") {
      let key = (getKey ? getKey(location, matches) : null) || location.key;
      savedScrollPositions[key] = window.scrollY;
    }
    try {
      sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
    } catch (error) {
      process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") : void 0;
    }
    window.history.scrollRestoration = "auto";
  }, [storageKey, getKey, navigation.state, location, matches]));
  // Read in any saved scroll locations
  if (typeof document !== "undefined") {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      try {
        let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
        if (sessionPositions) {
          savedScrollPositions = JSON.parse(sessionPositions);
        }
      } catch (e) {
        // no-op, use default empty object
      }
    }, [storageKey]);
    // Enable scroll restoration in the router
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey(// Strip the basename to match useLocation()
      _extends({}, location, {
        pathname: stripBasename(location.pathname, basename) || location.pathname
      }), matches) : getKey;
      let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
      return () => disableScrollRestoration && disableScrollRestoration();
    }, [router, basename, getKey]);
    // Restore scrolling when state.restoreScrollPosition changes
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      // Explicit false means don't do anything (used for submissions)
      if (restoreScrollPosition === false) {
        return;
      }
      // been here before, scroll to it
      if (typeof restoreScrollPosition === "number") {
        window.scrollTo(0, restoreScrollPosition);
        return;
      }
      // try to scroll to the hash
      if (location.hash) {
        let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
        if (el) {
          el.scrollIntoView();
          return;
        }
      }
      // Don't reset if this navigation opted out
      if (preventScrollReset === true) {
        return;
      }
      // otherwise go to the top on new locations
      window.scrollTo(0, 0);
    }, [location, restoreScrollPosition, preventScrollReset]);
  }
}
/**
 * Setup a callback to be fired on the window's `beforeunload` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function useBeforeUnload(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("beforeunload", callback, opts);
    return () => {
      window.removeEventListener("beforeunload", callback, opts);
    };
  }, [callback, capture]);
}
/**
 * Setup a callback to be fired on the window's `pagehide` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.  This event is better supported than beforeunload across browsers.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function usePageHide(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("pagehide", callback, opts);
    return () => {
      window.removeEventListener("pagehide", callback, opts);
    };
  }, [callback, capture]);
}
/**
 * Wrapper around useBlocker to show a window.confirm prompt to users instead
 * of building a custom UI with useBlocker.
 *
 * Warning: This has *a lot of rough edges* and behaves very differently (and
 * very incorrectly in some cases) across browsers if user click addition
 * back/forward navigations while the confirm is open.  Use at your own risk.
 */
function usePrompt(_ref10) {
  let {
    when,
    message
  } = _ref10;
  let blocker = useBlocker(when);
  React.useEffect(() => {
    if (blocker.state === "blocked") {
      let proceed = window.confirm(message);
      if (proceed) {
        // This timeout is needed to avoid a weird "race" on POP navigations
        // between the `window.history` revert navigation and the result of
        // `window.confirm`
        setTimeout(blocker.proceed, 0);
      } else {
        blocker.reset();
      }
    }
  }, [blocker, message]);
  React.useEffect(() => {
    if (blocker.state === "blocked" && !when) {
      blocker.reset();
    }
  }, [blocker, when]);
}
/**
 * Return a boolean indicating if there is an active view transition to the
 * given href.  You can use this value to render CSS classes or viewTransitionName
 * styles onto your elements
 *
 * @param href The destination href
 * @param [opts.relative] Relative routing type ("route" | "path")
 */
function useViewTransitionState(to, opts) {
  if (opts === void 0) {
    opts = {};
  }
  let vtContext = React.useContext(ViewTransitionContext);
  !(vtContext != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  " + "Did you accidentally import `RouterProvider` from `react-router`?") : UNSAFE_invariant(false) : void 0;
  let {
    basename
  } = useDataRouterContext(DataRouterHook.useViewTransitionState);
  let path = useResolvedPath(to, {
    relative: opts.relative
  });
  if (!vtContext.isTransitioning) {
    return false;
  }
  let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  // Transition is active if we're going to or coming from the indicated
  // destination.  This ensures that other PUSH navigations that reverse
  // an indicated transition apply.  I.e., on the list view you have:
  //
  //   <NavLink to="/details/1" viewTransition>
  //
  // If you click the breadcrumb back to the list view:
  //
  //   <NavLink to="/list" viewTransition>
  //
  // We should apply the transition because it's indicated as active going
  // from /list -> /details/1 and therefore should be active on the reverse
  // (even though this isn't strictly a POP reverse)
  return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
}
//#endregion

export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit, useViewTransitionState };
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sources":["../dom.ts","../index.tsx"],"sourcesContent":["import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],"names":["defaultMethod","defaultEncType","isHtmlElement","object","tagName","isButtonElement","toLowerCase","isFormElement","isInputElement","isModifiedEvent","event","metaKey","altKey","ctrlKey","shiftKey","shouldProcessLinkClick","target","button","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","getSearchParamsForLocation","locationSearch","defaultSearchParams","searchParams","forEach","_","has","getAll","append","_formDataSupportsSubmitter","isFormDataSubmitterSupported","FormData","document","createElement","e","supportedFormEncTypes","Set","getFormEncType","encType","process","env","NODE_ENV","warning","getFormSubmissionInfo","basename","method","action","formData","body","attr","getAttribute","stripBasename","type","form","Error","name","prefix","undefined","REACT_ROUTER_VERSION","window","__reactRouterVersion","createBrowserRouter","routes","opts","createRouter","future","_extends","v7_prependBasename","history","createBrowserHistory","hydrationData","parseHydrationData","mapRouteProperties","dataStrategy","patchRoutesOnNavigation","initialize","createHashRouter","createHashHistory","_window","state","__staticRouterHydrationData","errors","deserializeErrors","entries","serialized","val","__type","ErrorResponseImpl","status","statusText","data","internal","__subType","ErrorConstructor","error","message","stack","ViewTransitionContext","React","createContext","isTransitioning","displayName","FetchersContext","Map","START_TRANSITION","startTransitionImpl","FLUSH_SYNC","flushSyncImpl","ReactDOM","USE_ID","useIdImpl","startTransitionSafe","cb","flushSyncSafe","Deferred","constructor","promise","Promise","resolve","reject","reason","RouterProvider","_ref","fallbackElement","router","setStateImpl","useState","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","useRef","v7_startTransition","optInStartTransition","useCallback","setState","newState","_ref2","deletedFetchers","flushSync","viewTransitionOpts","fetchers","fetcher","current","set","delete","isViewTransitionUnavailable","startViewTransition","skipTransition","currentLocation","nextLocation","t","finished","finally","useLayoutEffect","subscribe","useEffect","renderPromise","location","v7_partialHydration","navigator","useMemo","createHref","encodeLocation","go","n","navigate","push","to","preventScrollReset","replace","dataRouterContext","static","routerFuture","v7_relativeSplatPath","logV6DeprecationWarnings","Fragment","DataRouterContext","Provider","DataRouterStateContext","Router","navigationType","historyAction","initialized","MemoizedDataRoutes","DataRoutes","_ref3","useRoutesImpl","BrowserRouter","_ref4","children","historyRef","v5Compat","listen","HashRouter","_ref5","HistoryRouter","_ref6","isBrowser","ABSOLUTE_URL_REGEX","Link","forwardRef","LinkWithRef","_ref7","ref","onClick","relative","reloadDocument","viewTransition","rest","_objectWithoutPropertiesLoose","_excluded","useContext","NavigationContext","absoluteHref","isExternal","test","currentUrl","URL","href","targetUrl","startsWith","protocol","path","pathname","origin","search","hash","useHref","internalOnClick","useLinkClickHandler","handleClick","defaultPrevented","NavLink","NavLinkWithRef","_ref8","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","_excluded2","useResolvedPath","useLocation","routerState","useViewTransitionState","toPathname","locationPathname","nextLocationPathname","navigation","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","filter","Boolean","join","Form","_ref9","forwardedRef","fetcherKey","onSubmit","props","_excluded3","submit","useSubmit","formAction","useFormAction","formMethod","submitHandler","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","_ref0","getKey","storageKey","useScrollRestoration","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","invariant","useDataRouterState","_temp","replaceProp","useNavigate","createPath","useSearchParams","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","setSearchParams","nextInit","navigateOptions","newSearchParams","validateClientSideSubmission","fetcherId","getUniqueFetcherId","String","UseSubmit","currentRouteId","useRouteId","options","fetch","formEncType","fromRouteId","_temp2","routeContext","RouteContext","match","matches","slice","params","indexValues","hasNakedIndexParam","some","qs","toString","route","index","joinPaths","useFetcher","_temp3","_route$matches","UseFetcher","routeId","id","defaultKey","setFetcherKey","getFetcher","deleteFetcher","load","submitImpl","FetcherForm","get","IDLE_FETCHER","fetcherWithComponents","useFetchers","UseFetchers","from","_ref1","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","_temp4","UseScrollRestoration","restoreScrollPosition","useMatches","useNavigation","scrollRestoration","usePageHide","scrollY","sessionStorage","setItem","JSON","stringify","sessionPositions","getItem","parse","getKeyWithoutBasename","disableScrollRestoration","enableScrollRestoration","scrollTo","el","getElementById","decodeURIComponent","scrollIntoView","useBeforeUnload","callback","capture","addEventListener","removeEventListener","usePrompt","_ref10","when","blocker","useBlocker","proceed","confirm","setTimeout","reset","currentPath","nextPath","matchPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,MAAMA,aAAa,GAAmB,KAAK,CAAA;AAClD,MAAMC,cAAc,GAAgB,mCAAmC,CAAA;AAEjE,SAAUC,aAAaA,CAACC,MAAW,EAAA;EACvC,OAAOA,MAAM,IAAI,IAAI,IAAI,OAAOA,MAAM,CAACC,OAAO,KAAK,QAAQ,CAAA;AAC7D,CAAA;AAEM,SAAUC,eAAeA,CAACF,MAAW,EAAA;AAC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EAAEuK,WAAW,CAAC,IAAI,IAAI,CAAA;AAEjD,CAAA;AAIA;;;;"}/**
 * React Router DOM v6.30.6
 *
 * 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
 */
'use strict';

/* eslint-env node */

if (process.env.NODE_ENV === "production") {
  module.exports = require("./umd/react-router-dom.production.min.js");
} else {
  module.exports = require("./umd/react-router-dom.development.js");
}
/**
 * React Router DOM v6.30.6
 *
 * 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
 */
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { UNSAFE_mapRouteProperties, UNSAFE_logV6DeprecationWarnings, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Router, UNSAFE_useRoutesImpl, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, useBlocker } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, replace, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, UNSAFE_ErrorResponseImpl, UNSAFE_invariant, joinPaths, IDLE_FETCHER, matchPath } from '@remix-run/router';
export { UNSAFE_ErrorResponseImpl } from '@remix-run/router';

const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
  return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
  return event.button === 0 && (
  // Ignore everything but left clicks
  !target || target === "_self") &&
  // Let browser handle "target=_blank" etc.
  !isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
 * Creates a URLSearchParams object using the given initializer.
 *
 * This is identical to `new URLSearchParams(init)` except it also
 * supports arrays as values in the object form of the initializer
 * instead of just strings. This is convenient when you need multiple
 * values for a given key, but don't want to use an array initializer.
 *
 * For example, instead of:
 *
 *   let searchParams = new URLSearchParams([
 *     ['sort', 'name'],
 *     ['sort', 'price']
 *   ]);
 *
 * you can do:
 *
 *   let searchParams = createSearchParams({
 *     sort: ['name', 'price']
 *   });
 */
function createSearchParams(init = "") {
  return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
    let value = init[key];
    return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
  }, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  let searchParams = createSearchParams(locationSearch);
  if (defaultSearchParams) {
    // Use `defaultSearchParams.forEach(...)` here instead of iterating of
    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
    // web extensions. Relevant Bugzilla tickets:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
    defaultSearchParams.forEach((_, key) => {
      if (!searchParams.has(key)) {
        defaultSearchParams.getAll(key).forEach(value => {
          searchParams.append(key, value);
        });
      }
    });
  }
  return searchParams;
}

// Thanks https://github.com/sindresorhus/type-fest!

// One-time check for submitter support
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
  if (_formDataSupportsSubmitter === null) {
    try {
      new FormData(document.createElement("form"),
      // @ts-expect-error if FormData supports the submitter parameter, this will throw
      0);
      _formDataSupportsSubmitter = false;
    } catch (e) {
      _formDataSupportsSubmitter = true;
    }
  }
  return _formDataSupportsSubmitter;
}

/**
 * Submit options shared by both navigations and fetchers
 */

/**
 * Submit options available to fetchers
 */

/**
 * Submit options available to navigations
 */

const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
  if (encType != null && !supportedFormEncTypes.has(encType)) {
    UNSAFE_warning(false, `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` ` + `and will default to "${defaultEncType}"`) ;
    return null;
  }
  return encType;
}
function getFormSubmissionInfo(target, basename) {
  let method;
  let action;
  let encType;
  let formData;
  let body;
  if (isFormElement(target)) {
    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(target);
  } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
    let form = target.form;
    if (form == null) {
      throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
    }

    // <button>/<input type="submit"> may override attributes of <form>

    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("formaction") || form.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;

    // Build a FormData object populated from a form and submitter
    formData = new FormData(form, target);

    // If this browser doesn't support the `FormData(el, submitter)` format,
    // then tack on the submitter value at the end.  This is a lightweight
    // solution that is not 100% spec compliant.  For complete support in older
    // browsers, consider using the `formdata-submitter-polyfill` package
    if (!isFormDataSubmitterSupported()) {
      let {
        name,
        type,
        value
      } = target;
      if (type === "image") {
        let prefix = name ? `${name}.` : "";
        formData.append(`${prefix}x`, "0");
        formData.append(`${prefix}y`, "0");
      } else if (name) {
        formData.append(name, value);
      }
    }
  } else if (isHtmlElement(target)) {
    throw new Error(`Cannot submit element that is not <form>, <button>, or ` + `<input type="submit|image">`);
  } else {
    method = defaultMethod;
    action = null;
    encType = defaultEncType;
    body = target;
  }

  // Send body for <Form encType="text/plain" so we encode it into text
  if (formData && encType === "text/plain") {
    body = formData;
    formData = undefined;
  }
  return {
    action,
    method: method.toLowerCase(),
    encType,
    formData,
    body
  };
}

/**
 * NOTE: If you refactor this to split up the modules into separate files,
 * you'll need to update the rollup config for react-router-dom-v5-compat.
 */
//#endregion
// HEY YOU! DON'T TOUCH THIS VARIABLE!
//
// It is replaced with the proper version at build time via a babel plugin in
// the rollup config.
//
// Export a global property onto the window for React Router detection by the
// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`
// to detect and properly classify live websites as being built with React Router:
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
const REACT_ROUTER_VERSION = "6";
try {
  window.__reactRouterVersion = REACT_ROUTER_VERSION;
} catch (e) {
  // no-op
}

////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////

function createBrowserRouter(routes, opts) {
  return createRouter({
    basename: opts?.basename,
    future: {
      ...opts?.future,
      v7_prependBasename: true
    },
    history: createBrowserHistory({
      window: opts?.window
    }),
    hydrationData: opts?.hydrationData || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    dataStrategy: opts?.dataStrategy,
    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
    window: opts?.window
  }).initialize();
}
function createHashRouter(routes, opts) {
  return createRouter({
    basename: opts?.basename,
    future: {
      ...opts?.future,
      v7_prependBasename: true
    },
    history: createHashHistory({
      window: opts?.window
    }),
    hydrationData: opts?.hydrationData || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    dataStrategy: opts?.dataStrategy,
    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
    window: opts?.window
  }).initialize();
}
function parseHydrationData() {
  let state = window?.__staticRouterHydrationData;
  if (state && state.errors) {
    state = {
      ...state,
      errors: deserializeErrors(state.errors)
    };
  }
  return state;
}
function deserializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // serializeErrors in react-router-dom/server.tsx :)
    if (val && val.__type === "RouteErrorResponse") {
      serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
    } else if (val && val.__type === "Error") {
      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
      if (val.__subType) {
        let ErrorConstructor = window[val.__subType];
        if (typeof ErrorConstructor === "function") {
          try {
            // @ts-expect-error
            let error = new ErrorConstructor(val.message);
            // Wipe away the client-side stack trace.  Nothing to fill it in with
            // because we don't serialize SSR stack traces for security reasons
            error.stack = "";
            serialized[key] = error;
          } catch (e) {
            // no-op - fall through and create a normal Error
          }
        }
      }
      if (serialized[key] == null) {
        let error = new Error(val.message);
        // Wipe away the client-side stack trace.  Nothing to fill it in with
        // because we don't serialize SSR stack traces for security reasons
        error.stack = "";
        serialized[key] = error;
      }
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Contexts
////////////////////////////////////////////////////////////////////////////////

const ViewTransitionContext = /*#__PURE__*/React.createContext({
  isTransitioning: false
});
{
  ViewTransitionContext.displayName = "ViewTransition";
}

// TODO: (v7) Change the useFetcher data from `any` to `unknown`

const FetchersContext = /*#__PURE__*/React.createContext(new Map());
{
  FetchersContext.displayName = "Fetchers";
}

//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////

/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
const FLUSH_SYNC = "flushSync";
const flushSyncImpl = ReactDOM[FLUSH_SYNC];
const USE_ID = "useId";
const useIdImpl = React[USE_ID];
function startTransitionSafe(cb) {
  if (startTransitionImpl) {
    startTransitionImpl(cb);
  } else {
    cb();
  }
}
function flushSyncSafe(cb) {
  if (flushSyncImpl) {
    flushSyncImpl(cb);
  } else {
    cb();
  }
}
class Deferred {
  status = "pending";

  // @ts-expect-error - no initializer

  // @ts-expect-error - no initializer

  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = value => {
        if (this.status === "pending") {
          this.status = "resolved";
          resolve(value);
        }
      };
      this.reject = reason => {
        if (this.status === "pending") {
          this.status = "rejected";
          reject(reason);
        }
      };
    });
  }
}

/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider({
  fallbackElement,
  router,
  future
}) {
  let [state, setStateImpl] = React.useState(router.state);
  let [pendingState, setPendingState] = React.useState();
  let [vtContext, setVtContext] = React.useState({
    isTransitioning: false
  });
  let [renderDfd, setRenderDfd] = React.useState();
  let [transition, setTransition] = React.useState();
  let [interruption, setInterruption] = React.useState();
  let fetcherData = React.useRef(new Map());
  let {
    v7_startTransition
  } = future || {};
  let optInStartTransition = React.useCallback(cb => {
    if (v7_startTransition) {
      startTransitionSafe(cb);
    } else {
      cb();
    }
  }, [v7_startTransition]);
  let setState = React.useCallback((newState, {
    deletedFetchers,
    flushSync: flushSync,
    viewTransitionOpts: viewTransitionOpts
  }) => {
    newState.fetchers.forEach((fetcher, key) => {
      if (fetcher.data !== undefined) {
        fetcherData.current.set(key, fetcher.data);
      }
    });
    deletedFetchers.forEach(key => fetcherData.current.delete(key));
    let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function";

    // If this isn't a view transition or it's not available in this browser,
    // just update and be done with it
    if (!viewTransitionOpts || isViewTransitionUnavailable) {
      if (flushSync) {
        flushSyncSafe(() => setStateImpl(newState));
      } else {
        optInStartTransition(() => setStateImpl(newState));
      }
      return;
    }

    // flushSync + startViewTransition
    if (flushSync) {
      // Flush through the context to mark DOM elements as transition=ing
      flushSyncSafe(() => {
        // Cancel any pending transitions
        if (transition) {
          renderDfd && renderDfd.resolve();
          transition.skipTransition();
        }
        setVtContext({
          isTransitioning: true,
          flushSync: true,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      });

      // Update the DOM
      let t = router.window.document.startViewTransition(() => {
        flushSyncSafe(() => setStateImpl(newState));
      });

      // Clean up after the animation completes
      t.finished.finally(() => {
        flushSyncSafe(() => {
          setRenderDfd(undefined);
          setTransition(undefined);
          setPendingState(undefined);
          setVtContext({
            isTransitioning: false
          });
        });
      });
      flushSyncSafe(() => setTransition(t));
      return;
    }

    // startTransition + startViewTransition
    if (transition) {
      // Interrupting an in-progress transition, cancel and let everything flush
      // out, and then kick off a new transition from the interruption state
      renderDfd && renderDfd.resolve();
      transition.skipTransition();
      setInterruption({
        state: newState,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    } else {
      // Completed navigation update with opted-in view transitions, let 'er rip
      setPendingState(newState);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    }
  }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);

  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);

  // When we start a view transition, create a Deferred we can use for the
  // eventual "completed" render
  React.useEffect(() => {
    if (vtContext.isTransitioning && !vtContext.flushSync) {
      setRenderDfd(new Deferred());
    }
  }, [vtContext]);

  // Once the deferred is created, kick off startViewTransition() to update the
  // DOM and then wait on the Deferred to resolve (indicating the DOM update has
  // happened)
  React.useEffect(() => {
    if (renderDfd && pendingState && router.window) {
      let newState = pendingState;
      let renderPromise = renderDfd.promise;
      let transition = router.window.document.startViewTransition(async () => {
        optInStartTransition(() => setStateImpl(newState));
        await renderPromise;
      });
      transition.finished.finally(() => {
        setRenderDfd(undefined);
        setTransition(undefined);
        setPendingState(undefined);
        setVtContext({
          isTransitioning: false
        });
      });
      setTransition(transition);
    }
  }, [optInStartTransition, pendingState, renderDfd, router.window]);

  // When the new location finally renders and is committed to the DOM, this
  // effect will run to resolve the transition
  React.useEffect(() => {
    if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
      renderDfd.resolve();
    }
  }, [renderDfd, transition, state.location, pendingState]);

  // If we get interrupted with a new navigation during a transition, we skip
  // the active transition, let it cleanup, then kick it off again here
  React.useEffect(() => {
    if (!vtContext.isTransitioning && interruption) {
      setPendingState(interruption.state);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: interruption.currentLocation,
        nextLocation: interruption.nextLocation
      });
      setInterruption(undefined);
    }
  }, [vtContext.isTransitioning, interruption]);
  React.useEffect(() => {
    UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts?.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts?.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);
  let routerFuture = React.useMemo(() => ({
    v7_relativeSplatPath: router.future.v7_relativeSplatPath
  }), [router.future.v7_relativeSplatPath]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future, router.future), [future, router.future]);

  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
    value: fetcherData.current
  }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
    value: vtContext
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: routerFuture
  }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  }) : fallbackElement))))), null);
}

// Memoize to avoid re-renders when updating `ViewTransitionContext`
const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes);
function DataRoutes({
  routes,
  future,
  state
}) {
  return UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` for use in web browsers. Provides the cleanest URLs.
 */
function BrowserRouter({
  basename,
  children,
  future,
  window
}) {
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` for use in web browsers. Stores the location in the hash
 * portion of the URL so it is not sent to the server.
 */
function HashRouter({
  basename,
  children,
  future,
  window
}) {
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createHashHistory({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` that accepts a pre-instantiated history object. It's important
 * to note that using your own history object is highly discouraged and may add
 * two versions of the history library to your bundles unless you use the same
 * version of the history library that React Router uses internally.
 */
function HistoryRouter({
  basename,
  children,
  future,
  history
}) {
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
{
  HistoryRouter.displayName = "unstable_HistoryRouter";
}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;

/**
 * The public API for rendering a history-aware `<a>`.
 */
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({
  onClick,
  relative,
  reloadDocument,
  replace,
  state,
  target,
  to,
  preventScrollReset,
  viewTransition,
  ...rest
}, ref) {
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);

  // Rendered into <a href> for absolute URLs
  let absoluteHref;
  let isExternal = false;
  if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
    // Render the absolute href server- and client-side
    absoluteHref = to;

    // Only check for external origins client-side
    if (isBrowser) {
      try {
        let currentUrl = new URL(window.location.href);
        let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
        let path = stripBasename(targetUrl.pathname, basename);
        if (targetUrl.origin === currentUrl.origin && path != null) {
          // Strip the protocol/origin/basename for same-origin absolute URLs
          to = path + targetUrl.search + targetUrl.hash;
        } else {
          isExternal = true;
        }
      } catch (e) {
        // We can't do external URL detection without a valid URL
        UNSAFE_warning(false, `<Link to="${to}"> contains an invalid URL which will probably break ` + `when clicked - please update to a valid URL path.`) ;
      }
    }
  }

  // Rendered into <a href> for relative URLs
  let href = useHref(to, {
    relative
  });
  let internalOnClick = useLinkClickHandler(to, {
    replace,
    state,
    target,
    preventScrollReset,
    relative,
    viewTransition
  });
  function handleClick(event) {
    if (onClick) onClick(event);
    if (!event.defaultPrevented) {
      internalOnClick(event);
    }
  }
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    React.createElement("a", Object.assign({}, rest, {
      href: absoluteHref || href,
      onClick: isExternal || reloadDocument ? onClick : handleClick,
      ref: ref,
      target: target
    }))
  );
});
{
  Link.displayName = "Link";
}
/**
 * A `<Link>` wrapper that knows if it's "active" or not.
 */
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({
  "aria-current": ariaCurrentProp = "page",
  caseSensitive = false,
  className: classNameProp = "",
  end = false,
  style: styleProp,
  to,
  viewTransition,
  children,
  ...rest
}, ref) {
  let path = useResolvedPath(to, {
    relative: rest.relative
  });
  let location = useLocation();
  let routerState = React.useContext(UNSAFE_DataRouterStateContext);
  let {
    navigator,
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let isTransitioning = routerState != null &&
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useViewTransitionState(path) && viewTransition === true;
  let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  let locationPathname = location.pathname;
  let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  if (!caseSensitive) {
    locationPathname = locationPathname.toLowerCase();
    nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
    toPathname = toPathname.toLowerCase();
  }
  if (nextLocationPathname && basename) {
    nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  }

  // If the `to` has a trailing slash, look at that exact spot.  Otherwise,
  // we're looking for a slash _after_ what's in `to`.  For example:
  //
  // <NavLink to="/users"> and <NavLink to="/users/">
  // both want to look for a / at index 6 to match URL `/users/matt`
  const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  let renderProps = {
    isActive,
    isPending,
    isTransitioning
  };
  let ariaCurrent = isActive ? ariaCurrentProp : undefined;
  let className;
  if (typeof classNameProp === "function") {
    className = classNameProp(renderProps);
  } else {
    // If the className prop is not a function, we use a default `active`
    // class for <NavLink />s that are active. In v5 `active` was the default
    // value for `activeClassName`, but we are removing that API and can still
    // use the old default behavior for a cleaner upgrade path and keep the
    // simple styling rules working as they currently do.
    className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  }
  let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  return /*#__PURE__*/React.createElement(Link, Object.assign({}, rest, {
    "aria-current": ariaCurrent,
    className: className,
    ref: ref,
    style: style,
    to: to,
    viewTransition: viewTransition
  }), typeof children === "function" ? children(renderProps) : children);
});
{
  NavLink.displayName = "NavLink";
}

/**
 * Form props shared by navigations and fetchers
 */

/**
 * Form props available to fetchers
 */

/**
 * Form props available to navigations
 */

/**
 * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
 * that the interaction with the server is with `fetch` instead of new document
 * requests, allowing components to add nicer UX to the page as the form is
 * submitted and returns with data.
 */
const Form = /*#__PURE__*/React.forwardRef(({
  fetcherKey,
  navigate,
  reloadDocument,
  replace,
  state,
  method: _method = defaultMethod,
  action,
  onSubmit,
  relative,
  preventScrollReset,
  viewTransition,
  ...props
}, forwardedRef) => {
  let submit = useSubmit();
  let formAction = useFormAction(action, {
    relative
  });
  let formMethod = _method.toLowerCase() === "get" ? "get" : "post";
  let submitHandler = event => {
    onSubmit && onSubmit(event);
    if (event.defaultPrevented) return;
    event.preventDefault();
    let submitter = event.nativeEvent.submitter;
    let submitMethod = submitter?.getAttribute("formmethod") || _method;
    submit(submitter || event.currentTarget, {
      fetcherKey,
      method: submitMethod,
      navigate,
      replace,
      state,
      relative,
      preventScrollReset,
      viewTransition
    });
  };
  return /*#__PURE__*/React.createElement("form", Object.assign({
    ref: forwardedRef,
    method: formMethod,
    action: formAction,
    onSubmit: reloadDocument ? onSubmit : submitHandler
  }, props));
});
{
  Form.displayName = "Form";
}
/**
 * This component will emulate the browser's scroll restoration on location
 * changes.
 */
function ScrollRestoration({
  getKey,
  storageKey
}) {
  useScrollRestoration({
    getKey,
    storageKey
  });
  return null;
}
{
  ScrollRestoration.displayName = "ScrollRestoration";
}
//#endregion

////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
  DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
  DataRouterHook["UseSubmit"] = "useSubmit";
  DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
  DataRouterHook["UseFetcher"] = "useFetcher";
  DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
  return DataRouterHook;
}(DataRouterHook || {});
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
  DataRouterStateHook["UseFetcher"] = "useFetcher";
  DataRouterStateHook["UseFetchers"] = "useFetchers";
  DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
  return DataRouterStateHook;
}(DataRouterStateHook || {}); // Internal hooks
function getDataRouterConsoleError(hookName) {
  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
  let ctx = React.useContext(UNSAFE_DataRouterContext);
  !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = React.useContext(UNSAFE_DataRouterStateContext);
  !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
  return state;
}

// External hooks

/**
 * Handles the click behavior for router `<Link>` components. This is useful if
 * you need to create custom `<Link>` components with the same click behavior we
 * use in our exported `<Link>`.
 */
function useLinkClickHandler(to, {
  target,
  replace: replaceProp,
  state,
  preventScrollReset,
  relative,
  viewTransition
} = {}) {
  let navigate = useNavigate();
  let location = useLocation();
  let path = useResolvedPath(to, {
    relative
  });
  return React.useCallback(event => {
    if (shouldProcessLinkClick(event, target)) {
      event.preventDefault();

      // If the URL hasn't changed, a regular <a> will do a replace instead of
      // a push, so do the same here unless the replace prop is explicitly set
      let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
      navigate(to, {
        replace,
        state,
        preventScrollReset,
        relative,
        viewTransition
      });
    }
  }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
}

/**
 * A convenient wrapper for reading and writing search parameters via the
 * URLSearchParams interface.
 */
function useSearchParams(defaultInit) {
  UNSAFE_warning(typeof URLSearchParams !== "undefined", `You cannot use the \`useSearchParams\` hook in a browser that does not ` + `support the URLSearchParams API. If you need to support Internet ` + `Explorer 11, we recommend you load a polyfill such as ` + `https://github.com/ungap/url-search-params.`) ;
  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
  let hasSetSearchParamsRef = React.useRef(false);
  let location = useLocation();
  let searchParams = React.useMemo(() =>
  // Only merge in the defaults if we haven't yet called setSearchParams.
  // Once we call that we want those to take precedence, otherwise you can't
  // remove a param with setSearchParams({}) if it has an initial value
  getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
  let navigate = useNavigate();
  let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
    const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
    hasSetSearchParamsRef.current = true;
    navigate("?" + newSearchParams, navigateOptions);
  }, [navigate, searchParams]);
  return [searchParams, setSearchParams];
}

/**
 * Submits a HTML `<form>` to the server without reloading the page.
 */

/**
 * Submits a fetcher `<form>` to the server without reloading the page.
 */

function validateClientSideSubmission() {
  if (typeof document === "undefined") {
    throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
  }
}
let fetcherId = 0;
let getUniqueFetcherId = () => `__${String(++fetcherId)}__`;

/**
 * Returns a function that may be used to programmatically submit a form (or
 * some arbitrary data) to the server.
 */
function useSubmit() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseSubmit);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let currentRouteId = UNSAFE_useRouteId();
  return React.useCallback((target, options = {}) => {
    validateClientSideSubmission();
    let {
      action,
      method,
      encType,
      formData,
      body
    } = getFormSubmissionInfo(target, basename);
    if (options.navigate === false) {
      let key = options.fetcherKey || getUniqueFetcherId();
      router.fetch(key, currentRouteId, options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        flushSync: options.flushSync
      });
    } else {
      router.navigate(options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        replace: options.replace,
        state: options.state,
        fromRouteId: currentRouteId,
        flushSync: options.flushSync,
        viewTransition: options.viewTransition
      });
    }
  }, [router, basename, currentRouteId]);
}

// v7: Eventually we should deprecate this entirely in favor of using the
// router method directly?
function useFormAction(action, {
  relative
} = {}) {
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let routeContext = React.useContext(UNSAFE_RouteContext);
  !routeContext ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext")  : void 0;
  let [match] = routeContext.matches.slice(-1);
  // Shallow clone path so we can modify it below, otherwise we modify the
  // object referenced by useMemo inside useResolvedPath
  let path = {
    ...useResolvedPath(action ? action : ".", {
      relative
    })
  };

  // If no action was specified, browsers will persist current search params
  // when determining the path, so match that behavior
  // https://github.com/remix-run/remix/issues/927
  let location = useLocation();
  if (action == null) {
    // Safe to write to this directly here since if action was undefined, we
    // would have called useResolvedPath(".") which will never include a search
    path.search = location.search;

    // When grabbing search params from the URL, remove any included ?index param
    // since it might not apply to our contextual route.  We add it back based
    // on match.route.index below
    let params = new URLSearchParams(path.search);
    let indexValues = params.getAll("index");
    let hasNakedIndexParam = indexValues.some(v => v === "");
    if (hasNakedIndexParam) {
      params.delete("index");
      indexValues.filter(v => v).forEach(v => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? `?${qs}` : "";
    }
  }
  if ((!action || action === ".") && match.route.index) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }

  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the form action.  If this is a root navigation, then just use
  // the raw basename which allows the basename to have full control over the
  // presence of a trailing slash on root actions
  if (basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`

/**
 * Interacts with route loaders and actions without causing a navigation. Great
 * for any interaction that stays on the same page.
 */
function useFetcher({
  key
} = {}) {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseFetcher);
  let state = useDataRouterState(DataRouterStateHook.UseFetcher);
  let fetcherData = React.useContext(FetchersContext);
  let route = React.useContext(UNSAFE_RouteContext);
  let routeId = route.matches[route.matches.length - 1]?.route.id;
  !fetcherData ? UNSAFE_invariant(false, `useFetcher must be used inside a FetchersContext`)  : void 0;
  !route ? UNSAFE_invariant(false, `useFetcher must be used inside a RouteContext`)  : void 0;
  !(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`)  : void 0;

  // Fetcher key handling
  // OK to call conditionally to feature detect `useId`
  // eslint-disable-next-line react-hooks/rules-of-hooks
  let defaultKey = useIdImpl ? useIdImpl() : "";
  let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
  if (key && key !== fetcherKey) {
    setFetcherKey(key);
  } else if (!fetcherKey) {
    // We will only fall through here when `useId` is not available
    setFetcherKey(getUniqueFetcherId());
  }

  // Registration/cleanup
  React.useEffect(() => {
    router.getFetcher(fetcherKey);
    return () => {
      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
      // will not delete immediately but instead queue up a delete after the
      // fetcher returns to an `idle` state
      router.deleteFetcher(fetcherKey);
    };
  }, [router, fetcherKey]);

  // Fetcher additions
  let load = React.useCallback((href, opts) => {
    !routeId ? UNSAFE_invariant(false, "No routeId available for fetcher.load()")  : void 0;
    router.fetch(fetcherKey, routeId, href, opts);
  }, [fetcherKey, routeId, router]);
  let submitImpl = useSubmit();
  let submit = React.useCallback((target, opts) => {
    submitImpl(target, {
      ...opts,
      navigate: false,
      fetcherKey
    });
  }, [fetcherKey, submitImpl]);
  let FetcherForm = React.useMemo(() => {
    let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
      return /*#__PURE__*/React.createElement(Form, Object.assign({}, props, {
        navigate: false,
        fetcherKey: fetcherKey,
        ref: ref
      }));
    });
    {
      FetcherForm.displayName = "fetcher.Form";
    }
    return FetcherForm;
  }, [fetcherKey]);

  // Exposed FetcherWithComponents
  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  let data = fetcherData.get(fetcherKey);
  let fetcherWithComponents = React.useMemo(() => ({
    Form: FetcherForm,
    submit,
    load,
    ...fetcher,
    data
  }), [FetcherForm, submit, load, fetcher, data]);
  return fetcherWithComponents;
}

/**
 * Provides all fetchers currently on the page. Useful for layouts and parent
 * routes that need to provide pending/optimistic UI regarding the fetch.
 */
function useFetchers() {
  let state = useDataRouterState(DataRouterStateHook.UseFetchers);
  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({
    ...fetcher,
    key
  }));
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};

/**
 * When rendered inside a RouterProvider, will restore scroll positions on navigations
 */
function useScrollRestoration({
  getKey,
  storageKey
} = {}) {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
  let {
    restoreScrollPosition,
    preventScrollReset
  } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let location = useLocation();
  let matches = useMatches();
  let navigation = useNavigation();

  // Trigger manual scroll restoration while we're active
  React.useEffect(() => {
    window.history.scrollRestoration = "manual";
    return () => {
      window.history.scrollRestoration = "auto";
    };
  }, []);

  // Save positions on pagehide
  usePageHide(React.useCallback(() => {
    if (navigation.state === "idle") {
      let key = (getKey ? getKey(location, matches) : null) || location.key;
      savedScrollPositions[key] = window.scrollY;
    }
    try {
      sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
    } catch (error) {
      UNSAFE_warning(false, `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`) ;
    }
    window.history.scrollRestoration = "auto";
  }, [storageKey, getKey, navigation.state, location, matches]));

  // Read in any saved scroll locations
  if (typeof document !== "undefined") {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      try {
        let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
        if (sessionPositions) {
          savedScrollPositions = JSON.parse(sessionPositions);
        }
      } catch (e) {
        // no-op, use default empty object
      }
    }, [storageKey]);

    // Enable scroll restoration in the router
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey(
      // Strip the basename to match useLocation()
      {
        ...location,
        pathname: stripBasename(location.pathname, basename) || location.pathname
      }, matches) : getKey;
      let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
      return () => disableScrollRestoration && disableScrollRestoration();
    }, [router, basename, getKey]);

    // Restore scrolling when state.restoreScrollPosition changes
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      // Explicit false means don't do anything (used for submissions)
      if (restoreScrollPosition === false) {
        return;
      }

      // been here before, scroll to it
      if (typeof restoreScrollPosition === "number") {
        window.scrollTo(0, restoreScrollPosition);
        return;
      }

      // try to scroll to the hash
      if (location.hash) {
        let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
        if (el) {
          el.scrollIntoView();
          return;
        }
      }

      // Don't reset if this navigation opted out
      if (preventScrollReset === true) {
        return;
      }

      // otherwise go to the top on new locations
      window.scrollTo(0, 0);
    }, [location, restoreScrollPosition, preventScrollReset]);
  }
}

/**
 * Setup a callback to be fired on the window's `beforeunload` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function useBeforeUnload(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("beforeunload", callback, opts);
    return () => {
      window.removeEventListener("beforeunload", callback, opts);
    };
  }, [callback, capture]);
}

/**
 * Setup a callback to be fired on the window's `pagehide` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.  This event is better supported than beforeunload across browsers.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function usePageHide(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("pagehide", callback, opts);
    return () => {
      window.removeEventListener("pagehide", callback, opts);
    };
  }, [callback, capture]);
}

/**
 * Wrapper around useBlocker to show a window.confirm prompt to users instead
 * of building a custom UI with useBlocker.
 *
 * Warning: This has *a lot of rough edges* and behaves very differently (and
 * very incorrectly in some cases) across browsers if user click addition
 * back/forward navigations while the confirm is open.  Use at your own risk.
 */
function usePrompt({
  when,
  message
}) {
  let blocker = useBlocker(when);
  React.useEffect(() => {
    if (blocker.state === "blocked") {
      let proceed = window.confirm(message);
      if (proceed) {
        // This timeout is needed to avoid a weird "race" on POP navigations
        // between the `window.history` revert navigation and the result of
        // `window.confirm`
        setTimeout(blocker.proceed, 0);
      } else {
        blocker.reset();
      }
    }
  }, [blocker, message]);
  React.useEffect(() => {
    if (blocker.state === "blocked" && !when) {
      blocker.reset();
    }
  }, [blocker, when]);
}

/**
 * Return a boolean indicating if there is an active view transition to the
 * given href.  You can use this value to render CSS classes or viewTransitionName
 * styles onto your elements
 *
 * @param href The destination href
 * @param [opts.relative] Relative routing type ("route" | "path")
 */
function useViewTransitionState(to, opts = {}) {
  let vtContext = React.useContext(ViewTransitionContext);
  !(vtContext != null) ? UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  " + "Did you accidentally import `RouterProvider` from `react-router`?")  : void 0;
  let {
    basename
  } = useDataRouterContext(DataRouterHook.useViewTransitionState);
  let path = useResolvedPath(to, {
    relative: opts.relative
  });
  if (!vtContext.isTransitioning) {
    return false;
  }
  let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;

  // Transition is active if we're going to or coming from the indicated
  // destination.  This ensures that other PUSH navigations that reverse
  // an indicated transition apply.  I.e., on the list view you have:
  //
  //   <NavLink to="/details/1" viewTransition>
  //
  // If you click the breadcrumb back to the list view:
  //
  //   <NavLink to="/list" viewTransition>
  //
  // We should apply the transition because it's indicated as active going
  // from /list -> /details/1 and therefore should be active on the reverse
  // (even though this isn't strictly a POP reverse)
  return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
}

//#endregion

export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit, useViewTransitionState };
//# sourceMappingURL=react-router-dom.development.js.map
{"version":3,"file":"react-router-dom.development.js","sources":["../dom.ts","../index.tsx"],"sourcesContent":["import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],"names":["defaultMethod","defaultEncType","isHtmlElement","object","tagName","isButtonElement","toLowerCase","isFormElement","isInputElement","isModifiedEvent","event","metaKey","altKey","ctrlKey","shiftKey","shouldProcessLinkClick","target","button","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","getSearchParamsForLocation","locationSearch","defaultSearchParams","searchParams","forEach","_","has","getAll","append","_formDataSupportsSubmitter","isFormDataSubmitterSupported","FormData","document","createElement","e","supportedFormEncTypes","Set","getFormEncType","encType","process","warning","getFormSubmissionInfo","basename","method","action","formData","body","attr","getAttribute","stripBasename","type","form","Error","name","prefix","undefined","REACT_ROUTER_VERSION","window","__reactRouterVersion","createBrowserRouter","routes","opts","createRouter","future","v7_prependBasename","history","createBrowserHistory","hydrationData","parseHydrationData","mapRouteProperties","dataStrategy","patchRoutesOnNavigation","initialize","createHashRouter","createHashHistory","state","__staticRouterHydrationData","errors","deserializeErrors","entries","serialized","val","__type","ErrorResponseImpl","status","statusText","data","internal","__subType","ErrorConstructor","error","message","stack","ViewTransitionContext","React","createContext","isTransitioning","displayName","FetchersContext","Map","START_TRANSITION","startTransitionImpl","FLUSH_SYNC","flushSyncImpl","ReactDOM","USE_ID","useIdImpl","startTransitionSafe","cb","flushSyncSafe","Deferred","constructor","promise","Promise","resolve","reject","reason","RouterProvider","fallbackElement","router","setStateImpl","useState","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","useRef","v7_startTransition","optInStartTransition","useCallback","setState","newState","deletedFetchers","flushSync","viewTransitionOpts","fetchers","fetcher","current","set","delete","isViewTransitionUnavailable","startViewTransition","skipTransition","currentLocation","nextLocation","t","finished","finally","useLayoutEffect","subscribe","useEffect","renderPromise","location","v7_partialHydration","navigator","useMemo","createHref","encodeLocation","go","n","navigate","push","to","preventScrollReset","replace","dataRouterContext","static","routerFuture","v7_relativeSplatPath","logV6DeprecationWarnings","Fragment","DataRouterContext","Provider","DataRouterStateContext","Router","navigationType","historyAction","initialized","MemoizedDataRoutes","DataRoutes","useRoutesImpl","BrowserRouter","children","historyRef","v5Compat","listen","HashRouter","HistoryRouter","isBrowser","ABSOLUTE_URL_REGEX","Link","forwardRef","LinkWithRef","onClick","relative","reloadDocument","viewTransition","rest","ref","useContext","NavigationContext","absoluteHref","isExternal","test","currentUrl","URL","href","targetUrl","startsWith","protocol","path","pathname","origin","search","hash","useHref","internalOnClick","useLinkClickHandler","handleClick","defaultPrevented","assign","NavLink","NavLinkWithRef","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","useResolvedPath","useLocation","routerState","useViewTransitionState","toPathname","locationPathname","nextLocationPathname","navigation","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","filter","Boolean","join","Form","fetcherKey","onSubmit","props","forwardedRef","submit","useSubmit","formAction","useFormAction","formMethod","submitHandler","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","getKey","storageKey","useScrollRestoration","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","invariant","useDataRouterState","replaceProp","useNavigate","createPath","useSearchParams","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","setSearchParams","nextInit","navigateOptions","newSearchParams","validateClientSideSubmission","fetcherId","getUniqueFetcherId","String","UseSubmit","currentRouteId","useRouteId","options","fetch","formEncType","fromRouteId","routeContext","RouteContext","match","matches","slice","params","indexValues","hasNakedIndexParam","some","qs","toString","route","index","joinPaths","useFetcher","UseFetcher","routeId","id","defaultKey","setFetcherKey","getFetcher","deleteFetcher","load","submitImpl","FetcherForm","get","IDLE_FETCHER","fetcherWithComponents","useFetchers","UseFetchers","from","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","UseScrollRestoration","restoreScrollPosition","useMatches","useNavigation","scrollRestoration","usePageHide","scrollY","sessionStorage","setItem","JSON","stringify","sessionPositions","getItem","parse","getKeyWithoutBasename","disableScrollRestoration","enableScrollRestoration","scrollTo","el","getElementById","decodeURIComponent","scrollIntoView","useBeforeUnload","callback","capture","addEventListener","removeEventListener","usePrompt","when","blocker","useBlocker","proceed","confirm","setTimeout","reset","currentPath","nextPath","matchPath"],"mappings":";;;;;;;;;;;;;;;;;AAOO,MAAMA,aAA6B,GAAG,KAAK,CAAA;AAClD,MAAMC,cAA2B,GAAG,mCAAmC,CAAA;AAEhE,SAASC,aAAaA,CAACC,MAAW,EAAyB;EAChE,OAAOA,MAAM,IAAI,IAAI,IAAI,OAAOA,MAAM,CAACC,OAAO,KAAK,QAAQ,CAAA;AAC7D,CAAA;AAEO,SAASC,eAAeA,CAACF,MAAW,EAA+B;AACxE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,QAAQ,CAAA;AAC3E,CAAA;AAEO,SAASC,aAAaA,CAACJ,MAAW,EAA6B;AACpE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,MAAM,CAAA;AACzE,CAAA;AAEO,SAASE,cAAcA,CAACL,MAAW,EAA8B;AACtE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,OAAO,CAAA;AAC1E,CAAA;AAOA,SAASG,eAAeA,CAACC,KAAwB,EAAE;AACjD,EAAA,OAAO,CAAC,EAAEA,KAAK,CAACC,OAAO,IAAID,KAAK,CAACE,MAAM,IAAIF,KAAK,CAACG,OAAO,IAAIH,KAAK,CAACI,QAAQ,CA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AACpC,EAAA,IAAI6J,QAAQ,GACVtU,aAAa,CAAC2E,SAAS,CAAC2B,YAAY,CAACmE,QAAQ,EAAEhL,QAAQ,CAAC,IACxDkF,SAAS,CAAC2B,YAAY,CAACmE,QAAQ,CAAA;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACA,OACE8J,SAAS,CAAC/J,IAAI,CAACC,QAAQ,EAAE6J,QAAQ,CAAC,IAAI,IAAI,IAC1CC,SAAS,CAAC/J,IAAI,CAACC,QAAQ,EAAE4J,WAAW,CAAC,IAAI,IAAI,CAAA;AAEjD,CAAA;;AAIA;;;;"}/**
 * React Router DOM v6.30.6
 *
 * 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
 */
import*as e from"react";import*as t from"react-dom";import{UNSAFE_mapRouteProperties as n,UNSAFE_logV6DeprecationWarnings as r,UNSAFE_DataRouterContext as a,UNSAFE_DataRouterStateContext as o,Router as i,UNSAFE_useRoutesImpl as s,UNSAFE_NavigationContext as u,useHref as c,useResolvedPath as l,useLocation as f,useNavigate as d,createPath as m,UNSAFE_useRouteId as h,UNSAFE_RouteContext as p,useMatches as w,useNavigation as v,useBlocker as g}from"react-router";export{AbortedDeferredError,Await,MemoryRouter,Navigate,NavigationType,Outlet,Route,Router,Routes,UNSAFE_DataRouterContext,UNSAFE_DataRouterStateContext,UNSAFE_LocationContext,UNSAFE_NavigationContext,UNSAFE_RouteContext,UNSAFE_useRouteId,createMemoryRouter,createPath,createRoutesFromChildren,createRoutesFromElements,defer,generatePath,isRouteErrorResponse,json,matchPath,matchRoutes,parsePath,redirect,redirectDocument,renderMatches,replace,resolvePath,useActionData,useAsyncError,useAsyncValue,useBlocker,useHref,useInRouterContext,useLoaderData,useLocation,useMatch,useMatches,useNavigate,useNavigation,useNavigationType,useOutlet,useOutletContext,useParams,useResolvedPath,useRevalidator,useRouteError,useRouteLoaderData,useRoutes}from"react-router";import{stripBasename as y,createRouter as b,createBrowserHistory as S,createHashHistory as E,UNSAFE_ErrorResponseImpl as R,UNSAFE_invariant as T,joinPaths as L,IDLE_FETCHER as x,matchPath as C}from"@remix-run/router";export{UNSAFE_ErrorResponseImpl}from"@remix-run/router";const _="get",A="application/x-www-form-urlencoded";function F(e){return null!=e&&"string"==typeof e.tagName}function U(e=""){return new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}let k=null;const N=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function P(e){return null==e||N.has(e)?e:null}function D(e,t){let n,r,a,o,i;if(F(s=e)&&"form"===s.tagName.toLowerCase()){let i=e.getAttribute("action");r=i?y(i,t):null,n=e.getAttribute("method")||_,a=P(e.getAttribute("enctype"))||A,o=new FormData(e)}else if(function(e){return F(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return F(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||i.getAttribute("action");if(r=s?y(s,t):null,n=e.getAttribute("formmethod")||i.getAttribute("method")||_,a=P(e.getAttribute("formenctype"))||P(i.getAttribute("enctype"))||A,o=new FormData(i,e),!function(){if(null===k)try{new FormData(document.createElement("form"),0),k=!1}catch(e){k=!0}return k}()){let{name:t,type:n,value:r}=e;if("image"===n){let e=t?`${t}.`:"";o.append(`${e}x`,"0"),o.append(`${e}y`,"0")}else t&&o.append(t,r)}}else{if(F(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=_,r=null,a=A,i=e}var s;return o&&"text/plain"===a&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}try{window.__reactRouterVersion="6"}catch(Re){}function O(e,t){return b({basename:t?.basename,future:{...t?.future,v7_prependBasename:!0},history:S({window:t?.window}),hydrationData:t?.hydrationData||M(),routes:e,mapRouteProperties:n,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window}).initialize()}function K(e,t){return b({basename:t?.basename,future:{...t?.future,v7_prependBasename:!0},history:E({window:t?.window}),hydrationData:t?.hydrationData||M(),routes:e,mapRouteProperties:n,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window}).initialize()}function M(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:j(e.errors)}),e}function j(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,a]of t)if(a&&"RouteErrorResponse"===a.__type)n[r]=new R(a.status,a.statusText,a.data,!0===a.internal);else if(a&&"Error"===a.__type){if(a.__subType){let e=window[a.__subType];if("function"==typeof e)try{let t=new e(a.message);t.stack="",n[r]=t}catch(Re){}}if(null==n[r]){let e=new Error(a.message);e.stack="",n[r]=e}}else n[r]=a;return n}const I=e.createContext({isTransitioning:!1}),V=e.createContext(new Map),H=e.startTransition,z=t.flushSync,B=e.useId;function $(e){z?z(e):e()}class W{status="pending";constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{"pending"===this.status&&(this.status="resolved",e(t))},this.reject=e=>{"pending"===this.status&&(this.status="rejected",t(e))}})}}function Y({fallbackElement:t,router:n,future:s}){let[u,c]=e.useState(n.state),[l,f]=e.useState(),[d,m]=e.useState({isTransitioning:!1}),[h,p]=e.useState(),[w,v]=e.useState(),[g,y]=e.useState(),b=e.useRef(new Map),{v7_startTransition:S}=s||{},E=e.useCallback(e=>{S?function(e){H?H(e):e()}(e):e()},[S]),R=e.useCallback((e,{deletedFetchers:t,flushSync:r,viewTransitionOpts:a})=>{e.fetchers.forEach((e,t)=>{void 0!==e.data&&b.current.set(t,e.data)}),t.forEach(e=>b.current.delete(e));let o=null==n.window||null==n.window.document||"function"!=typeof n.window.document.startViewTransition;if(a&&!o){if(r){$(()=>{w&&(h&&h.resolve(),w.skipTransition()),m({isTransitioning:!0,flushSync:!0,currentLocation:a.currentLocation,nextLocation:a.nextLocation})});let t=n.window.document.startViewTransition(()=>{$(()=>c(e))});return t.finished.finally(()=>{$(()=>{p(void 0),v(void 0),f(void 0),m({isTransitioning:!1})})}),void $(()=>v(t))}w?(h&&h.resolve(),w.skipTransition(),y({state:e,currentLocation:a.currentLocation,nextLocation:a.nextLocation})):(f(e),m({isTransitioning:!0,flushSync:!1,currentLocation:a.currentLocation,nextLocation:a.nextLocation}))}else r?$(()=>c(e)):E(()=>c(e))},[n.window,w,h,b,E]);e.useLayoutEffect(()=>n.subscribe(R),[n,R]),e.useEffect(()=>{d.isTransitioning&&!d.flushSync&&p(new W)},[d]),e.useEffect(()=>{if(h&&l&&n.window){let e=l,t=h.promise,r=n.window.document.startViewTransition(async()=>{E(()=>c(e)),await t});r.finished.finally(()=>{p(void 0),v(void 0),f(void 0),m({isTransitioning:!1})}),v(r)}},[E,l,h,n.window]),e.useEffect(()=>{h&&l&&u.location.key===l.location.key&&h.resolve()},[h,w,u.location,l]),e.useEffect(()=>{!d.isTransitioning&&g&&(f(g.state),m({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),y(void 0))},[d.isTransitioning,g]),e.useEffect(()=>{},[]);let T=e.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:e=>n.navigate(e),push:(e,t,r)=>n.navigate(e,{state:t,preventScrollReset:r?.preventScrollReset}),replace:(e,t,r)=>n.navigate(e,{replace:!0,state:t,preventScrollReset:r?.preventScrollReset})}),[n]),L=n.basename||"/",x=e.useMemo(()=>({router:n,navigator:T,static:!1,basename:L}),[n,T,L]),C=e.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return e.useEffect(()=>r(s,n.future),[s,n.future]),e.createElement(e.Fragment,null,e.createElement(a.Provider,{value:x},e.createElement(o.Provider,{value:u},e.createElement(V.Provider,{value:b.current},e.createElement(I.Provider,{value:d},e.createElement(i,{basename:L,location:u.location,navigationType:u.historyAction,navigator:T,future:C},u.initialized||n.future.v7_partialHydration?e.createElement(J,{routes:n.routes,future:n.future,state:u}):t))))),null)}const J=e.memo(q);function q({routes:e,future:t,state:n}){return s(e,void 0,n,t)}function G({basename:t,children:n,future:a,window:o}){let s=e.useRef();null==s.current&&(s.current=S({window:o,v5Compat:!0}));let u=s.current,[c,l]=e.useState({action:u.action,location:u.location}),{v7_startTransition:f}=a||{},d=e.useCallback(e=>{f&&H?H(()=>l(e)):l(e)},[l,f]);return e.useLayoutEffect(()=>u.listen(d),[u,d]),e.useEffect(()=>r(a),[a]),e.createElement(i,{basename:t,children:n,location:c.location,navigationType:c.action,navigator:u,future:a})}function Q({basename:t,children:n,future:a,window:o}){let s=e.useRef();null==s.current&&(s.current=E({window:o,v5Compat:!0}));let u=s.current,[c,l]=e.useState({action:u.action,location:u.location}),{v7_startTransition:f}=a||{},d=e.useCallback(e=>{f&&H?H(()=>l(e)):l(e)},[l,f]);return e.useLayoutEffect(()=>u.listen(d),[u,d]),e.useEffect(()=>r(a),[a]),e.createElement(i,{basename:t,children:n,location:c.location,navigationType:c.action,navigator:u,future:a})}function X({basename:t,children:n,future:a,history:o}){let[s,u]=e.useState({action:o.action,location:o.location}),{v7_startTransition:c}=a||{},l=e.useCallback(e=>{c&&H?H(()=>u(e)):u(e)},[u,c]);return e.useLayoutEffect(()=>o.listen(l),[o,l]),e.useEffect(()=>r(a),[a]),e.createElement(i,{basename:t,children:n,location:s.location,navigationType:s.action,navigator:o,future:a})}const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,ee=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,te=e.forwardRef(function({onClick:t,relative:n,reloadDocument:r,replace:a,state:o,target:i,to:s,preventScrollReset:l,viewTransition:f,...d},m){let h,{basename:p}=e.useContext(u),w=!1;if("string"==typeof s&&ee.test(s)&&(h=s,Z))try{let e=new URL(window.location.href),t=s.startsWith("//")?new URL(e.protocol+s):new URL(s),n=y(t.pathname,p);t.origin===e.origin&&null!=n?s=n+t.search+t.hash:w=!0}catch(Re){}let v=c(s,{relative:n}),g=ce(s,{replace:a,state:o,target:i,preventScrollReset:l,relative:n,viewTransition:f});return e.createElement("a",Object.assign({},d,{href:h||v,onClick:w||r?t:function(e){t&&t(e),e.defaultPrevented||g(e)},ref:m,target:i}))}),ne=e.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:a=!1,style:i,to:s,viewTransition:c,children:d,...m},h){let p=l(s,{relative:m.relative}),w=f(),v=e.useContext(o),{navigator:g,basename:b}=e.useContext(u),S=null!=v&&Ee(p)&&!0===c,E=g.encodeLocation?g.encodeLocation(p).pathname:p.pathname,R=w.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;n||(R=R.toLowerCase(),T=T?T.toLowerCase():null,E=E.toLowerCase()),T&&b&&(T=y(T,b)||T);const L="/"!==E&&E.endsWith("/")?E.length-1:E.length;let x,C=R===E||!a&&R.startsWith(E)&&"/"===R.charAt(L),_=null!=T&&(T===E||!a&&T.startsWith(E)&&"/"===T.charAt(E.length)),A={isActive:C,isPending:_,isTransitioning:S},F=C?t:void 0;x="function"==typeof r?r(A):[r,C?"active":null,_?"pending":null,S?"transitioning":null].filter(Boolean).join(" ");let U="function"==typeof i?i(A):i;return e.createElement(te,Object.assign({},m,{"aria-current":F,className:x,ref:h,style:U,to:s,viewTransition:c}),"function"==typeof d?d(A):d)}),re=e.forwardRef(({fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i=_,action:s,onSubmit:u,relative:c,preventScrollReset:l,viewTransition:f,...d},m)=>{let h=me(),p=he(s,{relative:c}),w="get"===i.toLowerCase()?"get":"post";return e.createElement("form",Object.assign({ref:m,method:w,action:p,onSubmit:r?u:e=>{if(u&&u(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute("formmethod")||i;h(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:a,state:o,relative:c,preventScrollReset:l,viewTransition:f})}},d))});function ae({getKey:e,storageKey:t}){return ye({getKey:e,storageKey:t}),null}var oe=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(oe||{}),ie=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(ie||{});function se(t){let n=e.useContext(a);return n||T(!1),n}function ue(t){let n=e.useContext(o);return n||T(!1),n}function ce(t,{target:n,replace:r,state:a,preventScrollReset:o,relative:i,viewTransition:s}={}){let u=d(),c=f(),h=l(t,{relative:i});return e.useCallback(e=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(e,n)){e.preventDefault();let n=void 0!==r?r:m(c)===m(h);u(t,{replace:n,state:a,preventScrollReset:o,relative:i,viewTransition:s})}},[c,u,h,r,a,n,t,o,i,s])}function le(t){let n=e.useRef(U(t)),r=e.useRef(!1),a=f(),o=e.useMemo(()=>function(e,t){let n=U(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}(a.search,r.current?null:n.current),[a.search]),i=d(),s=e.useCallback((e,t)=>{const n=U("function"==typeof e?e(o):e);r.current=!0,i("?"+n,t)},[i,o]);return[o,s]}let fe=0,de=()=>`__${String(++fe)}__`;function me(){let{router:t}=se(oe.UseSubmit),{basename:n}=e.useContext(u),r=h();return e.useCallback((e,a={})=>{!function(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}();let{action:o,method:i,encType:s,formData:u,body:c}=D(e,n);if(!1===a.navigate){let e=a.fetcherKey||de();t.fetch(e,r,a.action||o,{preventScrollReset:a.preventScrollReset,formData:u,body:c,formMethod:a.method||i,formEncType:a.encType||s,flushSync:a.flushSync})}else t.navigate(a.action||o,{preventScrollReset:a.preventScrollReset,formData:u,body:c,formMethod:a.method||i,formEncType:a.encType||s,replace:a.replace,state:a.state,fromRouteId:r,flushSync:a.flushSync,viewTransition:a.viewTransition})},[t,n,r])}function he(t,{relative:n}={}){let{basename:r}=e.useContext(u),a=e.useContext(p);a||T(!1);let[o]=a.matches.slice(-1),i={...l(t||".",{relative:n})},s=f();if(null==t){i.search=s.search;let e=new URLSearchParams(i.search),t=e.getAll("index");if(t.some(e=>""===e)){e.delete("index"),t.filter(e=>e).forEach(t=>e.append("index",t));let n=e.toString();i.search=n?`?${n}`:""}}return t&&"."!==t||!o.route.index||(i.search=i.search?i.search.replace(/^\?/,"?index&"):"?index"),"/"!==r&&(i.pathname="/"===i.pathname?r:L([r,i.pathname])),m(i)}function pe({key:t}={}){let{router:n}=se(oe.UseFetcher),r=ue(ie.UseFetcher),a=e.useContext(V),o=e.useContext(p),i=o.matches[o.matches.length-1]?.route.id;a||T(!1),o||T(!1),null==i&&T(!1);let s=B?B():"",[u,c]=e.useState(t||s);t&&t!==u?c(t):u||c(de()),e.useEffect(()=>(n.getFetcher(u),()=>{n.deleteFetcher(u)}),[n,u]);let l=e.useCallback((e,t)=>{i||T(!1),n.fetch(u,i,e,t)},[u,i,n]),f=me(),d=e.useCallback((e,t)=>{f(e,{...t,navigate:!1,fetcherKey:u})},[u,f]),m=e.useMemo(()=>e.forwardRef((t,n)=>e.createElement(re,Object.assign({},t,{navigate:!1,fetcherKey:u,ref:n}))),[u]),h=r.fetchers.get(u)||x,w=a.get(u);return e.useMemo(()=>({Form:m,submit:d,load:l,...h,data:w}),[m,d,l,h,w])}function we(){let e=ue(ie.UseFetchers);return Array.from(e.fetchers.entries()).map(([e,t])=>({...t,key:e}))}const ve="react-router-scroll-positions";let ge={};function ye({getKey:t,storageKey:n}={}){let{router:r}=se(oe.UseScrollRestoration),{restoreScrollPosition:a,preventScrollReset:o}=ue(ie.UseScrollRestoration),{basename:i}=e.useContext(u),s=f(),c=w(),l=v();e.useEffect(()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"}),[]),function(t,n){let{capture:r}=n||{};e.useEffect(()=>{let e=null!=r?{capture:r}:void 0;return window.addEventListener("pagehide",t,e),()=>{window.removeEventListener("pagehide",t,e)}},[t,r])}(e.useCallback(()=>{if("idle"===l.state){let e=(t?t(s,c):null)||s.key;ge[e]=window.scrollY}try{sessionStorage.setItem(n||ve,JSON.stringify(ge))}catch(e){}window.history.scrollRestoration="auto"},[n,t,l.state,s,c])),"undefined"!=typeof document&&(e.useLayoutEffect(()=>{try{let e=sessionStorage.getItem(n||ve);e&&(ge=JSON.parse(e))}catch(Re){}},[n]),e.useLayoutEffect(()=>{let e=t&&"/"!==i?(e,n)=>t({...e,pathname:y(e.pathname,i)||e.pathname},n):t,n=r?.enableScrollRestoration(ge,()=>window.scrollY,e);return()=>n&&n()},[r,i,t]),e.useLayoutEffect(()=>{if(!1!==a)if("number"!=typeof a){if(s.hash){let e=document.getElementById(decodeURIComponent(s.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==o&&window.scrollTo(0,0)}else window.scrollTo(0,a)},[s,a,o]))}function be(t,n){let{capture:r}=n||{};e.useEffect(()=>{let e=null!=r?{capture:r}:void 0;return window.addEventListener("beforeunload",t,e),()=>{window.removeEventListener("beforeunload",t,e)}},[t,r])}function Se({when:t,message:n}){let r=g(t);e.useEffect(()=>{if("blocked"===r.state){window.confirm(n)?setTimeout(r.proceed,0):r.reset()}},[r,n]),e.useEffect(()=>{"blocked"!==r.state||t||r.reset()},[r,t])}function Ee(t,n={}){let r=e.useContext(I);null==r&&T(!1);let{basename:a}=se(oe.useViewTransitionState),o=l(t,{relative:n.relative});if(!r.isTransitioning)return!1;let i=y(r.currentLocation.pathname,a)||r.currentLocation.pathname,s=y(r.nextLocation.pathname,a)||r.nextLocation.pathname;return null!=C(o.pathname,s)||null!=C(o.pathname,i)}export{G as BrowserRouter,re as Form,Q as HashRouter,te as Link,ne as NavLink,Y as RouterProvider,ae as ScrollRestoration,V as UNSAFE_FetchersContext,I as UNSAFE_ViewTransitionContext,ye as UNSAFE_useScrollRestoration,O as createBrowserRouter,K as createHashRouter,U as createSearchParams,X as unstable_HistoryRouter,Se as unstable_usePrompt,be as useBeforeUnload,pe as useFetcher,we as useFetchers,he as useFormAction,ce as useLinkClickHandler,le as useSearchParams,me as useSubmit,Ee as useViewTransitionState};
//# sourceMappingURL=react-router-dom.production.min.js.map
{"version":3,"file":"react-router-dom.production.min.js","sources":["../dom.ts","../index.tsx"],"sourcesContent":["import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],"names":["defaultMethod","defaultEncType","isHtmlElement","object","tagName","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","_formDataSupportsSubmitter","supportedFormEncTypes","Set","getFormEncType","encType","has","getFormSubmissionInfo","target","basename","method","action","formData","body","toLowerCase","attr","getAttribute","stripBasename","FormData","isButtonElement","isInputElement","type","form","Error","document","createElement","e","isFormDataSubmitterSupported","name","prefix","append","undefined","window","__reactRouterVersion","createBrowserRouter","routes","opts","createRouter","future","v7_prependBasename","history","createBrowserHistory","hydrationData","parseHydrationData","mapRouteProperties","dataStrategy","patchRoutesOnNavigation","initialize","createHashRouter","createHashHistory","state","__staticRouterHydrationData","errors","deserializeErrors","entries","serialized","val","__type","ErrorResponseImpl","status","statusText","data","internal","__subType","ErrorConstructor","error","message","stack","ViewTransitionContext","React","createContext","isTransitioning","FetchersContext","Map","startTransitionImpl","flushSyncImpl","ReactDOM","useIdImpl","flushSyncSafe","cb","Deferred","constructor","this","promise","Promise","resolve","reject","reason","RouterProvider","fallbackElement","router","setStateImpl","useState","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","useRef","v7_startTransition","optInStartTransition","useCallback","startTransitionSafe","setState","newState","deletedFetchers","flushSync","viewTransitionOpts","fetchers","forEach","fetcher","current","set","delete","isViewTransitionUnavailable","startViewTransition","skipTransition","currentLocation","nextLocation","t","finished","finally","useLayoutEffect","subscribe","useEffect","renderPromise","async","location","navigator","useMemo","createHref","encodeLocation","go","n","navigate","push","to","preventScrollReset","replace","dataRouterContext","static","routerFuture","v7_relativeSplatPath","logV6DeprecationWarnings","Fragment","DataRouterContext","Provider","DataRouterStateContext","Router","navigationType","historyAction","initialized","v7_partialHydration","MemoizedDataRoutes","DataRoutes","useRoutesImpl","BrowserRouter","children","historyRef","v5Compat","listen","HashRouter","HistoryRouter","isBrowser","ABSOLUTE_URL_REGEX","Link","forwardRef","onClick","relative","reloadDocument","viewTransition","rest","ref","absoluteHref","useContext","NavigationContext","isExternal","test","currentUrl","URL","href","targetUrl","startsWith","protocol","path","pathname","origin","search","hash","useHref","internalOnClick","useLinkClickHandler","assign","event","defaultPrevented","NavLink","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","useResolvedPath","useLocation","routerState","useViewTransitionState","toPathname","locationPathname","nextLocationPathname","navigation","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","filter","Boolean","join","Form","fetcherKey","onSubmit","props","forwardedRef","submit","useSubmit","formAction","useFormAction","formMethod","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","getKey","storageKey","useScrollRestoration","DataRouterHook","DataRouterStateHook","useDataRouterContext","hookName","ctx","invariant","useDataRouterState","replaceProp","useNavigate","button","metaKey","altKey","ctrlKey","shiftKey","isModifiedEvent","shouldProcessLinkClick","createPath","useSearchParams","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","searchParams","locationSearch","defaultSearchParams","_","getAll","getSearchParamsForLocation","setSearchParams","nextInit","navigateOptions","newSearchParams","fetcherId","getUniqueFetcherId","String","UseSubmit","currentRouteId","useRouteId","options","validateClientSideSubmission","fetch","formEncType","fromRouteId","routeContext","RouteContext","match","matches","slice","params","indexValues","some","qs","toString","route","index","joinPaths","useFetcher","UseFetcher","routeId","id","defaultKey","setFetcherKey","getFetcher","deleteFetcher","load","submitImpl","FetcherForm","get","IDLE_FETCHER","useFetchers","UseFetchers","from","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","UseScrollRestoration","restoreScrollPosition","useMatches","useNavigation","scrollRestoration","callback","capture","addEventListener","removeEventListener","usePageHide","scrollY","sessionStorage","setItem","JSON","stringify","sessionPositions","getItem","parse","getKeyWithoutBasename","disableScrollRestoration","enableScrollRestoration","el","getElementById","decodeURIComponent","scrollIntoView","scrollTo","useBeforeUnload","usePrompt","when","blocker","useBlocker","confirm","setTimeout","proceed","reset","currentPath","nextPath","matchPath"],"mappings":";;;;;;;;;;m9CAOO,MAAMA,EAAgC,MACvCC,EAA8B,oCAE7B,SAASC,EAAcC,GAC5B,OAAiB,MAAVA,GAA4C,iBAAnBA,EAAOC,OACzC,CA+DO,SAASC,EACdC,EAA4B,IAE5B,OAAO,IAAIC,gBACO,iBAATD,GACPE,MAAMC,QAAQH,IACdA,aAAgBC,gBACZD,EACAI,OAAOC,KAAKL,GAAMM,OAAO,CAACC,EAAMC,KAC9B,IAAIC,EAAQT,EAAKQ,GACjB,OAAOD,EAAKG,OACVR,MAAMC,QAAQM,GAASA,EAAME,IAAKC,GAAM,CAACJ,EAAKI,IAAM,CAAC,CAACJ,EAAKC,MAE5D,IAEX,CA4CA,IAAII,EAA6C,KAgGjD,MAAMC,EAA0C,IAAIC,IAAI,CACtD,oCACA,sBACA,eAGF,SAASC,EAAeC,GACtB,OAAe,MAAXA,GAAoBH,EAAsBI,IAAID,GAS3CA,EAFE,IAGX,CAEO,SAASE,EACdC,EACAC,GAQA,IAAIC,EACAC,EACAN,EACAO,EACAC,EAEJ,GAtPO7B,EADqBC,EAuPVuB,IAtP+C,SAAjCvB,EAAOC,QAAQ4B,cAsPpB,CAIzB,IAAIC,EAAOP,EAAOQ,aAAa,UAC/BL,EAASI,EAAOE,EAAcF,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S,EAAG,EAnBnB,MAFEzT,OAAOyT,SAAS,EAAGxB,IAsBpB,CAAC5L,EAAU4L,EAAuBlL,IAEzC,CAYO,SAAS2M,GACdrB,EACAzC,GAEA,IAAI0C,QAAEA,GAAY1C,GAAW,CAAA,EAC7BvN,EAAM6D,UAAU,KACd,IAAI9F,EAAkB,MAAXkS,EAAkB,CAAEA,gBAAYvS,EAE3C,OADAC,OAAOuS,iBAAiB,eAAgBF,EAAUjS,GAC3C,KACLJ,OAAOwS,oBAAoB,eAAgBH,EAAUjS,KAEtD,CAACiS,EAAUC,GAChB,CAgCA,SAASqB,IAAUC,KACjBA,EAAI1R,QACJA,IAKA,IAAI2R,EAAUC,EAAWF,GAEzBvR,EAAM6D,UAAU,KACd,GAAsB,YAAlB2N,EAAQ3S,MAAqB,CACjBlB,OAAO+T,QAAQ7R,GAK3B8R,WAAWH,EAAQI,QAAS,GAE5BJ,EAAQK,OAEZ,GACC,CAACL,EAAS3R,IAEbG,EAAM6D,UAAU,KACQ,YAAlB2N,EAAQ3S,OAAwB0S,GAClCC,EAAQK,SAET,CAACL,EAASD,GACf,CAYA,SAASxI,GACPtE,EACA1G,EAA2C,IAE3C,IAAI2D,EAAY1B,EAAM+G,WAAWhH,GAGlB,MAAb2B,GADF6J,GAAS,GAMT,IAAInP,SAAEA,GAAagP,GACjBF,GAAenC,wBAEbtB,EAAOmB,EAAgBnE,EAAI,CAAEgC,SAAU1I,EAAK0I,WAChD,IAAK/E,EAAUxB,gBACb,OAAO,EAGT,IAAI4R,EACFlV,EAAc8E,EAAU4B,gBAAgBoE,SAAUtL,IAClDsF,EAAU4B,gBAAgBoE,SACxBqK,EACFnV,EAAc8E,EAAU6B,aAAamE,SAAUtL,IAC/CsF,EAAU6B,aAAamE,SAezB,OACwC,MAAtCsK,EAAUvK,EAAKC,SAAUqK,IACgB,MAAzCC,EAAUvK,EAAKC,SAAUoK,EAE7B"}'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var router = require('@remix-run/router');
var reactRouter = require('react-router');
var reactRouterDom = require('react-router-dom');

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var React__namespace = /*#__PURE__*/_interopNamespace(React);

/**
 * A `<Router>` that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouter({
  basename,
  children,
  location: locationProp = "/",
  future
}) {
  if (typeof locationProp === "string") {
    locationProp = reactRouterDom.parsePath(locationProp);
  }
  let action = router.Action.Pop;
  let location = {
    pathname: locationProp.pathname || "/",
    search: locationProp.search || "",
    hash: locationProp.hash || "",
    state: locationProp.state != null ? locationProp.state : null,
    key: locationProp.key || "default"
  };
  let staticNavigator = getStatelessNavigator();
  return /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
    basename: basename,
    children: children,
    location: location,
    navigationType: action,
    navigator: staticNavigator,
    future: future,
    static: true
  });
}
/**
 * A Data Router that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouterProvider({
  context,
  router: router$1,
  hydrate = true,
  nonce
}) {
  !(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.UNSAFE_invariant(false) : void 0;
  let dataRouterContext = {
    router: router$1,
    navigator: getStatelessNavigator(),
    static: true,
    staticContext: context,
    basename: context.basename || "/"
  };
  let fetchersContext = new Map();
  let hydrateScript = "";
  if (hydrate !== false) {
    let data = {
      loaderData: context.loaderData,
      actionData: context.actionData,
      errors: serializeErrors(context.errors)
    };
    // Use JSON.parse here instead of embedding a raw JS object here to speed
    // up parsing on the client.  Dual-stringify is needed to ensure all quotes
    // are properly escaped in the resulting string.  See:
    //   https://v8.dev/blog/cost-of-javascript-2019#json
    let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
    hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  }
  let {
    state
  } = dataRouterContext.router;
  return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_FetchersContext.Provider, {
    value: fetchersContext
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_ViewTransitionContext.Provider, {
    value: {
      isTransitioning: false
    }
  }, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
    basename: dataRouterContext.basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: dataRouterContext.navigator,
    static: dataRouterContext.static,
    future: {
      v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
    }
  }, /*#__PURE__*/React__namespace.createElement(DataRoutes, {
    routes: router$1.routes,
    future: router$1.future,
    state: state
  })))))), hydrateScript ? (/*#__PURE__*/React__namespace.createElement("script", {
    suppressHydrationWarning: true,
    nonce: nonce,
    dangerouslySetInnerHTML: {
      __html: hydrateScript
    }
  })) : null);
}
function DataRoutes({
  routes,
  future,
  state
}) {
  return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
function serializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // deserializeErrors in react-router-dom/index.tsx :)
    if (router.isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      // Do not serialize stack traces from SSR for security reasons
      serialized[key] = {
        message: val.message,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.
        ...(val.name !== "Error" ? {
          __subType: val.name
        } : {})
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
function getStatelessNavigator() {
  return {
    createHref,
    encodeLocation,
    push(to) {
      throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
    },
    replace(to) {
      throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
    },
    go(delta) {
      throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
    },
    back() {
      throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
    },
    forward() {
      throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
    }
  };
}
function createStaticHandler(routes, opts) {
  return router.createStaticHandler(routes, {
    ...opts,
    mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties
  });
}
function createStaticRouter(routes, context, opts = {}) {
  let manifest = {};
  let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest);
  // Because our context matches may be from a framework-agnostic set of
  // routes passed to createStaticHandler(), we update them here with our
  // newly created/enhanced data routes
  let matches = context.matches.map(match => {
    let route = manifest[match.route.id] || match.route;
    return {
      ...match,
      route
    };
  });
  let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
  return {
    get basename() {
      return context.basename;
    },
    get future() {
      return {
        v7_fetcherPersist: false,
        v7_normalizeFormMethod: false,
        v7_partialHydration: opts.future?.v7_partialHydration === true,
        v7_prependBasename: false,
        v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true,
        v7_skipActionErrorRevalidation: false
      };
    },
    get state() {
      return {
        historyAction: router.Action.Pop,
        location: context.location,
        matches,
        loaderData: context.loaderData,
        actionData: context.actionData,
        errors: context.errors,
        initialized: true,
        navigation: router.IDLE_NAVIGATION,
        restoreScrollPosition: null,
        preventScrollReset: false,
        revalidation: "idle",
        fetchers: new Map(),
        blockers: new Map()
      };
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return undefined;
    },
    initialize() {
      throw msg("initialize");
    },
    subscribe() {
      throw msg("subscribe");
    },
    enableScrollRestoration() {
      throw msg("enableScrollRestoration");
    },
    navigate() {
      throw msg("navigate");
    },
    fetch() {
      throw msg("fetch");
    },
    revalidate() {
      throw msg("revalidate");
    },
    createHref,
    encodeLocation,
    getFetcher() {
      return router.IDLE_FETCHER;
    },
    deleteFetcher() {
      throw msg("deleteFetcher");
    },
    dispose() {
      throw msg("dispose");
    },
    getBlocker() {
      return router.IDLE_BLOCKER;
    },
    deleteBlocker() {
      throw msg("deleteBlocker");
    },
    patchRoutes() {
      throw msg("patchRoutes");
    },
    _internalFetchControllers: new Map(),
    _internalActiveDeferreds: new Map(),
    _internalSetRoutes() {
      throw msg("_internalSetRoutes");
    }
  };
}
function createHref(to) {
  return typeof to === "string" ? to : reactRouterDom.createPath(to);
}
function encodeLocation(to) {
  let href = typeof to === "string" ? to : reactRouterDom.createPath(to);
  // Treating this as a full URL will strip any trailing spaces so we need to
  // pre-encode them since they might be part of a matching splat param from
  // an ancestor route
  href = href.replace(/ $/, "%20");
  let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
  return {
    pathname: encoded.pathname,
    search: encoded.search,
    hash: encoded.hash
  };
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function htmlEscape(str) {
  return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]);
}

exports.StaticRouter = StaticRouter;
exports.StaticRouterProvider = StaticRouterProvider;
exports.createStaticHandler = createStaticHandler;
exports.createStaticRouter = createStaticRouter;
import * as React from 'react';
import { Action, UNSAFE_invariant, isRouteErrorResponse, createStaticHandler as createStaticHandler$1, UNSAFE_convertRoutesToDataRoutes, IDLE_NAVIGATION, IDLE_FETCHER, IDLE_BLOCKER } from '@remix-run/router';
import { UNSAFE_useRoutesImpl, UNSAFE_mapRouteProperties } from 'react-router';
import { parsePath, Router, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_FetchersContext, UNSAFE_ViewTransitionContext, createPath } from 'react-router-dom';

/**
 * A `<Router>` that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouter({
  basename,
  children,
  location: locationProp = "/",
  future
}) {
  if (typeof locationProp === "string") {
    locationProp = parsePath(locationProp);
  }
  let action = Action.Pop;
  let location = {
    pathname: locationProp.pathname || "/",
    search: locationProp.search || "",
    hash: locationProp.hash || "",
    state: locationProp.state != null ? locationProp.state : null,
    key: locationProp.key || "default"
  };
  let staticNavigator = getStatelessNavigator();
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: location,
    navigationType: action,
    navigator: staticNavigator,
    future: future,
    static: true
  });
}
/**
 * A Data Router that may not navigate to any other location. This is useful
 * on the server where there is no stateful UI.
 */
function StaticRouterProvider({
  context,
  router,
  hydrate = true,
  nonce
}) {
  !(router && context) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : UNSAFE_invariant(false) : void 0;
  let dataRouterContext = {
    router,
    navigator: getStatelessNavigator(),
    static: true,
    staticContext: context,
    basename: context.basename || "/"
  };
  let fetchersContext = new Map();
  let hydrateScript = "";
  if (hydrate !== false) {
    let data = {
      loaderData: context.loaderData,
      actionData: context.actionData,
      errors: serializeErrors(context.errors)
    };
    // Use JSON.parse here instead of embedding a raw JS object here to speed
    // up parsing on the client.  Dual-stringify is needed to ensure all quotes
    // are properly escaped in the resulting string.  See:
    //   https://v8.dev/blog/cost-of-javascript-2019#json
    let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
    hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  }
  let {
    state
  } = dataRouterContext.router;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(UNSAFE_FetchersContext.Provider, {
    value: fetchersContext
  }, /*#__PURE__*/React.createElement(UNSAFE_ViewTransitionContext.Provider, {
    value: {
      isTransitioning: false
    }
  }, /*#__PURE__*/React.createElement(Router, {
    basename: dataRouterContext.basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: dataRouterContext.navigator,
    static: dataRouterContext.static,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, /*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  })))))), hydrateScript ? /*#__PURE__*/React.createElement("script", {
    suppressHydrationWarning: true,
    nonce: nonce,
    dangerouslySetInnerHTML: {
      __html: hydrateScript
    }
  }) : null);
}
function DataRoutes({
  routes,
  future,
  state
}) {
  return UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
function serializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // deserializeErrors in react-router-dom/index.tsx :)
    if (isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      // Do not serialize stack traces from SSR for security reasons
      serialized[key] = {
        message: val.message,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.
        ...(val.name !== "Error" ? {
          __subType: val.name
        } : {})
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
function getStatelessNavigator() {
  return {
    createHref,
    encodeLocation,
    push(to) {
      throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
    },
    replace(to) {
      throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
    },
    go(delta) {
      throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
    },
    back() {
      throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
    },
    forward() {
      throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
    }
  };
}
function createStaticHandler(routes, opts) {
  return createStaticHandler$1(routes, {
    ...opts,
    mapRouteProperties: UNSAFE_mapRouteProperties
  });
}
function createStaticRouter(routes, context, opts = {}) {
  let manifest = {};
  let dataRoutes = UNSAFE_convertRoutesToDataRoutes(routes, UNSAFE_mapRouteProperties, undefined, manifest);

  // Because our context matches may be from a framework-agnostic set of
  // routes passed to createStaticHandler(), we update them here with our
  // newly created/enhanced data routes
  let matches = context.matches.map(match => {
    let route = manifest[match.route.id] || match.route;
    return {
      ...match,
      route
    };
  });
  let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
  return {
    get basename() {
      return context.basename;
    },
    get future() {
      return {
        v7_fetcherPersist: false,
        v7_normalizeFormMethod: false,
        v7_partialHydration: opts.future?.v7_partialHydration === true,
        v7_prependBasename: false,
        v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true,
        v7_skipActionErrorRevalidation: false
      };
    },
    get state() {
      return {
        historyAction: Action.Pop,
        location: context.location,
        matches,
        loaderData: context.loaderData,
        actionData: context.actionData,
        errors: context.errors,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        restoreScrollPosition: null,
        preventScrollReset: false,
        revalidation: "idle",
        fetchers: new Map(),
        blockers: new Map()
      };
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return undefined;
    },
    initialize() {
      throw msg("initialize");
    },
    subscribe() {
      throw msg("subscribe");
    },
    enableScrollRestoration() {
      throw msg("enableScrollRestoration");
    },
    navigate() {
      throw msg("navigate");
    },
    fetch() {
      throw msg("fetch");
    },
    revalidate() {
      throw msg("revalidate");
    },
    createHref,
    encodeLocation,
    getFetcher() {
      return IDLE_FETCHER;
    },
    deleteFetcher() {
      throw msg("deleteFetcher");
    },
    dispose() {
      throw msg("dispose");
    },
    getBlocker() {
      return IDLE_BLOCKER;
    },
    deleteBlocker() {
      throw msg("deleteBlocker");
    },
    patchRoutes() {
      throw msg("patchRoutes");
    },
    _internalFetchControllers: new Map(),
    _internalActiveDeferreds: new Map(),
    _internalSetRoutes() {
      throw msg("_internalSetRoutes");
    }
  };
}
function createHref(to) {
  return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
  let href = typeof to === "string" ? to : createPath(to);
  // Treating this as a full URL will strip any trailing spaces so we need to
  // pre-encode them since they might be part of a matching splat param from
  // an ancestor route
  href = href.replace(/ $/, "%20");
  let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
  return {
    pathname: encoded.pathname,
    search: encoded.search,
    hash: encoded.hash
  };
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;

// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function htmlEscape(str) {
  return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]);
}

export { StaticRouter, StaticRouterProvider, createStaticHandler, createStaticRouter };
/**
 * React Router DOM v6.30.6
 *
 * 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
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom'), require('react-router'), require('@remix-run/router')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom', 'react-router', '@remix-run/router'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouterDOM = {}, global.React, global.ReactDOM, global.ReactRouter, global.RemixRouter));
})(this, (function (exports, React, ReactDOM, reactRouter, router) { 'use strict';

  function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
      Object.keys(e).forEach(function (k) {
        if (k !== 'default') {
          var d = Object.getOwnPropertyDescriptor(e, k);
          Object.defineProperty(n, k, d.get ? d : {
            enumerable: true,
            get: function () { return e[k]; }
          });
        }
      });
    }
    n["default"] = e;
    return Object.freeze(n);
  }

  var React__namespace = /*#__PURE__*/_interopNamespace(React);
  var ReactDOM__namespace = /*#__PURE__*/_interopNamespace(ReactDOM);

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }
  function _objectWithoutPropertiesLoose(r, e) {
    if (null == r) return {};
    var t = {};
    for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
      if (-1 !== e.indexOf(n)) continue;
      t[n] = r[n];
    }
    return t;
  }

  const defaultMethod = "get";
  const defaultEncType = "application/x-www-form-urlencoded";
  function isHtmlElement(object) {
    return object != null && typeof object.tagName === "string";
  }
  function isButtonElement(object) {
    return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
  }
  function isFormElement(object) {
    return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
  }
  function isInputElement(object) {
    return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
  }
  function isModifiedEvent(event) {
    return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  }
  function shouldProcessLinkClick(event, target) {
    return event.button === 0 && (
    // Ignore everything but left clicks
    !target || target === "_self") &&
    // Let browser handle "target=_blank" etc.
    !isModifiedEvent(event) // Ignore clicks with modifier keys
  ;
  }
  /**
   * Creates a URLSearchParams object using the given initializer.
   *
   * This is identical to `new URLSearchParams(init)` except it also
   * supports arrays as values in the object form of the initializer
   * instead of just strings. This is convenient when you need multiple
   * values for a given key, but don't want to use an array initializer.
   *
   * For example, instead of:
   *
   *   let searchParams = new URLSearchParams([
   *     ['sort', 'name'],
   *     ['sort', 'price']
   *   ]);
   *
   * you can do:
   *
   *   let searchParams = createSearchParams({
   *     sort: ['name', 'price']
   *   });
   */
  function createSearchParams(init) {
    if (init === void 0) {
      init = "";
    }
    return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
      let value = init[key];
      return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
    }, []));
  }
  function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
    let searchParams = createSearchParams(locationSearch);
    if (defaultSearchParams) {
      // Use `defaultSearchParams.forEach(...)` here instead of iterating of
      // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
      // web extensions. Relevant Bugzilla tickets:
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
      defaultSearchParams.forEach((_, key) => {
        if (!searchParams.has(key)) {
          defaultSearchParams.getAll(key).forEach(value => {
            searchParams.append(key, value);
          });
        }
      });
    }
    return searchParams;
  }

  // Thanks https://github.com/sindresorhus/type-fest!

  // One-time check for submitter support
  let _formDataSupportsSubmitter = null;
  function isFormDataSubmitterSupported() {
    if (_formDataSupportsSubmitter === null) {
      try {
        new FormData(document.createElement("form"),
        // @ts-expect-error if FormData supports the submitter parameter, this will throw
        0);
        _formDataSupportsSubmitter = false;
      } catch (e) {
        _formDataSupportsSubmitter = true;
      }
    }
    return _formDataSupportsSubmitter;
  }

  /**
   * Submit options shared by both navigations and fetchers
   */

  /**
   * Submit options available to fetchers
   */

  /**
   * Submit options available to navigations
   */

  const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
  function getFormEncType(encType) {
    if (encType != null && !supportedFormEncTypes.has(encType)) {
      router.UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) ;
      return null;
    }
    return encType;
  }
  function getFormSubmissionInfo(target, basename) {
    let method;
    let action;
    let encType;
    let formData;
    let body;
    if (isFormElement(target)) {
      // When grabbing the action from the element, it will have had the basename
      // prefixed to ensure non-JS scenarios work, so strip it since we'll
      // re-prefix in the router
      let attr = target.getAttribute("action");
      action = attr ? router.stripBasename(attr, basename) : null;
      method = target.getAttribute("method") || defaultMethod;
      encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
      formData = new FormData(target);
    } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
      let form = target.form;
      if (form == null) {
        throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
      }

      // <button>/<input type="submit"> may override attributes of <form>

      // When grabbing the action from the element, it will have had the basename
      // prefixed to ensure non-JS scenarios work, so strip it since we'll
      // re-prefix in the router
      let attr = target.getAttribute("formaction") || form.getAttribute("action");
      action = attr ? router.stripBasename(attr, basename) : null;
      method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
      encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;

      // Build a FormData object populated from a form and submitter
      formData = new FormData(form, target);

      // If this browser doesn't support the `FormData(el, submitter)` format,
      // then tack on the submitter value at the end.  This is a lightweight
      // solution that is not 100% spec compliant.  For complete support in older
      // browsers, consider using the `formdata-submitter-polyfill` package
      if (!isFormDataSubmitterSupported()) {
        let {
          name,
          type,
          value
        } = target;
        if (type === "image") {
          let prefix = name ? name + "." : "";
          formData.append(prefix + "x", "0");
          formData.append(prefix + "y", "0");
        } else if (name) {
          formData.append(name, value);
        }
      }
    } else if (isHtmlElement(target)) {
      throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
    } else {
      method = defaultMethod;
      action = null;
      encType = defaultEncType;
      body = target;
    }

    // Send body for <Form encType="text/plain" so we encode it into text
    if (formData && encType === "text/plain") {
      body = formData;
      formData = undefined;
    }
    return {
      action,
      method: method.toLowerCase(),
      encType,
      formData,
      body
    };
  }

  const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"],
    _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"],
    _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
  //#endregion
  // HEY YOU! DON'T TOUCH THIS VARIABLE!
  //
  // It is replaced with the proper version at build time via a babel plugin in
  // the rollup config.
  //
  // Export a global property onto the window for React Router detection by the
  // Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`
  // to detect and properly classify live websites as being built with React Router:
  // https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
  const REACT_ROUTER_VERSION = "6";
  try {
    window.__reactRouterVersion = REACT_ROUTER_VERSION;
  } catch (e) {
    // no-op
  }

  ////////////////////////////////////////////////////////////////////////////////
  //#region Routers
  ////////////////////////////////////////////////////////////////////////////////

  function createBrowserRouter(routes, opts) {
    return router.createRouter({
      basename: opts == null ? void 0 : opts.basename,
      future: _extends({}, opts == null ? void 0 : opts.future, {
        v7_prependBasename: true
      }),
      history: router.createBrowserHistory({
        window: opts == null ? void 0 : opts.window
      }),
      hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
      routes,
      mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties,
      dataStrategy: opts == null ? void 0 : opts.dataStrategy,
      patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
      window: opts == null ? void 0 : opts.window
    }).initialize();
  }
  function createHashRouter(routes, opts) {
    return router.createRouter({
      basename: opts == null ? void 0 : opts.basename,
      future: _extends({}, opts == null ? void 0 : opts.future, {
        v7_prependBasename: true
      }),
      history: router.createHashHistory({
        window: opts == null ? void 0 : opts.window
      }),
      hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
      routes,
      mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties,
      dataStrategy: opts == null ? void 0 : opts.dataStrategy,
      patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
      window: opts == null ? void 0 : opts.window
    }).initialize();
  }
  function parseHydrationData() {
    var _window;
    let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
    if (state && state.errors) {
      state = _extends({}, state, {
        errors: deserializeErrors(state.errors)
      });
    }
    return state;
  }
  function deserializeErrors(errors) {
    if (!errors) return null;
    let entries = Object.entries(errors);
    let serialized = {};
    for (let [key, val] of entries) {
      // Hey you!  If you change this, please change the corresponding logic in
      // serializeErrors in react-router-dom/server.tsx :)
      if (val && val.__type === "RouteErrorResponse") {
        serialized[key] = new router.UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
      } else if (val && val.__type === "Error") {
        // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
        if (val.__subType) {
          let ErrorConstructor = window[val.__subType];
          if (typeof ErrorConstructor === "function") {
            try {
              // @ts-expect-error
              let error = new ErrorConstructor(val.message);
              // Wipe away the client-side stack trace.  Nothing to fill it in with
              // because we don't serialize SSR stack traces for security reasons
              error.stack = "";
              serialized[key] = error;
            } catch (e) {
              // no-op - fall through and create a normal Error
            }
          }
        }
        if (serialized[key] == null) {
          let error = new Error(val.message);
          // Wipe away the client-side stack trace.  Nothing to fill it in with
          // because we don't serialize SSR stack traces for security reasons
          error.stack = "";
          serialized[key] = error;
        }
      } else {
        serialized[key] = val;
      }
    }
    return serialized;
  }

  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Contexts
  ////////////////////////////////////////////////////////////////////////////////

  const ViewTransitionContext = /*#__PURE__*/React__namespace.createContext({
    isTransitioning: false
  });
  {
    ViewTransitionContext.displayName = "ViewTransition";
  }

  // TODO: (v7) Change the useFetcher data from `any` to `unknown`

  const FetchersContext = /*#__PURE__*/React__namespace.createContext(new Map());
  {
    FetchersContext.displayName = "Fetchers";
  }

  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Components
  ////////////////////////////////////////////////////////////////////////////////

  /**
    Webpack + React 17 fails to compile on any of the following because webpack
    complains that `startTransition` doesn't exist in `React`:
    * import { startTransition } from "react"
    * import * as React from from "react";
      "startTransition" in React ? React.startTransition(() => setState()) : setState()
    * import * as React from from "react";
      "startTransition" in React ? React["startTransition"](() => setState()) : setState()

    Moving it to a constant such as the following solves the Webpack/React 17 issue:
    * import * as React from from "react";
      const START_TRANSITION = "startTransition";
      START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

    However, that introduces webpack/terser minification issues in production builds
    in React 18 where minification/obfuscation ends up removing the call of
    React.startTransition entirely from the first half of the ternary.  Grabbing
    this exported reference once up front resolves that issue.

    See https://github.com/remix-run/react-router/issues/10579
  */
  const START_TRANSITION = "startTransition";
  const startTransitionImpl = React__namespace[START_TRANSITION];
  const FLUSH_SYNC = "flushSync";
  const flushSyncImpl = ReactDOM__namespace[FLUSH_SYNC];
  const USE_ID = "useId";
  const useIdImpl = React__namespace[USE_ID];
  function startTransitionSafe(cb) {
    if (startTransitionImpl) {
      startTransitionImpl(cb);
    } else {
      cb();
    }
  }
  function flushSyncSafe(cb) {
    if (flushSyncImpl) {
      flushSyncImpl(cb);
    } else {
      cb();
    }
  }
  class Deferred {
    // @ts-expect-error - no initializer

    // @ts-expect-error - no initializer

    constructor() {
      this.status = "pending";
      this.promise = new Promise((resolve, reject) => {
        this.resolve = value => {
          if (this.status === "pending") {
            this.status = "resolved";
            resolve(value);
          }
        };
        this.reject = reason => {
          if (this.status === "pending") {
            this.status = "rejected";
            reject(reason);
          }
        };
      });
    }
  }

  /**
   * Given a Remix Router instance, render the appropriate UI
   */
  function RouterProvider(_ref) {
    let {
      fallbackElement,
      router: router$1,
      future
    } = _ref;
    let [state, setStateImpl] = React__namespace.useState(router$1.state);
    let [pendingState, setPendingState] = React__namespace.useState();
    let [vtContext, setVtContext] = React__namespace.useState({
      isTransitioning: false
    });
    let [renderDfd, setRenderDfd] = React__namespace.useState();
    let [transition, setTransition] = React__namespace.useState();
    let [interruption, setInterruption] = React__namespace.useState();
    let fetcherData = React__namespace.useRef(new Map());
    let {
      v7_startTransition
    } = future || {};
    let optInStartTransition = React__namespace.useCallback(cb => {
      if (v7_startTransition) {
        startTransitionSafe(cb);
      } else {
        cb();
      }
    }, [v7_startTransition]);
    let setState = React__namespace.useCallback((newState, _ref2) => {
      let {
        deletedFetchers,
        flushSync: flushSync,
        viewTransitionOpts: viewTransitionOpts
      } = _ref2;
      newState.fetchers.forEach((fetcher, key) => {
        if (fetcher.data !== undefined) {
          fetcherData.current.set(key, fetcher.data);
        }
      });
      deletedFetchers.forEach(key => fetcherData.current.delete(key));
      let isViewTransitionUnavailable = router$1.window == null || router$1.window.document == null || typeof router$1.window.document.startViewTransition !== "function";

      // If this isn't a view transition or it's not available in this browser,
      // just update and be done with it
      if (!viewTransitionOpts || isViewTransitionUnavailable) {
        if (flushSync) {
          flushSyncSafe(() => setStateImpl(newState));
        } else {
          optInStartTransition(() => setStateImpl(newState));
        }
        return;
      }

      // flushSync + startViewTransition
      if (flushSync) {
        // Flush through the context to mark DOM elements as transition=ing
        flushSyncSafe(() => {
          // Cancel any pending transitions
          if (transition) {
            renderDfd && renderDfd.resolve();
            transition.skipTransition();
          }
          setVtContext({
            isTransitioning: true,
            flushSync: true,
            currentLocation: viewTransitionOpts.currentLocation,
            nextLocation: viewTransitionOpts.nextLocation
          });
        });

        // Update the DOM
        let t = router$1.window.document.startViewTransition(() => {
          flushSyncSafe(() => setStateImpl(newState));
        });

        // Clean up after the animation completes
        t.finished.finally(() => {
          flushSyncSafe(() => {
            setRenderDfd(undefined);
            setTransition(undefined);
            setPendingState(undefined);
            setVtContext({
              isTransitioning: false
            });
          });
        });
        flushSyncSafe(() => setTransition(t));
        return;
      }

      // startTransition + startViewTransition
      if (transition) {
        // Interrupting an in-progress transition, cancel and let everything flush
        // out, and then kick off a new transition from the interruption state
        renderDfd && renderDfd.resolve();
        transition.skipTransition();
        setInterruption({
          state: newState,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      } else {
        // Completed navigation update with opted-in view transitions, let 'er rip
        setPendingState(newState);
        setVtContext({
          isTransitioning: true,
          flushSync: false,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      }
    }, [router$1.window, transition, renderDfd, fetcherData, optInStartTransition]);

    // Need to use a layout effect here so we are subscribed early enough to
    // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
    React__namespace.useLayoutEffect(() => router$1.subscribe(setState), [router$1, setState]);

    // When we start a view transition, create a Deferred we can use for the
    // eventual "completed" render
    React__namespace.useEffect(() => {
      if (vtContext.isTransitioning && !vtContext.flushSync) {
        setRenderDfd(new Deferred());
      }
    }, [vtContext]);

    // Once the deferred is created, kick off startViewTransition() to update the
    // DOM and then wait on the Deferred to resolve (indicating the DOM update has
    // happened)
    React__namespace.useEffect(() => {
      if (renderDfd && pendingState && router$1.window) {
        let newState = pendingState;
        let renderPromise = renderDfd.promise;
        let transition = router$1.window.document.startViewTransition(async () => {
          optInStartTransition(() => setStateImpl(newState));
          await renderPromise;
        });
        transition.finished.finally(() => {
          setRenderDfd(undefined);
          setTransition(undefined);
          setPendingState(undefined);
          setVtContext({
            isTransitioning: false
          });
        });
        setTransition(transition);
      }
    }, [optInStartTransition, pendingState, renderDfd, router$1.window]);

    // When the new location finally renders and is committed to the DOM, this
    // effect will run to resolve the transition
    React__namespace.useEffect(() => {
      if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
        renderDfd.resolve();
      }
    }, [renderDfd, transition, state.location, pendingState]);

    // If we get interrupted with a new navigation during a transition, we skip
    // the active transition, let it cleanup, then kick it off again here
    React__namespace.useEffect(() => {
      if (!vtContext.isTransitioning && interruption) {
        setPendingState(interruption.state);
        setVtContext({
          isTransitioning: true,
          flushSync: false,
          currentLocation: interruption.currentLocation,
          nextLocation: interruption.nextLocation
        });
        setInterruption(undefined);
      }
    }, [vtContext.isTransitioning, interruption]);
    React__namespace.useEffect(() => {
      router.UNSAFE_warning(fallbackElement == null || !router$1.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
      // Only log this once on initial mount
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    let navigator = React__namespace.useMemo(() => {
      return {
        createHref: router$1.createHref,
        encodeLocation: router$1.encodeLocation,
        go: n => router$1.navigate(n),
        push: (to, state, opts) => router$1.navigate(to, {
          state,
          preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
        }),
        replace: (to, state, opts) => router$1.navigate(to, {
          replace: true,
          state,
          preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
        })
      };
    }, [router$1]);
    let basename = router$1.basename || "/";
    let dataRouterContext = React__namespace.useMemo(() => ({
      router: router$1,
      navigator,
      static: false,
      basename
    }), [router$1, navigator, basename]);
    let routerFuture = React__namespace.useMemo(() => ({
      v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
    }), [router$1.future.v7_relativeSplatPath]);
    React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future, router$1.future), [future, router$1.future]);

    // The fragment and {null} here are important!  We need them to keep React 18's
    // useId happy when we are server-rendering since we may have a <script> here
    // containing the hydrated server-side staticContext (from StaticRouterProvider).
    // useId relies on the component tree structure to generate deterministic id's
    // so we need to ensure it remains the same on the client even though
    // we don't need the <script> tag
    return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouter.UNSAFE_DataRouterContext.Provider, {
      value: dataRouterContext
    }, /*#__PURE__*/React__namespace.createElement(reactRouter.UNSAFE_DataRouterStateContext.Provider, {
      value: state
    }, /*#__PURE__*/React__namespace.createElement(FetchersContext.Provider, {
      value: fetcherData.current
    }, /*#__PURE__*/React__namespace.createElement(ViewTransitionContext.Provider, {
      value: vtContext
    }, /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
      basename: basename,
      location: state.location,
      navigationType: state.historyAction,
      navigator: navigator,
      future: routerFuture
    }, state.initialized || router$1.future.v7_partialHydration ? /*#__PURE__*/React__namespace.createElement(MemoizedDataRoutes, {
      routes: router$1.routes,
      future: router$1.future,
      state: state
    }) : fallbackElement))))), null);
  }

  // Memoize to avoid re-renders when updating `ViewTransitionContext`
  const MemoizedDataRoutes = /*#__PURE__*/React__namespace.memo(DataRoutes);
  function DataRoutes(_ref3) {
    let {
      routes,
      future,
      state
    } = _ref3;
    return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future);
  }
  /**
   * A `<Router>` for use in web browsers. Provides the cleanest URLs.
   */
  function BrowserRouter(_ref4) {
    let {
      basename,
      children,
      future,
      window
    } = _ref4;
    let historyRef = React__namespace.useRef();
    if (historyRef.current == null) {
      historyRef.current = router.createBrowserHistory({
        window,
        v5Compat: true
      });
    }
    let history = historyRef.current;
    let [state, setStateImpl] = React__namespace.useState({
      action: history.action,
      location: history.location
    });
    let {
      v7_startTransition
    } = future || {};
    let setState = React__namespace.useCallback(newState => {
      v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
    }, [setStateImpl, v7_startTransition]);
    React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
    React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
    return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
      basename: basename,
      children: children,
      location: state.location,
      navigationType: state.action,
      navigator: history,
      future: future
    });
  }
  /**
   * A `<Router>` for use in web browsers. Stores the location in the hash
   * portion of the URL so it is not sent to the server.
   */
  function HashRouter(_ref5) {
    let {
      basename,
      children,
      future,
      window
    } = _ref5;
    let historyRef = React__namespace.useRef();
    if (historyRef.current == null) {
      historyRef.current = router.createHashHistory({
        window,
        v5Compat: true
      });
    }
    let history = historyRef.current;
    let [state, setStateImpl] = React__namespace.useState({
      action: history.action,
      location: history.location
    });
    let {
      v7_startTransition
    } = future || {};
    let setState = React__namespace.useCallback(newState => {
      v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
    }, [setStateImpl, v7_startTransition]);
    React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
    React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
    return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
      basename: basename,
      children: children,
      location: state.location,
      navigationType: state.action,
      navigator: history,
      future: future
    });
  }
  /**
   * A `<Router>` that accepts a pre-instantiated history object. It's important
   * to note that using your own history object is highly discouraged and may add
   * two versions of the history library to your bundles unless you use the same
   * version of the history library that React Router uses internally.
   */
  function HistoryRouter(_ref6) {
    let {
      basename,
      children,
      future,
      history
    } = _ref6;
    let [state, setStateImpl] = React__namespace.useState({
      action: history.action,
      location: history.location
    });
    let {
      v7_startTransition
    } = future || {};
    let setState = React__namespace.useCallback(newState => {
      v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
    }, [setStateImpl, v7_startTransition]);
    React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
    React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
    return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
      basename: basename,
      children: children,
      location: state.location,
      navigationType: state.action,
      navigator: history,
      future: future
    });
  }
  {
    HistoryRouter.displayName = "unstable_HistoryRouter";
  }
  const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;

  /**
   * The public API for rendering a history-aware `<a>`.
   */
  const Link = /*#__PURE__*/React__namespace.forwardRef(function LinkWithRef(_ref7, ref) {
    let {
        onClick,
        relative,
        reloadDocument,
        replace,
        state,
        target,
        to,
        preventScrollReset,
        viewTransition
      } = _ref7,
      rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
    let {
      basename
    } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);

    // Rendered into <a href> for absolute URLs
    let absoluteHref;
    let isExternal = false;
    if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
      // Render the absolute href server- and client-side
      absoluteHref = to;

      // Only check for external origins client-side
      if (isBrowser) {
        try {
          let currentUrl = new URL(window.location.href);
          let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
          let path = router.stripBasename(targetUrl.pathname, basename);
          if (targetUrl.origin === currentUrl.origin && path != null) {
            // Strip the protocol/origin/basename for same-origin absolute URLs
            to = path + targetUrl.search + targetUrl.hash;
          } else {
            isExternal = true;
          }
        } catch (e) {
          // We can't do external URL detection without a valid URL
          router.UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") ;
        }
      }
    }

    // Rendered into <a href> for relative URLs
    let href = reactRouter.useHref(to, {
      relative
    });
    let internalOnClick = useLinkClickHandler(to, {
      replace,
      state,
      target,
      preventScrollReset,
      relative,
      viewTransition
    });
    function handleClick(event) {
      if (onClick) onClick(event);
      if (!event.defaultPrevented) {
        internalOnClick(event);
      }
    }
    return (
      /*#__PURE__*/
      // eslint-disable-next-line jsx-a11y/anchor-has-content
      React__namespace.createElement("a", _extends({}, rest, {
        href: absoluteHref || href,
        onClick: isExternal || reloadDocument ? onClick : handleClick,
        ref: ref,
        target: target
      }))
    );
  });
  {
    Link.displayName = "Link";
  }
  /**
   * A `<Link>` wrapper that knows if it's "active" or not.
   */
  const NavLink = /*#__PURE__*/React__namespace.forwardRef(function NavLinkWithRef(_ref8, ref) {
    let {
        "aria-current": ariaCurrentProp = "page",
        caseSensitive = false,
        className: classNameProp = "",
        end = false,
        style: styleProp,
        to,
        viewTransition,
        children
      } = _ref8,
      rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
    let path = reactRouter.useResolvedPath(to, {
      relative: rest.relative
    });
    let location = reactRouter.useLocation();
    let routerState = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
    let {
      navigator,
      basename
    } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
    let isTransitioning = routerState != null &&
    // Conditional usage is OK here because the usage of a data router is static
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useViewTransitionState(path) && viewTransition === true;
    let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
    let locationPathname = location.pathname;
    let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
    if (!caseSensitive) {
      locationPathname = locationPathname.toLowerCase();
      nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
      toPathname = toPathname.toLowerCase();
    }
    if (nextLocationPathname && basename) {
      nextLocationPathname = router.stripBasename(nextLocationPathname, basename) || nextLocationPathname;
    }

    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,
    // we're looking for a slash _after_ what's in `to`.  For example:
    //
    // <NavLink to="/users"> and <NavLink to="/users/">
    // both want to look for a / at index 6 to match URL `/users/matt`
    const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
    let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
    let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
    let renderProps = {
      isActive,
      isPending,
      isTransitioning
    };
    let ariaCurrent = isActive ? ariaCurrentProp : undefined;
    let className;
    if (typeof classNameProp === "function") {
      className = classNameProp(renderProps);
    } else {
      // If the className prop is not a function, we use a default `active`
      // class for <NavLink />s that are active. In v5 `active` was the default
      // value for `activeClassName`, but we are removing that API and can still
      // use the old default behavior for a cleaner upgrade path and keep the
      // simple styling rules working as they currently do.
      className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
    }
    let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
    return /*#__PURE__*/React__namespace.createElement(Link, _extends({}, rest, {
      "aria-current": ariaCurrent,
      className: className,
      ref: ref,
      style: style,
      to: to,
      viewTransition: viewTransition
    }), typeof children === "function" ? children(renderProps) : children);
  });
  {
    NavLink.displayName = "NavLink";
  }

  /**
   * Form props shared by navigations and fetchers
   */

  /**
   * Form props available to fetchers
   */

  /**
   * Form props available to navigations
   */

  /**
   * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
   * that the interaction with the server is with `fetch` instead of new document
   * requests, allowing components to add nicer UX to the page as the form is
   * submitted and returns with data.
   */
  const Form = /*#__PURE__*/React__namespace.forwardRef((_ref9, forwardedRef) => {
    let {
        fetcherKey,
        navigate,
        reloadDocument,
        replace,
        state,
        method = defaultMethod,
        action,
        onSubmit,
        relative,
        preventScrollReset,
        viewTransition
      } = _ref9,
      props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
    let submit = useSubmit();
    let formAction = useFormAction(action, {
      relative
    });
    let formMethod = method.toLowerCase() === "get" ? "get" : "post";
    let submitHandler = event => {
      onSubmit && onSubmit(event);
      if (event.defaultPrevented) return;
      event.preventDefault();
      let submitter = event.nativeEvent.submitter;
      let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
      submit(submitter || event.currentTarget, {
        fetcherKey,
        method: submitMethod,
        navigate,
        replace,
        state,
        relative,
        preventScrollReset,
        viewTransition
      });
    };
    return /*#__PURE__*/React__namespace.createElement("form", _extends({
      ref: forwardedRef,
      method: formMethod,
      action: formAction,
      onSubmit: reloadDocument ? onSubmit : submitHandler
    }, props));
  });
  {
    Form.displayName = "Form";
  }
  /**
   * This component will emulate the browser's scroll restoration on location
   * changes.
   */
  function ScrollRestoration(_ref0) {
    let {
      getKey,
      storageKey
    } = _ref0;
    useScrollRestoration({
      getKey,
      storageKey
    });
    return null;
  }
  {
    ScrollRestoration.displayName = "ScrollRestoration";
  }
  //#endregion

  ////////////////////////////////////////////////////////////////////////////////
  //#region Hooks
  ////////////////////////////////////////////////////////////////////////////////
  var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
    DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
    DataRouterHook["UseSubmit"] = "useSubmit";
    DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
    DataRouterHook["UseFetcher"] = "useFetcher";
    DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
    return DataRouterHook;
  }(DataRouterHook || {});
  var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
    DataRouterStateHook["UseFetcher"] = "useFetcher";
    DataRouterStateHook["UseFetchers"] = "useFetchers";
    DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
    return DataRouterStateHook;
  }(DataRouterStateHook || {}); // Internal hooks
  function getDataRouterConsoleError(hookName) {
    return hookName + " must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.";
  }
  function useDataRouterContext(hookName) {
    let ctx = React__namespace.useContext(reactRouter.UNSAFE_DataRouterContext);
    !ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
    return ctx;
  }
  function useDataRouterState(hookName) {
    let state = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
    !state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName))  : void 0;
    return state;
  }

  // External hooks

  /**
   * Handles the click behavior for router `<Link>` components. This is useful if
   * you need to create custom `<Link>` components with the same click behavior we
   * use in our exported `<Link>`.
   */
  function useLinkClickHandler(to, _temp) {
    let {
      target,
      replace: replaceProp,
      state,
      preventScrollReset,
      relative,
      viewTransition
    } = _temp === void 0 ? {} : _temp;
    let navigate = reactRouter.useNavigate();
    let location = reactRouter.useLocation();
    let path = reactRouter.useResolvedPath(to, {
      relative
    });
    return React__namespace.useCallback(event => {
      if (shouldProcessLinkClick(event, target)) {
        event.preventDefault();

        // If the URL hasn't changed, a regular <a> will do a replace instead of
        // a push, so do the same here unless the replace prop is explicitly set
        let replace = replaceProp !== undefined ? replaceProp : reactRouter.createPath(location) === reactRouter.createPath(path);
        navigate(to, {
          replace,
          state,
          preventScrollReset,
          relative,
          viewTransition
        });
      }
    }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
  }

  /**
   * A convenient wrapper for reading and writing search parameters via the
   * URLSearchParams interface.
   */
  function useSearchParams(defaultInit) {
    router.UNSAFE_warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params.") ;
    let defaultSearchParamsRef = React__namespace.useRef(createSearchParams(defaultInit));
    let hasSetSearchParamsRef = React__namespace.useRef(false);
    let location = reactRouter.useLocation();
    let searchParams = React__namespace.useMemo(() =>
    // Only merge in the defaults if we haven't yet called setSearchParams.
    // Once we call that we want those to take precedence, otherwise you can't
    // remove a param with setSearchParams({}) if it has an initial value
    getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
    let navigate = reactRouter.useNavigate();
    let setSearchParams = React__namespace.useCallback((nextInit, navigateOptions) => {
      const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
      hasSetSearchParamsRef.current = true;
      navigate("?" + newSearchParams, navigateOptions);
    }, [navigate, searchParams]);
    return [searchParams, setSearchParams];
  }

  /**
   * Submits a HTML `<form>` to the server without reloading the page.
   */

  /**
   * Submits a fetcher `<form>` to the server without reloading the page.
   */

  function validateClientSideSubmission() {
    if (typeof document === "undefined") {
      throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
    }
  }
  let fetcherId = 0;
  let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";

  /**
   * Returns a function that may be used to programmatically submit a form (or
   * some arbitrary data) to the server.
   */
  function useSubmit() {
    let {
      router
    } = useDataRouterContext(DataRouterHook.UseSubmit);
    let {
      basename
    } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
    let currentRouteId = reactRouter.UNSAFE_useRouteId();
    return React__namespace.useCallback(function (target, options) {
      if (options === void 0) {
        options = {};
      }
      validateClientSideSubmission();
      let {
        action,
        method,
        encType,
        formData,
        body
      } = getFormSubmissionInfo(target, basename);
      if (options.navigate === false) {
        let key = options.fetcherKey || getUniqueFetcherId();
        router.fetch(key, currentRouteId, options.action || action, {
          preventScrollReset: options.preventScrollReset,
          formData,
          body,
          formMethod: options.method || method,
          formEncType: options.encType || encType,
          flushSync: options.flushSync
        });
      } else {
        router.navigate(options.action || action, {
          preventScrollReset: options.preventScrollReset,
          formData,
          body,
          formMethod: options.method || method,
          formEncType: options.encType || encType,
          replace: options.replace,
          state: options.state,
          fromRouteId: currentRouteId,
          flushSync: options.flushSync,
          viewTransition: options.viewTransition
        });
      }
    }, [router, basename, currentRouteId]);
  }

  // v7: Eventually we should deprecate this entirely in favor of using the
  // router method directly?
  function useFormAction(action, _temp2) {
    let {
      relative
    } = _temp2 === void 0 ? {} : _temp2;
    let {
      basename
    } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
    let routeContext = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
    !routeContext ? router.UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext")  : void 0;
    let [match] = routeContext.matches.slice(-1);
    // Shallow clone path so we can modify it below, otherwise we modify the
    // object referenced by useMemo inside useResolvedPath
    let path = _extends({}, reactRouter.useResolvedPath(action ? action : ".", {
      relative
    }));

    // If no action was specified, browsers will persist current search params
    // when determining the path, so match that behavior
    // https://github.com/remix-run/remix/issues/927
    let location = reactRouter.useLocation();
    if (action == null) {
      // Safe to write to this directly here since if action was undefined, we
      // would have called useResolvedPath(".") which will never include a search
      path.search = location.search;

      // When grabbing search params from the URL, remove any included ?index param
      // since it might not apply to our contextual route.  We add it back based
      // on match.route.index below
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      let hasNakedIndexParam = indexValues.some(v => v === "");
      if (hasNakedIndexParam) {
        params.delete("index");
        indexValues.filter(v => v).forEach(v => params.append("index", v));
        let qs = params.toString();
        path.search = qs ? "?" + qs : "";
      }
    }
    if ((!action || action === ".") && match.route.index) {
      path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
    }

    // If we're operating within a basename, prepend it to the pathname prior
    // to creating the form action.  If this is a root navigation, then just use
    // the raw basename which allows the basename to have full control over the
    // presence of a trailing slash on root actions
    if (basename !== "/") {
      path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
    }
    return reactRouter.createPath(path);
  }
  // TODO: (v7) Change the useFetcher generic default from `any` to `unknown`

  /**
   * Interacts with route loaders and actions without causing a navigation. Great
   * for any interaction that stays on the same page.
   */
  function useFetcher(_temp3) {
    var _route$matches;
    let {
      key
    } = _temp3 === void 0 ? {} : _temp3;
    let {
      router: router$1
    } = useDataRouterContext(DataRouterHook.UseFetcher);
    let state = useDataRouterState(DataRouterStateHook.UseFetcher);
    let fetcherData = React__namespace.useContext(FetchersContext);
    let route = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
    let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
    !fetcherData ? router.UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext")  : void 0;
    !route ? router.UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext")  : void 0;
    !(routeId != null) ? router.UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"")  : void 0;

    // Fetcher key handling
    // OK to call conditionally to feature detect `useId`
    // eslint-disable-next-line react-hooks/rules-of-hooks
    let defaultKey = useIdImpl ? useIdImpl() : "";
    let [fetcherKey, setFetcherKey] = React__namespace.useState(key || defaultKey);
    if (key && key !== fetcherKey) {
      setFetcherKey(key);
    } else if (!fetcherKey) {
      // We will only fall through here when `useId` is not available
      setFetcherKey(getUniqueFetcherId());
    }

    // Registration/cleanup
    React__namespace.useEffect(() => {
      router$1.getFetcher(fetcherKey);
      return () => {
        // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
        // will not delete immediately but instead queue up a delete after the
        // fetcher returns to an `idle` state
        router$1.deleteFetcher(fetcherKey);
      };
    }, [router$1, fetcherKey]);

    // Fetcher additions
    let load = React__namespace.useCallback((href, opts) => {
      !routeId ? router.UNSAFE_invariant(false, "No routeId available for fetcher.load()")  : void 0;
      router$1.fetch(fetcherKey, routeId, href, opts);
    }, [fetcherKey, routeId, router$1]);
    let submitImpl = useSubmit();
    let submit = React__namespace.useCallback((target, opts) => {
      submitImpl(target, _extends({}, opts, {
        navigate: false,
        fetcherKey
      }));
    }, [fetcherKey, submitImpl]);
    let FetcherForm = React__namespace.useMemo(() => {
      let FetcherForm = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
        return /*#__PURE__*/React__namespace.createElement(Form, _extends({}, props, {
          navigate: false,
          fetcherKey: fetcherKey,
          ref: ref
        }));
      });
      {
        FetcherForm.displayName = "fetcher.Form";
      }
      return FetcherForm;
    }, [fetcherKey]);

    // Exposed FetcherWithComponents
    let fetcher = state.fetchers.get(fetcherKey) || router.IDLE_FETCHER;
    let data = fetcherData.get(fetcherKey);
    let fetcherWithComponents = React__namespace.useMemo(() => _extends({
      Form: FetcherForm,
      submit,
      load
    }, fetcher, {
      data
    }), [FetcherForm, submit, load, fetcher, data]);
    return fetcherWithComponents;
  }

  /**
   * Provides all fetchers currently on the page. Useful for layouts and parent
   * routes that need to provide pending/optimistic UI regarding the fetch.
   */
  function useFetchers() {
    let state = useDataRouterState(DataRouterStateHook.UseFetchers);
    return Array.from(state.fetchers.entries()).map(_ref1 => {
      let [key, fetcher] = _ref1;
      return _extends({}, fetcher, {
        key
      });
    });
  }
  const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
  let savedScrollPositions = {};

  /**
   * When rendered inside a RouterProvider, will restore scroll positions on navigations
   */
  function useScrollRestoration(_temp4) {
    let {
      getKey,
      storageKey
    } = _temp4 === void 0 ? {} : _temp4;
    let {
      router: router$1
    } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
    let {
      restoreScrollPosition,
      preventScrollReset
    } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
    let {
      basename
    } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
    let location = reactRouter.useLocation();
    let matches = reactRouter.useMatches();
    let navigation = reactRouter.useNavigation();

    // Trigger manual scroll restoration while we're active
    React__namespace.useEffect(() => {
      window.history.scrollRestoration = "manual";
      return () => {
        window.history.scrollRestoration = "auto";
      };
    }, []);

    // Save positions on pagehide
    usePageHide(React__namespace.useCallback(() => {
      if (navigation.state === "idle") {
        let key = (getKey ? getKey(location, matches) : null) || location.key;
        savedScrollPositions[key] = window.scrollY;
      }
      try {
        sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
      } catch (error) {
        router.UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") ;
      }
      window.history.scrollRestoration = "auto";
    }, [storageKey, getKey, navigation.state, location, matches]));

    // Read in any saved scroll locations
    if (typeof document !== "undefined") {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      React__namespace.useLayoutEffect(() => {
        try {
          let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
          if (sessionPositions) {
            savedScrollPositions = JSON.parse(sessionPositions);
          }
        } catch (e) {
          // no-op, use default empty object
        }
      }, [storageKey]);

      // Enable scroll restoration in the router
      // eslint-disable-next-line react-hooks/rules-of-hooks
      React__namespace.useLayoutEffect(() => {
        let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey(// Strip the basename to match useLocation()
        _extends({}, location, {
          pathname: router.stripBasename(location.pathname, basename) || location.pathname
        }), matches) : getKey;
        let disableScrollRestoration = router$1 == null ? void 0 : router$1.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
        return () => disableScrollRestoration && disableScrollRestoration();
      }, [router$1, basename, getKey]);

      // Restore scrolling when state.restoreScrollPosition changes
      // eslint-disable-next-line react-hooks/rules-of-hooks
      React__namespace.useLayoutEffect(() => {
        // Explicit false means don't do anything (used for submissions)
        if (restoreScrollPosition === false) {
          return;
        }

        // been here before, scroll to it
        if (typeof restoreScrollPosition === "number") {
          window.scrollTo(0, restoreScrollPosition);
          return;
        }

        // try to scroll to the hash
        if (location.hash) {
          let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
          if (el) {
            el.scrollIntoView();
            return;
          }
        }

        // Don't reset if this navigation opted out
        if (preventScrollReset === true) {
          return;
        }

        // otherwise go to the top on new locations
        window.scrollTo(0, 0);
      }, [location, restoreScrollPosition, preventScrollReset]);
    }
  }

  /**
   * Setup a callback to be fired on the window's `beforeunload` event. This is
   * useful for saving some data to `window.localStorage` just before the page
   * refreshes.
   *
   * Note: The `callback` argument should be a function created with
   * `React.useCallback()`.
   */
  function useBeforeUnload(callback, options) {
    let {
      capture
    } = options || {};
    React__namespace.useEffect(() => {
      let opts = capture != null ? {
        capture
      } : undefined;
      window.addEventListener("beforeunload", callback, opts);
      return () => {
        window.removeEventListener("beforeunload", callback, opts);
      };
    }, [callback, capture]);
  }

  /**
   * Setup a callback to be fired on the window's `pagehide` event. This is
   * useful for saving some data to `window.localStorage` just before the page
   * refreshes.  This event is better supported than beforeunload across browsers.
   *
   * Note: The `callback` argument should be a function created with
   * `React.useCallback()`.
   */
  function usePageHide(callback, options) {
    let {
      capture
    } = options || {};
    React__namespace.useEffect(() => {
      let opts = capture != null ? {
        capture
      } : undefined;
      window.addEventListener("pagehide", callback, opts);
      return () => {
        window.removeEventListener("pagehide", callback, opts);
      };
    }, [callback, capture]);
  }

  /**
   * Wrapper around useBlocker to show a window.confirm prompt to users instead
   * of building a custom UI with useBlocker.
   *
   * Warning: This has *a lot of rough edges* and behaves very differently (and
   * very incorrectly in some cases) across browsers if user click addition
   * back/forward navigations while the confirm is open.  Use at your own risk.
   */
  function usePrompt(_ref10) {
    let {
      when,
      message
    } = _ref10;
    let blocker = reactRouter.useBlocker(when);
    React__namespace.useEffect(() => {
      if (blocker.state === "blocked") {
        let proceed = window.confirm(message);
        if (proceed) {
          // This timeout is needed to avoid a weird "race" on POP navigations
          // between the `window.history` revert navigation and the result of
          // `window.confirm`
          setTimeout(blocker.proceed, 0);
        } else {
          blocker.reset();
        }
      }
    }, [blocker, message]);
    React__namespace.useEffect(() => {
      if (blocker.state === "blocked" && !when) {
        blocker.reset();
      }
    }, [blocker, when]);
  }

  /**
   * Return a boolean indicating if there is an active view transition to the
   * given href.  You can use this value to render CSS classes or viewTransitionName
   * styles onto your elements
   *
   * @param href The destination href
   * @param [opts.relative] Relative routing type ("route" | "path")
   */
  function useViewTransitionState(to, opts) {
    if (opts === void 0) {
      opts = {};
    }
    let vtContext = React__namespace.useContext(ViewTransitionContext);
    !(vtContext != null) ? router.UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  " + "Did you accidentally import `RouterProvider` from `react-router`?")  : void 0;
    let {
      basename
    } = useDataRouterContext(DataRouterHook.useViewTransitionState);
    let path = reactRouter.useResolvedPath(to, {
      relative: opts.relative
    });
    if (!vtContext.isTransitioning) {
      return false;
    }
    let currentPath = router.stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
    let nextPath = router.stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;

    // Transition is active if we're going to or coming from the indicated
    // destination.  This ensures that other PUSH navigations that reverse
    // an indicated transition apply.  I.e., on the list view you have:
    //
    //   <NavLink to="/details/1" viewTransition>
    //
    // If you click the breadcrumb back to the list view:
    //
    //   <NavLink to="/list" viewTransition>
    //
    // We should apply the transition because it's indicated as active going
    // from /list -> /details/1 and therefore should be active on the reverse
    // (even though this isn't strictly a POP reverse)
    return router.matchPath(path.pathname, nextPath) != null || router.matchPath(path.pathname, currentPath) != null;
  }

  //#endregion

  Object.defineProperty(exports, 'AbortedDeferredError', {
    enumerable: true,
    get: function () { return reactRouter.AbortedDeferredError; }
  });
  Object.defineProperty(exports, 'Await', {
    enumerable: true,
    get: function () { return reactRouter.Await; }
  });
  Object.defineProperty(exports, 'MemoryRouter', {
    enumerable: true,
    get: function () { return reactRouter.MemoryRouter; }
  });
  Object.defineProperty(exports, 'Navigate', {
    enumerable: true,
    get: function () { return reactRouter.Navigate; }
  });
  Object.defineProperty(exports, 'NavigationType', {
    enumerable: true,
    get: function () { return reactRouter.NavigationType; }
  });
  Object.defineProperty(exports, 'Outlet', {
    enumerable: true,
    get: function () { return reactRouter.Outlet; }
  });
  Object.defineProperty(exports, 'Route', {
    enumerable: true,
    get: function () { return reactRouter.Route; }
  });
  Object.defineProperty(exports, 'Router', {
    enumerable: true,
    get: function () { return reactRouter.Router; }
  });
  Object.defineProperty(exports, 'Routes', {
    enumerable: true,
    get: function () { return reactRouter.Routes; }
  });
  Object.defineProperty(exports, 'UNSAFE_DataRouterContext', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_DataRouterContext; }
  });
  Object.defineProperty(exports, 'UNSAFE_DataRouterStateContext', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_DataRouterStateContext; }
  });
  Object.defineProperty(exports, 'UNSAFE_LocationContext', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_LocationContext; }
  });
  Object.defineProperty(exports, 'UNSAFE_NavigationContext', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_NavigationContext; }
  });
  Object.defineProperty(exports, 'UNSAFE_RouteContext', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_RouteContext; }
  });
  Object.defineProperty(exports, 'UNSAFE_useRouteId', {
    enumerable: true,
    get: function () { return reactRouter.UNSAFE_useRouteId; }
  });
  Object.defineProperty(exports, 'createMemoryRouter', {
    enumerable: true,
    get: function () { return reactRouter.createMemoryRouter; }
  });
  Object.defineProperty(exports, 'createPath', {
    enumerable: true,
    get: function () { return reactRouter.createPath; }
  });
  Object.defineProperty(exports, 'createRoutesFromChildren', {
    enumerable: true,
    get: function () { return reactRouter.createRoutesFromChildren; }
  });
  Object.defineProperty(exports, 'createRoutesFromElements', {
    enumerable: true,
    get: function () { return reactRouter.createRoutesFromElements; }
  });
  Object.defineProperty(exports, 'defer', {
    enumerable: true,
    get: function () { return reactRouter.defer; }
  });
  Object.defineProperty(exports, 'generatePath', {
    enumerable: true,
    get: function () { return reactRouter.generatePath; }
  });
  Object.defineProperty(exports, 'isRouteErrorResponse', {
    enumerable: true,
    get: function () { return reactRouter.isRouteErrorResponse; }
  });
  Object.defineProperty(exports, 'json', {
    enumerable: true,
    get: function () { return reactRouter.json; }
  });
  Object.defineProperty(exports, 'matchPath', {
    enumerable: true,
    get: function () { return reactRouter.matchPath; }
  });
  Object.defineProperty(exports, 'matchRoutes', {
    enumerable: true,
    get: function () { return reactRouter.matchRoutes; }
  });
  Object.defineProperty(exports, 'parsePath', {
    enumerable: true,
    get: function () { return reactRouter.parsePath; }
  });
  Object.defineProperty(exports, 'redirect', {
    enumerable: true,
    get: function () { return reactRouter.redirect; }
  });
  Object.defineProperty(exports, 'redirectDocument', {
    enumerable: true,
    get: function () { return reactRouter.redirectDocument; }
  });
  Object.defineProperty(exports, 'renderMatches', {
    enumerable: true,
    get: function () { return reactRouter.renderMatches; }
  });
  Object.defineProperty(exports, 'replace', {
    enumerable: true,
    get: function () { return reactRouter.replace; }
  });
  Object.defineProperty(exports, 'resolvePath', {
    enumerable: true,
    get: function () { return reactRouter.resolvePath; }
  });
  Object.defineProperty(exports, 'useActionData', {
    enumerable: true,
    get: function () { return reactRouter.useActionData; }
  });
  Object.defineProperty(exports, 'useAsyncError', {
    enumerable: true,
    get: function () { return reactRouter.useAsyncError; }
  });
  Object.defineProperty(exports, 'useAsyncValue', {
    enumerable: true,
    get: function () { return reactRouter.useAsyncValue; }
  });
  Object.defineProperty(exports, 'useBlocker', {
    enumerable: true,
    get: function () { return reactRouter.useBlocker; }
  });
  Object.defineProperty(exports, 'useHref', {
    enumerable: true,
    get: function () { return reactRouter.useHref; }
  });
  Object.defineProperty(exports, 'useInRouterContext', {
    enumerable: true,
    get: function () { return reactRouter.useInRouterContext; }
  });
  Object.defineProperty(exports, 'useLoaderData', {
    enumerable: true,
    get: function () { return reactRouter.useLoaderData; }
  });
  Object.defineProperty(exports, 'useLocation', {
    enumerable: true,
    get: function () { return reactRouter.useLocation; }
  });
  Object.defineProperty(exports, 'useMatch', {
    enumerable: true,
    get: function () { return reactRouter.useMatch; }
  });
  Object.defineProperty(exports, 'useMatches', {
    enumerable: true,
    get: function () { return reactRouter.useMatches; }
  });
  Object.defineProperty(exports, 'useNavigate', {
    enumerable: true,
    get: function () { return reactRouter.useNavigate; }
  });
  Object.defineProperty(exports, 'useNavigation', {
    enumerable: true,
    get: function () { return reactRouter.useNavigation; }
  });
  Object.defineProperty(exports, 'useNavigationType', {
    enumerable: true,
    get: function () { return reactRouter.useNavigationType; }
  });
  Object.defineProperty(exports, 'useOutlet', {
    enumerable: true,
    get: function () { return reactRouter.useOutlet; }
  });
  Object.defineProperty(exports, 'useOutletContext', {
    enumerable: true,
    get: function () { return reactRouter.useOutletContext; }
  });
  Object.defineProperty(exports, 'useParams', {
    enumerable: true,
    get: function () { return reactRouter.useParams; }
  });
  Object.defineProperty(exports, 'useResolvedPath', {
    enumerable: true,
    get: function () { return reactRouter.useResolvedPath; }
  });
  Object.defineProperty(exports, 'useRevalidator', {
    enumerable: true,
    get: function () { return reactRouter.useRevalidator; }
  });
  Object.defineProperty(exports, 'useRouteError', {
    enumerable: true,
    get: function () { return reactRouter.useRouteError; }
  });
  Object.defineProperty(exports, 'useRouteLoaderData', {
    enumerable: true,
    get: function () { return reactRouter.useRouteLoaderData; }
  });
  Object.defineProperty(exports, 'useRoutes', {
    enumerable: true,
    get: function () { return reactRouter.useRoutes; }
  });
  Object.defineProperty(exports, 'UNSAFE_ErrorResponseImpl', {
    enumerable: true,
    get: function () { return router.UNSAFE_ErrorResponseImpl; }
  });
  exports.BrowserRouter = BrowserRouter;
  exports.Form = Form;
  exports.HashRouter = HashRouter;
  exports.Link = Link;
  exports.NavLink = NavLink;
  exports.RouterProvider = RouterProvider;
  exports.ScrollRestoration = ScrollRestoration;
  exports.UNSAFE_FetchersContext = FetchersContext;
  exports.UNSAFE_ViewTransitionContext = ViewTransitionContext;
  exports.UNSAFE_useScrollRestoration = useScrollRestoration;
  exports.createBrowserRouter = createBrowserRouter;
  exports.createHashRouter = createHashRouter;
  exports.createSearchParams = createSearchParams;
  exports.unstable_HistoryRouter = HistoryRouter;
  exports.unstable_usePrompt = usePrompt;
  exports.useBeforeUnload = useBeforeUnload;
  exports.useFetcher = useFetcher;
  exports.useFetchers = useFetchers;
  exports.useFormAction = useFormAction;
  exports.useLinkClickHandler = useLinkClickHandler;
  exports.useSearchParams = useSearchParams;
  exports.useSubmit = useSubmit;
  exports.useViewTransitionState = useViewTransitionState;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=react-router-dom.development.js.map
{"version":3,"file":"react-router-dom.development.js","sources":["../../dom.ts","../../index.tsx"],"sourcesContent":["import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],"names":["defaultMethod","defaultEncType","isHtmlElement","object","tagName","isButtonElement","toLowerCase","isFormElement","isInputElement","isModifiedEvent","event","metaKey","altKey","ctrlKey","shiftKey","shouldProcessLinkClick","target","button","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","getSearchParamsForLocation","locationSearch","defaultSearchParams","searchParams","forEach","_","has","getAll","append","_formDataSupportsSubmitter","isFormDataSubmitterSupported","FormData","document","createElement","e","supportedFormEncTypes","Set","getFormEncType","encType","process","warning","getFormSubmissionInfo","basename","method","action","formData","body","attr","getAttribute","stripBasename","type","form","Error","name","prefix","undefined","REACT_ROUTER_VERSION","window","__reactRouterVersion","createBrowserRouter","routes","opts","createRouter","future","_extends","v7_prependBasename","history","createBrowserHistory","hydrationData","parseHydrationData","mapRouteProperties","dataStrategy","patchRoutesOnNavigation","initialize","createHashRouter","createHashHistory","_window","state","__staticRouterHydrationData","errors","deserializeErrors","entries","serialized","val","__type","ErrorResponseImpl","status","statusText","data","internal","__subType","ErrorConstructor","error","message","stack","ViewTransitionContext","React","createContext","isTransitioning","displayName","FetchersContext","Map","START_TRANSITION","startTransitionImpl","FLUSH_SYNC","flushSyncImpl","ReactDOM","USE_ID","useIdImpl","startTransitionSafe","cb","flushSyncSafe","Deferred","constructor","promise","Promise","resolve","reject","reason","RouterProvider","_ref","fallbackElement","router","setStateImpl","useState","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","useRef","v7_startTransition","optInStartTransition","useCallback","setState","newState","_ref2","deletedFetchers","flushSync","viewTransitionOpts","fetchers","fetcher","current","set","delete","isViewTransitionUnavailable","startViewTransition","skipTransition","currentLocation","nextLocation","t","finished","finally","useLayoutEffect","subscribe","useEffect","renderPromise","location","v7_partialHydration","navigator","useMemo","createHref","encodeLocation","go","n","navigate","push","to","preventScrollReset","replace","dataRouterContext","static","routerFuture","v7_relativeSplatPath","logV6DeprecationWarnings","Fragment","DataRouterContext","Provider","DataRouterStateContext","Router","navigationType","historyAction","initialized","MemoizedDataRoutes","DataRoutes","_ref3","useRoutesImpl","BrowserRouter","_ref4","children","historyRef","v5Compat","listen","HashRouter","_ref5","HistoryRouter","_ref6","isBrowser","ABSOLUTE_URL_REGEX","Link","forwardRef","LinkWithRef","_ref7","ref","onClick","relative","reloadDocument","viewTransition","rest","_objectWithoutPropertiesLoose","_excluded","useContext","NavigationContext","absoluteHref","isExternal","test","currentUrl","URL","href","targetUrl","startsWith","protocol","path","pathname","origin","search","hash","useHref","internalOnClick","useLinkClickHandler","handleClick","defaultPrevented","NavLink","NavLinkWithRef","_ref8","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","_excluded2","useResolvedPath","useLocation","routerState","useViewTransitionState","toPathname","locationPathname","nextLocationPathname","navigation","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","filter","Boolean","join","Form","_ref9","forwardedRef","fetcherKey","onSubmit","props","_excluded3","submit","useSubmit","formAction","useFormAction","formMethod","submitHandler","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","_ref0","getKey","storageKey","useScrollRestoration","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","invariant","useDataRouterState","_temp","replaceProp","useNavigate","createPath","useSearchParams","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","setSearchParams","nextInit","navigateOptions","newSearchParams","validateClientSideSubmission","fetcherId","getUniqueFetcherId","String","UseSubmit","currentRouteId","useRouteId","options","fetch","formEncType","fromRouteId","_temp2","routeContext","RouteContext","match","matches","slice","params","indexValues","hasNakedIndexParam","some","qs","toString","route","index","joinPaths","useFetcher","_temp3","_route$matches","UseFetcher","routeId","id","defaultKey","setFetcherKey","getFetcher","deleteFetcher","load","submitImpl","FetcherForm","get","IDLE_FETCHER","fetcherWithComponents","useFetchers","UseFetchers","from","_ref1","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","_temp4","UseScrollRestoration","restoreScrollPosition","useMatches","useNavigation","scrollRestoration","usePageHide","scrollY","sessionStorage","setItem","JSON","stringify","sessionPositions","getItem","parse","getKeyWithoutBasename","disableScrollRestoration","enableScrollRestoration","scrollTo","el","getElementById","decodeURIComponent","scrollIntoView","useBeforeUnload","callback","capture","addEventListener","removeEventListener","usePrompt","_ref10","when","blocker","useBlocker","proceed","confirm","setTimeout","reset","currentPath","nextPath","matchPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAOO,MAAMA,aAA6B,GAAG,KAAK,CAAA;EAClD,MAAMC,cAA2B,GAAG,mCAAmC,CAAA;EAEhE,SAASC,aAAaA,CAACC,MAAW,EAAyB;IAChE,OAAOA,MAAM,IAAI,IAAI,IAAI,OAAOA,MAAM,CAACC,OAAO,KAAK,QAAQ,CAAA;EAC7D,CAAA;EAEO,SAASC,eAAeA,CAACF,MAAW,EAA+B;EACxE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,QAAQ,CAAA;EAC3E,CAAA;EAEO,SAASC,aAAaA,CAACJ,MAAW,EAA6B;EACpE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,MAAM,CAAA;EACzE,CAAA;EAEO,SAASE,cAAcA,CAACL,MAAW,EAA8B;EACtE,EAAA,OAAOD,aAAa,CAACC,MAAM,CAAC,IAAIA,MAAM,CAACC,OAAO,CAACE,WAAW,EAAE,KAAK,OAAO,CAAA;EAC1E,CAAA;EAOA,SAASG,eAAeA,CAACC,KAAwB,EAAE;EACjD,EAAA,OAAO,CAAC,EAAEA,KAAK,CAACC,OAAO,IAAID,KAAK,CAACE,MA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,CAAC4B,YAAY,CAAC0E,QAAQ,CAAA;;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACA,OACEyK,gBAAS,CAAC1K,IAAI,CAACC,QAAQ,EAAEwK,QAAQ,CAAC,IAAI,IAAI,IAC1CC,gBAAS,CAAC1K,IAAI,CAACC,QAAQ,EAAEuK,WAAW,CAAC,IAAI,IAAI,CAAA;EAEjD,CAAA;;EAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}/**
 * React Router DOM v6.30.6
 *
 * 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
 */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("react-router"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","react-router","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.React,e.ReactDOM,e.ReactRouter,e.RemixRouter)}(this,function(e,t,n,r,o){"use strict";function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var i=a(t),u=a(n);function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s.apply(null,arguments)}function c(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}const l="get",f="application/x-www-form-urlencoded";function d(e){return null!=e&&"string"==typeof e.tagName}function m(e){return void 0===e&&(e=""),new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}let p=null;const v=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function h(e){return null==e||v.has(e)?e:null}function g(e,t){let n,r,a,i,u;if(d(s=e)&&"form"===s.tagName.toLowerCase()){let u=e.getAttribute("action");r=u?o.stripBasename(u,t):null,n=e.getAttribute("method")||l,a=h(e.getAttribute("enctype"))||f,i=new FormData(e)}else if(function(e){return d(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return d(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let u=e.form;if(null==u)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||u.getAttribute("action");if(r=s?o.stripBasename(s,t):null,n=e.getAttribute("formmethod")||u.getAttribute("method")||l,a=h(e.getAttribute("formenctype"))||h(u.getAttribute("enctype"))||f,i=new FormData(u,e),!function(){if(null===p)try{new FormData(document.createElement("form"),0),p=!1}catch(e){p=!0}return p}()){let{name:t,type:n,value:r}=e;if("image"===n){let e=t?t+".":"";i.append(e+"x","0"),i.append(e+"y","0")}else t&&i.append(t,r)}}else{if(d(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=l,r=null,a=f,u=e}var s;return i&&"text/plain"===a&&(u=i,i=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:i,body:u}}const b=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],y=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],w=["fetcherKey","navigate","reloadDocument","replace","state","method","action","onSubmit","relative","preventScrollReset","viewTransition"];try{window.__reactRouterVersion="6"}catch(e){}function R(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=s({},t,{errors:S(t.errors)})),t}function S(e){if(!e)return null;let t=Object.entries(e),n={};for(let[e,r]of t)if(r&&"RouteErrorResponse"===r.__type)n[e]=new o.UNSAFE_ErrorResponseImpl(r.status,r.statusText,r.data,!0===r.internal);else if(r&&"Error"===r.__type){if(r.__subType){let t=window[r.__subType];if("function"==typeof t)try{let o=new t(r.message);o.stack="",n[e]=o}catch(e){}}if(null==n[e]){let t=new Error(r.message);t.stack="",n[e]=t}}else n[e]=r;return n}const E=i.createContext({isTransitioning:!1}),P=i.createContext(new Map),O=i.startTransition,N=u.flushSync,_=i.useId;function A(e){N?N(e):e()}class F{constructor(){this.status="pending",this.promise=new Promise((e,t)=>{this.resolve=t=>{"pending"===this.status&&(this.status="resolved",e(t))},this.reject=e=>{"pending"===this.status&&(this.status="rejected",t(e))}})}}const C=i.memo(x);function x(e){let{routes:t,future:n,state:o}=e;return r.UNSAFE_useRoutesImpl(t,void 0,o,n)}const j="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,U=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,L=i.forwardRef(function(e,t){let n,{onClick:a,relative:u,reloadDocument:l,replace:f,state:d,target:m,to:p,preventScrollReset:v,viewTransition:h}=e,g=c(e,b),{basename:y}=i.useContext(r.UNSAFE_NavigationContext),w=!1;if("string"==typeof p&&U.test(p)&&(n=p,j))try{let e=new URL(window.location.href),t=p.startsWith("//")?new URL(e.protocol+p):new URL(p),n=o.stripBasename(t.pathname,y);t.origin===e.origin&&null!=n?p=n+t.search+t.hash:w=!0}catch(e){}let R=r.useHref(p,{relative:u}),S=I(p,{replace:f,state:d,target:m,preventScrollReset:v,relative:u,viewTransition:h});return i.createElement("a",s({},g,{href:n||R,onClick:w||l?a:function(e){a&&a(e),e.defaultPrevented||S(e)},ref:t,target:m}))}),T=i.forwardRef(function(e,t){let{"aria-current":n="page",caseSensitive:a=!1,className:u="",end:l=!1,style:f,to:d,viewTransition:m,children:p}=e,v=c(e,y),h=r.useResolvedPath(d,{relative:v.relative}),g=r.useLocation(),b=i.useContext(r.UNSAFE_DataRouterStateContext),{navigator:w,basename:R}=i.useContext(r.UNSAFE_NavigationContext),S=null!=b&&G(h)&&!0===m,E=w.encodeLocation?w.encodeLocation(h).pathname:h.pathname,P=g.pathname,O=b&&b.navigation&&b.navigation.location?b.navigation.location.pathname:null;a||(P=P.toLowerCase(),O=O?O.toLowerCase():null,E=E.toLowerCase()),O&&R&&(O=o.stripBasename(O,R)||O);const N="/"!==E&&E.endsWith("/")?E.length-1:E.length;let _,A=P===E||!l&&P.startsWith(E)&&"/"===P.charAt(N),F=null!=O&&(O===E||!l&&O.startsWith(E)&&"/"===O.charAt(E.length)),C={isActive:A,isPending:F,isTransitioning:S},x=A?n:void 0;_="function"==typeof u?u(C):[u,A?"active":null,F?"pending":null,S?"transitioning":null].filter(Boolean).join(" ");let j="function"==typeof f?f(C):f;return i.createElement(L,s({},v,{"aria-current":x,className:_,ref:t,style:j,to:d,viewTransition:m}),"function"==typeof p?p(C):p)}),D=i.forwardRef((e,t)=>{let{fetcherKey:n,navigate:r,reloadDocument:o,replace:a,state:u,method:f=l,action:d,onSubmit:m,relative:p,preventScrollReset:v,viewTransition:h}=e,g=c(e,w),b=W(),y=z(d,{relative:p}),R="get"===f.toLowerCase()?"get":"post";return i.createElement("form",s({ref:t,method:R,action:y,onSubmit:o?m:e=>{if(m&&m(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,o=(null==t?void 0:t.getAttribute("formmethod"))||f;b(t||e.currentTarget,{fetcherKey:n,method:o,navigate:r,replace:a,state:u,relative:p,preventScrollReset:v,viewTransition:h})}},g))});var k=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(k||{}),M=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(M||{});function B(e){let t=i.useContext(r.UNSAFE_DataRouterContext);return t||o.UNSAFE_invariant(!1),t}function H(e){let t=i.useContext(r.UNSAFE_DataRouterStateContext);return t||o.UNSAFE_invariant(!1),t}function I(e,t){let{target:n,replace:o,state:a,preventScrollReset:u,relative:s,viewTransition:c}=void 0===t?{}:t,l=r.useNavigate(),f=r.useLocation(),d=r.useResolvedPath(e,{relative:s});return i.useCallback(t=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(t,n)){t.preventDefault();let n=void 0!==o?o:r.createPath(f)===r.createPath(d);l(e,{replace:n,state:a,preventScrollReset:u,relative:s,viewTransition:c})}},[f,l,d,o,a,n,e,u,s,c])}let K=0,V=()=>"__"+String(++K)+"__";function W(){let{router:e}=B(k.UseSubmit),{basename:t}=i.useContext(r.UNSAFE_NavigationContext),n=r.UNSAFE_useRouteId();return i.useCallback(function(r,o){void 0===o&&(o={}),function(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}();let{action:a,method:i,encType:u,formData:s,body:c}=g(r,t);if(!1===o.navigate){let t=o.fetcherKey||V();e.fetch(t,n,o.action||a,{preventScrollReset:o.preventScrollReset,formData:s,body:c,formMethod:o.method||i,formEncType:o.encType||u,flushSync:o.flushSync})}else e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:s,body:c,formMethod:o.method||i,formEncType:o.encType||u,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[e,t,n])}function z(e,t){let{relative:n}=void 0===t?{}:t,{basename:a}=i.useContext(r.UNSAFE_NavigationContext),u=i.useContext(r.UNSAFE_RouteContext);u||o.UNSAFE_invariant(!1);let[c]=u.matches.slice(-1),l=s({},r.useResolvedPath(e||".",{relative:n})),f=r.useLocation();if(null==e){l.search=f.search;let e=new URLSearchParams(l.search),t=e.getAll("index");if(t.some(e=>""===e)){e.delete("index"),t.filter(e=>e).forEach(t=>e.append("index",t));let n=e.toString();l.search=n?"?"+n:""}}return e&&"."!==e||!c.route.index||(l.search=l.search?l.search.replace(/^\?/,"?index&"):"?index"),"/"!==a&&(l.pathname="/"===l.pathname?a:o.joinPaths([a,l.pathname])),r.createPath(l)}const q="react-router-scroll-positions";let Y={};function J(e){let{getKey:t,storageKey:n}=void 0===e?{}:e,{router:a}=B(k.UseScrollRestoration),{restoreScrollPosition:u,preventScrollReset:c}=H(M.UseScrollRestoration),{basename:l}=i.useContext(r.UNSAFE_NavigationContext),f=r.useLocation(),d=r.useMatches(),m=r.useNavigation();i.useEffect(()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"}),[]),function(e,t){let{capture:n}=t||{};i.useEffect(()=>{let t=null!=n?{capture:n}:void 0;return window.addEventListener("pagehide",e,t),()=>{window.removeEventListener("pagehide",e,t)}},[e,n])}(i.useCallback(()=>{if("idle"===m.state){let e=(t?t(f,d):null)||f.key;Y[e]=window.scrollY}try{sessionStorage.setItem(n||q,JSON.stringify(Y))}catch(e){}window.history.scrollRestoration="auto"},[n,t,m.state,f,d])),"undefined"!=typeof document&&(i.useLayoutEffect(()=>{try{let e=sessionStorage.getItem(n||q);e&&(Y=JSON.parse(e))}catch(e){}},[n]),i.useLayoutEffect(()=>{let e=t&&"/"!==l?(e,n)=>t(s({},e,{pathname:o.stripBasename(e.pathname,l)||e.pathname}),n):t,n=null==a?void 0:a.enableScrollRestoration(Y,()=>window.scrollY,e);return()=>n&&n()},[a,l,t]),i.useLayoutEffect(()=>{if(!1!==u)if("number"!=typeof u){if(f.hash){let e=document.getElementById(decodeURIComponent(f.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==c&&window.scrollTo(0,0)}else window.scrollTo(0,u)},[f,u,c]))}function G(e,t){void 0===t&&(t={});let n=i.useContext(E);null==n&&o.UNSAFE_invariant(!1);let{basename:a}=B(k.useViewTransitionState),u=r.useResolvedPath(e,{relative:t.relative});if(!n.isTransitioning)return!1;let s=o.stripBasename(n.currentLocation.pathname,a)||n.currentLocation.pathname,c=o.stripBasename(n.nextLocation.pathname,a)||n.nextLocation.pathname;return null!=o.matchPath(u.pathname,c)||null!=o.matchPath(u.pathname,s)}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"Await",{enumerable:!0,get:function(){return r.Await}}),Object.defineProperty(e,"MemoryRouter",{enumerable:!0,get:function(){return r.MemoryRouter}}),Object.defineProperty(e,"Navigate",{enumerable:!0,get:function(){return r.Navigate}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.NavigationType}}),Object.defineProperty(e,"Outlet",{enumerable:!0,get:function(){return r.Outlet}}),Object.defineProperty(e,"Route",{enumerable:!0,get:function(){return r.Route}}),Object.defineProperty(e,"Router",{enumerable:!0,get:function(){return r.Router}}),Object.defineProperty(e,"Routes",{enumerable:!0,get:function(){return r.Routes}}),Object.defineProperty(e,"UNSAFE_DataRouterContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterContext}}),Object.defineProperty(e,"UNSAFE_DataRouterStateContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterStateContext}}),Object.defineProperty(e,"UNSAFE_LocationContext",{enumerable:!0,get:function(){return r.UNSAFE_LocationContext}}),Object.defineProperty(e,"UNSAFE_NavigationContext",{enumerable:!0,get:function(){return r.UNSAFE_NavigationContext}}),Object.defineProperty(e,"UNSAFE_RouteContext",{enumerable:!0,get:function(){return r.UNSAFE_RouteContext}}),Object.defineProperty(e,"UNSAFE_useRouteId",{enumerable:!0,get:function(){return r.UNSAFE_useRouteId}}),Object.defineProperty(e,"createMemoryRouter",{enumerable:!0,get:function(){return r.createMemoryRouter}}),Object.defineProperty(e,"createPath",{enumerable:!0,get:function(){return r.createPath}}),Object.defineProperty(e,"createRoutesFromChildren",{enumerable:!0,get:function(){return r.createRoutesFromChildren}}),Object.defineProperty(e,"createRoutesFromElements",{enumerable:!0,get:function(){return r.createRoutesFromElements}}),Object.defineProperty(e,"defer",{enumerable:!0,get:function(){return r.defer}}),Object.defineProperty(e,"generatePath",{enumerable:!0,get:function(){return r.generatePath}}),Object.defineProperty(e,"isRouteErrorResponse",{enumerable:!0,get:function(){return r.isRouteErrorResponse}}),Object.defineProperty(e,"json",{enumerable:!0,get:function(){return r.json}}),Object.defineProperty(e,"matchPath",{enumerable:!0,get:function(){return r.matchPath}}),Object.defineProperty(e,"matchRoutes",{enumerable:!0,get:function(){return r.matchRoutes}}),Object.defineProperty(e,"parsePath",{enumerable:!0,get:function(){return r.parsePath}}),Object.defineProperty(e,"redirect",{enumerable:!0,get:function(){return r.redirect}}),Object.defineProperty(e,"redirectDocument",{enumerable:!0,get:function(){return r.redirectDocument}}),Object.defineProperty(e,"renderMatches",{enumerable:!0,get:function(){return r.renderMatches}}),Object.defineProperty(e,"replace",{enumerable:!0,get:function(){return r.replace}}),Object.defineProperty(e,"resolvePath",{enumerable:!0,get:function(){return r.resolvePath}}),Object.defineProperty(e,"useActionData",{enumerable:!0,get:function(){return r.useActionData}}),Object.defineProperty(e,"useAsyncError",{enumerable:!0,get:function(){return r.useAsyncError}}),Object.defineProperty(e,"useAsyncValue",{enumerable:!0,get:function(){return r.useAsyncValue}}),Object.defineProperty(e,"useBlocker",{enumerable:!0,get:function(){return r.useBlocker}}),Object.defineProperty(e,"useHref",{enumerable:!0,get:function(){return r.useHref}}),Object.defineProperty(e,"useInRouterContext",{enumerable:!0,get:function(){return r.useInRouterContext}}),Object.defineProperty(e,"useLoaderData",{enumerable:!0,get:function(){return r.useLoaderData}}),Object.defineProperty(e,"useLocation",{enumerable:!0,get:function(){return r.useLocation}}),Object.defineProperty(e,"useMatch",{enumerable:!0,get:function(){return r.useMatch}}),Object.defineProperty(e,"useMatches",{enumerable:!0,get:function(){return r.useMatches}}),Object.defineProperty(e,"useNavigate",{enumerable:!0,get:function(){return r.useNavigate}}),Object.defineProperty(e,"useNavigation",{enumerable:!0,get:function(){return r.useNavigation}}),Object.defineProperty(e,"useNavigationType",{enumerable:!0,get:function(){return r.useNavigationType}}),Object.defineProperty(e,"useOutlet",{enumerable:!0,get:function(){return r.useOutlet}}),Object.defineProperty(e,"useOutletContext",{enumerable:!0,get:function(){return r.useOutletContext}}),Object.defineProperty(e,"useParams",{enumerable:!0,get:function(){return r.useParams}}),Object.defineProperty(e,"useResolvedPath",{enumerable:!0,get:function(){return r.useResolvedPath}}),Object.defineProperty(e,"useRevalidator",{enumerable:!0,get:function(){return r.useRevalidator}}),Object.defineProperty(e,"useRouteError",{enumerable:!0,get:function(){return r.useRouteError}}),Object.defineProperty(e,"useRouteLoaderData",{enumerable:!0,get:function(){return r.useRouteLoaderData}}),Object.defineProperty(e,"useRoutes",{enumerable:!0,get:function(){return r.useRoutes}}),Object.defineProperty(e,"UNSAFE_ErrorResponseImpl",{enumerable:!0,get:function(){return o.UNSAFE_ErrorResponseImpl}}),e.BrowserRouter=function(e){let{basename:t,children:n,future:a,window:u}=e,s=i.useRef();null==s.current&&(s.current=o.createBrowserHistory({window:u,v5Compat:!0}));let c=s.current,[l,f]=i.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=i.useCallback(e=>{d&&O?O(()=>f(e)):f(e)},[f,d]);return i.useLayoutEffect(()=>c.listen(m),[c,m]),i.useEffect(()=>r.UNSAFE_logV6DeprecationWarnings(a),[a]),i.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.Form=D,e.HashRouter=function(e){let{basename:t,children:n,future:a,window:u}=e,s=i.useRef();null==s.current&&(s.current=o.createHashHistory({window:u,v5Compat:!0}));let c=s.current,[l,f]=i.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=i.useCallback(e=>{d&&O?O(()=>f(e)):f(e)},[f,d]);return i.useLayoutEffect(()=>c.listen(m),[c,m]),i.useEffect(()=>r.UNSAFE_logV6DeprecationWarnings(a),[a]),i.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.Link=L,e.NavLink=T,e.RouterProvider=function(e){let{fallbackElement:t,router:n,future:o}=e,[a,u]=i.useState(n.state),[s,c]=i.useState(),[l,f]=i.useState({isTransitioning:!1}),[d,m]=i.useState(),[p,v]=i.useState(),[h,g]=i.useState(),b=i.useRef(new Map),{v7_startTransition:y}=o||{},w=i.useCallback(e=>{y?function(e){O?O(e):e()}(e):e()},[y]),R=i.useCallback((e,t)=>{let{deletedFetchers:r,flushSync:o,viewTransitionOpts:a}=t;e.fetchers.forEach((e,t)=>{void 0!==e.data&&b.current.set(t,e.data)}),r.forEach(e=>b.current.delete(e));let i=null==n.window||null==n.window.document||"function"!=typeof n.window.document.startViewTransition;if(a&&!i){if(o){A(()=>{p&&(d&&d.resolve(),p.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:a.currentLocation,nextLocation:a.nextLocation})});let t=n.window.document.startViewTransition(()=>{A(()=>u(e))});return t.finished.finally(()=>{A(()=>{m(void 0),v(void 0),c(void 0),f({isTransitioning:!1})})}),void A(()=>v(t))}p?(d&&d.resolve(),p.skipTransition(),g({state:e,currentLocation:a.currentLocation,nextLocation:a.nextLocation})):(c(e),f({isTransitioning:!0,flushSync:!1,currentLocation:a.currentLocation,nextLocation:a.nextLocation}))}else o?A(()=>u(e)):w(()=>u(e))},[n.window,p,d,b,w]);i.useLayoutEffect(()=>n.subscribe(R),[n,R]),i.useEffect(()=>{l.isTransitioning&&!l.flushSync&&m(new F)},[l]),i.useEffect(()=>{if(d&&s&&n.window){let e=s,t=d.promise,r=n.window.document.startViewTransition(async()=>{w(()=>u(e)),await t});r.finished.finally(()=>{m(void 0),v(void 0),c(void 0),f({isTransitioning:!1})}),v(r)}},[w,s,d,n.window]),i.useEffect(()=>{d&&s&&a.location.key===s.location.key&&d.resolve()},[d,p,a.location,s]),i.useEffect(()=>{!l.isTransitioning&&h&&(c(h.state),f({isTransitioning:!0,flushSync:!1,currentLocation:h.currentLocation,nextLocation:h.nextLocation}),g(void 0))},[l.isTransitioning,h]),i.useEffect(()=>{},[]);let S=i.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:e=>n.navigate(e),push:(e,t,r)=>n.navigate(e,{state:t,preventScrollReset:null==r?void 0:r.preventScrollReset}),replace:(e,t,r)=>n.navigate(e,{replace:!0,state:t,preventScrollReset:null==r?void 0:r.preventScrollReset})}),[n]),N=n.basename||"/",_=i.useMemo(()=>({router:n,navigator:S,static:!1,basename:N}),[n,S,N]),x=i.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return i.useEffect(()=>r.UNSAFE_logV6DeprecationWarnings(o,n.future),[o,n.future]),i.createElement(i.Fragment,null,i.createElement(r.UNSAFE_DataRouterContext.Provider,{value:_},i.createElement(r.UNSAFE_DataRouterStateContext.Provider,{value:a},i.createElement(P.Provider,{value:b.current},i.createElement(E.Provider,{value:l},i.createElement(r.Router,{basename:N,location:a.location,navigationType:a.historyAction,navigator:S,future:x},a.initialized||n.future.v7_partialHydration?i.createElement(C,{routes:n.routes,future:n.future,state:a}):t))))),null)},e.ScrollRestoration=function(e){let{getKey:t,storageKey:n}=e;return J({getKey:t,storageKey:n}),null},e.UNSAFE_FetchersContext=P,e.UNSAFE_ViewTransitionContext=E,e.UNSAFE_useScrollRestoration=J,e.createBrowserRouter=function(e,t){return o.createRouter({basename:null==t?void 0:t.basename,future:s({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:o.createBrowserHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||R(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties,dataStrategy:null==t?void 0:t.dataStrategy,patchRoutesOnNavigation:null==t?void 0:t.patchRoutesOnNavigation,window:null==t?void 0:t.window}).initialize()},e.createHashRouter=function(e,t){return o.createRouter({basename:null==t?void 0:t.basename,future:s({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:o.createHashHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||R(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties,dataStrategy:null==t?void 0:t.dataStrategy,patchRoutesOnNavigation:null==t?void 0:t.patchRoutesOnNavigation,window:null==t?void 0:t.window}).initialize()},e.createSearchParams=m,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,future:o,history:a}=e,[u,s]=i.useState({action:a.action,location:a.location}),{v7_startTransition:c}=o||{},l=i.useCallback(e=>{c&&O?O(()=>s(e)):s(e)},[s,c]);return i.useLayoutEffect(()=>a.listen(l),[a,l]),i.useEffect(()=>r.UNSAFE_logV6DeprecationWarnings(o),[o]),i.createElement(r.Router,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:a,future:o})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.useBlocker(t);i.useEffect(()=>{if("blocked"===o.state){window.confirm(n)?setTimeout(o.proceed,0):o.reset()}},[o,n]),i.useEffect(()=>{"blocked"!==o.state||t||o.reset()},[o,t])},e.useBeforeUnload=function(e,t){let{capture:n}=t||{};i.useEffect(()=>{let t=null!=n?{capture:n}:void 0;return window.addEventListener("beforeunload",e,t),()=>{window.removeEventListener("beforeunload",e,t)}},[e,n])},e.useFetcher=function(e){var t;let{key:n}=void 0===e?{}:e,{router:a}=B(k.UseFetcher),u=H(M.UseFetcher),c=i.useContext(P),l=i.useContext(r.UNSAFE_RouteContext),f=null==(t=l.matches[l.matches.length-1])?void 0:t.route.id;c||o.UNSAFE_invariant(!1),l||o.UNSAFE_invariant(!1),null==f&&o.UNSAFE_invariant(!1);let d=_?_():"",[m,p]=i.useState(n||d);n&&n!==m?p(n):m||p(V()),i.useEffect(()=>(a.getFetcher(m),()=>{a.deleteFetcher(m)}),[a,m]);let v=i.useCallback((e,t)=>{f||o.UNSAFE_invariant(!1),a.fetch(m,f,e,t)},[m,f,a]),h=W(),g=i.useCallback((e,t)=>{h(e,s({},t,{navigate:!1,fetcherKey:m}))},[m,h]),b=i.useMemo(()=>i.forwardRef((e,t)=>i.createElement(D,s({},e,{navigate:!1,fetcherKey:m,ref:t}))),[m]),y=u.fetchers.get(m)||o.IDLE_FETCHER,w=c.get(m);return i.useMemo(()=>s({Form:b,submit:g,load:v},y,{data:w}),[b,g,v,y,w])},e.useFetchers=function(){let e=H(M.UseFetchers);return Array.from(e.fetchers.entries()).map(e=>{let[t,n]=e;return s({},n,{key:t})})},e.useFormAction=z,e.useLinkClickHandler=I,e.useSearchParams=function(e){let t=i.useRef(m(e)),n=i.useRef(!1),o=r.useLocation(),a=i.useMemo(()=>function(e,t){let n=m(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}(o.search,n.current?null:t.current),[o.search]),u=r.useNavigate(),s=i.useCallback((e,t)=>{const r=m("function"==typeof e?e(a):e);n.current=!0,u("?"+r,t)},[u,a]);return[a,s]},e.useSubmit=W,e.useViewTransitionState=G,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=react-router-dom.production.min.js.map
{"version":3,"file":"react-router-dom.production.min.js","sources":["../../dom.ts","../../index.tsx"],"sourcesContent":["import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],"names":["defaultMethod","defaultEncType","isHtmlElement","object","tagName","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","_formDataSupportsSubmitter","supportedFormEncTypes","Set","getFormEncType","encType","has","getFormSubmissionInfo","target","basename","method","action","formData","body","toLowerCase","attr","getAttribute","stripBasename","FormData","isButtonElement","isInputElement","type","form","Error","document","createElement","e","isFormDataSubmitterSupported","name","prefix","append","undefined","window","__reactRouterVersion","parseHydrationData","_window","state","__staticRouterHydrationData","errors","_extends","deserializeErrors","entries","serialized","val","__type","ErrorResponseImpl","status","statusText","data","internal","__subType","ErrorConstructor","error","message","stack","ViewTransitionContext","React","createContext","isTransitioning","FetchersContext","Map","startTransitionImpl","flushSyncImpl","ReactDOM","useIdImpl","flushSyncSafe","cb","Deferred","constructor","this","promise","Promise","resolve","reject","reason","MemoizedDataRoutes","DataRoutes","_ref3","routes","future","useRoutesImpl","UNSAFE_useRoutesImpl","isBrowser","ABSOLUTE_URL_REGEX","Link","forwardRef","_ref7","ref","absoluteHref","onClick","relative","reloadDocument","replace","to","preventScrollReset","viewTransition","rest","_objectWithoutPropertiesLoose","_excluded","useContext","NavigationContext","isExternal","test","currentUrl","URL","location","href","targetUrl","startsWith","protocol","path","pathname","origin","search","hash","useHref","internalOnClick","useLinkClickHandler","event","defaultPrevented","NavLink","_ref8","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","children","_excluded2","useResolvedPath","useLocation","routerState","DataRouterStateContext","UNSAFE_DataRouterStateContext","navigator","useViewTransitionState","toPathname","encodeLocation","locationPathname","nextLocationPathname","navigation","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","filter","Boolean","join","Form","_ref9","forwardedRef","fetcherKey","navigate","onSubmit","props","_excluded3","submit","useSubmit","formAction","useFormAction","formMethod","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","DataRouterHook","DataRouterStateHook","useDataRouterContext","hookName","ctx","DataRouterContext","UNSAFE_DataRouterContext","invariant","UNSAFE_invariant","useDataRouterState","_temp","replaceProp","useNavigate","useCallback","button","metaKey","altKey","ctrlKey","shiftKey","isModifiedEvent","shouldProcessLinkClick","createPath","fetcherId","getUniqueFetcherId","String","router","UseSubmit","currentRouteId","useRouteId","options","validateClientSideSubmission","fetch","formEncType","flushSync","fromRouteId","_temp2","routeContext","RouteContext","UNSAFE_RouteContext","match","matches","slice","params","indexValues","getAll","some","delete","forEach","qs","toString","route","index","joinPaths","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","useScrollRestoration","_temp4","getKey","storageKey","UseScrollRestoration","restoreScrollPosition","useMatches","useNavigation","useEffect","history","scrollRestoration","callback","capture","opts","addEventListener","removeEventListener","usePageHide","scrollY","sessionStorage","setItem","JSON","stringify","useLayoutEffect","sessionPositions","getItem","parse","getKeyWithoutBasename","disableScrollRestoration","enableScrollRestoration","el","getElementById","decodeURIComponent","scrollIntoView","scrollTo","vtContext","currentPath","currentLocation","nextPath","nextLocation","matchPath","_ref4","historyRef","useRef","current","createBrowserHistory","v5Compat","setStateImpl","useState","v7_startTransition","setState","newState","listen","logV6DeprecationWarnings","UNSAFE_logV6DeprecationWarnings","Router","navigationType","_ref5","createHashHistory","_ref","fallbackElement","pendingState","setPendingState","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","optInStartTransition","startTransitionSafe","_ref2","deletedFetchers","viewTransitionOpts","fetchers","fetcher","set","isViewTransitionUnavailable","startViewTransition","skipTransition","t","finished","finally","subscribe","renderPromise","async","useMemo","createHref","go","n","push","dataRouterContext","static","routerFuture","v7_relativeSplatPath","Fragment","Provider","historyAction","initialized","v7_partialHydration","_ref0","createRouter","v7_prependBasename","hydrationData","mapRouteProperties","UNSAFE_mapRouteProperties","dataStrategy","patchRoutesOnNavigation","initialize","_ref6","_ref10","when","blocker","useBlocker","confirm","setTimeout","proceed","reset","_temp3","_route$matches","UseFetcher","routeId","id","defaultKey","setFetcherKey","getFetcher","deleteFetcher","load","submitImpl","FetcherForm","get","IDLE_FETCHER","UseFetchers","from","_ref1","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","searchParams","locationSearch","defaultSearchParams","_","getSearchParamsForLocation","setSearchParams","nextInit","navigateOptions","newSearchParams"],"mappings":";;;;;;;;;;klCAOO,MAAMA,EAAgC,MACvCC,EAA8B,oCAE7B,SAASC,EAAcC,GAC5B,OAAiB,MAAVA,GAA4C,iBAAnBA,EAAOC,OACzC,CA+DO,SAASC,EACdC,GAEA,YAFyB,IAAzBA,IAAAA,EAA4B,IAErB,IAAIC,gBACO,i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QiJ,EAAmBR,EAAoB2L,aACnD,OAAOlX,MAAMmX,KAAKrU,EAAM0Q,SAASrQ,WAAW1C,IAAI2W,IAAA,IAAE9W,EAAKmT,GAAQ2D,EAAA,OAAAnU,KAC1DwQ,EAAO,CACVnT,SAEJ,8DAzTO,SACL+W,GAUA,IAAIC,EAAyBpT,EAAMqN,OAAO1R,EAAmBwX,IACzDE,EAAwBrT,EAAMqN,QAAO,GAErCpK,EAAW2B,EAAAA,cACX0O,EAAetT,EAAMkQ,QACvB,ID33CG,SACLqD,EACAC,GAEA,IAAIF,EAAe3X,EAAmB4X,GAiBtC,OAfIC,GAMFA,EAAoBrJ,QAAQ,CAACsJ,EAAGrX,KACzBkX,EAAaxW,IAAIV,IACpBoX,EAAoBxJ,OAAO5N,GAAK+N,QAAS9N,IACvCiX,EAAahV,OAAOlC,EAAKC,OAM1BiX,CACT,CCy2CMI,CACEzQ,EAASQ,OACT4P,EAAsB/F,QAAU,KAAO8F,EAAuB9F,SAElE,CAACrK,EAASQ,SAGR6C,EAAW0B,EAAAA,cACX2L,EAAkB3T,EAAMiI,YAC1B,CAAC2L,EAAUC,KACT,MAAMC,EAAkBnY,EACF,mBAAbiY,EAA0BA,EAASN,GAAgBM,GAE5DP,EAAsB/F,SAAU,EAChChH,EAAS,IAAMwN,EAAiBD,IAElC,CAACvN,EAAUgN,IAGb,MAAO,CAACA,EAAcK,EACxB"}'use strict';

var Module = require('module');
var path = require('path');

module.exports = function requireFromString(code, filename, opts) {
	if (typeof filename === 'object') {
		opts = filename;
		filename = undefined;
	}

	opts = opts || {};
	filename = filename || '';

	opts.appendPaths = opts.appendPaths || [];
	opts.prependPaths = opts.prependPaths || [];

	if (typeof code !== 'string') {
		throw new Error('code must be a string, not ' + typeof code);
	}

	var paths = Module._nodeModulePaths(path.dirname(filename));

	var parent = module.parent;
	var m = new Module(filename, parent);
	m.filename = filename;
	m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths);
	m._compile(code, filename);

	var exports = m.exports;
	parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1);

	return exports;
};
The MIT License (MIT)

Copyright (c) Vsevolod Strukchinsky <floatdrop@gmail.com> (github.com/floatdrop)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
{
  "name": "require-from-string",
  "version": "2.0.2",
  "description": "Require module from string",
  "license": "MIT",
  "repository": "floatdrop/require-from-string",
  "author": {
    "name": "Vsevolod Strukchinsky",
    "email": "floatdrop@gmail.com",
    "url": "github.com/floatdrop"
  },
  "engines": {
    "node": ">=0.10.0"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "mocha": "*"
  }
}MIT License

Copyright (c) Facebook, Inc. and its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/scheduler.production.min.js');
} else {
  module.exports = require('./cjs/scheduler.development.js');
}
{
  "name": "scheduler",
  "version": "0.23.2",
  "description": "Cooperative scheduler for the browser environment.",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/facebook/react.git",
    "directory": "packages/scheduler"
  },
  "license": "MIT",
  "homepage": "https://reactjs.org/",
  "dependencies": {
    "loose-envify": "^1.1.0"
  },
  "files": [
    "LICENSE",
    "README.md",
    "index.js",
    "unstable_mock.js",
    "unstable_post_task.js",
    "cjs/",
    "umd/"
  ],
  "browserify": {
    "transform": [
      "loose-envify"
    ]
  }
}'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/scheduler-unstable_mock.production.min.js');
} else {
  module.exports = require('./cjs/scheduler-unstable_mock.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/scheduler-unstable_post_task.production.min.js');
} else {
  module.exports = require('./cjs/scheduler-unstable_post_task.development.js');
}
/**
 * @license React
 * scheduler-unstable_mock.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = global || self, factory(global.SchedulerMock = {}));
}(this, (function (exports) { 'use strict';

  var enableSchedulerDebugging = false;
  var enableProfiling = false;

  function push(heap, node) {
    var index = heap.length;
    heap.push(node);
    siftUp(heap, node, index);
  }
  function peek(heap) {
    return heap.length === 0 ? null : heap[0];
  }
  function pop(heap) {
    if (heap.length === 0) {
      return null;
    }

    var first = heap[0];
    var last = heap.pop();

    if (last !== first) {
      heap[0] = last;
      siftDown(heap, last, 0);
    }

    return first;
  }

  function siftUp(heap, node, i) {
    var index = i;

    while (index > 0) {
      var parentIndex = index - 1 >>> 1;
      var parent = heap[parentIndex];

      if (compare(parent, node) > 0) {
        // The parent is larger. Swap positions.
        heap[parentIndex] = node;
        heap[index] = parent;
        index = parentIndex;
      } else {
        // The parent is smaller. Exit.
        return;
      }
    }
  }

  function siftDown(heap, node, i) {
    var index = i;
    var length = heap.length;
    var halfLength = length >>> 1;

    while (index < halfLength) {
      var leftIndex = (index + 1) * 2 - 1;
      var left = heap[leftIndex];
      var rightIndex = leftIndex + 1;
      var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

      if (compare(left, node) < 0) {
        if (rightIndex < length && compare(right, left) < 0) {
          heap[index] = right;
          heap[rightIndex] = node;
          index = rightIndex;
        } else {
          heap[index] = left;
          heap[leftIndex] = node;
          index = leftIndex;
        }
      } else if (rightIndex < length && compare(right, node) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        // Neither child is smaller. Exit.
        return;
      }
    }
  }

  function compare(a, b) {
    // Compare sort index first, then task id.
    var diff = a.sortIndex - b.sortIndex;
    return diff !== 0 ? diff : a.id - b.id;
  }

  // TODO: Use symbols?
  var ImmediatePriority = 1;
  var UserBlockingPriority = 2;
  var NormalPriority = 3;
  var LowPriority = 4;
  var IdlePriority = 5;

  function markTaskErrored(task, ms) {
  }

  /* eslint-disable no-var */
  // Math.pow(2, 30) - 1
  // 0b111111111111111111111111111111

  var maxSigned31BitInt = 1073741823; // Times out immediately

  var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

  var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
  var NORMAL_PRIORITY_TIMEOUT = 5000;
  var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

  var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

  var taskQueue = [];
  var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

  var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
  var currentTask = null;
  var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.

  var isPerformingWork = false;
  var isHostCallbackScheduled = false;
  var isHostTimeoutScheduled = false;
  var currentMockTime = 0;
  var scheduledCallback = null;
  var scheduledTimeout = null;
  var timeoutTime = -1;
  var yieldedValues = null;
  var expectedNumberOfYields = -1;
  var didStop = false;
  var isFlushing = false;
  var needsPaint = false;
  var shouldYieldForPaint = false;
  var disableYieldValue = false;

  function setDisableYieldValue(newValue) {
    disableYieldValue = newValue;
  }

  function advanceTimers(currentTime) {
    // Check for tasks that are no longer delayed and add them to the queue.
    var timer = peek(timerQueue);

    while (timer !== null) {
      if (timer.callback === null) {
        // Timer was cancelled.
        pop(timerQueue);
      } else if (timer.startTime <= currentTime) {
        // Timer fired. Transfer to the task queue.
        pop(timerQueue);
        timer.sortIndex = timer.expirationTime;
        push(taskQueue, timer);
      } else {
        // Remaining timers are pending.
        return;
      }

      timer = peek(timerQueue);
    }
  }

  function handleTimeout(currentTime) {
    isHostTimeoutScheduled = false;
    advanceTimers(currentTime);

    if (!isHostCallbackScheduled) {
      if (peek(taskQueue) !== null) {
        isHostCallbackScheduled = true;
        requestHostCallback(flushWork);
      } else {
        var firstTimer = peek(timerQueue);

        if (firstTimer !== null) {
          requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
      }
    }
  }

  function flushWork(hasTimeRemaining, initialTime) {


    isHostCallbackScheduled = false;

    if (isHostTimeoutScheduled) {
      // We scheduled a timeout but it's no longer needed. Cancel it.
      isHostTimeoutScheduled = false;
      cancelHostTimeout();
    }

    isPerformingWork = true;
    var previousPriorityLevel = currentPriorityLevel;

    try {
      if (enableProfiling) {
        try {
          return workLoop(hasTimeRemaining, initialTime);
        } catch (error) {
          if (currentTask !== null) {
            var currentTime = getCurrentTime();
            markTaskErrored(currentTask, currentTime);
            currentTask.isQueued = false;
          }

          throw error;
        }
      } else {
        // No catch in prod code path.
        return workLoop(hasTimeRemaining, initialTime);
      }
    } finally {
      currentTask = null;
      currentPriorityLevel = previousPriorityLevel;
      isPerformingWork = false;
    }
  }

  function workLoop(hasTimeRemaining, initialTime) {
    var currentTime = initialTime;
    advanceTimers(currentTime);
    currentTask = peek(taskQueue);

    while (currentTask !== null && !(enableSchedulerDebugging )) {
      if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
        // This currentTask hasn't expired, and we've reached the deadline.
        break;
      }

      var callback = currentTask.callback;

      if (typeof callback === 'function') {
        currentTask.callback = null;
        currentPriorityLevel = currentTask.priorityLevel;
        var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;

        var continuationCallback = callback(didUserCallbackTimeout);
        currentTime = getCurrentTime();

        if (typeof continuationCallback === 'function') {
          currentTask.callback = continuationCallback;
        } else {

          if (currentTask === peek(taskQueue)) {
            pop(taskQueue);
          }
        }

        advanceTimers(currentTime);
      } else {
        pop(taskQueue);
      }

      currentTask = peek(taskQueue);
    } // Return whether there's additional work


    if (currentTask !== null) {
      return true;
    } else {
      var firstTimer = peek(timerQueue);

      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }

      return false;
    }
  }

  function unstable_runWithPriority(priorityLevel, eventHandler) {
    switch (priorityLevel) {
      case ImmediatePriority:
      case UserBlockingPriority:
      case NormalPriority:
      case LowPriority:
      case IdlePriority:
        break;

      default:
        priorityLevel = NormalPriority;
    }

    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = priorityLevel;

    try {
      return eventHandler();
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  }

  function unstable_next(eventHandler) {
    var priorityLevel;

    switch (currentPriorityLevel) {
      case ImmediatePriority:
      case UserBlockingPriority:
      case NormalPriority:
        // Shift down to normal priority
        priorityLevel = NormalPriority;
        break;

      default:
        // Anything lower than normal priority should remain at the current level.
        priorityLevel = currentPriorityLevel;
        break;
    }

    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = priorityLevel;

    try {
      return eventHandler();
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  }

  function unstable_wrapCallback(callback) {
    var parentPriorityLevel = currentPriorityLevel;
    return function () {
      // This is a fork of runWithPriority, inlined for performance.
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = parentPriorityLevel;

      try {
        return callback.apply(this, arguments);
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
  }

  function unstable_scheduleCallback(priorityLevel, callback, options) {
    var currentTime = getCurrentTime();
    var startTime;

    if (typeof options === 'object' && options !== null) {
      var delay = options.delay;

      if (typeof delay === 'number' && delay > 0) {
        startTime = currentTime + delay;
      } else {
        startTime = currentTime;
      }
    } else {
      startTime = currentTime;
    }

    var timeout;

    switch (priorityLevel) {
      case ImmediatePriority:
        timeout = IMMEDIATE_PRIORITY_TIMEOUT;
        break;

      case UserBlockingPriority:
        timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
        break;

      case IdlePriority:
        timeout = IDLE_PRIORITY_TIMEOUT;
        break;

      case LowPriority:
        timeout = LOW_PRIORITY_TIMEOUT;
        break;

      case NormalPriority:
      default:
        timeout = NORMAL_PRIORITY_TIMEOUT;
        break;
    }

    var expirationTime = startTime + timeout;
    var newTask = {
      id: taskIdCounter++,
      callback: callback,
      priorityLevel: priorityLevel,
      startTime: startTime,
      expirationTime: expirationTime,
      sortIndex: -1
    };

    if (startTime > currentTime) {
      // This is a delayed task.
      newTask.sortIndex = startTime;
      push(timerQueue, newTask);

      if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
        // All tasks are delayed, and this is the task with the earliest delay.
        if (isHostTimeoutScheduled) {
          // Cancel an existing timeout.
          cancelHostTimeout();
        } else {
          isHostTimeoutScheduled = true;
        } // Schedule a timeout.


        requestHostTimeout(handleTimeout, startTime - currentTime);
      }
    } else {
      newTask.sortIndex = expirationTime;
      push(taskQueue, newTask);
      // wait until the next time we yield.


      if (!isHostCallbackScheduled && !isPerformingWork) {
        isHostCallbackScheduled = true;
        requestHostCallback(flushWork);
      }
    }

    return newTask;
  }

  function unstable_pauseExecution() {
  }

  function unstable_continueExecution() {

    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  function unstable_getFirstCallbackNode() {
    return peek(taskQueue);
  }

  function unstable_cancelCallback(task) {
    // remove from the queue because you can't remove arbitrary nodes from an
    // array based heap, only the first one.)


    task.callback = null;
  }

  function unstable_getCurrentPriorityLevel() {
    return currentPriorityLevel;
  }

  function requestHostCallback(callback) {
    scheduledCallback = callback;
  }

  function requestHostTimeout(callback, ms) {
    scheduledTimeout = callback;
    timeoutTime = currentMockTime + ms;
  }

  function cancelHostTimeout() {
    scheduledTimeout = null;
    timeoutTime = -1;
  }

  function shouldYieldToHost() {
    if (expectedNumberOfYields === 0 && yieldedValues === null || expectedNumberOfYields !== -1 && yieldedValues !== null && yieldedValues.length >= expectedNumberOfYields || shouldYieldForPaint && needsPaint) {
      // We yielded at least as many values as expected. Stop flushing.
      didStop = true;
      return true;
    }

    return false;
  }

  function getCurrentTime() {
    return currentMockTime;
  }

  function forceFrameRate() {// No-op
  }

  function reset() {
    if (isFlushing) {
      throw new Error('Cannot reset while already flushing work.');
    }

    currentMockTime = 0;
    scheduledCallback = null;
    scheduledTimeout = null;
    timeoutTime = -1;
    yieldedValues = null;
    expectedNumberOfYields = -1;
    didStop = false;
    isFlushing = false;
    needsPaint = false;
  } // Should only be used via an assertion helper that inspects the yielded values.


  function unstable_flushNumberOfYields(count) {
    if (isFlushing) {
      throw new Error('Already flushing work.');
    }

    if (scheduledCallback !== null) {
      var cb = scheduledCallback;
      expectedNumberOfYields = count;
      isFlushing = true;

      try {
        var hasMoreWork = true;

        do {
          hasMoreWork = cb(true, currentMockTime);
        } while (hasMoreWork && !didStop);

        if (!hasMoreWork) {
          scheduledCallback = null;
        }
      } finally {
        expectedNumberOfYields = -1;
        didStop = false;
        isFlushing = false;
      }
    }
  }

  function unstable_flushUntilNextPaint() {
    if (isFlushing) {
      throw new Error('Already flushing work.');
    }

    if (scheduledCallback !== null) {
      var cb = scheduledCallback;
      shouldYieldForPaint = true;
      needsPaint = false;
      isFlushing = true;

      try {
        var hasMoreWork = true;

        do {
          hasMoreWork = cb(true, currentMockTime);
        } while (hasMoreWork && !didStop);

        if (!hasMoreWork) {
          scheduledCallback = null;
        }
      } finally {
        shouldYieldForPaint = false;
        didStop = false;
        isFlushing = false;
      }
    }
  }

  function unstable_flushExpired() {
    if (isFlushing) {
      throw new Error('Already flushing work.');
    }

    if (scheduledCallback !== null) {
      isFlushing = true;

      try {
        var hasMoreWork = scheduledCallback(false, currentMockTime);

        if (!hasMoreWork) {
          scheduledCallback = null;
        }
      } finally {
        isFlushing = false;
      }
    }
  }

  function unstable_flushAllWithoutAsserting() {
    // Returns false if no work was flushed.
    if (isFlushing) {
      throw new Error('Already flushing work.');
    }

    if (scheduledCallback !== null) {
      var cb = scheduledCallback;
      isFlushing = true;

      try {
        var hasMoreWork = true;

        do {
          hasMoreWork = cb(true, currentMockTime);
        } while (hasMoreWork);

        if (!hasMoreWork) {
          scheduledCallback = null;
        }

        return true;
      } finally {
        isFlushing = false;
      }
    } else {
      return false;
    }
  }

  function unstable_clearYields() {
    if (yieldedValues === null) {
      return [];
    }

    var values = yieldedValues;
    yieldedValues = null;
    return values;
  }

  function unstable_flushAll() {
    if (yieldedValues !== null) {
      throw new Error('Log is not empty. Assert on the log of yielded values before ' + 'flushing additional work.');
    }

    unstable_flushAllWithoutAsserting();

    if (yieldedValues !== null) {
      throw new Error('While flushing work, something yielded a value. Use an ' + 'assertion helper to assert on the log of yielded values, e.g. ' + 'expect(Scheduler).toFlushAndYield([...])');
    }
  }

  function unstable_yieldValue(value) {
    // eslint-disable-next-line react-internal/no-production-logging
    if (console.log.name === 'disabledLog' || disableYieldValue) {
      // If console.log has been patched, we assume we're in render
      // replaying and we ignore any values yielding in the second pass.
      return;
    }

    if (yieldedValues === null) {
      yieldedValues = [value];
    } else {
      yieldedValues.push(value);
    }
  }

  function unstable_advanceTime(ms) {
    // eslint-disable-next-line react-internal/no-production-logging
    if (console.log.name === 'disabledLog' || disableYieldValue) {
      // If console.log has been patched, we assume we're in render
      // replaying and we ignore any time advancing in the second pass.
      return;
    }

    currentMockTime += ms;

    if (scheduledTimeout !== null && timeoutTime <= currentMockTime) {
      scheduledTimeout(currentMockTime);
      timeoutTime = -1;
      scheduledTimeout = null;
    }
  }

  function requestPaint() {
    needsPaint = true;
  }
  var unstable_Profiling =  null;

  exports.reset = reset;
  exports.unstable_IdlePriority = IdlePriority;
  exports.unstable_ImmediatePriority = ImmediatePriority;
  exports.unstable_LowPriority = LowPriority;
  exports.unstable_NormalPriority = NormalPriority;
  exports.unstable_Profiling = unstable_Profiling;
  exports.unstable_UserBlockingPriority = UserBlockingPriority;
  exports.unstable_advanceTime = unstable_advanceTime;
  exports.unstable_cancelCallback = unstable_cancelCallback;
  exports.unstable_clearYields = unstable_clearYields;
  exports.unstable_continueExecution = unstable_continueExecution;
  exports.unstable_flushAll = unstable_flushAll;
  exports.unstable_flushAllWithoutAsserting = unstable_flushAllWithoutAsserting;
  exports.unstable_flushExpired = unstable_flushExpired;
  exports.unstable_flushNumberOfYields = unstable_flushNumberOfYields;
  exports.unstable_flushUntilNextPaint = unstable_flushUntilNextPaint;
  exports.unstable_forceFrameRate = forceFrameRate;
  exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
  exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
  exports.unstable_next = unstable_next;
  exports.unstable_now = getCurrentTime;
  exports.unstable_pauseExecution = unstable_pauseExecution;
  exports.unstable_requestPaint = requestPaint;
  exports.unstable_runWithPriority = unstable_runWithPriority;
  exports.unstable_scheduleCallback = unstable_scheduleCallback;
  exports.unstable_setDisableYieldValue = setDisableYieldValue;
  exports.unstable_shouldYield = shouldYieldToHost;
  exports.unstable_wrapCallback = unstable_wrapCallback;
  exports.unstable_yieldValue = unstable_yieldValue;

})));
/**
 * @license React
 * scheduler-unstable_mock.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(){'use strict';(function(a,p){"object"===typeof exports&&"undefined"!==typeof module?p(exports):"function"===typeof define&&define.amd?define(["exports"],p):(a=a||self,p(a.SchedulerMock={}))})(this,function(a){function p(b,k){var c=b.length;b.push(k);a:for(;0<c;){var a=c-1>>>1,v=b[a];if(0<z(v,k))b[a]=k,b[c]=v,c=a;else break a}}function m(b){return 0===b.length?null:b[0]}function A(b){if(0===b.length)return null;var k=b[0],c=b.pop();if(c!==k){b[0]=c;a:for(var a=0,v=b.length,f=v>>>1;a<f;){var d=2*(a+
1)-1,g=b[d],e=d+1,h=b[e];if(0>z(g,c))e<v&&0>z(h,g)?(b[a]=h,b[e]=c,a=e):(b[a]=g,b[d]=c,a=d);else if(e<v&&0>z(h,c))b[a]=h,b[e]=c,a=e;else break a}}return k}function z(b,a){var k=b.sortIndex-a.sortIndex;return 0!==k?k:b.id-a.id}function D(b){for(var a=m(r);null!==a;){if(null===a.callback)A(r);else if(a.startTime<=b)A(r),a.sortIndex=a.expirationTime,p(n,a);else break;a=m(r)}}function E(b){y=!1;D(b);if(!u)if(null!==m(n))u=!0,f=F;else{var a=m(r);null!==a&&(b=a.startTime-b,q=E,t=g+b)}}function F(b,a){u=
!1;y&&(y=!1,q=null,t=-1);B=!0;var c=d;try{D(a);for(h=m(n);null!==h&&(!(h.expirationTime>a)||b&&!I());){var k=h.callback;if("function"===typeof k){h.callback=null;d=h.priorityLevel;var e=k(h.expirationTime<=a);a=g;"function"===typeof e?h.callback=e:h===m(n)&&A(n);D(a)}else A(n);h=m(n)}if(null!==h)var f=!0;else{var l=m(r);if(null!==l){var p=l.startTime-a;q=E;t=g+p}f=!1}return f}finally{h=null,d=c,B=!1}}function I(){return 0===w&&null===l||-1!==w&&null!==l&&l.length>=w||G&&C?x=!0:!1}function J(){if(e)throw Error("Already flushing work.");
if(null!==f){var b=f;e=!0;try{var a=!0;do a=b(!0,g);while(a);a||(f=null);return!0}finally{e=!1}}else return!1}var n=[],r=[],K=1,h=null,d=3,B=!1,u=!1,y=!1,g=0,f=null,q=null,t=-1,l=null,w=-1,x=!1,e=!1,C=!1,G=!1,H=!1;a.reset=function(){if(e)throw Error("Cannot reset while already flushing work.");g=0;q=f=null;t=-1;l=null;w=-1;C=e=x=!1};a.unstable_IdlePriority=5;a.unstable_ImmediatePriority=1;a.unstable_LowPriority=4;a.unstable_NormalPriority=3;a.unstable_Profiling=null;a.unstable_UserBlockingPriority=
2;a.unstable_advanceTime=function(b){"disabledLog"===console.log.name||H||(g+=b,null!==q&&t<=g&&(q(g),t=-1,q=null))};a.unstable_cancelCallback=function(b){b.callback=null};a.unstable_clearYields=function(){if(null===l)return[];var b=l;l=null;return b};a.unstable_continueExecution=function(){u||B||(u=!0,f=F)};a.unstable_flushAll=function(){if(null!==l)throw Error("Log is not empty. Assert on the log of yielded values before flushing additional work.");J();if(null!==l)throw Error("While flushing work, something yielded a value. Use an assertion helper to assert on the log of yielded values, e.g. expect(Scheduler).toFlushAndYield([...])");
};a.unstable_flushAllWithoutAsserting=J;a.unstable_flushExpired=function(){if(e)throw Error("Already flushing work.");if(null!==f){e=!0;try{f(!1,g)||(f=null)}finally{e=!1}}};a.unstable_flushNumberOfYields=function(b){if(e)throw Error("Already flushing work.");if(null!==f){var a=f;w=b;e=!0;try{b=!0;do b=a(!0,g);while(b&&!x);b||(f=null)}finally{w=-1,e=x=!1}}};a.unstable_flushUntilNextPaint=function(){if(e)throw Error("Already flushing work.");if(null!==f){var a=f;G=!0;C=!1;e=!0;try{var k=!0;do k=a(!0,
g);while(k&&!x);k||(f=null)}finally{e=x=G=!1}}};a.unstable_forceFrameRate=function(){};a.unstable_getCurrentPriorityLevel=function(){return d};a.unstable_getFirstCallbackNode=function(){return m(n)};a.unstable_next=function(a){switch(d){case 1:case 2:case 3:var b=3;break;default:b=d}var c=d;d=b;try{return a()}finally{d=c}};a.unstable_now=function(){return g};a.unstable_pauseExecution=function(){};a.unstable_requestPaint=function(){C=!0};a.unstable_runWithPriority=function(a,e){switch(a){case 1:case 2:case 3:case 4:case 5:break;
default:a=3}var b=d;d=a;try{return e()}finally{d=b}};a.unstable_scheduleCallback=function(a,e,c){var b=g;"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?b+c:b):c=b;switch(a){case 1:var d=-1;break;case 2:d=250;break;case 5:d=1073741823;break;case 4:d=1E4;break;default:d=5E3}d=c+d;a={id:K++,callback:e,priorityLevel:a,startTime:c,expirationTime:d,sortIndex:-1};c>b?(a.sortIndex=c,p(r,a),null===m(n)&&a===m(r)&&(y?(q=null,t=-1):y=!0,q=E,t=g+(c-b))):(a.sortIndex=d,p(n,a),u||B||(u=!0,
f=F));return a};a.unstable_setDisableYieldValue=function(a){H=a};a.unstable_shouldYield=I;a.unstable_wrapCallback=function(a){var b=d;return function(){var c=d;d=b;try{return a.apply(this,arguments)}finally{d=c}}};a.unstable_yieldValue=function(a){"disabledLog"===console.log.name||H||(null===l?l=[a]:l.push(a))}});
})();
/**
 * @license React
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* eslint-disable max-len */

'use strict';

(function(global, factory) {
  // eslint-disable-next-line no-unused-expressions
  typeof exports === 'object' && typeof module !== 'undefined'
    ? (module.exports = factory(require('react')))
    : typeof define === 'function' && define.amd // eslint-disable-line no-undef
    ? define(['react'], factory) // eslint-disable-line no-undef
    : (global.Scheduler = factory(global));
})(this, function(global) {
  function unstable_now() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_now.apply(
      this,
      arguments
    );
  }

  function unstable_scheduleCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_scheduleCallback.apply(
      this,
      arguments
    );
  }

  function unstable_cancelCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_cancelCallback.apply(
      this,
      arguments
    );
  }

  function unstable_shouldYield() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_shouldYield.apply(
      this,
      arguments
    );
  }

  function unstable_requestPaint() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_requestPaint.apply(
      this,
      arguments
    );
  }

  function unstable_runWithPriority() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_runWithPriority.apply(
      this,
      arguments
    );
  }

  function unstable_next() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_next.apply(
      this,
      arguments
    );
  }

  function unstable_wrapCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_wrapCallback.apply(
      this,
      arguments
    );
  }

  function unstable_getCurrentPriorityLevel() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getCurrentPriorityLevel.apply(
      this,
      arguments
    );
  }

  function unstable_getFirstCallbackNode() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getFirstCallbackNode.apply(
      this,
      arguments
    );
  }

  function unstable_pauseExecution() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_pauseExecution.apply(
      this,
      arguments
    );
  }

  function unstable_continueExecution() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_continueExecution.apply(
      this,
      arguments
    );
  }

  function unstable_forceFrameRate() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_forceFrameRate.apply(
      this,
      arguments
    );
  }

  return Object.freeze({
    unstable_now: unstable_now,
    unstable_scheduleCallback: unstable_scheduleCallback,
    unstable_cancelCallback: unstable_cancelCallback,
    unstable_shouldYield: unstable_shouldYield,
    unstable_requestPaint: unstable_requestPaint,
    unstable_runWithPriority: unstable_runWithPriority,
    unstable_next: unstable_next,
    unstable_wrapCallback: unstable_wrapCallback,
    unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
    unstable_continueExecution: unstable_continueExecution,
    unstable_pauseExecution: unstable_pauseExecution,
    unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
    unstable_forceFrameRate: unstable_forceFrameRate,
    get unstable_IdlePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_IdlePriority;
    },
    get unstable_ImmediatePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_ImmediatePriority;
    },
    get unstable_LowPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_LowPriority;
    },
    get unstable_NormalPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_NormalPriority;
    },
    get unstable_UserBlockingPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_UserBlockingPriority;
    },
    get unstable_Profiling() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_Profiling;
    },
  });
});
/**
 * @license React
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* eslint-disable max-len */

'use strict';

(function(global, factory) {
  // eslint-disable-next-line no-unused-expressions
  typeof exports === 'object' && typeof module !== 'undefined'
    ? (module.exports = factory(require('react')))
    : typeof define === 'function' && define.amd // eslint-disable-line no-undef
    ? define(['react'], factory) // eslint-disable-line no-undef
    : (global.Scheduler = factory(global));
})(this, function(global) {
  function unstable_now() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_now.apply(
      this,
      arguments
    );
  }

  function unstable_scheduleCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_scheduleCallback.apply(
      this,
      arguments
    );
  }

  function unstable_cancelCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_cancelCallback.apply(
      this,
      arguments
    );
  }

  function unstable_shouldYield() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_shouldYield.apply(
      this,
      arguments
    );
  }

  function unstable_requestPaint() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_requestPaint.apply(
      this,
      arguments
    );
  }

  function unstable_runWithPriority() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_runWithPriority.apply(
      this,
      arguments
    );
  }

  function unstable_next() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_next.apply(
      this,
      arguments
    );
  }

  function unstable_wrapCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_wrapCallback.apply(
      this,
      arguments
    );
  }

  function unstable_getCurrentPriorityLevel() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getCurrentPriorityLevel.apply(
      this,
      arguments
    );
  }

  function unstable_getFirstCallbackNode() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getFirstCallbackNode.apply(
      this,
      arguments
    );
  }

  function unstable_pauseExecution() {
    return undefined;
  }

  function unstable_continueExecution() {
    return undefined;
  }

  function unstable_forceFrameRate() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_forceFrameRate.apply(
      this,
      arguments
    );
  }

  return Object.freeze({
    unstable_now: unstable_now,
    unstable_scheduleCallback: unstable_scheduleCallback,
    unstable_cancelCallback: unstable_cancelCallback,
    unstable_shouldYield: unstable_shouldYield,
    unstable_requestPaint: unstable_requestPaint,
    unstable_runWithPriority: unstable_runWithPriority,
    unstable_next: unstable_next,
    unstable_wrapCallback: unstable_wrapCallback,
    unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
    unstable_continueExecution: unstable_continueExecution,
    unstable_pauseExecution: unstable_pauseExecution,
    unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
    unstable_forceFrameRate: unstable_forceFrameRate,
    get unstable_IdlePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_IdlePriority;
    },
    get unstable_ImmediatePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_ImmediatePriority;
    },
    get unstable_LowPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_LowPriority;
    },
    get unstable_NormalPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_NormalPriority;
    },
    get unstable_UserBlockingPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_UserBlockingPriority;
    },
    get unstable_Profiling() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_Profiling;
    },
  });
});
/**
 * @license React
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* eslint-disable max-len */

'use strict';

(function(global, factory) {
  // eslint-disable-next-line no-unused-expressions
  typeof exports === 'object' && typeof module !== 'undefined'
    ? (module.exports = factory(require('react')))
    : typeof define === 'function' && define.amd // eslint-disable-line no-undef
    ? define(['react'], factory) // eslint-disable-line no-undef
    : (global.Scheduler = factory(global));
})(this, function(global) {
  function unstable_now() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_now.apply(
      this,
      arguments
    );
  }

  function unstable_scheduleCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_scheduleCallback.apply(
      this,
      arguments
    );
  }

  function unstable_cancelCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_cancelCallback.apply(
      this,
      arguments
    );
  }

  function unstable_shouldYield() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_shouldYield.apply(
      this,
      arguments
    );
  }

  function unstable_requestPaint() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_requestPaint.apply(
      this,
      arguments
    );
  }

  function unstable_runWithPriority() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_runWithPriority.apply(
      this,
      arguments
    );
  }

  function unstable_next() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_next.apply(
      this,
      arguments
    );
  }

  function unstable_wrapCallback() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_wrapCallback.apply(
      this,
      arguments
    );
  }

  function unstable_getCurrentPriorityLevel() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getCurrentPriorityLevel.apply(
      this,
      arguments
    );
  }

  function unstable_getFirstCallbackNode() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getFirstCallbackNode.apply(
      this,
      arguments
    );
  }

  function unstable_pauseExecution() {
    return undefined;
  }

  function unstable_continueExecution() {
    return undefined;
  }

  function unstable_forceFrameRate() {
    return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_forceFrameRate.apply(
      this,
      arguments
    );
  }

  return Object.freeze({
    unstable_now: unstable_now,
    unstable_scheduleCallback: unstable_scheduleCallback,
    unstable_cancelCallback: unstable_cancelCallback,
    unstable_shouldYield: unstable_shouldYield,
    unstable_requestPaint: unstable_requestPaint,
    unstable_runWithPriority: unstable_runWithPriority,
    unstable_next: unstable_next,
    unstable_wrapCallback: unstable_wrapCallback,
    unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
    unstable_continueExecution: unstable_continueExecution,
    unstable_pauseExecution: unstable_pauseExecution,
    unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
    unstable_forceFrameRate: unstable_forceFrameRate,
    get unstable_IdlePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_IdlePriority;
    },
    get unstable_ImmediatePriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_ImmediatePriority;
    },
    get unstable_LowPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_LowPriority;
    },
    get unstable_NormalPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_NormalPriority;
    },
    get unstable_UserBlockingPriority() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_UserBlockingPriority;
    },
    get unstable_Profiling() {
      return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .Scheduler.unstable_Profiling;
    },
  });
});
/**
 * @license React
 * scheduler-unstable_mock.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var enableSchedulerDebugging = false;
var enableProfiling = false;

function push(heap, node) {
  var index = heap.length;
  heap.push(node);
  siftUp(heap, node, index);
}
function peek(heap) {
  return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
  if (heap.length === 0) {
    return null;
  }

  var first = heap[0];
  var last = heap.pop();

  if (last !== first) {
    heap[0] = last;
    siftDown(heap, last, 0);
  }

  return first;
}

function siftUp(heap, node, i) {
  var index = i;

  while (index > 0) {
    var parentIndex = index - 1 >>> 1;
    var parent = heap[parentIndex];

    if (compare(parent, node) > 0) {
      // The parent is larger. Swap positions.
      heap[parentIndex] = node;
      heap[index] = parent;
      index = parentIndex;
    } else {
      // The parent is smaller. Exit.
      return;
    }
  }
}

function siftDown(heap, node, i) {
  var index = i;
  var length = heap.length;
  var halfLength = length >>> 1;

  while (index < halfLength) {
    var leftIndex = (index + 1) * 2 - 1;
    var left = heap[leftIndex];
    var rightIndex = leftIndex + 1;
    var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

    if (compare(left, node) < 0) {
      if (rightIndex < length && compare(right, left) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        heap[index] = left;
        heap[leftIndex] = node;
        index = leftIndex;
      }
    } else if (rightIndex < length && compare(right, node) < 0) {
      heap[index] = right;
      heap[rightIndex] = node;
      index = rightIndex;
    } else {
      // Neither child is smaller. Exit.
      return;
    }
  }
}

function compare(a, b) {
  // Compare sort index first, then task id.
  var diff = a.sortIndex - b.sortIndex;
  return diff !== 0 ? diff : a.id - b.id;
}

// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;

function markTaskErrored(task, ms) {
}

/* eslint-disable no-var */
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111

var maxSigned31BitInt = 1073741823; // Times out immediately

var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.

var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false;
var currentMockTime = 0;
var scheduledCallback = null;
var scheduledTimeout = null;
var timeoutTime = -1;
var yieldedValues = null;
var expectedNumberOfYields = -1;
var didStop = false;
var isFlushing = false;
var needsPaint = false;
var shouldYieldForPaint = false;
var disableYieldValue = false;

function setDisableYieldValue(newValue) {
  disableYieldValue = newValue;
}

function advanceTimers(currentTime) {
  // Check for tasks that are no longer delayed and add them to the queue.
  var timer = peek(timerQueue);

  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
    } else {
      // Remaining timers are pending.
      return;
    }

    timer = peek(timerQueue);
  }
}

function handleTimeout(currentTime) {
  isHostTimeoutScheduled = false;
  advanceTimers(currentTime);

  if (!isHostCallbackScheduled) {
    if (peek(taskQueue) !== null) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    } else {
      var firstTimer = peek(timerQueue);

      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }
    }
  }
}

function flushWork(hasTimeRemaining, initialTime) {


  isHostCallbackScheduled = false;

  if (isHostTimeoutScheduled) {
    // We scheduled a timeout but it's no longer needed. Cancel it.
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  var previousPriorityLevel = currentPriorityLevel;

  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);
      } catch (error) {
        if (currentTask !== null) {
          var currentTime = getCurrentTime();
          markTaskErrored(currentTask, currentTime);
          currentTask.isQueued = false;
        }

        throw error;
      }
    } else {
      // No catch in prod code path.
      return workLoop(hasTimeRemaining, initialTime);
    }
  } finally {
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
  }
}

function workLoop(hasTimeRemaining, initialTime) {
  var currentTime = initialTime;
  advanceTimers(currentTime);
  currentTask = peek(taskQueue);

  while (currentTask !== null && !(enableSchedulerDebugging )) {
    if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
      // This currentTask hasn't expired, and we've reached the deadline.
      break;
    }

    var callback = currentTask.callback;

    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;

      var continuationCallback = callback(didUserCallbackTimeout);
      currentTime = getCurrentTime();

      if (typeof continuationCallback === 'function') {
        currentTask.callback = continuationCallback;
      } else {

        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }

      advanceTimers(currentTime);
    } else {
      pop(taskQueue);
    }

    currentTask = peek(taskQueue);
  } // Return whether there's additional work


  if (currentTask !== null) {
    return true;
  } else {
    var firstTimer = peek(timerQueue);

    if (firstTimer !== null) {
      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
    }

    return false;
  }
}

function unstable_runWithPriority(priorityLevel, eventHandler) {
  switch (priorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
    case LowPriority:
    case IdlePriority:
      break;

    default:
      priorityLevel = NormalPriority;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_next(eventHandler) {
  var priorityLevel;

  switch (currentPriorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
      // Shift down to normal priority
      priorityLevel = NormalPriority;
      break;

    default:
      // Anything lower than normal priority should remain at the current level.
      priorityLevel = currentPriorityLevel;
      break;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_wrapCallback(callback) {
  var parentPriorityLevel = currentPriorityLevel;
  return function () {
    // This is a fork of runWithPriority, inlined for performance.
    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = parentPriorityLevel;

    try {
      return callback.apply(this, arguments);
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  };
}

function unstable_scheduleCallback(priorityLevel, callback, options) {
  var currentTime = getCurrentTime();
  var startTime;

  if (typeof options === 'object' && options !== null) {
    var delay = options.delay;

    if (typeof delay === 'number' && delay > 0) {
      startTime = currentTime + delay;
    } else {
      startTime = currentTime;
    }
  } else {
    startTime = currentTime;
  }

  var timeout;

  switch (priorityLevel) {
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;

    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;

    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;

    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;

    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }

  var expirationTime = startTime + timeout;
  var newTask = {
    id: taskIdCounter++,
    callback: callback,
    priorityLevel: priorityLevel,
    startTime: startTime,
    expirationTime: expirationTime,
    sortIndex: -1
  };

  if (startTime > currentTime) {
    // This is a delayed task.
    newTask.sortIndex = startTime;
    push(timerQueue, newTask);

    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // All tasks are delayed, and this is the task with the earliest delay.
      if (isHostTimeoutScheduled) {
        // Cancel an existing timeout.
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      } // Schedule a timeout.


      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
    newTask.sortIndex = expirationTime;
    push(taskQueue, newTask);
    // wait until the next time we yield.


    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  return newTask;
}

function unstable_pauseExecution() {
}

function unstable_continueExecution() {

  if (!isHostCallbackScheduled && !isPerformingWork) {
    isHostCallbackScheduled = true;
    requestHostCallback(flushWork);
  }
}

function unstable_getFirstCallbackNode() {
  return peek(taskQueue);
}

function unstable_cancelCallback(task) {
  // remove from the queue because you can't remove arbitrary nodes from an
  // array based heap, only the first one.)


  task.callback = null;
}

function unstable_getCurrentPriorityLevel() {
  return currentPriorityLevel;
}

function requestHostCallback(callback) {
  scheduledCallback = callback;
}

function requestHostTimeout(callback, ms) {
  scheduledTimeout = callback;
  timeoutTime = currentMockTime + ms;
}

function cancelHostTimeout() {
  scheduledTimeout = null;
  timeoutTime = -1;
}

function shouldYieldToHost() {
  if (expectedNumberOfYields === 0 && yieldedValues === null || expectedNumberOfYields !== -1 && yieldedValues !== null && yieldedValues.length >= expectedNumberOfYields || shouldYieldForPaint && needsPaint) {
    // We yielded at least as many values as expected. Stop flushing.
    didStop = true;
    return true;
  }

  return false;
}

function getCurrentTime() {
  return currentMockTime;
}

function forceFrameRate() {// No-op
}

function reset() {
  if (isFlushing) {
    throw new Error('Cannot reset while already flushing work.');
  }

  currentMockTime = 0;
  scheduledCallback = null;
  scheduledTimeout = null;
  timeoutTime = -1;
  yieldedValues = null;
  expectedNumberOfYields = -1;
  didStop = false;
  isFlushing = false;
  needsPaint = false;
} // Should only be used via an assertion helper that inspects the yielded values.


function unstable_flushNumberOfYields(count) {
  if (isFlushing) {
    throw new Error('Already flushing work.');
  }

  if (scheduledCallback !== null) {
    var cb = scheduledCallback;
    expectedNumberOfYields = count;
    isFlushing = true;

    try {
      var hasMoreWork = true;

      do {
        hasMoreWork = cb(true, currentMockTime);
      } while (hasMoreWork && !didStop);

      if (!hasMoreWork) {
        scheduledCallback = null;
      }
    } finally {
      expectedNumberOfYields = -1;
      didStop = false;
      isFlushing = false;
    }
  }
}

function unstable_flushUntilNextPaint() {
  if (isFlushing) {
    throw new Error('Already flushing work.');
  }

  if (scheduledCallback !== null) {
    var cb = scheduledCallback;
    shouldYieldForPaint = true;
    needsPaint = false;
    isFlushing = true;

    try {
      var hasMoreWork = true;

      do {
        hasMoreWork = cb(true, currentMockTime);
      } while (hasMoreWork && !didStop);

      if (!hasMoreWork) {
        scheduledCallback = null;
      }
    } finally {
      shouldYieldForPaint = false;
      didStop = false;
      isFlushing = false;
    }
  }
}

function unstable_flushExpired() {
  if (isFlushing) {
    throw new Error('Already flushing work.');
  }

  if (scheduledCallback !== null) {
    isFlushing = true;

    try {
      var hasMoreWork = scheduledCallback(false, currentMockTime);

      if (!hasMoreWork) {
        scheduledCallback = null;
      }
    } finally {
      isFlushing = false;
    }
  }
}

function unstable_flushAllWithoutAsserting() {
  // Returns false if no work was flushed.
  if (isFlushing) {
    throw new Error('Already flushing work.');
  }

  if (scheduledCallback !== null) {
    var cb = scheduledCallback;
    isFlushing = true;

    try {
      var hasMoreWork = true;

      do {
        hasMoreWork = cb(true, currentMockTime);
      } while (hasMoreWork);

      if (!hasMoreWork) {
        scheduledCallback = null;
      }

      return true;
    } finally {
      isFlushing = false;
    }
  } else {
    return false;
  }
}

function unstable_clearYields() {
  if (yieldedValues === null) {
    return [];
  }

  var values = yieldedValues;
  yieldedValues = null;
  return values;
}

function unstable_flushAll() {
  if (yieldedValues !== null) {
    throw new Error('Log is not empty. Assert on the log of yielded values before ' + 'flushing additional work.');
  }

  unstable_flushAllWithoutAsserting();

  if (yieldedValues !== null) {
    throw new Error('While flushing work, something yielded a value. Use an ' + 'assertion helper to assert on the log of yielded values, e.g. ' + 'expect(Scheduler).toFlushAndYield([...])');
  }
}

function unstable_yieldValue(value) {
  // eslint-disable-next-line react-internal/no-production-logging
  if (console.log.name === 'disabledLog' || disableYieldValue) {
    // If console.log has been patched, we assume we're in render
    // replaying and we ignore any values yielding in the second pass.
    return;
  }

  if (yieldedValues === null) {
    yieldedValues = [value];
  } else {
    yieldedValues.push(value);
  }
}

function unstable_advanceTime(ms) {
  // eslint-disable-next-line react-internal/no-production-logging
  if (console.log.name === 'disabledLog' || disableYieldValue) {
    // If console.log has been patched, we assume we're in render
    // replaying and we ignore any time advancing in the second pass.
    return;
  }

  currentMockTime += ms;

  if (scheduledTimeout !== null && timeoutTime <= currentMockTime) {
    scheduledTimeout(currentMockTime);
    timeoutTime = -1;
    scheduledTimeout = null;
  }
}

function requestPaint() {
  needsPaint = true;
}
var unstable_Profiling =  null;

exports.reset = reset;
exports.unstable_IdlePriority = IdlePriority;
exports.unstable_ImmediatePriority = ImmediatePriority;
exports.unstable_LowPriority = LowPriority;
exports.unstable_NormalPriority = NormalPriority;
exports.unstable_Profiling = unstable_Profiling;
exports.unstable_UserBlockingPriority = UserBlockingPriority;
exports.unstable_advanceTime = unstable_advanceTime;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_clearYields = unstable_clearYields;
exports.unstable_continueExecution = unstable_continueExecution;
exports.unstable_flushAll = unstable_flushAll;
exports.unstable_flushAllWithoutAsserting = unstable_flushAllWithoutAsserting;
exports.unstable_flushExpired = unstable_flushExpired;
exports.unstable_flushNumberOfYields = unstable_flushNumberOfYields;
exports.unstable_flushUntilNextPaint = unstable_flushUntilNextPaint;
exports.unstable_forceFrameRate = forceFrameRate;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
exports.unstable_next = unstable_next;
exports.unstable_now = getCurrentTime;
exports.unstable_pauseExecution = unstable_pauseExecution;
exports.unstable_requestPaint = requestPaint;
exports.unstable_runWithPriority = unstable_runWithPriority;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_setDisableYieldValue = setDisableYieldValue;
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = unstable_wrapCallback;
exports.unstable_yieldValue = unstable_yieldValue;
  })();
}
/**
 * @license React
 * scheduler-unstable_mock.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,D=e>>>1;d<D;){var u=2*(d+1)-1,z=a[u],v=u+1,E=a[v];if(0>g(z,c))v<e&&0>g(E,z)?(a[d]=E,a[v]=c,d=v):(a[d]=z,a[u]=c,d=u);else if(v<e&&0>g(E,c))a[d]=E,a[v]=c,d=v;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var l=[],m=[],n=1,p=null,q=3,r=!1,t=!1,w=!1,x=0,y=null,A=null,B=-1,C=null,F=-1,G=!1,H=!1,I=!1,J=!1,K=!1;function L(a){for(var b=h(m);null!==b;){if(null===b.callback)k(m);else if(b.startTime<=a)k(m),b.sortIndex=b.expirationTime,f(l,b);else break;b=h(m)}}function M(a){w=!1;L(a);if(!t)if(null!==h(l))t=!0,y=N;else{var b=h(m);null!==b&&(a=b.startTime-a,A=M,B=x+a)}}
function N(a,b){t=!1;w&&(w=!1,A=null,B=-1);r=!0;var c=q;try{L(b);for(p=h(l);null!==p&&(!(p.expirationTime>b)||a&&!O());){var d=p.callback;if("function"===typeof d){p.callback=null;q=p.priorityLevel;var e=d(p.expirationTime<=b);b=x;"function"===typeof e?p.callback=e:p===h(l)&&k(l);L(b)}else k(l);p=h(l)}if(null!==p)var D=!0;else{var u=h(m);if(null!==u){var z=u.startTime-b;A=M;B=x+z}D=!1}return D}finally{p=null,q=c,r=!1}}
function O(){return 0===F&&null===C||-1!==F&&null!==C&&C.length>=F||J&&I?G=!0:!1}function P(){if(H)throw Error("Already flushing work.");if(null!==y){var a=y;H=!0;try{var b=!0;do b=a(!0,x);while(b);b||(y=null);return!0}finally{H=!1}}else return!1}exports.reset=function(){if(H)throw Error("Cannot reset while already flushing work.");x=0;A=y=null;B=-1;C=null;F=-1;I=H=G=!1};exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;
exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_advanceTime=function(a){"disabledLog"===console.log.name||K||(x+=a,null!==A&&B<=x&&(A(x),B=-1,A=null))};exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_clearYields=function(){if(null===C)return[];var a=C;C=null;return a};exports.unstable_continueExecution=function(){t||r||(t=!0,y=N)};
exports.unstable_flushAll=function(){if(null!==C)throw Error("Log is not empty. Assert on the log of yielded values before flushing additional work.");P();if(null!==C)throw Error("While flushing work, something yielded a value. Use an assertion helper to assert on the log of yielded values, e.g. expect(Scheduler).toFlushAndYield([...])");};exports.unstable_flushAllWithoutAsserting=P;
exports.unstable_flushExpired=function(){if(H)throw Error("Already flushing work.");if(null!==y){H=!0;try{y(!1,x)||(y=null)}finally{H=!1}}};exports.unstable_flushNumberOfYields=function(a){if(H)throw Error("Already flushing work.");if(null!==y){var b=y;F=a;H=!0;try{a=!0;do a=b(!0,x);while(a&&!G);a||(y=null)}finally{F=-1,H=G=!1}}};
exports.unstable_flushUntilNextPaint=function(){if(H)throw Error("Already flushing work.");if(null!==y){var a=y;J=!0;I=!1;H=!0;try{var b=!0;do b=a(!0,x);while(b&&!G);b||(y=null)}finally{H=G=J=!1}}};exports.unstable_forceFrameRate=function(){};exports.unstable_getCurrentPriorityLevel=function(){return q};exports.unstable_getFirstCallbackNode=function(){return h(l)};exports.unstable_next=function(a){switch(q){case 1:case 2:case 3:var b=3;break;default:b=q}var c=q;q=b;try{return a()}finally{q=c}};
exports.unstable_now=function(){return x};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=function(){I=!0};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=q;q=a;try{return b()}finally{q=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=x;"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:n++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(m,a),null===h(l)&&a===h(m)&&(w?(A=null,B=-1):w=!0,A=M,B=x+(c-d))):(a.sortIndex=e,f(l,a),t||r||(t=!0,y=N));return a};
exports.unstable_setDisableYieldValue=function(a){K=a};exports.unstable_shouldYield=O;exports.unstable_wrapCallback=function(a){var b=q;return function(){var c=q;q=b;try{return a.apply(this,arguments)}finally{q=c}}};exports.unstable_yieldValue=function(a){"disabledLog"===console.log.name||K||(null===C?C=[a]:C.push(a))};
/**
 * @license React
 * scheduler-unstable_post_task.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;

var perf = window.performance;
var setTimeout = window.setTimeout; // Use experimental Chrome Scheduler postTask API.

var scheduler = global.scheduler;
var getCurrentTime = perf.now.bind(perf);
var unstable_now = getCurrentTime; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.

var yieldInterval = 5;
var deadline = 0;
var currentPriorityLevel_DEPRECATED = NormalPriority; // `isInputPending` is not available. Since we have no way of knowing if
// there's pending input, always yield at the end of the frame.

function unstable_shouldYield() {
  return getCurrentTime() >= deadline;
}
function unstable_requestPaint() {// Since we yield every frame regardless, `requestPaint` has no effect.
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
  var postTaskPriority;

  switch (priorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
      postTaskPriority = 'user-blocking';
      break;

    case LowPriority:
    case NormalPriority:
      postTaskPriority = 'user-visible';
      break;

    case IdlePriority:
      postTaskPriority = 'background';
      break;

    default:
      postTaskPriority = 'user-visible';
      break;
  }

  var controller = new TaskController();
  var postTaskOptions = {
    priority: postTaskPriority,
    delay: typeof options === 'object' && options !== null ? options.delay : 0,
    signal: controller.signal
  };
  var node = {
    _controller: controller
  };
  scheduler.postTask(runTask.bind(null, priorityLevel, postTaskPriority, node, callback), postTaskOptions).catch(handleAbortError);
  return node;
}

function runTask(priorityLevel, postTaskPriority, node, callback) {
  deadline = getCurrentTime() + yieldInterval;

  try {
    currentPriorityLevel_DEPRECATED = priorityLevel;
    var _didTimeout_DEPRECATED = false;
    var result = callback(_didTimeout_DEPRECATED);

    if (typeof result === 'function') {
      // Assume this is a continuation
      var continuation = result;
      var continuationController = new TaskController();
      var continuationOptions = {
        priority: postTaskPriority,
        signal: continuationController.signal
      }; // Update the original callback node's controller, since even though we're
      // posting a new task, conceptually it's the same one.

      node._controller = continuationController;
      scheduler.postTask(runTask.bind(null, priorityLevel, postTaskPriority, node, continuation), continuationOptions).catch(handleAbortError);
    }
  } catch (error) {
    // We're inside a `postTask` promise. If we don't handle this error, then it
    // will trigger an "Unhandled promise rejection" error. We don't want that,
    // but we do want the default error reporting behavior that normal
    // (non-Promise) tasks get for unhandled errors.
    //
    // So we'll re-throw the error inside a regular browser task.
    setTimeout(function () {
      throw error;
    });
  } finally {
    currentPriorityLevel_DEPRECATED = NormalPriority;
  }
}

function handleAbortError(error) {// Abort errors are an implementation detail. We don't expose the
  // TaskController to the user, nor do we expose the promise that is returned
  // from `postTask`. So we should suppress them, since there's no way for the
  // user to handle them.
}

function unstable_cancelCallback(node) {
  var controller = node._controller;
  controller.abort();
}
function unstable_runWithPriority(priorityLevel, callback) {
  var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
  currentPriorityLevel_DEPRECATED = priorityLevel;

  try {
    return callback();
  } finally {
    currentPriorityLevel_DEPRECATED = previousPriorityLevel;
  }
}
function unstable_getCurrentPriorityLevel() {
  return currentPriorityLevel_DEPRECATED;
}
function unstable_next(callback) {
  var priorityLevel;

  switch (currentPriorityLevel_DEPRECATED) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
      // Shift down to normal priority
      priorityLevel = NormalPriority;
      break;

    default:
      // Anything lower than normal priority should remain at the current level.
      priorityLevel = currentPriorityLevel_DEPRECATED;
      break;
  }

  var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
  currentPriorityLevel_DEPRECATED = priorityLevel;

  try {
    return callback();
  } finally {
    currentPriorityLevel_DEPRECATED = previousPriorityLevel;
  }
}
function unstable_wrapCallback(callback) {
  var parentPriorityLevel = currentPriorityLevel_DEPRECATED;
  return function () {
    var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
    currentPriorityLevel_DEPRECATED = parentPriorityLevel;

    try {
      return callback();
    } finally {
      currentPriorityLevel_DEPRECATED = previousPriorityLevel;
    }
  };
}
function unstable_forceFrameRate() {}
function unstable_pauseExecution() {}
function unstable_continueExecution() {}
function unstable_getFirstCallbackNode() {
  return null;
} // Currently no profiling build

var unstable_Profiling = null;

exports.unstable_IdlePriority = IdlePriority;
exports.unstable_ImmediatePriority = ImmediatePriority;
exports.unstable_LowPriority = LowPriority;
exports.unstable_NormalPriority = NormalPriority;
exports.unstable_Profiling = unstable_Profiling;
exports.unstable_UserBlockingPriority = UserBlockingPriority;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_continueExecution = unstable_continueExecution;
exports.unstable_forceFrameRate = unstable_forceFrameRate;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
exports.unstable_next = unstable_next;
exports.unstable_now = unstable_now;
exports.unstable_pauseExecution = unstable_pauseExecution;
exports.unstable_requestPaint = unstable_requestPaint;
exports.unstable_runWithPriority = unstable_runWithPriority;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_shouldYield = unstable_shouldYield;
exports.unstable_wrapCallback = unstable_wrapCallback;
  })();
}
/**
 * @license React
 * scheduler-unstable_post_task.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';var a=window.performance,g=window.setTimeout,h=global.scheduler,k=a.now.bind(a),l=0,m=3;function p(c,d,b,f){l=k()+5;try{m=c;var e=f(!1);if("function"===typeof e){var n=new TaskController,r={priority:d,signal:n.signal};b._controller=n;h.postTask(p.bind(null,c,d,b,e),r).catch(q)}}catch(t){g(function(){throw t;})}finally{m=3}}function q(){}exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;
exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(c){c._controller.abort()};exports.unstable_continueExecution=function(){};exports.unstable_forceFrameRate=function(){};exports.unstable_getCurrentPriorityLevel=function(){return m};exports.unstable_getFirstCallbackNode=function(){return null};exports.unstable_next=function(c){switch(m){case 1:case 2:case 3:var d=3;break;default:d=m}var b=m;m=d;try{return c()}finally{m=b}};
exports.unstable_now=k;exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(c,d){var b=m;m=c;try{return d()}finally{m=b}};
exports.unstable_scheduleCallback=function(c,d,b){switch(c){case 1:case 2:var f="user-blocking";break;case 4:case 3:f="user-visible";break;case 5:f="background";break;default:f="user-visible"}var e=new TaskController;b={priority:f,delay:"object"===typeof b&&null!==b?b.delay:0,signal:e.signal};e={_controller:e};h.postTask(p.bind(null,c,f,e,d),b).catch(q);return e};exports.unstable_shouldYield=function(){return k()>=l};
exports.unstable_wrapCallback=function(c){var d=m;return function(){var b=m;m=d;try{return c()}finally{m=b}}};
/**
 * @license React
 * scheduler.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {

          'use strict';

/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
}
          var enableSchedulerDebugging = false;
var enableProfiling = false;
var frameYieldMs = 5;

function push(heap, node) {
  var index = heap.length;
  heap.push(node);
  siftUp(heap, node, index);
}
function peek(heap) {
  return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
  if (heap.length === 0) {
    return null;
  }

  var first = heap[0];
  var last = heap.pop();

  if (last !== first) {
    heap[0] = last;
    siftDown(heap, last, 0);
  }

  return first;
}

function siftUp(heap, node, i) {
  var index = i;

  while (index > 0) {
    var parentIndex = index - 1 >>> 1;
    var parent = heap[parentIndex];

    if (compare(parent, node) > 0) {
      // The parent is larger. Swap positions.
      heap[parentIndex] = node;
      heap[index] = parent;
      index = parentIndex;
    } else {
      // The parent is smaller. Exit.
      return;
    }
  }
}

function siftDown(heap, node, i) {
  var index = i;
  var length = heap.length;
  var halfLength = length >>> 1;

  while (index < halfLength) {
    var leftIndex = (index + 1) * 2 - 1;
    var left = heap[leftIndex];
    var rightIndex = leftIndex + 1;
    var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

    if (compare(left, node) < 0) {
      if (rightIndex < length && compare(right, left) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        heap[index] = left;
        heap[leftIndex] = node;
        index = leftIndex;
      }
    } else if (rightIndex < length && compare(right, node) < 0) {
      heap[index] = right;
      heap[rightIndex] = node;
      index = rightIndex;
    } else {
      // Neither child is smaller. Exit.
      return;
    }
  }
}

function compare(a, b) {
  // Compare sort index first, then task id.
  var diff = a.sortIndex - b.sortIndex;
  return diff !== 0 ? diff : a.id - b.id;
}

// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;

function markTaskErrored(task, ms) {
}

/* eslint-disable no-var */

var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';

if (hasPerformanceNow) {
  var localPerformance = performance;

  exports.unstable_now = function () {
    return localPerformance.now();
  };
} else {
  var localDate = Date;
  var initialTime = localDate.now();

  exports.unstable_now = function () {
    return localDate.now() - initialTime;
  };
} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111


var maxSigned31BitInt = 1073741823; // Times out immediately

var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.

var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.

var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom

var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;

function advanceTimers(currentTime) {
  // Check for tasks that are no longer delayed and add them to the queue.
  var timer = peek(timerQueue);

  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
    } else {
      // Remaining timers are pending.
      return;
    }

    timer = peek(timerQueue);
  }
}

function handleTimeout(currentTime) {
  isHostTimeoutScheduled = false;
  advanceTimers(currentTime);

  if (!isHostCallbackScheduled) {
    if (peek(taskQueue) !== null) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    } else {
      var firstTimer = peek(timerQueue);

      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }
    }
  }
}

function flushWork(hasTimeRemaining, initialTime) {


  isHostCallbackScheduled = false;

  if (isHostTimeoutScheduled) {
    // We scheduled a timeout but it's no longer needed. Cancel it.
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  var previousPriorityLevel = currentPriorityLevel;

  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);
      } catch (error) {
        if (currentTask !== null) {
          var currentTime = exports.unstable_now();
          markTaskErrored(currentTask, currentTime);
          currentTask.isQueued = false;
        }

        throw error;
      }
    } else {
      // No catch in prod code path.
      return workLoop(hasTimeRemaining, initialTime);
    }
  } finally {
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
  }
}

function workLoop(hasTimeRemaining, initialTime) {
  var currentTime = initialTime;
  advanceTimers(currentTime);
  currentTask = peek(taskQueue);

  while (currentTask !== null && !(enableSchedulerDebugging )) {
    if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
      // This currentTask hasn't expired, and we've reached the deadline.
      break;
    }

    var callback = currentTask.callback;

    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;

      var continuationCallback = callback(didUserCallbackTimeout);
      currentTime = exports.unstable_now();

      if (typeof continuationCallback === 'function') {
        currentTask.callback = continuationCallback;
      } else {

        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }

      advanceTimers(currentTime);
    } else {
      pop(taskQueue);
    }

    currentTask = peek(taskQueue);
  } // Return whether there's additional work


  if (currentTask !== null) {
    return true;
  } else {
    var firstTimer = peek(timerQueue);

    if (firstTimer !== null) {
      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
    }

    return false;
  }
}

function unstable_runWithPriority(priorityLevel, eventHandler) {
  switch (priorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
    case LowPriority:
    case IdlePriority:
      break;

    default:
      priorityLevel = NormalPriority;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_next(eventHandler) {
  var priorityLevel;

  switch (currentPriorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
      // Shift down to normal priority
      priorityLevel = NormalPriority;
      break;

    default:
      // Anything lower than normal priority should remain at the current level.
      priorityLevel = currentPriorityLevel;
      break;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_wrapCallback(callback) {
  var parentPriorityLevel = currentPriorityLevel;
  return function () {
    // This is a fork of runWithPriority, inlined for performance.
    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = parentPriorityLevel;

    try {
      return callback.apply(this, arguments);
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  };
}

function unstable_scheduleCallback(priorityLevel, callback, options) {
  var currentTime = exports.unstable_now();
  var startTime;

  if (typeof options === 'object' && options !== null) {
    var delay = options.delay;

    if (typeof delay === 'number' && delay > 0) {
      startTime = currentTime + delay;
    } else {
      startTime = currentTime;
    }
  } else {
    startTime = currentTime;
  }

  var timeout;

  switch (priorityLevel) {
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;

    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;

    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;

    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;

    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }

  var expirationTime = startTime + timeout;
  var newTask = {
    id: taskIdCounter++,
    callback: callback,
    priorityLevel: priorityLevel,
    startTime: startTime,
    expirationTime: expirationTime,
    sortIndex: -1
  };

  if (startTime > currentTime) {
    // This is a delayed task.
    newTask.sortIndex = startTime;
    push(timerQueue, newTask);

    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // All tasks are delayed, and this is the task with the earliest delay.
      if (isHostTimeoutScheduled) {
        // Cancel an existing timeout.
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      } // Schedule a timeout.


      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
    newTask.sortIndex = expirationTime;
    push(taskQueue, newTask);
    // wait until the next time we yield.


    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  return newTask;
}

function unstable_pauseExecution() {
}

function unstable_continueExecution() {

  if (!isHostCallbackScheduled && !isPerformingWork) {
    isHostCallbackScheduled = true;
    requestHostCallback(flushWork);
  }
}

function unstable_getFirstCallbackNode() {
  return peek(taskQueue);
}

function unstable_cancelCallback(task) {
  // remove from the queue because you can't remove arbitrary nodes from an
  // array based heap, only the first one.)


  task.callback = null;
}

function unstable_getCurrentPriorityLevel() {
  return currentPriorityLevel;
}

var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.

var frameInterval = frameYieldMs;
var startTime = -1;

function shouldYieldToHost() {
  var timeElapsed = exports.unstable_now() - startTime;

  if (timeElapsed < frameInterval) {
    // The main thread has only been blocked for a really short amount of time;
    // smaller than a single frame. Don't yield yet.
    return false;
  } // The main thread has been blocked for a non-negligible amount of time. We


  return true;
}

function requestPaint() {

}

function forceFrameRate(fps) {
  if (fps < 0 || fps > 125) {
    // Using console['error'] to evade Babel and ESLint
    console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
    return;
  }

  if (fps > 0) {
    frameInterval = Math.floor(1000 / fps);
  } else {
    // reset the framerate
    frameInterval = frameYieldMs;
  }
}

var performWorkUntilDeadline = function () {
  if (scheduledHostCallback !== null) {
    var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread
    // has been blocked.

    startTime = currentTime;
    var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
    // error can be observed.
    //
    // Intentionally not using a try-catch, since that makes some debugging
    // techniques harder. Instead, if `scheduledHostCallback` errors, then
    // `hasMoreWork` will remain true, and we'll continue the work loop.

    var hasMoreWork = true;

    try {
      hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
    } finally {
      if (hasMoreWork) {
        // If there's more work, schedule the next message event at the end
        // of the preceding one.
        schedulePerformWorkUntilDeadline();
      } else {
        isMessageLoopRunning = false;
        scheduledHostCallback = null;
      }
    }
  } else {
    isMessageLoopRunning = false;
  } // Yielding to the browser will give it a chance to paint, so we can
};

var schedulePerformWorkUntilDeadline;

if (typeof localSetImmediate === 'function') {
  // Node.js and old IE.
  // There's a few reasons for why we prefer setImmediate.
  //
  // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
  // (Even though this is a DOM fork of the Scheduler, you could get here
  // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
  // https://github.com/facebook/react/issues/20756
  //
  // But also, it runs earlier which is the semantic we want.
  // If other browsers ever implement it, it's better to use it.
  // Although both of these would be inferior to native scheduling.
  schedulePerformWorkUntilDeadline = function () {
    localSetImmediate(performWorkUntilDeadline);
  };
} else if (typeof MessageChannel !== 'undefined') {
  // DOM and Worker environments.
  // We prefer MessageChannel because of the 4ms setTimeout clamping.
  var channel = new MessageChannel();
  var port = channel.port2;
  channel.port1.onmessage = performWorkUntilDeadline;

  schedulePerformWorkUntilDeadline = function () {
    port.postMessage(null);
  };
} else {
  // We should only fallback here in non-browser environments.
  schedulePerformWorkUntilDeadline = function () {
    localSetTimeout(performWorkUntilDeadline, 0);
  };
}

function requestHostCallback(callback) {
  scheduledHostCallback = callback;

  if (!isMessageLoopRunning) {
    isMessageLoopRunning = true;
    schedulePerformWorkUntilDeadline();
  }
}

function requestHostTimeout(callback, ms) {
  taskTimeoutID = localSetTimeout(function () {
    callback(exports.unstable_now());
  }, ms);
}

function cancelHostTimeout() {
  localClearTimeout(taskTimeoutID);
  taskTimeoutID = -1;
}

var unstable_requestPaint = requestPaint;
var unstable_Profiling =  null;

exports.unstable_IdlePriority = IdlePriority;
exports.unstable_ImmediatePriority = ImmediatePriority;
exports.unstable_LowPriority = LowPriority;
exports.unstable_NormalPriority = NormalPriority;
exports.unstable_Profiling = unstable_Profiling;
exports.unstable_UserBlockingPriority = UserBlockingPriority;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_continueExecution = unstable_continueExecution;
exports.unstable_forceFrameRate = forceFrameRate;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
exports.unstable_next = unstable_next;
exports.unstable_pauseExecution = unstable_pauseExecution;
exports.unstable_requestPaint = unstable_requestPaint;
exports.unstable_runWithPriority = unstable_runWithPriority;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = unstable_wrapCallback;
          /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
    'function'
) {
  __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
        
  })();
}
/**
 * @license React
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;
"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}
function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;
function M(){return exports.unstable_now()-Q<P?!1:!0}function R(){if(null!==O){var a=exports.unstable_now();Q=a;var b=!0;try{b=O(!0,a)}finally{b?S():(N=!1,O=null)}}else N=!1}var S;if("function"===typeof F)S=function(){F(R)};else if("undefined"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null)}}else S=function(){D(R,0)};function I(a){O=a;N||(N=!0,S())}function K(a,b){L=D(function(){a(exports.unstable_now())},b)}
exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){A||z||(A=!0,I(J))};
exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<a?Math.floor(1E3/a):5};exports.unstable_getCurrentPriorityLevel=function(){return y};exports.unstable_getFirstCallbackNode=function(){return h(r)};exports.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y}var c=y;y=b;try{return a()}finally{y=c}};exports.unstable_pauseExecution=function(){};
exports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=y;y=a;try{return b()}finally{y=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};
exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'

// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
const constants = require('./internal/constants')
const SemVer = require('./classes/semver')
const identifiers = require('./internal/identifiers')
const parse = require('./functions/parse')
const valid = require('./functions/valid')
const clean = require('./functions/clean')
const inc = require('./functions/inc')
const diff = require('./functions/diff')
const major = require('./functions/major')
const minor = require('./functions/minor')
const patch = require('./functions/patch')
const prerelease = require('./functions/prerelease')
const compare = require('./functions/compare')
const rcompare = require('./functions/rcompare')
const compareLoose = require('./functions/compare-loose')
const compareBuild = require('./functions/compare-build')
const sort = require('./functions/sort')
const rsort = require('./functions/rsort')
const gt = require('./functions/gt')
const lt = require('./functions/lt')
const eq = require('./functions/eq')
const neq = require('./functions/neq')
const gte = require('./functions/gte')
const lte = require('./functions/lte')
const cmp = require('./functions/cmp')
const coerce = require('./functions/coerce')
const truncate = require('./functions/truncate')
const Comparator = require('./classes/comparator')
const Range = require('./classes/range')
const satisfies = require('./functions/satisfies')
const toComparators = require('./ranges/to-comparators')
const maxSatisfying = require('./ranges/max-satisfying')
const minSatisfying = require('./ranges/min-satisfying')
const minVersion = require('./ranges/min-version')
const validRange = require('./ranges/valid')
const outside = require('./ranges/outside')
const gtr = require('./ranges/gtr')
const ltr = require('./ranges/ltr')
const intersects = require('./ranges/intersects')
const simplifyRange = require('./ranges/simplify')
const subset = require('./ranges/subset')
module.exports = {
  parse,
  valid,
  clean,
  inc,
  diff,
  major,
  minor,
  patch,
  prerelease,
  compare,
  rcompare,
  compareLoose,
  compareBuild,
  sort,
  rsort,
  gt,
  lt,
  eq,
  neq,
  gte,
  lte,
  cmp,
  coerce,
  truncate,
  Comparator,
  Range,
  satisfies,
  toComparators,
  maxSatisfying,
  minSatisfying,
  minVersion,
  validRange,
  outside,
  gtr,
  ltr,
  intersects,
  simplifyRange,
  subset,
  SemVer,
  re: internalRe.re,
  src: internalRe.src,
  tokens: internalRe.t,
  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
  RELEASE_TYPES: constants.RELEASE_TYPES,
  compareIdentifiers: identifiers.compareIdentifiers,
  rcompareIdentifiers: identifiers.rcompareIdentifiers,
}
{
  "name": "semver",
  "version": "7.8.5",
  "description": "The semantic version parser used by npm.",
  "main": "index.js",
  "devDependencies": {
    "@npmcli/eslint-config": "^7.0.0",
    "@npmcli/template-oss": "5.0.0",
    "benchmark": "^2.1.4",
    "tap": "^16.0.0"
  },
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/node-semver.git"
  },
  "bin": {
    "semver": "bin/semver.js"
  },
  "files": [
    "bin/",
    "lib/",
    "classes/",
    "functions/",
    "internal/",
    "ranges/",
    "index.js",
    "preload.js",
    "range.bnf"
  ],
  "tap": {
    "timeout": 30,
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": ">=10"
  },
  "author": "GitHub Inc.",
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "5.0.0",
    "engines": ">=10",
    "distPaths": [
      "classes/",
      "functions/",
      "internal/",
      "ranges/",
      "index.js",
      "preload.js",
      "range.bnf"
    ],
    "allowPaths": [
      "/classes/",
      "/functions/",
      "/internal/",
      "/ranges/",
      "/index.js",
      "/preload.js",
      "/range.bnf",
      "/benchmarks"
    ],
    "publish": "true"
  }
}'use strict'

// XXX remove in v8 or beyond
module.exports = require('./index.js')
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | [1-9] ( [0-9] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= prepart ( '.' prepart ) *
prepart    ::= nr | alphanumid
build      ::= buildid ( '.' buildid ) *
alphanumid ::= ( [0-9] ) * [A-Za-z-] [-0-9A-Za-z] *
buildid    ::= [-0-9A-Za-z]+
'use strict'

// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr
'use strict'

const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
  r1 = new Range(r1, options)
  r2 = new Range(r2, options)
  return r1.intersects(r2, options)
}
module.exports = intersects
'use strict'

const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')

const maxSatisfying = (versions, range, options) => {
  let max = null
  let maxSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!max || maxSV.compare(v) === -1) {
        // compare(max, v, true)
        max = v
        maxSV = new SemVer(max, options)
      }
    }
  })
  return max
}
module.exports = maxSatisfying
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
  let min = null
  let minSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!min || minSV.compare(v) === 1) {
        // compare(min, v, true)
        min = v
        minSV = new SemVer(min, options)
      }
    }
  })
  return min
}
module.exports = minSatisfying
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')

const minVersion = (range, loose) => {
  range = new Range(range, loose)

  let minver = new SemVer('0.0.0')
  if (range.test(minver)) {
    return minver
  }

  minver = new SemVer('0.0.0-0')
  if (range.test(minver)) {
    return minver
  }

  minver = null
  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let setMin = null
    comparators.forEach((comparator) => {
      // Clone to avoid manipulating the comparator's semver object.
      const compver = new SemVer(comparator.semver.version)
      switch (comparator.operator) {
        case '>':
          if (compver.prerelease.length === 0) {
            compver.patch++
          } else {
            compver.prerelease.push(0)
          }
          compver.raw = compver.format()
          /* fallthrough */
        case '':
        case '>=':
          if (!setMin || gt(compver, setMin)) {
            setMin = compver
          }
          break
        case '<':
        case '<=':
          /* Ignore maximum versions */
          break
        /* istanbul ignore next */
        default:
          throw new Error(`Unexpected operation: ${comparator.operator}`)
      }
    })
    if (setMin && (!minver || gt(minver, setMin))) {
      minver = setMin
    }
  }

  if (minver && range.test(minver)) {
    return minver
  }

  return null
}
module.exports = minVersion
'use strict'

const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')

const outside = (version, range, hilo, options) => {
  version = new SemVer(version, options)
  range = new Range(range, options)

  let gtfn, ltefn, ltfn, comp, ecomp
  switch (hilo) {
    case '>':
      gtfn = gt
      ltefn = lte
      ltfn = lt
      comp = '>'
      ecomp = '>='
      break
    case '<':
      gtfn = lt
      ltefn = gte
      ltfn = gt
      comp = '<'
      ecomp = '<='
      break
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"')
  }

  // If it satisfies the range it is not outside
  if (satisfies(version, range, options)) {
    return false
  }

  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.

  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let high = null
    let low = null

    comparators.forEach((comparator) => {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator
      low = low || comparator
      if (gtfn(comparator.semver, high.semver, options)) {
        high = comparator
      } else if (ltfn(comparator.semver, low.semver, options)) {
        low = comparator
      }
    })

    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false
    }

    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false
    }
  }
  return true
}

module.exports = outside
'use strict'

// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
  const set = []
  let first = null
  let prev = null
  const v = versions.sort((a, b) => compare(a, b, options))
  for (const version of v) {
    const included = satisfies(version, range, options)
    if (included) {
      prev = version
      if (!first) {
        first = version
      }
    } else {
      if (prev) {
        set.push([first, prev])
      }
      prev = null
      first = null
    }
  }
  if (first) {
    set.push([first, null])
  }

  const ranges = []
  for (const [min, max] of set) {
    if (min === max) {
      ranges.push(min)
    } else if (!max && min === v[0]) {
      ranges.push('*')
    } else if (!max) {
      ranges.push(`>=${min}`)
    } else if (min === v[0]) {
      ranges.push(`<=${max}`)
    } else {
      ranges.push(`${min} - ${max}`)
    }
  }
  const simplified = ranges.join(' || ')
  const original = typeof range.raw === 'string' ? range.raw : String(range)
  return simplified.length < original.length ? simplified : range
}
'use strict'

const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')

// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
//   some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
//   - If C is only the ANY comparator, return true
//   - Else if in prerelease mode, return false
//   - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
//   - if in prerelease mode, return true
//   - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
//   - If GT, and EQ does not satisfy GT, return true (null set)
//   - If LT, and EQ does not satisfy LT, return true (null set)
//   - If EQ satisfies every C, return true
//   - Else return false
// - If GT
//   - If GT.semver is lower than any > or >= comp in C, return false
//   - If GT is >=, and GT.semver does not satisfy every C, return false
//   - If GT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
//   - If LT.semver is greater than any < or <= comp in C, return false
//   - If LT is <=, and LT.semver does not satisfy every C, return false
//   - If LT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true

const subset = (sub, dom, options = {}) => {
  if (sub === dom) {
    return true
  }

  sub = new Range(sub, options)
  dom = new Range(dom, options)
  let sawNonNull = false

  OUTER: for (const simpleSub of sub.set) {
    for (const simpleDom of dom.set) {
      const isSub = simpleSubset(simpleSub, simpleDom, options)
      sawNonNull = sawNonNull || isSub !== null
      if (isSub) {
        continue OUTER
      }
    }
    // the null set is a subset of everything, but null simple ranges in
    // a complex range should be ignored.  so if we saw a non-null range,
    // then we know this isn't a subset, but if EVERY simple range was null,
    // then it is a subset.
    if (sawNonNull) {
      return false
    }
  }
  return true
}

const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]

const simpleSubset = (sub, dom, options) => {
  if (sub === dom) {
    return true
  }

  if (sub.length === 1 && sub[0].semver === ANY) {
    if (dom.length === 1 && dom[0].semver === ANY) {
      return true
    } else if (options.includePrerelease) {
      sub = minimumVersionWithPreRelease
    } else {
      sub = minimumVersion
    }
  }

  if (dom.length === 1 && dom[0].semver === ANY) {
    if (options.includePrerelease) {
      return true
    } else {
      dom = minimumVersion
    }
  }

  const eqSet = new Set()
  let gt, lt
  for (const c of sub) {
    if (c.operator === '>' || c.operator === '>=') {
      gt = higherGT(gt, c, options)
    } else if (c.operator === '<' || c.operator === '<=') {
      lt = lowerLT(lt, c, options)
    } else {
      eqSet.add(c.semver)
    }
  }

  if (eqSet.size > 1) {
    return null
  }

  let gtltComp
  if (gt && lt) {
    gtltComp = compare(gt.semver, lt.semver, options)
    if (gtltComp > 0) {
      return null
    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
      return null
    }
  }

  // will iterate one or zero times
  for (const eq of eqSet) {
    if (gt && !satisfies(eq, String(gt), options)) {
      return null
    }

    if (lt && !satisfies(eq, String(lt), options)) {
      return null
    }

    for (const c of dom) {
      if (!satisfies(eq, String(c), options)) {
        return false
      }
    }

    return true
  }

  let higher, lower
  let hasDomLT, hasDomGT
  // if the subset has a prerelease, we need a comparator in the superset
  // with the same tuple and a prerelease, or it's not a subset
  let needDomLTPre = lt &&
    !options.includePrerelease &&
    lt.semver.prerelease.length ? lt.semver : false
  let needDomGTPre = gt &&
    !options.includePrerelease &&
    gt.semver.prerelease.length ? gt.semver : false
  // exception: <1.2.3-0 is the same as <1.2.3
  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
    needDomLTPre = false
  }

  for (const c of dom) {
    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
    if (gt) {
      if (needDomGTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomGTPre.major &&
            c.semver.minor === needDomGTPre.minor &&
            c.semver.patch === needDomGTPre.patch) {
          needDomGTPre = false
        }
      }
      if (c.operator === '>' || c.operator === '>=') {
        higher = higherGT(gt, c, options)
        if (higher === c && higher !== gt) {
          return false
        }
      } else if (gt.operator === '>=' && !c.test(gt.semver)) {
        return false
      }
    }
    if (lt) {
      if (needDomLTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomLTPre.major &&
            c.semver.minor === needDomLTPre.minor &&
            c.semver.patch === needDomLTPre.patch) {
          needDomLTPre = false
        }
      }
      if (c.operator === '<' || c.operator === '<=') {
        lower = lowerLT(lt, c, options)
        if (lower === c && lower !== lt) {
          return false
        }
      } else if (lt.operator === '<=' && !c.test(lt.semver)) {
        return false
      }
    }
    if (!c.operator && (lt || gt) && gtltComp !== 0) {
      return false
    }
  }

  // if there was a < or >, and nothing in the dom, then must be false
  // UNLESS it was limited by another range in the other direction.
  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
  if (gt && hasDomLT && !lt && gtltComp !== 0) {
    return false
  }

  if (lt && hasDomGT && !gt && gtltComp !== 0) {
    return false
  }

  // we needed a prerelease range in a specific tuple, but didn't get one
  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,
  // because it includes prereleases in the 1.2.3 tuple
  if (needDomGTPre || needDomLTPre) {
    return false
  }

  return true
}

// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp > 0 ? a
    : comp < 0 ? b
    : b.operator === '>' && a.operator === '>=' ? b
    : a
}

// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp < 0 ? a
    : comp > 0 ? b
    : b.operator === '<' && a.operator === '<=' ? b
    : a
}

module.exports = subset
'use strict'

const Range = require('../classes/range')

// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
  new Range(range, options).set
    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))

module.exports = toComparators
'use strict'

const Range = require('../classes/range')
const validRange = (range, options) => {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, options).range || '*'
  } catch (er) {
    return null
  }
}
module.exports = validRange
'use strict'

// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'

const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991

// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16

// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6

const RELEASE_TYPES = [
  'major',
  'premajor',
  'minor',
  'preminor',
  'patch',
  'prepatch',
  'prerelease',
]

module.exports = {
  MAX_LENGTH,
  MAX_SAFE_COMPONENT_LENGTH,
  MAX_SAFE_BUILD_LENGTH,
  MAX_SAFE_INTEGER,
  RELEASE_TYPES,
  SEMVER_SPEC_VERSION,
  FLAG_INCLUDE_PRERELEASE: 0b001,
  FLAG_LOOSE: 0b010,
}
'use strict'

const debug = (
  typeof process === 'object' &&
  process.env &&
  process.env.NODE_DEBUG &&
  /\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
  : () => {}

module.exports = debug
'use strict'

const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
  if (typeof a === 'number' && typeof b === 'number') {
    return a === b ? 0 : a < b ? -1 : 1
  }

  const anum = numeric.test(a)
  const bnum = numeric.test(b)

  if (anum && bnum) {
    a = +a
    b = +b
  }

  return a === b ? 0
    : (anum && !bnum) ? -1
    : (bnum && !anum) ? 1
    : a < b ? -1
    : 1
}

const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)

module.exports = {
  compareIdentifiers,
  rcompareIdentifiers,
}
'use strict'

class LRUCache {
  constructor () {
    this.max = 1000
    this.map = new Map()
  }

  get (key) {
    const value = this.map.get(key)
    if (value === undefined) {
      return undefined
    } else {
      // Remove the key from the map and add it to the end
      this.map.delete(key)
      this.map.set(key, value)
      return value
    }
  }

  delete (key) {
    return this.map.delete(key)
  }

  set (key, value) {
    const deleted = this.delete(key)

    if (!deleted && value !== undefined) {
      // If cache is full, delete the least recently used item
      if (this.map.size >= this.max) {
        const firstKey = this.map.keys().next().value
        this.delete(firstKey)
      }

      this.map.set(key, value)
    }

    return this
  }
}

module.exports = LRUCache
'use strict'

// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
  if (!options) {
    return emptyOpts
  }

  if (typeof options !== 'object') {
    return looseOption
  }

  return options
}
module.exports = parseOptions
'use strict'

const {
  MAX_SAFE_COMPONENT_LENGTH,
  MAX_SAFE_BUILD_LENGTH,
  MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}

// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const safeSrc = exports.safeSrc = []
const t = exports.t = {}
let R = 0

const LETTERDASHNUMBER = '[a-zA-Z0-9-]'

// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
  ['\\s', 1],
  ['\\d', MAX_LENGTH],
  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]

const makeSafeRegex = (value) => {
  for (const [token, max] of safeRegexReplacements) {
    value = value
      .split(`${token}*`).join(`${token}{0,${max}}`)
      .split(`${token}+`).join(`${token}{1,${max}}`)
  }
  return value
}

const createToken = (name, value, isGlobal) => {
  const safe = makeSafeRegex(value)
  const index = R++
  debug(name, index, value)
  t[name] = index
  src[index] = value
  safeSrc[index] = safe
  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}

// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.

// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.

createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')

// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.

createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)

// ## Main Version
// Three dot-separated numeric identifiers.

createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})`)

createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)

// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numeric identifiers include numeric identifiers but can be longer.
// Therefore non-numeric identifiers must go first.

createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIER]})`)

createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIERLOOSE]})`)

// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.

createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)

createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)

// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.

createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)

// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.

createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)

// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.

// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.

createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
  src[t.BUILD]}?`)

createToken('FULL', `^${src[t.FULLPLAIN]}$`)

// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
  src[t.BUILD]}?`)

createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)

createToken('GTLT', '((?:<|>)?=?)')

// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifier, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)

createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:${src[t.PRERELEASE]})?${
                     src[t.BUILD]}?` +
                   `)?)?`)

createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:${src[t.PRERELEASELOOSE]})?${
                          src[t.BUILD]}?` +
                        `)?)?`)

createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)

// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
              `(?:${src[t.PRERELEASE]})?` +
              `(?:${src[t.BUILD]})?` +
              `(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)

// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')

createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'

createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)

// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')

createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'

createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)

// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)

// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'

// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
                   `\\s+-\\s+` +
                   `(${src[t.XRANGEPLAIN]})` +
                   `\\s*$`)

createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s+-\\s+` +
                        `(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s*$`)

// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
'use strict'

const parse = require('./parse')
const clean = (version, options) => {
  const s = parse(version.trim().replace(/^[=v]+/, ''), options)
  return s ? s.version : null
}
module.exports = clean
'use strict'

const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')

const cmp = (a, op, b, loose) => {
  switch (op) {
    case '===':
      if (typeof a === 'object') {
        a = a.version
      }
      if (typeof b === 'object') {
        b = b.version
      }
      return a === b

    case '!==':
      if (typeof a === 'object') {
        a = a.version
      }
      if (typeof b === 'object') {
        b = b.version
      }
      return a !== b

    case '':
    case '=':
    case '==':
      return eq(a, b, loose)

    case '!=':
      return neq(a, b, loose)

    case '>':
      return gt(a, b, loose)

    case '>=':
      return gte(a, b, loose)

    case '<':
      return lt(a, b, loose)

    case '<=':
      return lte(a, b, loose)

    default:
      throw new TypeError(`Invalid operator: ${op}`)
  }
}
module.exports = cmp
'use strict'

const SemVer = require('../classes/semver')
const parse = require('./parse')
const { safeRe: re, t } = require('../internal/re')

const coerce = (version, options) => {
  if (version instanceof SemVer) {
    return version
  }

  if (typeof version === 'number') {
    version = String(version)
  }

  if (typeof version !== 'string') {
    return null
  }

  options = options || {}

  let match = null
  if (!options.rtl) {
    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
  } else {
    // Find the right-most coercible string that does not share
    // a terminus with a more left-ward coercible string.
    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
    //
    // Walk through the string checking with a /g regexp
    // Manually set the index so as to pick up overlapping matches.
    // Stop when we get a match that ends at the string end, since no
    // coercible string can be more right-ward without the same terminus.
    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
    let next
    while ((next = coerceRtlRegex.exec(version)) &&
        (!match || match.index + match[0].length !== version.length)
    ) {
      if (!match ||
            next.index + next[0].length !== match.index + match[0].length) {
        match = next
      }
      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
    }
    // leave it in a clean state
    coerceRtlRegex.lastIndex = -1
  }

  if (match === null) {
    return null
  }

  const major = match[2]
  const minor = match[3] || '0'
  const patch = match[4] || '0'
  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''

  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
module.exports = coerce
'use strict'

const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
  const versionA = new SemVer(a, loose)
  const versionB = new SemVer(b, loose)
  return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild
'use strict'

const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose
'use strict'

const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
  new SemVer(a, loose).compare(new SemVer(b, loose))

module.exports = compare
'use strict'

const parse = require('./parse.js')

const diff = (version1, version2) => {
  const v1 = parse(version1, null, true)
  const v2 = parse(version2, null, true)
  const comparison = v1.compare(v2)

  if (comparison === 0) {
    return null
  }

  const v1Higher = comparison > 0
  const highVersion = v1Higher ? v1 : v2
  const lowVersion = v1Higher ? v2 : v1
  const highHasPre = !!highVersion.prerelease.length
  const lowHasPre = !!lowVersion.prerelease.length

  if (lowHasPre && !highHasPre) {
    // Going from prerelease -> no prerelease requires some special casing

    // If the low version has only a major, then it will always be a major
    // Some examples:
    // 1.0.0-1 -> 1.0.0
    // 1.0.0-1 -> 1.1.1
    // 1.0.0-1 -> 2.0.0
    if (!lowVersion.patch && !lowVersion.minor) {
      return 'major'
    }

    // If the main part has no difference
    if (lowVersion.compareMain(highVersion) === 0) {
      if (lowVersion.minor && !lowVersion.patch) {
        return 'minor'
      }
      return 'patch'
    }
  }

  // add the `pre` prefix if we are going to a prerelease version
  const prefix = highHasPre ? 'pre' : ''

  if (v1.major !== v2.major) {
    return prefix + 'major'
  }

  if (v1.minor !== v2.minor) {
    return prefix + 'minor'
  }

  if (v1.patch !== v2.patch) {
    return prefix + 'patch'
  }

  // high and low are prereleases
  return 'prerelease'
}

module.exports = diff
'use strict'

const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
'use strict'

const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt
'use strict'

const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte
'use strict'

const SemVer = require('../classes/semver')

const inc = (version, release, options, identifier, identifierBase) => {
  if (typeof (options) === 'string') {
    identifierBase = identifier
    identifier = options
    options = undefined
  }

  try {
    return new SemVer(
      version instanceof SemVer ? version.version : version,
      options
    ).inc(release, identifier, identifierBase).version
  } catch (er) {
    return null
  }
}
module.exports = inc
'use strict'

const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt
'use strict'

const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte
'use strict'

const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major
'use strict'

const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor
'use strict'

const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq
'use strict'

const SemVer = require('../classes/semver')
const parse = (version, options, throwErrors = false) => {
  if (version instanceof SemVer) {
    return version
  }
  try {
    return new SemVer(version, options)
  } catch (er) {
    if (!throwErrors) {
      return null
    }
    throw er
  }
}

module.exports = parse
'use strict'

const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
'use strict'

const parse = require('./parse')
const prerelease = (version, options) => {
  const parsed = parse(version, options)
  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease
'use strict'

const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare
'use strict'

const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort
'use strict'

const Range = require('../classes/range')
const satisfies = (version, range, options) => {
  try {
    range = new Range(range, options)
  } catch (er) {
    return false
  }
  return range.test(version)
}
module.exports = satisfies
'use strict'

const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort
'use strict'

const parse = require('./parse')
const constants = require('../internal/constants')
const SemVer = require('../classes/semver')

const truncate = (version, truncation, options) => {
  if (!constants.RELEASE_TYPES.includes(truncation)) {
    return null
  }

  const clonedVersion = cloneInputVersion(version, options)
  return clonedVersion && doTruncation(clonedVersion, truncation)
}

const cloneInputVersion = (version, options) => {
  const versionStringToParse = (
    version instanceof SemVer ? version.version : version
  )

  return parse(versionStringToParse, options)
}

const doTruncation = (version, truncation) => {
  if (isPrerelease(truncation)) {
    return version.version
  }

  version.prerelease = []

  switch (truncation) {
    case 'major':
      version.minor = 0
      version.patch = 0
      break
    case 'minor':
      version.patch = 0
      break
  }

  return version.format()
}

const isPrerelease = (type) => {
  return type.startsWith('pre')
}

module.exports = truncate
'use strict'

const parse = require('./parse')
const valid = (version, options) => {
  const v = parse(version, options)
  return v ? v.version : null
}
module.exports = valid
'use strict'

const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
  static get ANY () {
    return ANY
  }

  constructor (comp, options) {
    options = parseOptions(options)

    if (comp instanceof Comparator) {
      if (comp.loose === !!options.loose) {
        return comp
      } else {
        comp = comp.value
      }
    }

    comp = comp.trim().split(/\s+/).join(' ')
    debug('comparator', comp, options)
    this.options = options
    this.loose = !!options.loose
    this.parse(comp)

    if (this.semver === ANY) {
      this.value = ''
    } else {
      this.value = this.operator + this.semver.version
    }

    debug('comp', this)
  }

  parse (comp) {
    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
    const m = comp.match(r)

    if (!m) {
      throw new TypeError(`Invalid comparator: ${comp}`)
    }

    this.operator = m[1] !== undefined ? m[1] : ''
    if (this.operator === '=') {
      this.operator = ''
    }

    // if it literally is just '>' or '' then allow anything.
    if (!m[2]) {
      this.semver = ANY
    } else {
      this.semver = new SemVer(m[2], this.options.loose)
    }
  }

  toString () {
    return this.value
  }

  test (version) {
    debug('Comparator.test', version, this.options.loose)

    if (this.semver === ANY || version === ANY) {
      return true
    }

    if (typeof version === 'string') {
      try {
        version = new SemVer(version, this.options)
      } catch (er) {
        return false
      }
    }

    return cmp(version, this.operator, this.semver, this.options)
  }

  intersects (comp, options) {
    if (!(comp instanceof Comparator)) {
      throw new TypeError('a Comparator is required')
    }

    if (this.operator === '') {
      if (this.value === '') {
        return true
      }
      return new Range(comp.value, options).test(this.value)
    } else if (comp.operator === '') {
      if (comp.value === '') {
        return true
      }
      return new Range(this.value, options).test(comp.semver)
    }

    options = parseOptions(options)

    // Special cases where nothing can possibly be lower
    if (options.includePrerelease &&
      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
      return false
    }
    if (!options.includePrerelease &&
      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
      return false
    }

    // Same direction increasing (> or >=)
    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
      return true
    }
    // Same direction decreasing (< or <=)
    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
      return true
    }
    // same SemVer and both sides are inclusive (<= or >=)
    if (
      (this.semver.version === comp.semver.version) &&
      this.operator.includes('=') && comp.operator.includes('=')) {
      return true
    }
    // opposite directions less than
    if (cmp(this.semver, '<', comp.semver, options) &&
      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
      return true
    }
    // opposite directions greater than
    if (cmp(this.semver, '>', comp.semver, options) &&
      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
      return true
    }
    return false
  }
}

module.exports = Comparator

const parseOptions = require('../internal/parse-options')
const { safeRe: re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')
'use strict'

module.exports = {
  SemVer: require('./semver.js'),
  Range: require('./range.js'),
  Comparator: require('./comparator.js'),
}
'use strict'

const SPACE_CHARACTERS = /\s+/g

// hoisted class for cyclic dependency
class Range {
  constructor (range, options) {
    options = parseOptions(options)

    if (range instanceof Range) {
      if (
        range.loose === !!options.loose &&
        range.includePrerelease === !!options.includePrerelease
      ) {
        return range
      } else {
        return new Range(range.raw, options)
      }
    }

    if (range instanceof Comparator) {
      // just put it in the set and return
      this.raw = range.value
      this.set = [[range]]
      this.formatted = undefined
      return this
    }

    this.options = options
    this.loose = !!options.loose
    this.includePrerelease = !!options.includePrerelease

    // First reduce all whitespace as much as possible so we do not have to rely
    // on potentially slow regexes like \s*. This is then stored and used for
    // future error messages as well.
    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')

    // First, split on ||
    this.set = this.raw
      .split('||')
      // map the range to a 2d array of comparators
      .map(r => this.parseRange(r.trim()))
      // throw out any comparator lists that are empty
      // this generally means that it was not a valid range, which is allowed
      // in loose mode, but will still throw if the WHOLE range is invalid.
      .filter(c => c.length)

    if (!this.set.length) {
      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
    }

    // if we have any that are not the null set, throw out null sets.
    if (this.set.length > 1) {
      // keep the first one, in case they're all null sets
      const first = this.set[0]
      this.set = this.set.filter(c => !isNullSet(c[0]))
      if (this.set.length === 0) {
        this.set = [first]
      } else if (this.set.length > 1) {
        // if we have any that are *, then the range is just *
        for (const c of this.set) {
          if (c.length === 1 && isAny(c[0])) {
            this.set = [c]
            break
          }
        }
      }
    }

    this.formatted = undefined
  }

  get range () {
    if (this.formatted === undefined) {
      this.formatted = ''
      for (let i = 0; i < this.set.length; i++) {
        if (i > 0) {
          this.formatted += '||'
        }
        const comps = this.set[i]
        for (let k = 0; k < comps.length; k++) {
          if (k > 0) {
            this.formatted += ' '
          }
          this.formatted += comps[k].toString().trim()
        }
      }
    }
    return this.formatted
  }

  format () {
    return this.range
  }

  toString () {
    return this.range
  }

  parseRange (range) {
    // strip build metadata so it can't bleed into the version
    range = range.replace(BUILDSTRIPRE, '')

    // memoize range parsing for performance.
    // this is a very hot path, and fully deterministic.
    const memoOpts =
      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
      (this.options.loose && FLAG_LOOSE)
    const memoKey = memoOpts + ':' + range
    const cached = cache.get(memoKey)
    if (cached) {
      return cached
    }

    const loose = this.options.loose
    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
    debug('hyphen replace', range)

    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
    debug('comparator trim', range)

    // `~ 1.2.3` => `~1.2.3`
    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
    debug('tilde trim', range)

    // `^ 1.2.3` => `^1.2.3`
    range = range.replace(re[t.CARETTRIM], caretTrimReplace)
    debug('caret trim', range)

    // At this point, the range is completely trimmed and
    // ready to be split into comparators.

    let rangeList = range
      .split(' ')
      .map(comp => parseComparator(comp, this.options))
      .join(' ')
      .split(/\s+/)
      // >=0.0.0 is equivalent to *
      .map(comp => replaceGTE0(comp, this.options))

    if (loose) {
      // in loose mode, throw out any that are not valid comparators
      rangeList = rangeList.filter(comp => {
        debug('loose invalid filter', comp, this.options)
        return !!comp.match(re[t.COMPARATORLOOSE])
      })
    }
    debug('range list', rangeList)

    // if any comparators are the null set, then replace with JUST null set
    // if more than one comparator, remove any * comparators
    // also, don't include the same comparator more than once
    const rangeMap = new Map()
    const comparators = rangeList.map(comp => new Comparator(comp, this.options))
    for (const comp of comparators) {
      if (isNullSet(comp)) {
        return [comp]
      }
      rangeMap.set(comp.value, comp)
    }
    if (rangeMap.size > 1 && rangeMap.has('')) {
      rangeMap.delete('')
    }

    const result = [...rangeMap.values()]
    cache.set(memoKey, result)
    return result
  }

  intersects (range, options) {
    if (!(range instanceof Range)) {
      throw new TypeError('a Range is required')
    }

    return this.set.some((thisComparators) => {
      return (
        isSatisfiable(thisComparators, options) &&
        range.set.some((rangeComparators) => {
          return (
            isSatisfiable(rangeComparators, options) &&
            thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options)
              })
            })
          )
        })
      )
    })
  }

  // if ANY of the sets match ALL of its comparators, then pass
  test (version) {
    if (!version) {
      return false
    }

    if (typeof version === 'string') {
      try {
        version = new SemVer(version, this.options)
      } catch (er) {
        return false
      }
    }

    for (let i = 0; i < this.set.length; i++) {
      if (testSet(this.set[i], version, this.options)) {
        return true
      }
    }
    return false
  }
}

module.exports = Range

const LRU = require('../internal/lrucache')
const cache = new LRU()

const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
  safeRe: re,
  src,
  t,
  comparatorTrimReplace,
  tildeTrimReplace,
  caretTrimReplace,
} = require('../internal/re')
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')

// unbounded global build-metadata stripper used by parseRange
const BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')

const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''

// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
  let result = true
  const remainingComparators = comparators.slice()
  let testComparator = remainingComparators.pop()

  while (result && remainingComparators.length) {
    result = remainingComparators.every((otherComparator) => {
      return testComparator.intersects(otherComparator, options)
    })

    testComparator = remainingComparators.pop()
  }

  return result
}

// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
  comp = comp.replace(re[t.BUILD], '')
  debug('comp', comp, options)
  comp = replaceCarets(comp, options)
  debug('caret', comp)
  comp = replaceTildes(comp, options)
  debug('tildes', comp)
  comp = replaceXRanges(comp, options)
  debug('xrange', comp)
  comp = replaceStars(comp, options)
  debug('stars', comp)
  return comp
}

const isX = id => !id || id.toLowerCase() === 'x' || id === '*'

const invalidXRangeOrder = (M, m, p) => (
  (isX(M) && !isX(m)) ||
  (isX(m) && p && !isX(p))
)

// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
  return comp
    .trim()
    .split(/\s+/)
    .map((c) => replaceTilde(c, options))
    .join(' ')
}

const replaceTilde = (comp, options) => {
  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
  // if we're including prereleases in the match, then the lower bound is
  // -0, the lowest possible prerelease value, just like x-ranges and carets.
  // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.
  const z = options.includePrerelease ? '-0' : ''
  return comp.replace(r, (_, M, m, p, pr) => {
    debug('tilde', comp, _, M, m, p, pr)
    let ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
    } else if (isX(p)) {
      // ~1.2 == >=1.2.0 <1.3.0-0
      ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
    } else if (pr) {
      debug('replaceTilde pr', pr)
      ret = `>=${M}.${m}.${p}-${pr
      } <${M}.${+m + 1}.0-0`
    } else {
      // ~1.2.3 == >=1.2.3 <1.3.0-0
      ret = `>=${M}.${m}.${p
      } <${M}.${+m + 1}.0-0`
    }

    debug('tilde return', ret)
    return ret
  })
}

// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
  return comp
    .trim()
    .split(/\s+/)
    .map((c) => replaceCaret(c, options))
    .join(' ')
}

const replaceCaret = (comp, options) => {
  debug('caret', comp, options)
  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
  const z = options.includePrerelease ? '-0' : ''
  return comp.replace(r, (_, M, m, p, pr) => {
    debug('caret', comp, _, M, m, p, pr)
    let ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
    } else if (isX(p)) {
      if (M === '0') {
        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
      } else {
        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
      }
    } else if (pr) {
      debug('replaceCaret pr', pr)
      if (M === '0') {
        if (m === '0') {
          ret = `>=${M}.${m}.${p}-${pr
          } <${M}.${m}.${+p + 1}-0`
        } else {
          ret = `>=${M}.${m}.${p}-${pr
          } <${M}.${+m + 1}.0-0`
        }
      } else {
        ret = `>=${M}.${m}.${p}-${pr
        } <${+M + 1}.0.0-0`
      }
    } else {
      debug('no pr')
      if (M === '0') {
        if (m === '0') {
          ret = `>=${M}.${m}.${p
          } <${M}.${m}.${+p + 1}-0`
        } else {
          ret = `>=${M}.${m}.${p
          } <${M}.${+m + 1}.0-0`
        }
      } else {
        ret = `>=${M}.${m}.${p
        } <${+M + 1}.0.0-0`
      }
    }

    debug('caret return', ret)
    return ret
  })
}

const replaceXRanges = (comp, options) => {
  debug('replaceXRanges', comp, options)
  return comp
    .split(/\s+/)
    .map((c) => replaceXRange(c, options))
    .join(' ')
}

const replaceXRange = (comp, options) => {
  comp = comp.trim()
  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
    debug('xRange', comp, ret, gtlt, M, m, p, pr)
    if (invalidXRangeOrder(M, m, p)) {
      return comp
    }

    const xM = isX(M)
    const xm = xM || isX(m)
    const xp = xm || isX(p)
    const anyX = xp

    if (gtlt === '=' && anyX) {
      gtlt = ''
    }

    // if we're including prereleases in the match, then we need
    // to fix this to -0, the lowest possible prerelease value
    pr = options.includePrerelease ? '-0' : ''

    if (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0-0'
      } else {
        // nothing is forbidden
        ret = '*'
      }
    } else if (gtlt && anyX) {
      // we know patch is an x, because we have any x at all.
      // replace X with 0
      if (xm) {
        m = 0
      }
      p = 0

      if (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        gtlt = '>='
        if (xm) {
          M = +M + 1
          m = 0
          p = 0
        } else {
          m = +m + 1
          p = 0
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<'
        if (xm) {
          M = +M + 1
        } else {
          m = +m + 1
        }
      }

      if (gtlt === '<') {
        pr = '-0'
      }

      ret = `${gtlt + M}.${m}.${p}${pr}`
    } else if (xm) {
      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
    } else if (xp) {
      ret = `>=${M}.${m}.0${pr
      } <${M}.${+m + 1}.0-0`
    }

    debug('xRange return', ret)

    return ret
  })
}

// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
  debug('replaceStars', comp, options)
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp
    .trim()
    .replace(re[t.STAR], '')
}

const replaceGTE0 = (comp, options) => {
  debug('replaceGTE0', comp, options)
  return comp
    .trim()
    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}

// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
// TODO build?
const hyphenReplace = incPr => ($0,
  from, fM, fm, fp, fpr, fb,
  to, tM, tm, tp, tpr) => {
  if (isX(fM)) {
    from = ''
  } else if (isX(fm)) {
    from = `>=${fM}.0.0${incPr ? '-0' : ''}`
  } else if (isX(fp)) {
    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
  } else if (fpr) {
    from = `>=${from}`
  } else {
    from = `>=${from}${incPr ? '-0' : ''}`
  }

  if (isX(tM)) {
    to = ''
  } else if (isX(tm)) {
    to = `<${+tM + 1}.0.0-0`
  } else if (isX(tp)) {
    to = `<${tM}.${+tm + 1}.0-0`
  } else if (tpr) {
    to = `<=${tM}.${tm}.${tp}-${tpr}`
  } else if (incPr) {
    to = `<${tM}.${tm}.${+tp + 1}-0`
  } else {
    to = `<=${to}`
  }

  return `${from} ${to}`.trim()
}

const testSet = (set, version, options) => {
  for (let i = 0; i < set.length; i++) {
    if (!set[i].test(version)) {
      return false
    }
  }

  if (version.prerelease.length && !options.includePrerelease) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (let i = 0; i < set.length; i++) {
      debug(set[i].semver)
      if (set[i].semver === Comparator.ANY) {
        continue
      }

      if (set[i].semver.prerelease.length > 0) {
        const allowed = set[i].semver
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch) {
          return true
        }
      }
    }

    // Version has a -pre, but it's not one of the ones we like.
    return false
  }

  return true
}
'use strict'

const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { safeRe: re, t } = require('../internal/re')

const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')

const isPrereleaseIdentifier = (prerelease, identifier) => {
  const identifiers = identifier.split('.')
  if (identifiers.length > prerelease.length) {
    return false
  }

  for (let i = 0; i < identifiers.length; i++) {
    if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {
      return false
    }
  }

  return true
}

class SemVer {
  constructor (version, options) {
    options = parseOptions(options)

    if (version instanceof SemVer) {
      if (version.loose === !!options.loose &&
        version.includePrerelease === !!options.includePrerelease) {
        return version
      } else {
        version = version.version
      }
    } else if (typeof version !== 'string') {
      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
    }

    if (version.length > MAX_LENGTH) {
      throw new TypeError(
        `version is longer than ${MAX_LENGTH} characters`
      )
    }

    debug('SemVer', version, options)
    this.options = options
    this.loose = !!options.loose
    // this isn't actually relevant for versions, but keep it so that we
    // don't run into trouble passing this.options around.
    this.includePrerelease = !!options.includePrerelease

    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])

    if (!m) {
      throw new TypeError(`Invalid Version: ${version}`)
    }

    this.raw = version

    // these are actually numbers
    this.major = +m[1]
    this.minor = +m[2]
    this.patch = +m[3]

    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
      throw new TypeError('Invalid major version')
    }

    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
      throw new TypeError('Invalid minor version')
    }

    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
      throw new TypeError('Invalid patch version')
    }

    // numberify any prerelease numeric ids
    if (!m[4]) {
      this.prerelease = []
    } else {
      this.prerelease = m[4].split('.').map((id) => {
        if (/^[0-9]+$/.test(id)) {
          const num = +id
          if (num >= 0 && num < MAX_SAFE_INTEGER) {
            return num
          }
        }
        return id
      })
    }

    this.build = m[5] ? m[5].split('.') : []
    this.format()
  }

  format () {
    this.version = `${this.major}.${this.minor}.${this.patch}`
    if (this.prerelease.length) {
      this.version += `-${this.prerelease.join('.')}`
    }
    return this.version
  }

  toString () {
    return this.version
  }

  compare (other) {
    debug('SemVer.compare', this.version, this.options, other)
    if (!(other instanceof SemVer)) {
      if (typeof other === 'string' && other === this.version) {
        return 0
      }
      other = new SemVer(other, this.options)
    }

    if (other.version === this.version) {
      return 0
    }

    return this.compareMain(other) || this.comparePre(other)
  }

  compareMain (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    if (this.major < other.major) {
      return -1
    }
    if (this.major > other.major) {
      return 1
    }
    if (this.minor < other.minor) {
      return -1
    }
    if (this.minor > other.minor) {
      return 1
    }
    if (this.patch < other.patch) {
      return -1
    }
    if (this.patch > other.patch) {
      return 1
    }
    return 0
  }

  comparePre (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    // NOT having a prerelease is > having one
    if (this.prerelease.length && !other.prerelease.length) {
      return -1
    } else if (!this.prerelease.length && other.prerelease.length) {
      return 1
    } else if (!this.prerelease.length && !other.prerelease.length) {
      return 0
    }

    let i = 0
    do {
      const a = this.prerelease[i]
      const b = other.prerelease[i]
      debug('prerelease compare', i, a, b)
      if (a === undefined && b === undefined) {
        return 0
      } else if (b === undefined) {
        return 1
      } else if (a === undefined) {
        return -1
      } else if (a === b) {
        continue
      } else {
        return compareIdentifiers(a, b)
      }
    } while (++i)
  }

  compareBuild (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    let i = 0
    do {
      const a = this.build[i]
      const b = other.build[i]
      debug('build compare', i, a, b)
      if (a === undefined && b === undefined) {
        return 0
      } else if (b === undefined) {
        return 1
      } else if (a === undefined) {
        return -1
      } else if (a === b) {
        continue
      } else {
        return compareIdentifiers(a, b)
      }
    } while (++i)
  }

  // preminor will bump the version up to the next minor release, and immediately
  // down to pre-release. premajor and prepatch work the same way.
  inc (release, identifier, identifierBase) {
    if (release.startsWith('pre')) {
      if (!identifier && identifierBase === false) {
        throw new Error('invalid increment argument: identifier is empty')
      }
      // Avoid an invalid semver results
      if (identifier) {
        const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
        if (!match || match[1] !== identifier) {
          throw new Error(`invalid identifier: ${identifier}`)
        }
      }
    }

    switch (release) {
      case 'premajor':
        this.prerelease.length = 0
        this.patch = 0
        this.minor = 0
        this.major++
        this.inc('pre', identifier, identifierBase)
        break
      case 'preminor':
        this.prerelease.length = 0
        this.patch = 0
        this.minor++
        this.inc('pre', identifier, identifierBase)
        break
      case 'prepatch':
        // If this is already a prerelease, it will bump to the next version
        // drop any prereleases that might already exist, since they are not
        // relevant at this point.
        this.prerelease.length = 0
        this.inc('patch', identifier, identifierBase)
        this.inc('pre', identifier, identifierBase)
        break
      // If the input is a non-prerelease version, this acts the same as
      // prepatch.
      case 'prerelease':
        if (this.prerelease.length === 0) {
          this.inc('patch', identifier, identifierBase)
        }
        this.inc('pre', identifier, identifierBase)
        break
      case 'release':
        if (this.prerelease.length === 0) {
          throw new Error(`version ${this.raw} is not a prerelease`)
        }
        this.prerelease.length = 0
        break

      case 'major':
        // If this is a pre-major version, bump up to the same major version.
        // Otherwise increment major.
        // 1.0.0-5 bumps to 1.0.0
        // 1.1.0 bumps to 2.0.0
        if (
          this.minor !== 0 ||
          this.patch !== 0 ||
          this.prerelease.length === 0
        ) {
          this.major++
        }
        this.minor = 0
        this.patch = 0
        this.prerelease = []
        break
      case 'minor':
        // If this is a pre-minor version, bump up to the same minor version.
        // Otherwise increment minor.
        // 1.2.0-5 bumps to 1.2.0
        // 1.2.1 bumps to 1.3.0
        if (this.patch !== 0 || this.prerelease.length === 0) {
          this.minor++
        }
        this.patch = 0
        this.prerelease = []
        break
      case 'patch':
        // If this is not a pre-release version, it will increment the patch.
        // If it is a pre-release it will bump up to the same patch version.
        // 1.2.0-5 patches to 1.2.0
        // 1.2.0 patches to 1.2.1
        if (this.prerelease.length === 0) {
          this.patch++
        }
        this.prerelease = []
        break
      // This probably shouldn't be used publicly.
      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
      case 'pre': {
        const base = Number(identifierBase) ? 1 : 0

        if (this.prerelease.length === 0) {
          this.prerelease = [base]
        } else {
          let i = this.prerelease.length
          while (--i >= 0) {
            if (typeof this.prerelease[i] === 'number') {
              this.prerelease[i]++
              i = -2
            }
          }
          if (i === -1) {
            // didn't increment anything
            if (identifier === this.prerelease.join('.') && identifierBase === false) {
              throw new Error('invalid increment argument: identifier already exists')
            }
            this.prerelease.push(base)
          }
        }
        if (identifier) {
          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
          let prerelease = [identifier, base]
          if (identifierBase === false) {
            prerelease = [identifier]
          }
          if (isPrereleaseIdentifier(this.prerelease, identifier)) {
            const prereleaseBase = this.prerelease[identifier.split('.').length]
            if (isNaN(prereleaseBase)) {
              this.prerelease = prerelease
            }
          } else {
            this.prerelease = prerelease
          }
        }
        break
      }
      default:
        throw new Error(`invalid increment argument: ${release}`)
    }
    this.raw = this.format()
    if (this.build.length) {
      this.raw += `+${this.build.join('.')}`
    }
    return this
  }
}

module.exports = SemVer
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.

'use strict'

const argv = process.argv.slice(2)

let versions = []

const range = []

let inc = null

const version = require('../package.json').version

let loose = false

let includePrerelease = false

let coerce = false

let rtl = false

let identifier

let identifierBase

const semver = require('../')
const parseOptions = require('../internal/parse-options')

let reverse = false

let options = {}

const main = () => {
  if (!argv.length) {
    return help()
  }
  while (argv.length) {
    let a = argv.shift()
    const indexOfEqualSign = a.indexOf('=')
    if (indexOfEqualSign !== -1) {
      const value = a.slice(indexOfEqualSign + 1)
      a = a.slice(0, indexOfEqualSign)
      argv.unshift(value)
    }

    switch (a) {
      case '-rv': case '-rev': case '--rev': case '--reverse':
        reverse = true
        break
      case '-l': case '--loose':
        loose = true
        break
      case '-p': case '--include-prerelease':
        includePrerelease = true
        break
      case '-v': case '--version':
        versions.push(argv.shift())
        break
      case '-i': case '--inc': case '--increment':
        if (semver.RELEASE_TYPES.includes(argv[0]) || (argv[0] === 'release')) {
          inc = { value: argv.shift(), maybeErrantValue: null, option: a }
        } else {
          inc = { value: 'patch', maybeErrantValue: argv[0], option: a }
        }
        break
      case '--preid':
        identifier = argv.shift()
        break
      case '-r': case '--range':
        range.push(argv.shift())
        break
      case '-n':
        identifierBase = argv.shift()
        if (identifierBase === 'false') {
          identifierBase = false
        }
        break
      case '-c': case '--coerce':
        coerce = true
        break
      case '--rtl':
        rtl = true
        break
      case '--ltr':
        rtl = false
        break
      case '-h': case '--help': case '-?':
        return help()
      default:
        versions.push(a)
        break
    }
  }

  options = parseOptions({ loose, includePrerelease, rtl })

  if (
    inc &&
    versions.includes(inc.maybeErrantValue) &&
    !semver.valid(inc.maybeErrantValue, options)
  ) {
    console.warn(`Invalid value for ${inc.option}; defaulting to 'patch'. This may become a failure in future major versions.`)
  }

  versions = versions.map((v) => {
    return coerce ? (semver.coerce(v, options) || { version: v }).version : v
  }).filter((v) => {
    return semver.valid(v, options)
  })
  if (!versions.length) {
    return fail()
  }
  if (inc && (versions.length !== 1 || range.length)) {
    return failInc()
  }

  for (let i = 0, l = range.length; i < l; i++) {
    versions = versions.filter((v) => {
      return semver.satisfies(v, range[i], options)
    })
    if (!versions.length) {
      return fail()
    }
  }
  versions
    .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options))
    .map(v => semver.clean(v, options))
    .map(v => inc ? semver.inc(v, inc.value, options, identifier, identifierBase) : v)
    .forEach(v => console.log(v))
}

const failInc = () => {
  console.error('--inc can only be used on a single version with no range')
  fail()
}

const fail = () => process.exit(1)

const help = () => console.log(
`SemVer ${version}

A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter

Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence

Options:
-r --range <range>
        Print versions that match the specified range.

-i --increment [<level>]
        Increment a version by the specified level.  Level can
        be one of: major, minor, patch, premajor, preminor,
        prepatch, prerelease, or release.  Default level is 'patch'.
        Only one version may be specified.

--preid <identifier>
        Identifier to be used to prefix premajor, preminor,
        prepatch or prerelease version increments.

-l --loose
        Interpret versions and ranges loosely

-p --include-prerelease
        Always include prerelease versions in range matching

-c --coerce
        Coerce a string into SemVer if possible
        (does not imply --loose)

--rtl
        Coerce version strings right to left

--ltr
        Coerce version strings left to right (default)

-n <base>
        Base number to be used for the prerelease identifier.
        Can be either 0 or 1, or false to omit the number altogether.
        Defaults to 0.

Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.

If no satisfying versions are found, then exits failure.

Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)

main()
{
  "name": "type-fest",
  "version": "2.19.0",
  "description": "A collection of essential TypeScript types",
  "license": "(MIT OR CC0-1.0)",
  "repository": "sindresorhus/type-fest",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "engines": {
    "node": ">=12.20"
  },
  "files": [
    "index.d.ts",
    "source"
  ],
  "devDependencies": {
    "@sindresorhus/tsconfig": "~0.7.0",
    "expect-type": "^0.13.0",
    "tsd": "^0.20.0",
    "typescript": "^4.6.3",
    "xo": "^0.43.0"
  },
  "types": "./index.d.ts"
}MIT License

Copyright (c) Meta Platforms, Inc. and affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/use-sync-external-store.production.js');
} else {
  module.exports = require('./cjs/use-sync-external-store.development.js');
}
{
  "name": "use-sync-external-store",
  "description": "Backwards compatible shim for React's useSyncExternalStore. Works with any React that supports hooks.",
  "version": "1.6.0",
  "exports": {
    ".": "./index.js",
    "./with-selector": "./with-selector.js",
    "./with-selector.js": "./with-selector.js",
    "./shim": {
      "react-native": "./shim/index.native.js",
      "default": "./shim/index.js"
    },
    "./shim/index.js": "./shim/index.js",
    "./shim/index.native": "./shim/index.native.js",
    "./shim/index.native.js": "./shim/index.native.js",
    "./shim/with-selector": "./shim/with-selector.js",
    "./shim/with-selector.js": "./shim/with-selector.js",
    "./package.json": "./package.json"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/facebook/react.git",
    "directory": "packages/use-sync-external-store"
  },
  "files": [
    "LICENSE",
    "README.md",
    "index.js",
    "index.native.js",
    "with-selector.js",
    "with-selector.native.js",
    "shim/",
    "cjs/"
  ],
  "license": "MIT",
  "peerDependencies": {
    "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
  },
  "devDependencies": {
    "react-17": "npm:react@^17",
    "react-dom-17": "npm:react-dom@^17"
  }
}'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/use-sync-external-store-with-selector.production.js');
} else {
  module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('../cjs/use-sync-external-store-shim.production.js');
} else {
  module.exports = require('../cjs/use-sync-external-store-shim.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('../cjs/use-sync-external-store-shim.native.production.js');
} else {
  module.exports = require('../cjs/use-sync-external-store-shim.native.development.js');
}
'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.js');
} else {
  module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');
}
/**
 * @license React
 * use-sync-external-store-shim.development.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
"production" !== process.env.NODE_ENV &&
  (function () {
    function is(x, y) {
      return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
    }
    function useSyncExternalStore$2(subscribe, getSnapshot) {
      didWarnOld18Alpha ||
        void 0 === React.startTransition ||
        ((didWarnOld18Alpha = !0),
        console.error(
          "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
        ));
      var value = getSnapshot();
      if (!didWarnUncachedGetSnapshot) {
        var cachedValue = getSnapshot();
        objectIs(value, cachedValue) ||
          (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ),
          (didWarnUncachedGetSnapshot = !0));
      }
      cachedValue = useState({
        inst: { value: value, getSnapshot: getSnapshot }
      });
      var inst = cachedValue[0].inst,
        forceUpdate = cachedValue[1];
      useLayoutEffect(
        function () {
          inst.value = value;
          inst.getSnapshot = getSnapshot;
          checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
        },
        [subscribe, value, getSnapshot]
      );
      useEffect(
        function () {
          checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
          return subscribe(function () {
            checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
          });
        },
        [subscribe]
      );
      useDebugValue(value);
      return value;
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      inst = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(inst, nextValue);
      } catch (error) {
        return !0;
      }
    }
    function useSyncExternalStore$1(subscribe, getSnapshot) {
      return getSnapshot();
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var React = require("react"),
      objectIs = "function" === typeof Object.is ? Object.is : is,
      useState = React.useState,
      useEffect = React.useEffect,
      useLayoutEffect = React.useLayoutEffect,
      useDebugValue = React.useDebugValue,
      didWarnOld18Alpha = !1,
      didWarnUncachedGetSnapshot = !1,
      shim =
        "undefined" === typeof window ||
        "undefined" === typeof window.document ||
        "undefined" === typeof window.document.createElement
          ? useSyncExternalStore$1
          : useSyncExternalStore$2;
    exports.useSyncExternalStore =
      void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
/**
 * @license React
 * use-sync-external-store-shim.native.development.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
"production" !== process.env.NODE_ENV &&
  (function () {
    function is(x, y) {
      return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
    }
    function useSyncExternalStore$1(subscribe, getSnapshot) {
      didWarnOld18Alpha ||
        void 0 === React.startTransition ||
        ((didWarnOld18Alpha = !0),
        console.error(
          "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
        ));
      var value = getSnapshot();
      if (!didWarnUncachedGetSnapshot) {
        var cachedValue = getSnapshot();
        objectIs(value, cachedValue) ||
          (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ),
          (didWarnUncachedGetSnapshot = !0));
      }
      cachedValue = useState({
        inst: { value: value, getSnapshot: getSnapshot }
      });
      var inst = cachedValue[0].inst,
        forceUpdate = cachedValue[1];
      useLayoutEffect(
        function () {
          inst.value = value;
          inst.getSnapshot = getSnapshot;
          checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
        },
        [subscribe, value, getSnapshot]
      );
      useEffect(
        function () {
          checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
          return subscribe(function () {
            checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
          });
        },
        [subscribe]
      );
      useDebugValue(value);
      return value;
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      inst = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(inst, nextValue);
      } catch (error) {
        return !0;
      }
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var React = require("react"),
      objectIs = "function" === typeof Object.is ? Object.is : is,
      useState = React.useState,
      useEffect = React.useEffect,
      useLayoutEffect = React.useLayoutEffect,
      useDebugValue = React.useDebugValue,
      didWarnOld18Alpha = !1,
      didWarnUncachedGetSnapshot = !1;
    exports.useSyncExternalStore =
      void 0 !== React.useSyncExternalStore
        ? React.useSyncExternalStore
        : useSyncExternalStore$1;
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
/**
 * @license React
 * use-sync-external-store-shim.native.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
var React = require("react");
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useState = React.useState,
  useEffect = React.useEffect,
  useLayoutEffect = React.useLayoutEffect,
  useDebugValue = React.useDebugValue;
function useSyncExternalStore$1(subscribe, getSnapshot) {
  var value = getSnapshot(),
    _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),
    inst = _useState[0].inst,
    forceUpdate = _useState[1];
  useLayoutEffect(
    function () {
      inst.value = value;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
    },
    [subscribe, value, getSnapshot]
  );
  useEffect(
    function () {
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      return subscribe(function () {
        checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      });
    },
    [subscribe]
  );
  useDebugValue(value);
  return value;
}
function checkIfSnapshotChanged(inst) {
  var latestGetSnapshot = inst.getSnapshot;
  inst = inst.value;
  try {
    var nextValue = latestGetSnapshot();
    return !objectIs(inst, nextValue);
  } catch (error) {
    return !0;
  }
}
exports.useSyncExternalStore =
  void 0 !== React.useSyncExternalStore
    ? React.useSyncExternalStore
    : useSyncExternalStore$1;
/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
var React = require("react");
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useState = React.useState,
  useEffect = React.useEffect,
  useLayoutEffect = React.useLayoutEffect,
  useDebugValue = React.useDebugValue;
function useSyncExternalStore$2(subscribe, getSnapshot) {
  var value = getSnapshot(),
    _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),
    inst = _useState[0].inst,
    forceUpdate = _useState[1];
  useLayoutEffect(
    function () {
      inst.value = value;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
    },
    [subscribe, value, getSnapshot]
  );
  useEffect(
    function () {
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      return subscribe(function () {
        checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      });
    },
    [subscribe]
  );
  useDebugValue(value);
  return value;
}
function checkIfSnapshotChanged(inst) {
  var latestGetSnapshot = inst.getSnapshot;
  inst = inst.value;
  try {
    var nextValue = latestGetSnapshot();
    return !objectIs(inst, nextValue);
  } catch (error) {
    return !0;
  }
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
  return getSnapshot();
}
var shim =
  "undefined" === typeof window ||
  "undefined" === typeof window.document ||
  "undefined" === typeof window.document.createElement
    ? useSyncExternalStore$1
    : useSyncExternalStore$2;
exports.useSyncExternalStore =
  void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
/**
 * @license React
 * use-sync-external-store-with-selector.development.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
"production" !== process.env.NODE_ENV &&
  (function () {
    function is(x, y) {
      return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var React = require("react"),
      objectIs = "function" === typeof Object.is ? Object.is : is,
      useSyncExternalStore = React.useSyncExternalStore,
      useRef = React.useRef,
      useEffect = React.useEffect,
      useMemo = React.useMemo,
      useDebugValue = React.useDebugValue;
    exports.useSyncExternalStoreWithSelector = function (
      subscribe,
      getSnapshot,
      getServerSnapshot,
      selector,
      isEqual
    ) {
      var instRef = useRef(null);
      if (null === instRef.current) {
        var inst = { hasValue: !1, value: null };
        instRef.current = inst;
      } else inst = instRef.current;
      instRef = useMemo(
        function () {
          function memoizedSelector(nextSnapshot) {
            if (!hasMemo) {
              hasMemo = !0;
              memoizedSnapshot = nextSnapshot;
              nextSnapshot = selector(nextSnapshot);
              if (void 0 !== isEqual && inst.hasValue) {
                var currentSelection = inst.value;
                if (isEqual(currentSelection, nextSnapshot))
                  return (memoizedSelection = currentSelection);
              }
              return (memoizedSelection = nextSnapshot);
            }
            currentSelection = memoizedSelection;
            if (objectIs(memoizedSnapshot, nextSnapshot))
              return currentSelection;
            var nextSelection = selector(nextSnapshot);
            if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
              return (memoizedSnapshot = nextSnapshot), currentSelection;
            memoizedSnapshot = nextSnapshot;
            return (memoizedSelection = nextSelection);
          }
          var hasMemo = !1,
            memoizedSnapshot,
            memoizedSelection,
            maybeGetServerSnapshot =
              void 0 === getServerSnapshot ? null : getServerSnapshot;
          return [
            function () {
              return memoizedSelector(getSnapshot());
            },
            null === maybeGetServerSnapshot
              ? void 0
              : function () {
                  return memoizedSelector(maybeGetServerSnapshot());
                }
          ];
        },
        [getSnapshot, getServerSnapshot, selector, isEqual]
      );
      var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
      useEffect(
        function () {
          inst.hasValue = !0;
          inst.value = value;
        },
        [value]
      );
      useDebugValue(value);
      return value;
    };
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
/**
 * @license React
 * use-sync-external-store-with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
var React = require("react");
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useSyncExternalStore = React.useSyncExternalStore,
  useRef = React.useRef,
  useEffect = React.useEffect,
  useMemo = React.useMemo,
  useDebugValue = React.useDebugValue;
exports.useSyncExternalStoreWithSelector = function (
  subscribe,
  getSnapshot,
  getServerSnapshot,
  selector,
  isEqual
) {
  var instRef = useRef(null);
  if (null === instRef.current) {
    var inst = { hasValue: !1, value: null };
    instRef.current = inst;
  } else inst = instRef.current;
  instRef = useMemo(
    function () {
      function memoizedSelector(nextSnapshot) {
        if (!hasMemo) {
          hasMemo = !0;
          memoizedSnapshot = nextSnapshot;
          nextSnapshot = selector(nextSnapshot);
          if (void 0 !== isEqual && inst.hasValue) {
            var currentSelection = inst.value;
            if (isEqual(currentSelection, nextSnapshot))
              return (memoizedSelection = currentSelection);
          }
          return (memoizedSelection = nextSnapshot);
        }
        currentSelection = memoizedSelection;
        if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
        var nextSelection = selector(nextSnapshot);
        if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
          return (memoizedSnapshot = nextSnapshot), currentSelection;
        memoizedSnapshot = nextSnapshot;
        return (memoizedSelection = nextSelection);
      }
      var hasMemo = !1,
        memoizedSnapshot,
        memoizedSelection,
        maybeGetServerSnapshot =
          void 0 === getServerSnapshot ? null : getServerSnapshot;
      return [
        function () {
          return memoizedSelector(getSnapshot());
        },
        null === maybeGetServerSnapshot
          ? void 0
          : function () {
              return memoizedSelector(maybeGetServerSnapshot());
            }
      ];
    },
    [getSnapshot, getServerSnapshot, selector, isEqual]
  );
  var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
  useEffect(
    function () {
      inst.hasValue = !0;
      inst.value = value;
    },
    [value]
  );
  useDebugValue(value);
  return value;
};
/**
 * @license React
 * use-sync-external-store.development.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
if ("production" !== process.env.NODE_ENV) {
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
    "function" ===
      typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
    __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
  var useSyncExternalStore$jscomp$inline_1 =
    require("react").useSyncExternalStore;
  console.error(
    "The main 'use-sync-external-store' entry point is not supported; all it does is re-export useSyncExternalStore from the 'react' package, so it only works with React 18+.\n\nIf you wish to support React 16 and 17, import from 'use-sync-external-store/shim' instead. It will fall back to a shimmed implementation when the native one is not available.\n\nIf you only support React 18+, you can import directly from 'react'."
  );
  exports.useSyncExternalStore = useSyncExternalStore$jscomp$inline_1;
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
    "function" ===
      typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
    __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
}
/**
 * @license React
 * use-sync-external-store.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
var useSyncExternalStore = require("react").useSyncExternalStore;
exports.useSyncExternalStore = useSyncExternalStore;
/**
 * @license React
 * use-sync-external-store-shim/with-selector.development.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
"production" !== process.env.NODE_ENV &&
  (function () {
    function is(x, y) {
      return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var React = require("react"),
      shim = require("use-sync-external-store/shim"),
      objectIs = "function" === typeof Object.is ? Object.is : is,
      useSyncExternalStore = shim.useSyncExternalStore,
      useRef = React.useRef,
      useEffect = React.useEffect,
      useMemo = React.useMemo,
      useDebugValue = React.useDebugValue;
    exports.useSyncExternalStoreWithSelector = function (
      subscribe,
      getSnapshot,
      getServerSnapshot,
      selector,
      isEqual
    ) {
      var instRef = useRef(null);
      if (null === instRef.current) {
        var inst = { hasValue: !1, value: null };
        instRef.current = inst;
      } else inst = instRef.current;
      instRef = useMemo(
        function () {
          function memoizedSelector(nextSnapshot) {
            if (!hasMemo) {
              hasMemo = !0;
              memoizedSnapshot = nextSnapshot;
              nextSnapshot = selector(nextSnapshot);
              if (void 0 !== isEqual && inst.hasValue) {
                var currentSelection = inst.value;
                if (isEqual(currentSelection, nextSnapshot))
                  return (memoizedSelection = currentSelection);
              }
              return (memoizedSelection = nextSnapshot);
            }
            currentSelection = memoizedSelection;
            if (objectIs(memoizedSnapshot, nextSnapshot))
              return currentSelection;
            var nextSelection = selector(nextSnapshot);
            if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
              return (memoizedSnapshot = nextSnapshot), currentSelection;
            memoizedSnapshot = nextSnapshot;
            return (memoizedSelection = nextSelection);
          }
          var hasMemo = !1,
            memoizedSnapshot,
            memoizedSelection,
            maybeGetServerSnapshot =
              void 0 === getServerSnapshot ? null : getServerSnapshot;
          return [
            function () {
              return memoizedSelector(getSnapshot());
            },
            null === maybeGetServerSnapshot
              ? void 0
              : function () {
                  return memoizedSelector(maybeGetServerSnapshot());
                }
          ];
        },
        [getSnapshot, getServerSnapshot, selector, isEqual]
      );
      var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
      useEffect(
        function () {
          inst.hasValue = !0;
          inst.value = value;
        },
        [value]
      );
      useDebugValue(value);
      return value;
    };
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      "function" ===
        typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

"use strict";
var React = require("react"),
  shim = require("use-sync-external-store/shim");
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useSyncExternalStore = shim.useSyncExternalStore,
  useRef = React.useRef,
  useEffect = React.useEffect,
  useMemo = React.useMemo,
  useDebugValue = React.useDebugValue;
exports.useSyncExternalStoreWithSelector = function (
  subscribe,
  getSnapshot,
  getServerSnapshot,
  selector,
  isEqual
) {
  var instRef = useRef(null);
  if (null === instRef.current) {
    var inst = { hasValue: !1, value: null };
    instRef.current = inst;
  } else inst = instRef.current;
  instRef = useMemo(
    function () {
      function memoizedSelector(nextSnapshot) {
        if (!hasMemo) {
          hasMemo = !0;
          memoizedSnapshot = nextSnapshot;
          nextSnapshot = selector(nextSnapshot);
          if (void 0 !== isEqual && inst.hasValue) {
            var currentSelection = inst.value;
            if (isEqual(currentSelection, nextSnapshot))
              return (memoizedSelection = currentSelection);
          }
          return (memoizedSelection = nextSnapshot);
        }
        currentSelection = memoizedSelection;
        if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
        var nextSelection = selector(nextSnapshot);
        if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
          return (memoizedSnapshot = nextSnapshot), currentSelection;
        memoizedSnapshot = nextSnapshot;
        return (memoizedSelection = nextSelection);
      }
      var hasMemo = !1,
        memoizedSnapshot,
        memoizedSelection,
        maybeGetServerSnapshot =
          void 0 === getServerSnapshot ? null : getServerSnapshot;
      return [
        function () {
          return memoizedSelector(getSnapshot());
        },
        null === maybeGetServerSnapshot
          ? void 0
          : function () {
              return memoizedSelector(maybeGetServerSnapshot());
            }
      ];
    },
    [getSnapshot, getServerSnapshot, selector, isEqual]
  );
  var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
  useEffect(
    function () {
      inst.hasValue = !0;
      inst.value = value;
    },
    [value]
  );
  useDebugValue(value);
  return value;
};
MIT License

Copyright (c) 2019 Paul Henschel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

var ReactExports = require('react');
var traditional = require('zustand/traditional');

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}

var createElement = ReactExports.createElement,
  reactCreateContext = ReactExports.createContext,
  useContext = ReactExports.useContext,
  useMemo = ReactExports.useMemo,
  useRef = ReactExports.useRef;
function createContext() {
  if (process.env.NODE_ENV !== 'production') {
    console.warn("[DEPRECATED] `context` will be removed in a future version. Instead use `import { createStore, useStore } from 'zustand'`. See: https://github.com/pmndrs/zustand/discussions/1180.");
  }
  var ZustandContext = reactCreateContext(undefined);
  var Provider = function Provider(_ref) {
    var createStore = _ref.createStore,
      children = _ref.children;
    var storeRef = useRef();
    if (!storeRef.current) {
      storeRef.current = createStore();
    }
    return createElement(ZustandContext.Provider, {
      value: storeRef.current
    }, children);
  };
  var useContextStore = function useContextStore(selector, equalityFn) {
    var store = useContext(ZustandContext);
    if (!store) {
      throw new Error('Seems like you have not used zustand provider as an ancestor.');
    }
    return traditional.useStoreWithEqualityFn(store, selector, equalityFn);
  };
  var useStoreApi = function useStoreApi() {
    var store = useContext(ZustandContext);
    if (!store) {
      throw new Error('Seems like you have not used zustand provider as an ancestor.');
    }
    return useMemo(function () {
      return _extends({}, store);
    }, [store]);
  };
  return {
    Provider: Provider,
    useStore: useContextStore,
    useStoreApi: useStoreApi
  };
}

module.exports = createContext;
'use strict';

var vanilla = require('zustand/vanilla');
var ReactExports = require('react');
var useSyncExternalStoreExports = require('use-sync-external-store/shim/with-selector');

var useDebugValue = ReactExports.useDebugValue;
var useSyncExternalStoreWithSelector = useSyncExternalStoreExports.useSyncExternalStoreWithSelector;
var didWarnAboutEqualityFn = false;
var identity = function identity(arg) {
  return arg;
};
function useStore(api, selector, equalityFn) {
  if (selector === void 0) {
    selector = identity;
  }
  if (process.env.NODE_ENV !== 'production' && equalityFn && !didWarnAboutEqualityFn) {
    console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937");
    didWarnAboutEqualityFn = true;
  }
  var slice = useSyncExternalStoreWithSelector(api.subscribe, api.getState, api.getServerState || api.getInitialState, selector, equalityFn);
  useDebugValue(slice);
  return slice;
}
var createImpl = function createImpl(createState) {
  if (process.env.NODE_ENV !== 'production' && typeof createState !== 'function') {
    console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");
  }
  var api = typeof createState === 'function' ? vanilla.createStore(createState) : createState;
  var useBoundStore = function useBoundStore(selector, equalityFn) {
    return useStore(api, selector, equalityFn);
  };
  Object.assign(useBoundStore, api);
  return useBoundStore;
};
var create = function create(createState) {
  return createState ? createImpl(createState) : createImpl;
};
var react = (function (createState) {
  if (process.env.NODE_ENV !== 'production') {
    console.warn("[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.");
  }
  return create(createState);
});

exports.create = create;
exports.default = react;
exports.useStore = useStore;
Object.keys(vanilla).forEach(function (k) {
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
    enumerable: true,
    get: function () { return vanilla[k]; }
  });
});

module.exports = react;
module.exports.create = create;
module.exports.useStore = useStore;
module.exports.createStore = vanilla.createStore;
exports.default = module.exports;
'use strict';

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
function _objectWithoutPropertiesLoose(r, e) {
  if (null == r) return {};
  var t = {};
  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
    if (e.includes(n)) continue;
    t[n] = r[n];
  }
  return t;
}

var reduxImpl = function reduxImpl(reducer, initial) {
  return function (set, _get, api) {
    api.dispatch = function (action) {
      set(function (state) {
        return reducer(state, action);
      }, false, action);
      return action;
    };
    api.dispatchFromDevtools = true;
    return _extends({
      dispatch: function dispatch() {
        var _ref;
        return (_ref = api).dispatch.apply(_ref, arguments);
      }
    }, initial);
  };
};
var redux = reduxImpl;

var _excluded = ["enabled", "anonymousActionType", "store"],
  _excluded2 = ["connection"];
var trackedConnections = new Map();
var getTrackedConnectionState = function getTrackedConnectionState(name) {
  var api = trackedConnections.get(name);
  if (!api) return {};
  return Object.fromEntries(Object.entries(api.stores).map(function (_ref) {
    var key = _ref[0],
      api = _ref[1];
    return [key, api.getState()];
  }));
};
var extractConnectionInformation = function extractConnectionInformation(store, extensionConnector, options) {
  if (store === undefined) {
    return {
      type: 'untracked',
      connection: extensionConnector.connect(options)
    };
  }
  var existingConnection = trackedConnections.get(options.name);
  if (existingConnection) {
    return _extends({
      type: 'tracked',
      store: store
    }, existingConnection);
  }
  var newConnection = {
    connection: extensionConnector.connect(options),
    stores: {}
  };
  trackedConnections.set(options.name, newConnection);
  return _extends({
    type: 'tracked',
    store: store
  }, newConnection);
};
var devtoolsImpl = function devtoolsImpl(fn, devtoolsOptions) {
  if (devtoolsOptions === void 0) {
    devtoolsOptions = {};
  }
  return function (set, get, api) {
    var _devtoolsOptions = devtoolsOptions,
      enabled = _devtoolsOptions.enabled,
      anonymousActionType = _devtoolsOptions.anonymousActionType,
      store = _devtoolsOptions.store,
      options = _objectWithoutPropertiesLoose(_devtoolsOptions, _excluded);
    var extensionConnector;
    try {
      extensionConnector = (enabled != null ? enabled : process.env.NODE_ENV !== 'production') && window.__REDUX_DEVTOOLS_EXTENSION__;
    } catch (_e) {}
    if (!extensionConnector) {
      if (process.env.NODE_ENV !== 'production' && enabled) {
        console.warn('[zustand devtools middleware] Please install/enable Redux devtools extension');
      }
      return fn(set, get, api);
    }
    var _extractConnectionInf = extractConnectionInformation(store, extensionConnector, options),
      connection = _extractConnectionInf.connection,
      connectionInformation = _objectWithoutPropertiesLoose(_extractConnectionInf, _excluded2);
    var isRecording = true;
    api.setState = function (state, replace, nameOrAction) {
      var _extends2;
      var r = set(state, replace);
      if (!isRecording) return r;
      var action = nameOrAction === undefined ? {
        type: anonymousActionType || 'anonymous'
      } : typeof nameOrAction === 'string' ? {
        type: nameOrAction
      } : nameOrAction;
      if (store === undefined) {
        connection == null || connection.send(action, get());
        return r;
      }
      connection == null || connection.send(_extends({}, action, {
        type: store + "/" + action.type
      }), _extends({}, getTrackedConnectionState(options.name), (_extends2 = {}, _extends2[store] = api.getState(), _extends2)));
      return r;
    };
    var setStateFromDevtools = function setStateFromDevtools() {
      var originalIsRecording = isRecording;
      isRecording = false;
      set.apply(void 0, arguments);
      isRecording = originalIsRecording;
    };
    var initialState = fn(api.setState, get, api);
    if (connectionInformation.type === 'untracked') {
      connection == null || connection.init(initialState);
    } else {
      connectionInformation.stores[connectionInformation.store] = api;
      connection == null || connection.init(Object.fromEntries(Object.entries(connectionInformation.stores).map(function (_ref2) {
        var key = _ref2[0],
          store = _ref2[1];
        return [key, key === connectionInformation.store ? initialState : store.getState()];
      })));
    }
    if (api.dispatchFromDevtools && typeof api.dispatch === 'function') {
      var didWarnAboutReservedActionType = false;
      var originalDispatch = api.dispatch;
      api.dispatch = function () {
        for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
          a[_key] = arguments[_key];
        }
        if (process.env.NODE_ENV !== 'production' && a[0].type === '__setState' && !didWarnAboutReservedActionType) {
          console.warn('[zustand devtools middleware] "__setState" action type is reserved ' + 'to set state from the devtools. Avoid using it.');
          didWarnAboutReservedActionType = true;
        }
        originalDispatch.apply(void 0, a);
      };
    }
    connection.subscribe(function (message) {
      switch (message.type) {
        case 'ACTION':
          if (typeof message.payload !== 'string') {
            console.error('[zustand devtools middleware] Unsupported action format');
            return;
          }
          return parseJsonThen(message.payload, function (action) {
            if (action.type === '__setState') {
              if (store === undefined) {
                setStateFromDevtools(action.state);
                return;
              }
              if (Object.keys(action.state).length !== 1) {
                console.error("\n                    [zustand devtools middleware] Unsupported __setState action format. \n                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n                    and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n                    ");
              }
              var stateFromDevtools = action.state[store];
              if (stateFromDevtools === undefined || stateFromDevtools === null) {
                return;
              }
              if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {
                setStateFromDevtools(stateFromDevtools);
              }
              return;
            }
            if (!api.dispatchFromDevtools) return;
            if (typeof api.dispatch !== 'function') return;
            api.dispatch(action);
          });
        case 'DISPATCH':
          switch (message.payload.type) {
            case 'RESET':
              setStateFromDevtools(initialState);
              if (store === undefined) {
                return connection == null ? void 0 : connection.init(api.getState());
              }
              return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
            case 'COMMIT':
              if (store === undefined) {
                connection == null || connection.init(api.getState());
                return;
              }
              return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
            case 'ROLLBACK':
              return parseJsonThen(message.state, function (state) {
                if (store === undefined) {
                  setStateFromDevtools(state);
                  connection == null || connection.init(api.getState());
                  return;
                }
                setStateFromDevtools(state[store]);
                connection == null || connection.init(getTrackedConnectionState(options.name));
              });
            case 'JUMP_TO_STATE':
            case 'JUMP_TO_ACTION':
              return parseJsonThen(message.state, function (state) {
                if (store === undefined) {
                  setStateFromDevtools(state);
                  return;
                }
                if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {
                  setStateFromDevtools(state[store]);
                }
              });
            case 'IMPORT_STATE':
              {
                var _nextLiftedState$comp;
                var nextLiftedState = message.payload.nextLiftedState;
                var lastComputedState = (_nextLiftedState$comp = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _nextLiftedState$comp.state;
                if (!lastComputedState) return;
                if (store === undefined) {
                  setStateFromDevtools(lastComputedState);
                } else {
                  setStateFromDevtools(lastComputedState[store]);
                }
                connection == null || connection.send(null, nextLiftedState);
                return;
              }
            case 'PAUSE_RECORDING':
              return isRecording = !isRecording;
          }
          return;
      }
    });
    return initialState;
  };
};
var devtools = devtoolsImpl;
var parseJsonThen = function parseJsonThen(stringified, f) {
  var parsed;
  try {
    parsed = JSON.parse(stringified);
  } catch (e) {
    console.error('[zustand devtools middleware] Could not parse the received json', e);
  }
  if (parsed !== undefined) f(parsed);
};

var subscribeWithSelectorImpl = function subscribeWithSelectorImpl(fn) {
  return function (set, get, api) {
    var origSubscribe = api.subscribe;
    api.subscribe = function (selector, optListener, options) {
      var listener = selector;
      if (optListener) {
        var equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
        var currentSlice = selector(api.getState());
        listener = function listener(state) {
          var nextSlice = selector(state);
          if (!equalityFn(currentSlice, nextSlice)) {
            var previousSlice = currentSlice;
            optListener(currentSlice = nextSlice, previousSlice);
          }
        };
        if (options != null && options.fireImmediately) {
          optListener(currentSlice, currentSlice);
        }
      }
      return origSubscribe(listener);
    };
    var initialState = fn(set, get, api);
    return initialState;
  };
};
var subscribeWithSelector = subscribeWithSelectorImpl;

var combine = function combine(initialState, create) {
  return function () {
    return Object.assign({}, initialState, create.apply(void 0, arguments));
  };
};

function createJSONStorage(getStorage, options) {
  var storage;
  try {
    storage = getStorage();
  } catch (_e) {
    return;
  }
  var persistStorage = {
    getItem: function getItem(name) {
      var _getItem;
      var parse = function parse(str) {
        if (str === null) {
          return null;
        }
        return JSON.parse(str, options == null ? void 0 : options.reviver);
      };
      var str = (_getItem = storage.getItem(name)) != null ? _getItem : null;
      if (str instanceof Promise) {
        return str.then(parse);
      }
      return parse(str);
    },
    setItem: function setItem(name, newValue) {
      return storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer));
    },
    removeItem: function removeItem(name) {
      return storage.removeItem(name);
    }
  };
  return persistStorage;
}
var _toThenable = function toThenable(fn) {
  return function (input) {
    try {
      var result = fn(input);
      if (result instanceof Promise) {
        return result;
      }
      return {
        then: function then(onFulfilled) {
          return _toThenable(onFulfilled)(result);
        },
        catch: function _catch(_onRejected) {
          return this;
        }
      };
    } catch (e) {
      return {
        then: function then(_onFulfilled) {
          return this;
        },
        catch: function _catch(onRejected) {
          return _toThenable(onRejected)(e);
        }
      };
    }
  };
};
var oldImpl = function oldImpl(config, baseOptions) {
  return function (set, get, api) {
    var options = _extends({
      getStorage: function getStorage() {
        return localStorage;
      },
      serialize: JSON.stringify,
      deserialize: JSON.parse,
      partialize: function partialize(state) {
        return state;
      },
      version: 0,
      merge: function merge(persistedState, currentState) {
        return _extends({}, currentState, persistedState);
      }
    }, baseOptions);
    var _hasHydrated = false;
    var hydrationListeners = new Set();
    var finishHydrationListeners = new Set();
    var storage;
    try {
      storage = options.getStorage();
    } catch (_e) {}
    if (!storage) {
      return config(function () {
        console.warn("[zustand persist middleware] Unable to update item '" + options.name + "', the given storage is currently unavailable.");
        set.apply(void 0, arguments);
      }, get, api);
    }
    var thenableSerialize = _toThenable(options.serialize);
    var setItem = function setItem() {
      var state = options.partialize(_extends({}, get()));
      var errorInSync;
      var thenable = thenableSerialize({
        state: state,
        version: options.version
      }).then(function (serializedValue) {
        return storage.setItem(options.name, serializedValue);
      }).catch(function (e) {
        errorInSync = e;
      });
      if (errorInSync) {
        throw errorInSync;
      }
      return thenable;
    };
    var savedSetState = api.setState;
    api.setState = function (state, replace) {
      savedSetState(state, replace);
      void setItem();
    };
    var configResult = config(function () {
      set.apply(void 0, arguments);
      void setItem();
    }, get, api);
    var stateFromStorage;
    var hydrate = function hydrate() {
      if (!storage) return;
      _hasHydrated = false;
      hydrationListeners.forEach(function (cb) {
        return cb(get());
      });
      var postRehydrationCallback = (options.onRehydrateStorage == null ? void 0 : options.onRehydrateStorage(get())) || undefined;
      return _toThenable(storage.getItem.bind(storage))(options.name).then(function (storageValue) {
        if (storageValue) {
          return options.deserialize(storageValue);
        }
      }).then(function (deserializedStorageValue) {
        if (deserializedStorageValue) {
          if (typeof deserializedStorageValue.version === 'number' && deserializedStorageValue.version !== options.version) {
            if (options.migrate) {
              return options.migrate(deserializedStorageValue.state, deserializedStorageValue.version);
            }
            console.error("State loaded from storage couldn't be migrated since no migrate function was provided");
          } else {
            return deserializedStorageValue.state;
          }
        }
      }).then(function (migratedState) {
        var _get;
        stateFromStorage = options.merge(migratedState, (_get = get()) != null ? _get : configResult);
        set(stateFromStorage, true);
        return setItem();
      }).then(function () {
        postRehydrationCallback == null || postRehydrationCallback(stateFromStorage, undefined);
        _hasHydrated = true;
        finishHydrationListeners.forEach(function (cb) {
          return cb(stateFromStorage);
        });
      }).catch(function (e) {
        postRehydrationCallback == null || postRehydrationCallback(undefined, e);
      });
    };
    api.persist = {
      setOptions: function setOptions(newOptions) {
        options = _extends({}, options, newOptions);
        if (newOptions.getStorage) {
          storage = newOptions.getStorage();
        }
      },
      clearStorage: function clearStorage() {
        var _storage;
        (_storage = storage) == null || _storage.removeItem(options.name);
      },
      getOptions: function getOptions() {
        return options;
      },
      rehydrate: function rehydrate() {
        return hydrate();
      },
      hasHydrated: function hasHydrated() {
        return _hasHydrated;
      },
      onHydrate: function onHydrate(cb) {
        hydrationListeners.add(cb);
        return function () {
          hydrationListeners.delete(cb);
        };
      },
      onFinishHydration: function onFinishHydration(cb) {
        finishHydrationListeners.add(cb);
        return function () {
          finishHydrationListeners.delete(cb);
        };
      }
    };
    hydrate();
    return stateFromStorage || configResult;
  };
};
var newImpl = function newImpl(config, baseOptions) {
  return function (set, get, api) {
    var options = _extends({
      storage: createJSONStorage(function () {
        return localStorage;
      }),
      partialize: function partialize(state) {
        return state;
      },
      version: 0,
      merge: function merge(persistedState, currentState) {
        return _extends({}, currentState, persistedState);
      }
    }, baseOptions);
    var _hasHydrated2 = false;
    var hydrationListeners = new Set();
    var finishHydrationListeners = new Set();
    var storage = options.storage;
    if (!storage) {
      return config(function () {
        console.warn("[zustand persist middleware] Unable to update item '" + options.name + "', the given storage is currently unavailable.");
        set.apply(void 0, arguments);
      }, get, api);
    }
    var setItem = function setItem() {
      var state = options.partialize(_extends({}, get()));
      return storage.setItem(options.name, {
        state: state,
        version: options.version
      });
    };
    var savedSetState = api.setState;
    api.setState = function (state, replace) {
      savedSetState(state, replace);
      void setItem();
    };
    var configResult = config(function () {
      set.apply(void 0, arguments);
      void setItem();
    }, get, api);
    api.getInitialState = function () {
      return configResult;
    };
    var stateFromStorage;
    var hydrate = function hydrate() {
      var _get3;
      if (!storage) return;
      _hasHydrated2 = false;
      hydrationListeners.forEach(function (cb) {
        var _get2;
        return cb((_get2 = get()) != null ? _get2 : configResult);
      });
      var postRehydrationCallback = (options.onRehydrateStorage == null ? void 0 : options.onRehydrateStorage((_get3 = get()) != null ? _get3 : configResult)) || undefined;
      return _toThenable(storage.getItem.bind(storage))(options.name).then(function (deserializedStorageValue) {
        if (deserializedStorageValue) {
          if (typeof deserializedStorageValue.version === 'number' && deserializedStorageValue.version !== options.version) {
            if (options.migrate) {
              return [true, options.migrate(deserializedStorageValue.state, deserializedStorageValue.version)];
            }
            console.error("State loaded from storage couldn't be migrated since no migrate function was provided");
          } else {
            return [false, deserializedStorageValue.state];
          }
        }
        return [false, undefined];
      }).then(function (migrationResult) {
        var _get4;
        var migrated = migrationResult[0],
          migratedState = migrationResult[1];
        stateFromStorage = options.merge(migratedState, (_get4 = get()) != null ? _get4 : configResult);
        set(stateFromStorage, true);
        if (migrated) {
          return setItem();
        }
      }).then(function () {
        postRehydrationCallback == null || postRehydrationCallback(stateFromStorage, undefined);
        stateFromStorage = get();
        _hasHydrated2 = true;
        finishHydrationListeners.forEach(function (cb) {
          return cb(stateFromStorage);
        });
      }).catch(function (e) {
        postRehydrationCallback == null || postRehydrationCallback(undefined, e);
      });
    };
    api.persist = {
      setOptions: function setOptions(newOptions) {
        options = _extends({}, options, newOptions);
        if (newOptions.storage) {
          storage = newOptions.storage;
        }
      },
      clearStorage: function clearStorage() {
        var _storage2;
        (_storage2 = storage) == null || _storage2.removeItem(options.name);
      },
      getOptions: function getOptions() {
        return options;
      },
      rehydrate: function rehydrate() {
        return hydrate();
      },
      hasHydrated: function hasHydrated() {
        return _hasHydrated2;
      },
      onHydrate: function onHydrate(cb) {
        hydrationListeners.add(cb);
        return function () {
          hydrationListeners.delete(cb);
        };
      },
      onFinishHydration: function onFinishHydration(cb) {
        finishHydrationListeners.add(cb);
        return function () {
          finishHydrationListeners.delete(cb);
        };
      }
    };
    if (!options.skipHydration) {
      hydrate();
    }
    return stateFromStorage || configResult;
  };
};
var persistImpl = function persistImpl(config, baseOptions) {
  if ('getStorage' in baseOptions || 'serialize' in baseOptions || 'deserialize' in baseOptions) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead.');
    }
    return oldImpl(config, baseOptions);
  }
  return newImpl(config, baseOptions);
};
var persist = persistImpl;

exports.combine = combine;
exports.createJSONStorage = createJSONStorage;
exports.devtools = devtools;
exports.persist = persist;
exports.redux = redux;
exports.subscribeWithSelector = subscribeWithSelector;
{
  "name": "zustand",
  "description": "ðŸ�» Bear necessities for state management in React",
  "private": false,
  "version": "4.5.7",
  "main": "./index.js",
  "types": "./index.d.ts",
  "typesVersions": {
    "<4.0": {
      "esm/*": [
        "ts3.4/*"
      ],
      "*": [
        "ts3.4/*"
      ]
    }
  },
  "files": [
    "**"
  ],
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "react-native": {
        "types": "./index.d.ts",
        "default": "./index.js"
      },
      "import": {
        "types": "./esm/index.d.mts",
        "default": "./esm/index.mjs"
      },
      "module": {
        "types": "./esm/index.d.ts",
        "default": "./esm/index.js"
      },
      "default": {
        "types": "./index.d.ts",
        "default": "./index.js"
      }
    },
    "./vanilla": {
      "react-native": {
        "types": "./vanilla.d.ts",
        "default": "./vanilla.js"
      },
      "import": {
        "types": "./esm/vanilla.d.mts",
        "default": "./esm/vanilla.mjs"
      },
      "module": {
        "types": "./esm/vanilla.d.ts",
        "default": "./esm/vanilla.js"
      },
      "default": {
        "types": "./vanilla.d.ts",
        "default": "./vanilla.js"
      }
    },
    "./middleware": {
      "react-native": {
        "types": "./middleware.d.ts",
        "default": "./middleware.js"
      },
      "import": {
        "types": "./esm/middleware.d.mts",
        "default": "./esm/middleware.mjs"
      },
      "module": {
        "types": "./esm/middleware.d.ts",
        "default": "./esm/middleware.js"
      },
      "default": {
        "types": "./middleware.d.ts",
        "default": "./middleware.js"
      }
    },
    "./middleware/immer": {
      "react-native": {
        "types": "./middleware/immer.d.ts",
        "default": "./middleware/immer.js"
      },
      "import": {
        "types": "./esm/middleware/immer.d.mts",
        "default": "./esm/middleware/immer.mjs"
      },
      "module": {
        "types": "./esm/middleware/immer.d.ts",
        "default": "./esm/middleware/immer.js"
      },
      "default": {
        "types": "./middleware/immer.d.ts",
        "default": "./middleware/immer.js"
      }
    },
    "./shallow": {
      "react-native": {
        "types": "./shallow.d.ts",
        "default": "./shallow.js"
      },
      "import": {
        "types": "./esm/shallow.d.mts",
        "default": "./esm/shallow.mjs"
      },
      "module": {
        "types": "./esm/shallow.d.ts",
        "default": "./esm/shallow.js"
      },
      "default": {
        "types": "./shallow.d.ts",
        "default": "./shallow.js"
      }
    },
    "./vanilla/shallow": {
      "react-native": {
        "types": "./vanilla/shallow.d.ts",
        "default": "./vanilla/shallow.js"
      },
      "import": {
        "types": "./esm/vanilla/shallow.d.mts",
        "default": "./esm/vanilla/shallow.mjs"
      },
      "module": {
        "types": "./esm/vanilla/shallow.d.ts",
        "default": "./esm/vanilla/shallow.js"
      },
      "default": {
        "types": "./vanilla/shallow.d.ts",
        "default": "./vanilla/shallow.js"
      }
    },
    "./react/shallow": {
      "react-native": {
        "types": "./react/shallow.d.ts",
        "default": "./react/shallow.js"
      },
      "import": {
        "types": "./esm/react/shallow.d.mts",
        "default": "./esm/react/shallow.mjs"
      },
      "module": {
        "types": "./esm/react/shallow.d.ts",
        "default": "./esm/react/shallow.js"
      },
      "default": {
        "types": "./react/shallow.d.ts",
        "default": "./react/shallow.js"
      }
    },
    "./traditional": {
      "react-native": {
        "types": "./traditional.d.ts",
        "default": "./traditional.js"
      },
      "import": {
        "types": "./esm/traditional.d.mts",
        "default": "./esm/traditional.mjs"
      },
      "module": {
        "types": "./esm/traditional.d.ts",
        "default": "./esm/traditional.js"
      },
      "default": {
        "types": "./traditional.d.ts",
        "default": "./traditional.js"
      }
    },
    "./context": {
      "react-native": {
        "types": "./context.d.ts",
        "default": "./context.js"
      },
      "import": {
        "types": "./esm/context.d.mts",
        "default": "./esm/context.mjs"
      },
      "module": {
        "types": "./esm/context.d.ts",
        "default": "./esm/context.js"
      },
      "default": {
        "types": "./context.d.ts",
        "default": "./context.js"
      }
    }
  },
  "sideEffects": false,
  "engines": {
    "node": ">=12.7.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/pmndrs/zustand.git"
  },
  "author": "Paul Henschel",
  "license": "MIT",
  "homepage": "https://github.com/pmndrs/zustand",
  "packageManager": "pnpm@8.15.0",
  "dependencies": {
    "use-sync-external-store": "^1.2.2"
  },
  "peerDependencies": {
    "@types/react": ">=16.8",
    "immer": ">=9.0.6",
    "react": ">=16.8"
  },
  "peerDependenciesMeta": {
    "@types/react": {
      "optional": true
    },
    "immer": {
      "optional": true
    },
    "react": {
      "optional": true
    }
  }
}'use strict';

function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _createForOfIteratorHelperLoose(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (t) return (t = t.call(r)).next.bind(t);
  if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
    t && (r = t);
    var o = 0;
    return function () {
      return o >= r.length ? {
        done: !0
      } : {
        done: !1,
        value: r[o++]
      };
    };
  }
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}

function shallow$1(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
      var _step$value = _step.value,
        key = _step$value[0],
        value = _step$value[1];
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
      var _value = _step2.value;
      if (!objB.has(_value)) {
        return false;
      }
    }
    return true;
  }
  var keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
    var keyA = _keysA[_i];
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

var shallow = (function (objA, objB) {
  if (process.env.NODE_ENV !== 'production') {
    console.warn("[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`.");
  }
  return shallow$1(objA, objB);
});

exports.default = shallow;
exports.shallow = shallow$1;

module.exports = shallow;
module.exports.shallow = shallow$1;
exports.default = module.exports;
'use strict';

var ReactExports = require('react');
var useSyncExternalStoreExports = require('use-sync-external-store/shim/with-selector');
var vanilla = require('zustand/vanilla');

var useDebugValue = ReactExports.useDebugValue;
var useSyncExternalStoreWithSelector = useSyncExternalStoreExports.useSyncExternalStoreWithSelector;
var identity = function identity(arg) {
  return arg;
};
function useStoreWithEqualityFn(api, selector, equalityFn) {
  if (selector === void 0) {
    selector = identity;
  }
  var slice = useSyncExternalStoreWithSelector(api.subscribe, api.getState, api.getServerState || api.getInitialState, selector, equalityFn);
  useDebugValue(slice);
  return slice;
}
var createWithEqualityFnImpl = function createWithEqualityFnImpl(createState, defaultEqualityFn) {
  var api = vanilla.createStore(createState);
  var useBoundStoreWithEqualityFn = function useBoundStoreWithEqualityFn(selector, equalityFn) {
    if (equalityFn === void 0) {
      equalityFn = defaultEqualityFn;
    }
    return useStoreWithEqualityFn(api, selector, equalityFn);
  };
  Object.assign(useBoundStoreWithEqualityFn, api);
  return useBoundStoreWithEqualityFn;
};
var createWithEqualityFn = function createWithEqualityFn(createState, defaultEqualityFn) {
  return createState ? createWithEqualityFnImpl(createState, defaultEqualityFn) : createWithEqualityFnImpl;
};

exports.createWithEqualityFn = createWithEqualityFn;
exports.useStoreWithEqualityFn = useStoreWithEqualityFn;
'use strict';

var createStoreImpl = function createStoreImpl(createState) {
  var state;
  var listeners = new Set();
  var setState = function setState(partial, replace) {
    var nextState = typeof partial === 'function' ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      var _previousState = state;
      state = (replace != null ? replace : typeof nextState !== 'object' || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach(function (listener) {
        return listener(state, _previousState);
      });
    }
  };
  var getState = function getState() {
    return state;
  };
  var getInitialState = function getInitialState() {
    return initialState;
  };
  var subscribe = function subscribe(listener) {
    listeners.add(listener);
    return function () {
      return listeners.delete(listener);
    };
  };
  var destroy = function destroy() {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected.');
    }
    listeners.clear();
  };
  var api = {
    setState: setState,
    getState: getState,
    getInitialState: getInitialState,
    subscribe: subscribe,
    destroy: destroy
  };
  var initialState = state = createState(setState, getState, api);
  return api;
};
var createStore = function createStore(createState) {
  return createState ? createStoreImpl(createState) : createStoreImpl;
};
var vanilla = (function (createState) {
  if (process.env.NODE_ENV !== 'production') {
    console.warn("[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'.");
  }
  return createStore(createState);
});

exports.createStore = createStore;
exports.default = vanilla;

module.exports = vanilla;
module.exports.createStore = createStore;
exports.default = module.exports;
'use strict';

function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _createForOfIteratorHelperLoose(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (t) return (t = t.call(r)).next.bind(t);
  if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
    t && (r = t);
    var o = 0;
    return function () {
      return o >= r.length ? {
        done: !0
      } : {
        done: !1,
        value: r[o++]
      };
    };
  }
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}

function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
      var _step$value = _step.value,
        key = _step$value[0],
        value = _step$value[1];
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
      var _value = _step2.value;
      if (!objB.has(_value)) {
        return false;
      }
    }
    return true;
  }
  var keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
    var keyA = _keysA[_i];
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

exports.shallow = shallow;
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('zustand/traditional')) :
  typeof define === 'function' && define.amd ? define(['react', 'zustand/traditional'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.zustandContext = factory(global.React, global.traditional));
})(this, (function (ReactExports, traditional) { 'use strict';

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }

  var createElement = ReactExports.createElement,
    reactCreateContext = ReactExports.createContext,
    useContext = ReactExports.useContext,
    useMemo = ReactExports.useMemo,
    useRef = ReactExports.useRef;
  function createContext() {
    {
      console.warn("[DEPRECATED] `context` will be removed in a future version. Instead use `import { createStore, useStore } from 'zustand'`. See: https://github.com/pmndrs/zustand/discussions/1180.");
    }
    var ZustandContext = reactCreateContext(undefined);
    var Provider = function Provider(_ref) {
      var createStore = _ref.createStore,
        children = _ref.children;
      var storeRef = useRef();
      if (!storeRef.current) {
        storeRef.current = createStore();
      }
      return createElement(ZustandContext.Provider, {
        value: storeRef.current
      }, children);
    };
    var useContextStore = function useContextStore(selector, equalityFn) {
      var store = useContext(ZustandContext);
      if (!store) {
        throw new Error('Seems like you have not used zustand provider as an ancestor.');
      }
      return traditional.useStoreWithEqualityFn(store, selector, equalityFn);
    };
    var useStoreApi = function useStoreApi() {
      var store = useContext(ZustandContext);
      if (!store) {
        throw new Error('Seems like you have not used zustand provider as an ancestor.');
      }
      return useMemo(function () {
        return _extends({}, store);
      }, [store]);
    };
    return {
      Provider: Provider,
      useStore: useContextStore,
      useStoreApi: useStoreApi
    };
  }

  return createContext;

}));
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("react"),require("zustand/traditional")):"function"==typeof define&&define.amd?define(["react","zustand/traditional"],r):(e="undefined"!=typeof globalThis?globalThis:e||self).zustandContext=r(e.React,e.traditional)}(this,(function(e,r){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},t.apply(null,arguments)}var n=e.createElement,o=e.createContext,u=e.useContext,i=e.useMemo,a=e.useRef;return function(){var e=o(void 0);return{Provider:function(r){var t=r.createStore,o=r.children,u=a();return u.current||(u.current=t()),n(e.Provider,{value:u.current},o)},useStore:function(t,n){var o=u(e);if(!o)throw new Error("Seems like you have not used zustand provider as an ancestor.");return r.useStoreWithEqualityFn(o,t,n)},useStoreApi:function(){var r=u(e);if(!r)throw new Error("Seems like you have not used zustand provider as an ancestor.");return i((function(){return t({},r)}),[r])}}}}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zustand/vanilla'), require('react'), require('use-sync-external-store/shim/with-selector')) :
  typeof define === 'function' && define.amd ? define(['exports', 'zustand/vanilla', 'react', 'use-sync-external-store/shim/with-selector'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustand = {}, global.zustandVanilla, global.React, global.useSyncExternalStoreShimWithSelector));
})(this, (function (exports, vanilla, ReactExports, useSyncExternalStoreExports) { 'use strict';

  var useDebugValue = ReactExports.useDebugValue;
  var useSyncExternalStoreWithSelector = useSyncExternalStoreExports.useSyncExternalStoreWithSelector;
  var didWarnAboutEqualityFn = false;
  var identity = function identity(arg) {
    return arg;
  };
  function useStore(api, selector, equalityFn) {
    if (selector === void 0) {
      selector = identity;
    }
    if (equalityFn && !didWarnAboutEqualityFn) {
      console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937");
      didWarnAboutEqualityFn = true;
    }
    var slice = useSyncExternalStoreWithSelector(api.subscribe, api.getState, api.getServerState || api.getInitialState, selector, equalityFn);
    useDebugValue(slice);
    return slice;
  }
  var createImpl = function createImpl(createState) {
    if (typeof createState !== 'function') {
      console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");
    }
    var api = typeof createState === 'function' ? vanilla.createStore(createState) : createState;
    var useBoundStore = function useBoundStore(selector, equalityFn) {
      return useStore(api, selector, equalityFn);
    };
    Object.assign(useBoundStore, api);
    return useBoundStore;
  };
  var create = function create(createState) {
    return createState ? createImpl(createState) : createImpl;
  };
  var react = (function (createState) {
    {
      console.warn("[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.");
    }
    return create(createState);
  });

  exports.create = create;
  exports.default = react;
  exports.useStore = useStore;
  Object.keys(vanilla).forEach(function (k) {
    if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
      enumerable: true,
      get: function () { return vanilla[k]; }
    });
  });

  Object.defineProperty(exports, '__esModule', { value: true });

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("zustand/vanilla"),require("react"),require("use-sync-external-store/shim/with-selector")):"function"==typeof define&&define.amd?define(["exports","zustand/vanilla","react","use-sync-external-store/shim/with-selector"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustand={},e.zustandVanilla,e.React,e.useSyncExternalStoreShimWithSelector)}(this,(function(e,t,n,r){"use strict";var u=n.useDebugValue,o=r.useSyncExternalStoreWithSelector,i=function(e){return e};function a(e,t,n){void 0===t&&(t=i);var r=o(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return u(r),r}var c=function(e){var n="function"==typeof e?t.createStore(e):e,r=function(e,t){return a(n,e,t)};return Object.assign(r,n),r},s=function(e){return e?c(e):c};e.create=s,e.default=function(e){return s(e)},e.useStore=a,Object.keys(t).forEach((function(n){"default"===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})),Object.defineProperty(e,"__esModule",{value:!0})}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandMiddleware = {}));
})(this, (function (exports) { 'use strict';

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }
  function _objectWithoutPropertiesLoose(r, e) {
    if (null == r) return {};
    var t = {};
    for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
      if (e.includes(n)) continue;
      t[n] = r[n];
    }
    return t;
  }

  var reduxImpl = function reduxImpl(reducer, initial) {
    return function (set, _get, api) {
      api.dispatch = function (action) {
        set(function (state) {
          return reducer(state, action);
        }, false, action);
        return action;
      };
      api.dispatchFromDevtools = true;
      return _extends({
        dispatch: function dispatch() {
          var _ref;
          return (_ref = api).dispatch.apply(_ref, arguments);
        }
      }, initial);
    };
  };
  var redux = reduxImpl;

  var _excluded = ["enabled", "anonymousActionType", "store"],
    _excluded2 = ["connection"];
  var trackedConnections = new Map();
  var getTrackedConnectionState = function getTrackedConnectionState(name) {
    var api = trackedConnections.get(name);
    if (!api) return {};
    return Object.fromEntries(Object.entries(api.stores).map(function (_ref) {
      var key = _ref[0],
        api = _ref[1];
      return [key, api.getState()];
    }));
  };
  var extractConnectionInformation = function extractConnectionInformation(store, extensionConnector, options) {
    if (store === undefined) {
      return {
        type: 'untracked',
        connection: extensionConnector.connect(options)
      };
    }
    var existingConnection = trackedConnections.get(options.name);
    if (existingConnection) {
      return _extends({
        type: 'tracked',
        store: store
      }, existingConnection);
    }
    var newConnection = {
      connection: extensionConnector.connect(options),
      stores: {}
    };
    trackedConnections.set(options.name, newConnection);
    return _extends({
      type: 'tracked',
      store: store
    }, newConnection);
  };
  var devtoolsImpl = function devtoolsImpl(fn, devtoolsOptions) {
    if (devtoolsOptions === void 0) {
      devtoolsOptions = {};
    }
    return function (set, get, api) {
      var _devtoolsOptions = devtoolsOptions,
        enabled = _devtoolsOptions.enabled,
        anonymousActionType = _devtoolsOptions.anonymousActionType,
        store = _devtoolsOptions.store,
        options = _objectWithoutPropertiesLoose(_devtoolsOptions, _excluded);
      var extensionConnector;
      try {
        extensionConnector = (enabled != null ? enabled : "development" !== 'production') && window.__REDUX_DEVTOOLS_EXTENSION__;
      } catch (_e) {}
      if (!extensionConnector) {
        if (enabled) {
          console.warn('[zustand devtools middleware] Please install/enable Redux devtools extension');
        }
        return fn(set, get, api);
      }
      var _extractConnectionInf = extractConnectionInformation(store, extensionConnector, options),
        connection = _extractConnectionInf.connection,
        connectionInformation = _objectWithoutPropertiesLoose(_extractConnectionInf, _excluded2);
      var isRecording = true;
      api.setState = function (state, replace, nameOrAction) {
        var _extends2;
        var r = set(state, replace);
        if (!isRecording) return r;
        var action = nameOrAction === undefined ? {
          type: anonymousActionType || 'anonymous'
        } : typeof nameOrAction === 'string' ? {
          type: nameOrAction
        } : nameOrAction;
        if (store === undefined) {
          connection == null || connection.send(action, get());
          return r;
        }
        connection == null || connection.send(_extends({}, action, {
          type: store + "/" + action.type
        }), _extends({}, getTrackedConnectionState(options.name), (_extends2 = {}, _extends2[store] = api.getState(), _extends2)));
        return r;
      };
      var setStateFromDevtools = function setStateFromDevtools() {
        var originalIsRecording = isRecording;
        isRecording = false;
        set.apply(void 0, arguments);
        isRecording = originalIsRecording;
      };
      var initialState = fn(api.setState, get, api);
      if (connectionInformation.type === 'untracked') {
        connection == null || connection.init(initialState);
      } else {
        connectionInformation.stores[connectionInformation.store] = api;
        connection == null || connection.init(Object.fromEntries(Object.entries(connectionInformation.stores).map(function (_ref2) {
          var key = _ref2[0],
            store = _ref2[1];
          return [key, key === connectionInformation.store ? initialState : store.getState()];
        })));
      }
      if (api.dispatchFromDevtools && typeof api.dispatch === 'function') {
        var didWarnAboutReservedActionType = false;
        var originalDispatch = api.dispatch;
        api.dispatch = function () {
          for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
            a[_key] = arguments[_key];
          }
          if (a[0].type === '__setState' && !didWarnAboutReservedActionType) {
            console.warn('[zustand devtools middleware] "__setState" action type is reserved ' + 'to set state from the devtools. Avoid using it.');
            didWarnAboutReservedActionType = true;
          }
          originalDispatch.apply(void 0, a);
        };
      }
      connection.subscribe(function (message) {
        switch (message.type) {
          case 'ACTION':
            if (typeof message.payload !== 'string') {
              console.error('[zustand devtools middleware] Unsupported action format');
              return;
            }
            return parseJsonThen(message.payload, function (action) {
              if (action.type === '__setState') {
                if (store === undefined) {
                  setStateFromDevtools(action.state);
                  return;
                }
                if (Object.keys(action.state).length !== 1) {
                  console.error("\n                    [zustand devtools middleware] Unsupported __setState action format. \n                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n                    and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n                    ");
                }
                var stateFromDevtools = action.state[store];
                if (stateFromDevtools === undefined || stateFromDevtools === null) {
                  return;
                }
                if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {
                  setStateFromDevtools(stateFromDevtools);
                }
                return;
              }
              if (!api.dispatchFromDevtools) return;
              if (typeof api.dispatch !== 'function') return;
              api.dispatch(action);
            });
          case 'DISPATCH':
            switch (message.payload.type) {
              case 'RESET':
                setStateFromDevtools(initialState);
                if (store === undefined) {
                  return connection == null ? void 0 : connection.init(api.getState());
                }
                return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
              case 'COMMIT':
                if (store === undefined) {
                  connection == null || connection.init(api.getState());
                  return;
                }
                return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
              case 'ROLLBACK':
                return parseJsonThen(message.state, function (state) {
                  if (store === undefined) {
                    setStateFromDevtools(state);
                    connection == null || connection.init(api.getState());
                    return;
                  }
                  setStateFromDevtools(state[store]);
                  connection == null || connection.init(getTrackedConnectionState(options.name));
                });
              case 'JUMP_TO_STATE':
              case 'JUMP_TO_ACTION':
                return parseJsonThen(message.state, function (state) {
                  if (store === undefined) {
                    setStateFromDevtools(state);
                    return;
                  }
                  if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {
                    setStateFromDevtools(state[store]);
                  }
                });
              case 'IMPORT_STATE':
                {
                  var _nextLiftedState$comp;
                  var nextLiftedState = message.payload.nextLiftedState;
                  var lastComputedState = (_nextLiftedState$comp = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _nextLiftedState$comp.state;
                  if (!lastComputedState) return;
                  if (store === undefined) {
                    setStateFromDevtools(lastComputedState);
                  } else {
                    setStateFromDevtools(lastComputedState[store]);
                  }
                  connection == null || connection.send(null, nextLiftedState);
                  return;
                }
              case 'PAUSE_RECORDING':
                return isRecording = !isRecording;
            }
            return;
        }
      });
      return initialState;
    };
  };
  var devtools = devtoolsImpl;
  var parseJsonThen = function parseJsonThen(stringified, f) {
    var parsed;
    try {
      parsed = JSON.parse(stringified);
    } catch (e) {
      console.error('[zustand devtools middleware] Could not parse the received json', e);
    }
    if (parsed !== undefined) f(parsed);
  };

  var subscribeWithSelectorImpl = function subscribeWithSelectorImpl(fn) {
    return function (set, get, api) {
      var origSubscribe = api.subscribe;
      api.subscribe = function (selector, optListener, options) {
        var listener = selector;
        if (optListener) {
          var equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
          var currentSlice = selector(api.getState());
          listener = function listener(state) {
            var nextSlice = selector(state);
            if (!equalityFn(currentSlice, nextSlice)) {
              var previousSlice = currentSlice;
              optListener(currentSlice = nextSlice, previousSlice);
            }
          };
          if (options != null && options.fireImmediately) {
            optListener(currentSlice, currentSlice);
          }
        }
        return origSubscribe(listener);
      };
      var initialState = fn(set, get, api);
      return initialState;
    };
  };
  var subscribeWithSelector = subscribeWithSelectorImpl;

  var combine = function combine(initialState, create) {
    return function () {
      return Object.assign({}, initialState, create.apply(void 0, arguments));
    };
  };

  function createJSONStorage(getStorage, options) {
    var storage;
    try {
      storage = getStorage();
    } catch (_e) {
      return;
    }
    var persistStorage = {
      getItem: function getItem(name) {
        var _getItem;
        var parse = function parse(str) {
          if (str === null) {
            return null;
          }
          return JSON.parse(str, options == null ? void 0 : options.reviver);
        };
        var str = (_getItem = storage.getItem(name)) != null ? _getItem : null;
        if (str instanceof Promise) {
          return str.then(parse);
        }
        return parse(str);
      },
      setItem: function setItem(name, newValue) {
        return storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer));
      },
      removeItem: function removeItem(name) {
        return storage.removeItem(name);
      }
    };
    return persistStorage;
  }
  var _toThenable = function toThenable(fn) {
    return function (input) {
      try {
        var result = fn(input);
        if (result instanceof Promise) {
          return result;
        }
        return {
          then: function then(onFulfilled) {
            return _toThenable(onFulfilled)(result);
          },
          catch: function _catch(_onRejected) {
            return this;
          }
        };
      } catch (e) {
        return {
          then: function then(_onFulfilled) {
            return this;
          },
          catch: function _catch(onRejected) {
            return _toThenable(onRejected)(e);
          }
        };
      }
    };
  };
  var oldImpl = function oldImpl(config, baseOptions) {
    return function (set, get, api) {
      var options = _extends({
        getStorage: function getStorage() {
          return localStorage;
        },
        serialize: JSON.stringify,
        deserialize: JSON.parse,
        partialize: function partialize(state) {
          return state;
        },
        version: 0,
        merge: function merge(persistedState, currentState) {
          return _extends({}, currentState, persistedState);
        }
      }, baseOptions);
      var _hasHydrated = false;
      var hydrationListeners = new Set();
      var finishHydrationListeners = new Set();
      var storage;
      try {
        storage = options.getStorage();
      } catch (_e) {}
      if (!storage) {
        return config(function () {
          console.warn("[zustand persist middleware] Unable to update item '" + options.name + "', the given storage is currently unavailable.");
          set.apply(void 0, arguments);
        }, get, api);
      }
      var thenableSerialize = _toThenable(options.serialize);
      var setItem = function setItem() {
        var state = options.partialize(_extends({}, get()));
        var errorInSync;
        var thenable = thenableSerialize({
          state: state,
          version: options.version
        }).then(function (serializedValue) {
          return storage.setItem(options.name, serializedValue);
        }).catch(function (e) {
          errorInSync = e;
        });
        if (errorInSync) {
          throw errorInSync;
        }
        return thenable;
      };
      var savedSetState = api.setState;
      api.setState = function (state, replace) {
        savedSetState(state, replace);
        void setItem();
      };
      var configResult = config(function () {
        set.apply(void 0, arguments);
        void setItem();
      }, get, api);
      var stateFromStorage;
      var hydrate = function hydrate() {
        if (!storage) return;
        _hasHydrated = false;
        hydrationListeners.forEach(function (cb) {
          return cb(get());
        });
        var postRehydrationCallback = (options.onRehydrateStorage == null ? void 0 : options.onRehydrateStorage(get())) || undefined;
        return _toThenable(storage.getItem.bind(storage))(options.name).then(function (storageValue) {
          if (storageValue) {
            return options.deserialize(storageValue);
          }
        }).then(function (deserializedStorageValue) {
          if (deserializedStorageValue) {
            if (typeof deserializedStorageValue.version === 'number' && deserializedStorageValue.version !== options.version) {
              if (options.migrate) {
                return options.migrate(deserializedStorageValue.state, deserializedStorageValue.version);
              }
              console.error("State loaded from storage couldn't be migrated since no migrate function was provided");
            } else {
              return deserializedStorageValue.state;
            }
          }
        }).then(function (migratedState) {
          var _get;
          stateFromStorage = options.merge(migratedState, (_get = get()) != null ? _get : configResult);
          set(stateFromStorage, true);
          return setItem();
        }).then(function () {
          postRehydrationCallback == null || postRehydrationCallback(stateFromStorage, undefined);
          _hasHydrated = true;
          finishHydrationListeners.forEach(function (cb) {
            return cb(stateFromStorage);
          });
        }).catch(function (e) {
          postRehydrationCallback == null || postRehydrationCallback(undefined, e);
        });
      };
      api.persist = {
        setOptions: function setOptions(newOptions) {
          options = _extends({}, options, newOptions);
          if (newOptions.getStorage) {
            storage = newOptions.getStorage();
          }
        },
        clearStorage: function clearStorage() {
          var _storage;
          (_storage = storage) == null || _storage.removeItem(options.name);
        },
        getOptions: function getOptions() {
          return options;
        },
        rehydrate: function rehydrate() {
          return hydrate();
        },
        hasHydrated: function hasHydrated() {
          return _hasHydrated;
        },
        onHydrate: function onHydrate(cb) {
          hydrationListeners.add(cb);
          return function () {
            hydrationListeners.delete(cb);
          };
        },
        onFinishHydration: function onFinishHydration(cb) {
          finishHydrationListeners.add(cb);
          return function () {
            finishHydrationListeners.delete(cb);
          };
        }
      };
      hydrate();
      return stateFromStorage || configResult;
    };
  };
  var newImpl = function newImpl(config, baseOptions) {
    return function (set, get, api) {
      var options = _extends({
        storage: createJSONStorage(function () {
          return localStorage;
        }),
        partialize: function partialize(state) {
          return state;
        },
        version: 0,
        merge: function merge(persistedState, currentState) {
          return _extends({}, currentState, persistedState);
        }
      }, baseOptions);
      var _hasHydrated2 = false;
      var hydrationListeners = new Set();
      var finishHydrationListeners = new Set();
      var storage = options.storage;
      if (!storage) {
        return config(function () {
          console.warn("[zustand persist middleware] Unable to update item '" + options.name + "', the given storage is currently unavailable.");
          set.apply(void 0, arguments);
        }, get, api);
      }
      var setItem = function setItem() {
        var state = options.partialize(_extends({}, get()));
        return storage.setItem(options.name, {
          state: state,
          version: options.version
        });
      };
      var savedSetState = api.setState;
      api.setState = function (state, replace) {
        savedSetState(state, replace);
        void setItem();
      };
      var configResult = config(function () {
        set.apply(void 0, arguments);
        void setItem();
      }, get, api);
      api.getInitialState = function () {
        return configResult;
      };
      var stateFromStorage;
      var hydrate = function hydrate() {
        var _get3;
        if (!storage) return;
        _hasHydrated2 = false;
        hydrationListeners.forEach(function (cb) {
          var _get2;
          return cb((_get2 = get()) != null ? _get2 : configResult);
        });
        var postRehydrationCallback = (options.onRehydrateStorage == null ? void 0 : options.onRehydrateStorage((_get3 = get()) != null ? _get3 : configResult)) || undefined;
        return _toThenable(storage.getItem.bind(storage))(options.name).then(function (deserializedStorageValue) {
          if (deserializedStorageValue) {
            if (typeof deserializedStorageValue.version === 'number' && deserializedStorageValue.version !== options.version) {
              if (options.migrate) {
                return [true, options.migrate(deserializedStorageValue.state, deserializedStorageValue.version)];
              }
              console.error("State loaded from storage couldn't be migrated since no migrate function was provided");
            } else {
              return [false, deserializedStorageValue.state];
            }
          }
          return [false, undefined];
        }).then(function (migrationResult) {
          var _get4;
          var migrated = migrationResult[0],
            migratedState = migrationResult[1];
          stateFromStorage = options.merge(migratedState, (_get4 = get()) != null ? _get4 : configResult);
          set(stateFromStorage, true);
          if (migrated) {
            return setItem();
          }
        }).then(function () {
          postRehydrationCallback == null || postRehydrationCallback(stateFromStorage, undefined);
          stateFromStorage = get();
          _hasHydrated2 = true;
          finishHydrationListeners.forEach(function (cb) {
            return cb(stateFromStorage);
          });
        }).catch(function (e) {
          postRehydrationCallback == null || postRehydrationCallback(undefined, e);
        });
      };
      api.persist = {
        setOptions: function setOptions(newOptions) {
          options = _extends({}, options, newOptions);
          if (newOptions.storage) {
            storage = newOptions.storage;
          }
        },
        clearStorage: function clearStorage() {
          var _storage2;
          (_storage2 = storage) == null || _storage2.removeItem(options.name);
        },
        getOptions: function getOptions() {
          return options;
        },
        rehydrate: function rehydrate() {
          return hydrate();
        },
        hasHydrated: function hasHydrated() {
          return _hasHydrated2;
        },
        onHydrate: function onHydrate(cb) {
          hydrationListeners.add(cb);
          return function () {
            hydrationListeners.delete(cb);
          };
        },
        onFinishHydration: function onFinishHydration(cb) {
          finishHydrationListeners.add(cb);
          return function () {
            finishHydrationListeners.delete(cb);
          };
        }
      };
      if (!options.skipHydration) {
        hydrate();
      }
      return stateFromStorage || configResult;
    };
  };
  var persistImpl = function persistImpl(config, baseOptions) {
    if ('getStorage' in baseOptions || 'serialize' in baseOptions || 'deserialize' in baseOptions) {
      {
        console.warn('[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead.');
      }
      return oldImpl(config, baseOptions);
    }
    return newImpl(config, baseOptions);
  };
  var persist = persistImpl;

  exports.combine = combine;
  exports.createJSONStorage = createJSONStorage;
  exports.devtools = devtools;
  exports.persist = persist;
  exports.redux = redux;
  exports.subscribeWithSelector = subscribeWithSelector;

}));
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).zustandMiddleware={})}(this,(function(t){"use strict";function e(){return e=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},e.apply(null,arguments)}function n(t,e){if(null==t)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.includes(r))continue;n[r]=t[r]}return n}var r=function(t,n){return function(r,i,o){return o.dispatch=function(e){return r((function(n){return t(n,e)}),!1,e),e},o.dispatchFromDevtools=!0,e({dispatch:function(){var t;return(t=o).dispatch.apply(t,arguments)}},n)}},i=["enabled","anonymousActionType","store"],o=["connection"],a=new Map,u=function(t){var e=a.get(t);return e?Object.fromEntries(Object.entries(e.stores).map((function(t){return[t[0],t[1].getState()]}))):{}},c=function(t,r){return void 0===r&&(r={}),function(c,f,l){var d,v=r,p=v.enabled,g=v.anonymousActionType,y=v.store,m=n(v,i);try{d=null!=p&&p&&window.__REDUX_DEVTOOLS_EXTENSION__}catch(t){}if(!d)return t(c,f,l);var h=function(t,n,r){if(void 0===t)return{type:"untracked",connection:n.connect(r)};var i=a.get(r.name);if(i)return e({type:"tracked",store:t},i);var o={connection:n.connect(r),stores:{}};return a.set(r.name,o),e({type:"tracked",store:t},o)}(y,d,m),S=h.connection,b=n(h,o),O=!0;l.setState=function(t,n,r){var i,o=c(t,n);if(!O)return o;var a=void 0===r?{type:g||"anonymous"}:"string"==typeof r?{type:r}:r;return void 0===y?(null==S||S.send(a,f()),o):(null==S||S.send(e({},a,{type:y+"/"+a.type}),e({},u(m.name),((i={})[y]=l.getState(),i))),o)};var w=function(){var t=O;O=!1,c.apply(void 0,arguments),O=t},I=t(l.setState,f,l);if("untracked"===b.type?null==S||S.init(I):(b.stores[b.store]=l,null==S||S.init(Object.fromEntries(Object.entries(b.stores).map((function(t){var e=t[0],n=t[1];return[e,e===b.store?I:n.getState()]}))))),l.dispatchFromDevtools&&"function"==typeof l.dispatch){var T=l.dispatch;l.dispatch=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];T.apply(void 0,e)}}return S.subscribe((function(t){switch(t.type){case"ACTION":return"string"!=typeof t.payload?void console.error("[zustand devtools middleware] Unsupported action format"):s(t.payload,(function(t){if("__setState"!==t.type)l.dispatchFromDevtools&&"function"==typeof l.dispatch&&l.dispatch(t);else{if(void 0===y)return void w(t.state);1!==Object.keys(t.state).length&&console.error('\n                    [zustand devtools middleware] Unsupported __setState action format. \n                    When using \'store\' option in devtools(), the \'state\' should have only one key, which is a value of \'store\' that was passed in devtools(),\n                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }\n                    ');var e=t.state[y];if(null==e)return;JSON.stringify(l.getState())!==JSON.stringify(e)&&w(e)}}));case"DISPATCH":switch(t.payload.type){case"RESET":return w(I),void 0===y?null==S?void 0:S.init(l.getState()):null==S?void 0:S.init(u(m.name));case"COMMIT":return void 0===y?void(null==S||S.init(l.getState())):null==S?void 0:S.init(u(m.name));case"ROLLBACK":return s(t.state,(function(t){if(void 0===y)return w(t),void(null==S||S.init(l.getState()));w(t[y]),null==S||S.init(u(m.name))}));case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return s(t.state,(function(t){void 0!==y?JSON.stringify(l.getState())!==JSON.stringify(t[y])&&w(t[y]):w(t)}));case"IMPORT_STATE":var e,n=t.payload.nextLiftedState,r=null==(e=n.computedStates.slice(-1)[0])?void 0:e.state;if(!r)return;return w(void 0===y?r:r[y]),void(null==S||S.send(null,n));case"PAUSE_RECORDING":return O=!O}return}})),I}},s=function(t,e){var n;try{n=JSON.parse(t)}catch(t){console.error("[zustand devtools middleware] Could not parse the received json",t)}void 0!==n&&e(n)},f=function(t){return function(e,n,r){var i=r.subscribe;return r.subscribe=function(t,e,n){var o=t;if(e){var a=(null==n?void 0:n.equalityFn)||Object.is,u=t(r.getState());o=function(n){var r=t(n);if(!a(u,r)){var i=u;e(u=r,i)}},null!=n&&n.fireImmediately&&e(u,u)}return i(o)},t(e,n,r)}};function l(t,e){var n;try{n=t()}catch(t){return}return{getItem:function(t){var r,i=function(t){return null===t?null:JSON.parse(t,null==e?void 0:e.reviver)},o=null!=(r=n.getItem(t))?r:null;return o instanceof Promise?o.then(i):i(o)},setItem:function(t,r){return n.setItem(t,JSON.stringify(r,null==e?void 0:e.replacer))},removeItem:function(t){return n.removeItem(t)}}}var d=function(t){return function(e){try{var n=t(e);return n instanceof Promise?n:{then:function(t){return d(t)(n)},catch:function(t){return this}}}catch(t){return{then:function(t){return this},catch:function(e){return d(e)(t)}}}}},v=function(t,n){return"getStorage"in n||"serialize"in n||"deserialize"in n?function(t,n){return function(r,i,o){var a,u=e({getStorage:function(){return localStorage},serialize:JSON.stringify,deserialize:JSON.parse,partialize:function(t){return t},version:0,merge:function(t,n){return e({},n,t)}},n),c=!1,s=new Set,f=new Set;try{a=u.getStorage()}catch(t){}if(!a)return t((function(){console.warn("[zustand persist middleware] Unable to update item '"+u.name+"', the given storage is currently unavailable."),r.apply(void 0,arguments)}),i,o);var l=d(u.serialize),v=function(){var t,n=u.partialize(e({},i())),r=l({state:n,version:u.version}).then((function(t){return a.setItem(u.name,t)})).catch((function(e){t=e}));if(t)throw t;return r},p=o.setState;o.setState=function(t,e){p(t,e),v()};var g,y=t((function(){r.apply(void 0,arguments),v()}),i,o),m=function(){if(a){c=!1,s.forEach((function(t){return t(i())}));var t=(null==u.onRehydrateStorage?void 0:u.onRehydrateStorage(i()))||void 0;return d(a.getItem.bind(a))(u.name).then((function(t){if(t)return u.deserialize(t)})).then((function(t){if(t){if("number"!=typeof t.version||t.version===u.version)return t.state;if(u.migrate)return u.migrate(t.state,t.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}})).then((function(t){var e;return g=u.merge(t,null!=(e=i())?e:y),r(g,!0),v()})).then((function(){null==t||t(g,void 0),c=!0,f.forEach((function(t){return t(g)}))})).catch((function(e){null==t||t(void 0,e)}))}};return o.persist={setOptions:function(t){u=e({},u,t),t.getStorage&&(a=t.getStorage())},clearStorage:function(){var t;null==(t=a)||t.removeItem(u.name)},getOptions:function(){return u},rehydrate:function(){return m()},hasHydrated:function(){return c},onHydrate:function(t){return s.add(t),function(){s.delete(t)}},onFinishHydration:function(t){return f.add(t),function(){f.delete(t)}}},m(),g||y}}(t,n):function(t,n){return function(r,i,o){var a=e({storage:l((function(){return localStorage})),partialize:function(t){return t},version:0,merge:function(t,n){return e({},n,t)}},n),u=!1,c=new Set,s=new Set,f=a.storage;if(!f)return t((function(){console.warn("[zustand persist middleware] Unable to update item '"+a.name+"', the given storage is currently unavailable."),r.apply(void 0,arguments)}),i,o);var v=function(){var t=a.partialize(e({},i()));return f.setItem(a.name,{state:t,version:a.version})},p=o.setState;o.setState=function(t,e){p(t,e),v()};var g,y=t((function(){r.apply(void 0,arguments),v()}),i,o);o.getInitialState=function(){return y};var m=function(){var t;if(f){u=!1,c.forEach((function(t){var e;return t(null!=(e=i())?e:y)}));var e=(null==a.onRehydrateStorage?void 0:a.onRehydrateStorage(null!=(t=i())?t:y))||void 0;return d(f.getItem.bind(f))(a.name).then((function(t){if(t){if("number"!=typeof t.version||t.version===a.version)return[!1,t.state];if(a.migrate)return[!0,a.migrate(t.state,t.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]})).then((function(t){var e,n=t[0],o=t[1];if(g=a.merge(o,null!=(e=i())?e:y),r(g,!0),n)return v()})).then((function(){null==e||e(g,void 0),g=i(),u=!0,s.forEach((function(t){return t(g)}))})).catch((function(t){null==e||e(void 0,t)}))}};return o.persist={setOptions:function(t){a=e({},a,t),t.storage&&(f=t.storage)},clearStorage:function(){var t;null==(t=f)||t.removeItem(a.name)},getOptions:function(){return a},rehydrate:function(){return m()},hasHydrated:function(){return u},onHydrate:function(t){return c.add(t),function(){c.delete(t)}},onFinishHydration:function(t){return s.add(t),function(){s.delete(t)}}},a.skipHydration||m(),g||y}}(t,n)};t.combine=function(t,e){return function(){return Object.assign({},t,e.apply(void 0,arguments))}},t.createJSONStorage=l,t.devtools=c,t.persist=v,t.redux=r,t.subscribeWithSelector=f}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandShallow = {}));
})(this, (function (exports) { 'use strict';

  function _arrayLikeToArray(r, a) {
    (null == a || a > r.length) && (a = r.length);
    for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
    return n;
  }
  function _createForOfIteratorHelperLoose(r, e) {
    var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (t) return (t = t.call(r)).next.bind(t);
    if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
      t && (r = t);
      var o = 0;
      return function () {
        return o >= r.length ? {
          done: !0
        } : {
          done: !1,
          value: r[o++]
        };
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  function _unsupportedIterableToArray(r, a) {
    if (r) {
      if ("string" == typeof r) return _arrayLikeToArray(r, a);
      var t = {}.toString.call(r).slice(8, -1);
      return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
    }
  }

  function shallow$1(objA, objB) {
    if (Object.is(objA, objB)) {
      return true;
    }
    if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
      return false;
    }
    if (objA instanceof Map && objB instanceof Map) {
      if (objA.size !== objB.size) return false;
      for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
        var _step$value = _step.value,
          key = _step$value[0],
          value = _step$value[1];
        if (!Object.is(value, objB.get(key))) {
          return false;
        }
      }
      return true;
    }
    if (objA instanceof Set && objB instanceof Set) {
      if (objA.size !== objB.size) return false;
      for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
        var _value = _step2.value;
        if (!objB.has(_value)) {
          return false;
        }
      }
      return true;
    }
    var keysA = Object.keys(objA);
    if (keysA.length !== Object.keys(objB).length) {
      return false;
    }
    for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
      var keyA = _keysA[_i];
      if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
        return false;
      }
    }
    return true;
  }

  var shallow = (function (objA, objB) {
    {
      console.warn("[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`.");
    }
    return shallow$1(objA, objB);
  });

  exports.default = shallow;
  exports.shallow = shallow$1;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandShallow={})}(this,(function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function r(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e))||r){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(var n,o=r(e);!(n=o()).done;){var i=n.value,a=i[0],f=i[1];if(!Object.is(f,t.get(a)))return!1}return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(var u,l=r(e);!(u=l()).done;){var s=u.value;if(!t.has(s))return!1}return!0}var c=Object.keys(e);if(c.length!==Object.keys(t).length)return!1;for(var d=0,y=c;d<y.length;d++){var b=y[d];if(!Object.prototype.hasOwnProperty.call(t,b)||!Object.is(e[b],t[b]))return!1}return!0}e.default=function(e,t){return n(e,t)},e.shallow=n,Object.defineProperty(e,"__esModule",{value:!0})}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('use-sync-external-store/shim/with-selector'), require('zustand/vanilla')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', 'use-sync-external-store/shim/with-selector', 'zustand/vanilla'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandTraditional = {}, global.React, global.useSyncExternalStoreShimWithSelector, global.zustandVanilla));
})(this, (function (exports, ReactExports, useSyncExternalStoreExports, vanilla) { 'use strict';

  var useDebugValue = ReactExports.useDebugValue;
  var useSyncExternalStoreWithSelector = useSyncExternalStoreExports.useSyncExternalStoreWithSelector;
  var identity = function identity(arg) {
    return arg;
  };
  function useStoreWithEqualityFn(api, selector, equalityFn) {
    if (selector === void 0) {
      selector = identity;
    }
    var slice = useSyncExternalStoreWithSelector(api.subscribe, api.getState, api.getServerState || api.getInitialState, selector, equalityFn);
    useDebugValue(slice);
    return slice;
  }
  var createWithEqualityFnImpl = function createWithEqualityFnImpl(createState, defaultEqualityFn) {
    var api = vanilla.createStore(createState);
    var useBoundStoreWithEqualityFn = function useBoundStoreWithEqualityFn(selector, equalityFn) {
      if (equalityFn === void 0) {
        equalityFn = defaultEqualityFn;
      }
      return useStoreWithEqualityFn(api, selector, equalityFn);
    };
    Object.assign(useBoundStoreWithEqualityFn, api);
    return useBoundStoreWithEqualityFn;
  };
  var createWithEqualityFn = function createWithEqualityFn(createState, defaultEqualityFn) {
    return createState ? createWithEqualityFnImpl(createState, defaultEqualityFn) : createWithEqualityFnImpl;
  };

  exports.createWithEqualityFn = createWithEqualityFn;
  exports.useStoreWithEqualityFn = useStoreWithEqualityFn;

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("use-sync-external-store/shim/with-selector"),require("zustand/vanilla")):"function"==typeof define&&define.amd?define(["exports","react","use-sync-external-store/shim/with-selector","zustand/vanilla"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandTraditional={},e.React,e.useSyncExternalStoreShimWithSelector,e.zustandVanilla)}(this,(function(e,t,n,r){"use strict";var i=t.useDebugValue,a=n.useSyncExternalStoreWithSelector,u=function(e){return e};function o(e,t,n){void 0===t&&(t=u);var r=a(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return i(r),r}var s=function(e,t){var n=r.createStore(e),i=function(e,r){return void 0===r&&(r=t),o(n,e,r)};return Object.assign(i,n),i};e.createWithEqualityFn=function(e,t){return e?s(e,t):s},e.useStoreWithEqualityFn=o}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandVanilla = {}));
})(this, (function (exports) { 'use strict';

  var createStoreImpl = function createStoreImpl(createState) {
    var state;
    var listeners = new Set();
    var setState = function setState(partial, replace) {
      var nextState = typeof partial === 'function' ? partial(state) : partial;
      if (!Object.is(nextState, state)) {
        var _previousState = state;
        state = (replace != null ? replace : typeof nextState !== 'object' || nextState === null) ? nextState : Object.assign({}, state, nextState);
        listeners.forEach(function (listener) {
          return listener(state, _previousState);
        });
      }
    };
    var getState = function getState() {
      return state;
    };
    var getInitialState = function getInitialState() {
      return initialState;
    };
    var subscribe = function subscribe(listener) {
      listeners.add(listener);
      return function () {
        return listeners.delete(listener);
      };
    };
    var destroy = function destroy() {
      {
        console.warn('[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected.');
      }
      listeners.clear();
    };
    var api = {
      setState: setState,
      getState: getState,
      getInitialState: getInitialState,
      subscribe: subscribe,
      destroy: destroy
    };
    var initialState = state = createState(setState, getState, api);
    return api;
  };
  var createStore = function createStore(createState) {
    return createState ? createStoreImpl(createState) : createStoreImpl;
  };
  var vanilla = (function (createState) {
    {
      console.warn("[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'.");
    }
    return createStore(createState);
  });

  exports.createStore = createStore;
  exports.default = vanilla;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandVanilla={})}(this,(function(e){"use strict";var t=function(e){var t,n=new Set,o=function(e,o){var u="function"==typeof e?e(t):e;if(!Object.is(u,t)){var r=t;t=(null!=o?o:"object"!=typeof u||null===u)?u:Object.assign({},t,u),n.forEach((function(e){return e(t,r)}))}},u=function(){return t},r={setState:o,getState:u,getInitialState:function(){return i},subscribe:function(e){return n.add(e),function(){return n.delete(e)}},destroy:function(){n.clear()}},i=t=e(o,u,r);return r},n=function(e){return e?t(e):t};e.createStore=n,e.default=function(e){return n(e)},Object.defineProperty(e,"__esModule",{value:!0})}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandVanillaShallow = {}));
})(this, (function (exports) { 'use strict';

  function _arrayLikeToArray(r, a) {
    (null == a || a > r.length) && (a = r.length);
    for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
    return n;
  }
  function _createForOfIteratorHelperLoose(r, e) {
    var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (t) return (t = t.call(r)).next.bind(t);
    if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
      t && (r = t);
      var o = 0;
      return function () {
        return o >= r.length ? {
          done: !0
        } : {
          done: !1,
          value: r[o++]
        };
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  function _unsupportedIterableToArray(r, a) {
    if (r) {
      if ("string" == typeof r) return _arrayLikeToArray(r, a);
      var t = {}.toString.call(r).slice(8, -1);
      return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
    }
  }

  function shallow(objA, objB) {
    if (Object.is(objA, objB)) {
      return true;
    }
    if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
      return false;
    }
    if (objA instanceof Map && objB instanceof Map) {
      if (objA.size !== objB.size) return false;
      for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
        var _step$value = _step.value,
          key = _step$value[0],
          value = _step$value[1];
        if (!Object.is(value, objB.get(key))) {
          return false;
        }
      }
      return true;
    }
    if (objA instanceof Set && objB instanceof Set) {
      if (objA.size !== objB.size) return false;
      for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
        var _value = _step2.value;
        if (!objB.has(_value)) {
          return false;
        }
      }
      return true;
    }
    var keysA = Object.keys(objA);
    if (keysA.length !== Object.keys(objB).length) {
      return false;
    }
    for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
      var keyA = _keysA[_i];
      if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
        return false;
      }
    }
    return true;
  }

  exports.shallow = shallow;

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandVanillaShallow={})}(this,(function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function r(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e))||r){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}e.shallow=function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(var n,o=r(e);!(n=o()).done;){var i=n.value,a=i[0],f=i[1];if(!Object.is(f,t.get(a)))return!1}return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(var l,u=r(e);!(l=u()).done;){var s=l.value;if(!t.has(s))return!1}return!0}var c=Object.keys(e);if(c.length!==Object.keys(t).length)return!1;for(var d=0,y=c;d<y.length;d++){var b=y[d];if(!Object.prototype.hasOwnProperty.call(t,b)||!Object.is(e[b],t[b]))return!1}return!0}}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandReactShallow = {}, global.React));
})(this, (function (exports, ReactExports) { 'use strict';

  function _arrayLikeToArray(r, a) {
    (null == a || a > r.length) && (a = r.length);
    for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
    return n;
  }
  function _createForOfIteratorHelperLoose(r, e) {
    var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (t) return (t = t.call(r)).next.bind(t);
    if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
      t && (r = t);
      var o = 0;
      return function () {
        return o >= r.length ? {
          done: !0
        } : {
          done: !1,
          value: r[o++]
        };
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  function _unsupportedIterableToArray(r, a) {
    if (r) {
      if ("string" == typeof r) return _arrayLikeToArray(r, a);
      var t = {}.toString.call(r).slice(8, -1);
      return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
    }
  }

  function shallow(objA, objB) {
    if (Object.is(objA, objB)) {
      return true;
    }
    if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
      return false;
    }
    if (objA instanceof Map && objB instanceof Map) {
      if (objA.size !== objB.size) return false;
      for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
        var _step$value = _step.value,
          key = _step$value[0],
          value = _step$value[1];
        if (!Object.is(value, objB.get(key))) {
          return false;
        }
      }
      return true;
    }
    if (objA instanceof Set && objB instanceof Set) {
      if (objA.size !== objB.size) return false;
      for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
        var _value = _step2.value;
        if (!objB.has(_value)) {
          return false;
        }
      }
      return true;
    }
    var keysA = Object.keys(objA);
    if (keysA.length !== Object.keys(objB).length) {
      return false;
    }
    for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
      var keyA = _keysA[_i];
      if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
        return false;
      }
    }
    return true;
  }

  var useRef = ReactExports.useRef;
  function useShallow(selector) {
    var prev = useRef();
    return function (state) {
      var next = selector(state);
      return shallow(prev.current, next) ? prev.current : prev.current = next;
    };
  }

  exports.useShallow = useShallow;

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandReactShallow={},e.React)}(this,(function(e,t){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function n(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(e))||t){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o=t.useRef;e.useShallow=function(e){var t=o();return function(r){var o=e(r);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(var r,o=n(e);!(r=o()).done;){var i=r.value,a=i[0],u=i[1];if(!Object.is(u,t.get(a)))return!1}return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(var f,c=n(e);!(f=c()).done;){var l=f.value;if(!t.has(l))return!1}return!0}var s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(var d=0,y=s;d<y.length;d++){var b=y[d];if(!Object.prototype.hasOwnProperty.call(t,b)||!Object.is(e[b],t[b]))return!1}return!0}(t.current,o)?t.current:t.current=o}}}));
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('immer')) :
  typeof define === 'function' && define.amd ? define(['exports', 'immer'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zustandMiddlewareImmer = {}, global.immer));
})(this, (function (exports, immer$1) { 'use strict';

  var immerImpl = function immerImpl(initializer) {
    return function (set, get, store) {
      store.setState = function (updater, replace) {
        var nextState = typeof updater === 'function' ? immer$1.produce(updater) : updater;
        for (var _len = arguments.length, a = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          a[_key - 2] = arguments[_key];
        }
        return set.apply(void 0, [nextState, replace].concat(a));
      };
      return initializer(store.setState, get, store);
    };
  };
  var immer = immerImpl;

  exports.immer = immer;

}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("immer")):"function"==typeof define&&define.amd?define(["exports","immer"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).zustandMiddlewareImmer={},e.immer)}(this,(function(e,t){"use strict";var n=function(e){return function(n,r,i){return i.setState=function(e,r){for(var i="function"==typeof e?t.produce(e):e,o=arguments.length,f=new Array(o>2?o-2:0),u=2;u<o;u++)f[u-2]=arguments[u];return n.apply(void 0,[i,r].concat(f))},e(i.setState,r,i)}};e.immer=n}));
System.register(['react', 'zustand/traditional'], (function (exports) {
  'use strict';
  var ReactExports, useStoreWithEqualityFn;
  return {
    setters: [function (module) {
      ReactExports = module.default;
    }, function (module) {
      useStoreWithEqualityFn = module.useStoreWithEqualityFn;
    }],
    execute: (function () {

      exports("default", createContext);

      const {
        createElement,
        createContext: reactCreateContext,
        useContext,
        useMemo,
        useRef
      } = ReactExports;
      function createContext() {
        {
          console.warn(
            "[DEPRECATED] `context` will be removed in a future version. Instead use `import { createStore, useStore } from 'zustand'`. See: https://github.com/pmndrs/zustand/discussions/1180."
          );
        }
        const ZustandContext = reactCreateContext(void 0);
        const Provider = ({
          createStore,
          children
        }) => {
          const storeRef = useRef();
          if (!storeRef.current) {
            storeRef.current = createStore();
          }
          return createElement(
            ZustandContext.Provider,
            { value: storeRef.current },
            children
          );
        };
        const useContextStore = (selector, equalityFn) => {
          const store = useContext(ZustandContext);
          if (!store) {
            throw new Error(
              "Seems like you have not used zustand provider as an ancestor."
            );
          }
          return useStoreWithEqualityFn(
            store,
            selector,
            equalityFn
          );
        };
        const useStoreApi = () => {
          const store = useContext(ZustandContext);
          if (!store) {
            throw new Error(
              "Seems like you have not used zustand provider as an ancestor."
            );
          }
          return useMemo(() => ({ ...store }), [store]);
        };
        return {
          Provider,
          useStore: useContextStore,
          useStoreApi
        };
      }

    })
  };
}));
System.register(["react","zustand/traditional"],function(a){"use strict";var o,s;return{setters:[function(r){o=r.default},function(r){s=r.useStoreWithEqualityFn}],execute:function(){a("default",l);const{createElement:r,createContext:c,useContext:i,useMemo:d,useRef:f}=o;function l(){const n=c(void 0);return{Provider:({createStore:e,children:u})=>{const t=f();return t.current||(t.current=e()),r(n.Provider,{value:t.current},u)},useStore:(e,u)=>{const t=i(n);if(!t)throw new Error("Seems like you have not used zustand provider as an ancestor.");return s(t,e,u)},useStoreApi:()=>{const e=i(n);if(!e)throw new Error("Seems like you have not used zustand provider as an ancestor.");return d(()=>({...e}),[e])}}}}}});
System.register(['zustand/vanilla', 'react', 'use-sync-external-store/shim/with-selector'], (function (exports) {
  'use strict';
  var _starExcludes = {
    __proto__: null,
    create: 1,
    default: 1,
    useStore: 1
  };
  var createStore, ReactExports, useSyncExternalStoreExports;
  return {
    setters: [function (module) {
      createStore = module.createStore;
      var setter = { __proto__: null };
      for (var name in module) {
        if (!_starExcludes[name]) setter[name] = module[name];
      }
      exports(setter);
    }, function (module) {
      ReactExports = module.default;
    }, function (module) {
      useSyncExternalStoreExports = module.default;
    }],
    execute: (function () {

      exports("useStore", useStore);

      const { useDebugValue } = ReactExports;
      const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
      let didWarnAboutEqualityFn = false;
      const identity = (arg) => arg;
      function useStore(api, selector = identity, equalityFn) {
        if (equalityFn && !didWarnAboutEqualityFn) {
          console.warn(
            "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"
          );
          didWarnAboutEqualityFn = true;
        }
        const slice = useSyncExternalStoreWithSelector(
          api.subscribe,
          api.getState,
          api.getServerState || api.getInitialState,
          selector,
          equalityFn
        );
        useDebugValue(slice);
        return slice;
      }
      const createImpl = (createState) => {
        if (typeof createState !== "function") {
          console.warn(
            "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`."
          );
        }
        const api = typeof createState === "function" ? createStore(createState) : createState;
        const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);
        Object.assign(useBoundStore, api);
        return useBoundStore;
      };
      const create = exports("create", (createState) => createState ? createImpl(createState) : createImpl);
      var react = exports("default", (createState) => {
        {
          console.warn(
            "[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`."
          );
        }
        return create(createState);
      });

    })
  };
}));
System.register(["zustand/vanilla","react","use-sync-external-store/shim/with-selector"],function(n){"use strict";var _={__proto__:null,create:1,default:1,useStore:1},o,i,l;return{setters:[function(t){o=t.createStore;var c={__proto__:null};for(var r in t)_[r]||(c[r]=t[r]);n(c)},function(t){i=t.default},function(t){l=t.default}],execute:function(){n("useStore",f);const{useDebugValue:t}=i,{useSyncExternalStoreWithSelector:c}=l,r=e=>e;function f(e,s=r,u){const a=c(e.subscribe,e.getState,e.getServerState||e.getInitialState,s,u);return t(a),a}const S=e=>{const s=typeof e=="function"?o(e):e,u=(a,g)=>f(s,a,g);return Object.assign(u,s),u},v=n("create",e=>e?S(e):S);var d=n("default",e=>v(e))}}});
System.register([], (function (exports) {
  'use strict';
  return {
    execute: (function () {

      exports("createJSONStorage", createJSONStorage);

      const reduxImpl = (reducer, initial) => (set, _get, api) => {
        api.dispatch = (action) => {
          set((state) => reducer(state, action), false, action);
          return action;
        };
        api.dispatchFromDevtools = true;
        return { dispatch: (...a) => api.dispatch(...a), ...initial };
      };
      const redux = exports("redux", reduxImpl);

      const trackedConnections = /* @__PURE__ */ new Map();
      const getTrackedConnectionState = (name) => {
        const api = trackedConnections.get(name);
        if (!api) return {};
        return Object.fromEntries(
          Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])
        );
      };
      const extractConnectionInformation = (store, extensionConnector, options) => {
        if (store === void 0) {
          return {
            type: "untracked",
            connection: extensionConnector.connect(options)
          };
        }
        const existingConnection = trackedConnections.get(options.name);
        if (existingConnection) {
          return { type: "tracked", store, ...existingConnection };
        }
        const newConnection = {
          connection: extensionConnector.connect(options),
          stores: {}
        };
        trackedConnections.set(options.name, newConnection);
        return { type: "tracked", store, ...newConnection };
      };
      const devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {
        const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;
        let extensionConnector;
        try {
          extensionConnector = (enabled != null ? enabled : true) && window.__REDUX_DEVTOOLS_EXTENSION__;
        } catch (_e) {
        }
        if (!extensionConnector) {
          if (enabled) {
            console.warn(
              "[zustand devtools middleware] Please install/enable Redux devtools extension"
            );
          }
          return fn(set, get, api);
        }
        const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);
        let isRecording = true;
        api.setState = (state, replace, nameOrAction) => {
          const r = set(state, replace);
          if (!isRecording) return r;
          const action = nameOrAction === void 0 ? { type: anonymousActionType || "anonymous" } : typeof nameOrAction === "string" ? { type: nameOrAction } : nameOrAction;
          if (store === void 0) {
            connection == null ? void 0 : connection.send(action, get());
            return r;
          }
          connection == null ? void 0 : connection.send(
            {
              ...action,
              type: `${store}/${action.type}`
            },
            {
              ...getTrackedConnectionState(options.name),
              [store]: api.getState()
            }
          );
          return r;
        };
        const setStateFromDevtools = (...a) => {
          const originalIsRecording = isRecording;
          isRecording = false;
          set(...a);
          isRecording = originalIsRecording;
        };
        const initialState = fn(api.setState, get, api);
        if (connectionInformation.type === "untracked") {
          connection == null ? void 0 : connection.init(initialState);
        } else {
          connectionInformation.stores[connectionInformation.store] = api;
          connection == null ? void 0 : connection.init(
            Object.fromEntries(
              Object.entries(connectionInformation.stores).map(([key, store2]) => [
                key,
                key === connectionInformation.store ? initialState : store2.getState()
              ])
            )
          );
        }
        if (api.dispatchFromDevtools && typeof api.dispatch === "function") {
          let didWarnAboutReservedActionType = false;
          const originalDispatch = api.dispatch;
          api.dispatch = (...a) => {
            if (a[0].type === "__setState" && !didWarnAboutReservedActionType) {
              console.warn(
                '[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'
              );
              didWarnAboutReservedActionType = true;
            }
            originalDispatch(...a);
          };
        }
        connection.subscribe((message) => {
          var _a;
          switch (message.type) {
            case "ACTION":
              if (typeof message.payload !== "string") {
                console.error(
                  "[zustand devtools middleware] Unsupported action format"
                );
                return;
              }
              return parseJsonThen(
                message.payload,
                (action) => {
                  if (action.type === "__setState") {
                    if (store === void 0) {
                      setStateFromDevtools(action.state);
                      return;
                    }
                    if (Object.keys(action.state).length !== 1) {
                      console.error(
                        `
                    [zustand devtools middleware] Unsupported __setState action format. 
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `
                      );
                    }
                    const stateFromDevtools = action.state[store];
                    if (stateFromDevtools === void 0 || stateFromDevtools === null) {
                      return;
                    }
                    if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {
                      setStateFromDevtools(stateFromDevtools);
                    }
                    return;
                  }
                  if (!api.dispatchFromDevtools) return;
                  if (typeof api.dispatch !== "function") return;
                  api.dispatch(action);
                }
              );
            case "DISPATCH":
              switch (message.payload.type) {
                case "RESET":
                  setStateFromDevtools(initialState);
                  if (store === void 0) {
                    return connection == null ? void 0 : connection.init(api.getState());
                  }
                  return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
                case "COMMIT":
                  if (store === void 0) {
                    connection == null ? void 0 : connection.init(api.getState());
                    return;
                  }
                  return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
                case "ROLLBACK":
                  return parseJsonThen(message.state, (state) => {
                    if (store === void 0) {
                      setStateFromDevtools(state);
                      connection == null ? void 0 : connection.init(api.getState());
                      return;
                    }
                    setStateFromDevtools(state[store]);
                    connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
                  });
                case "JUMP_TO_STATE":
                case "JUMP_TO_ACTION":
                  return parseJsonThen(message.state, (state) => {
                    if (store === void 0) {
                      setStateFromDevtools(state);
                      return;
                    }
                    if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {
                      setStateFromDevtools(state[store]);
                    }
                  });
                case "IMPORT_STATE": {
                  const { nextLiftedState } = message.payload;
                  const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;
                  if (!lastComputedState) return;
                  if (store === void 0) {
                    setStateFromDevtools(lastComputedState);
                  } else {
                    setStateFromDevtools(lastComputedState[store]);
                  }
                  connection == null ? void 0 : connection.send(
                    null,
                    // FIXME no-any
                    nextLiftedState
                  );
                  return;
                }
                case "PAUSE_RECORDING":
                  return isRecording = !isRecording;
              }
              return;
          }
        });
        return initialState;
      };
      const devtools = exports("devtools", devtoolsImpl);
      const parseJsonThen = (stringified, f) => {
        let parsed;
        try {
          parsed = JSON.parse(stringified);
        } catch (e) {
          console.error(
            "[zustand devtools middleware] Could not parse the received json",
            e
          );
        }
        if (parsed !== void 0) f(parsed);
      };

      const subscribeWithSelectorImpl = (fn) => (set, get, api) => {
        const origSubscribe = api.subscribe;
        api.subscribe = (selector, optListener, options) => {
          let listener = selector;
          if (optListener) {
            const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
            let currentSlice = selector(api.getState());
            listener = (state) => {
              const nextSlice = selector(state);
              if (!equalityFn(currentSlice, nextSlice)) {
                const previousSlice = currentSlice;
                optListener(currentSlice = nextSlice, previousSlice);
              }
            };
            if (options == null ? void 0 : options.fireImmediately) {
              optListener(currentSlice, currentSlice);
            }
          }
          return origSubscribe(listener);
        };
        const initialState = fn(set, get, api);
        return initialState;
      };
      const subscribeWithSelector = exports("subscribeWithSelector", subscribeWithSelectorImpl);

      const combine = exports("combine", (initialState, create) => (...a) => Object.assign({}, initialState, create(...a)));

      function createJSONStorage(getStorage, options) {
        let storage;
        try {
          storage = getStorage();
        } catch (_e) {
          return;
        }
        const persistStorage = {
          getItem: (name) => {
            var _a;
            const parse = (str2) => {
              if (str2 === null) {
                return null;
              }
              return JSON.parse(str2, options == null ? void 0 : options.reviver);
            };
            const str = (_a = storage.getItem(name)) != null ? _a : null;
            if (str instanceof Promise) {
              return str.then(parse);
            }
            return parse(str);
          },
          setItem: (name, newValue) => storage.setItem(
            name,
            JSON.stringify(newValue, options == null ? void 0 : options.replacer)
          ),
          removeItem: (name) => storage.removeItem(name)
        };
        return persistStorage;
      }
      const toThenable = (fn) => (input) => {
        try {
          const result = fn(input);
          if (result instanceof Promise) {
            return result;
          }
          return {
            then(onFulfilled) {
              return toThenable(onFulfilled)(result);
            },
            catch(_onRejected) {
              return this;
            }
          };
        } catch (e) {
          return {
            then(_onFulfilled) {
              return this;
            },
            catch(onRejected) {
              return toThenable(onRejected)(e);
            }
          };
        }
      };
      const oldImpl = (config, baseOptions) => (set, get, api) => {
        let options = {
          getStorage: () => localStorage,
          serialize: JSON.stringify,
          deserialize: JSON.parse,
          partialize: (state) => state,
          version: 0,
          merge: (persistedState, currentState) => ({
            ...currentState,
            ...persistedState
          }),
          ...baseOptions
        };
        let hasHydrated = false;
        const hydrationListeners = /* @__PURE__ */ new Set();
        const finishHydrationListeners = /* @__PURE__ */ new Set();
        let storage;
        try {
          storage = options.getStorage();
        } catch (_e) {
        }
        if (!storage) {
          return config(
            (...args) => {
              console.warn(
                `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
              );
              set(...args);
            },
            get,
            api
          );
        }
        const thenableSerialize = toThenable(options.serialize);
        const setItem = () => {
          const state = options.partialize({ ...get() });
          let errorInSync;
          const thenable = thenableSerialize({ state, version: options.version }).then(
            (serializedValue) => storage.setItem(options.name, serializedValue)
          ).catch((e) => {
            errorInSync = e;
          });
          if (errorInSync) {
            throw errorInSync;
          }
          return thenable;
        };
        const savedSetState = api.setState;
        api.setState = (state, replace) => {
          savedSetState(state, replace);
          void setItem();
        };
        const configResult = config(
          (...args) => {
            set(...args);
            void setItem();
          },
          get,
          api
        );
        let stateFromStorage;
        const hydrate = () => {
          var _a;
          if (!storage) return;
          hasHydrated = false;
          hydrationListeners.forEach((cb) => cb(get()));
          const postRehydrationCallback = ((_a = options.onRehydrateStorage) == null ? void 0 : _a.call(options, get())) || void 0;
          return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => {
            if (storageValue) {
              return options.deserialize(storageValue);
            }
          }).then((deserializedStorageValue) => {
            if (deserializedStorageValue) {
              if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
                if (options.migrate) {
                  return options.migrate(
                    deserializedStorageValue.state,
                    deserializedStorageValue.version
                  );
                }
                console.error(
                  `State loaded from storage couldn't be migrated since no migrate function was provided`
                );
              } else {
                return deserializedStorageValue.state;
              }
            }
          }).then((migratedState) => {
            var _a2;
            stateFromStorage = options.merge(
              migratedState,
              (_a2 = get()) != null ? _a2 : configResult
            );
            set(stateFromStorage, true);
            return setItem();
          }).then(() => {
            postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
            hasHydrated = true;
            finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
          }).catch((e) => {
            postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
          });
        };
        api.persist = {
          setOptions: (newOptions) => {
            options = {
              ...options,
              ...newOptions
            };
            if (newOptions.getStorage) {
              storage = newOptions.getStorage();
            }
          },
          clearStorage: () => {
            storage == null ? void 0 : storage.removeItem(options.name);
          },
          getOptions: () => options,
          rehydrate: () => hydrate(),
          hasHydrated: () => hasHydrated,
          onHydrate: (cb) => {
            hydrationListeners.add(cb);
            return () => {
              hydrationListeners.delete(cb);
            };
          },
          onFinishHydration: (cb) => {
            finishHydrationListeners.add(cb);
            return () => {
              finishHydrationListeners.delete(cb);
            };
          }
        };
        hydrate();
        return stateFromStorage || configResult;
      };
      const newImpl = (config, baseOptions) => (set, get, api) => {
        let options = {
          storage: createJSONStorage(() => localStorage),
          partialize: (state) => state,
          version: 0,
          merge: (persistedState, currentState) => ({
            ...currentState,
            ...persistedState
          }),
          ...baseOptions
        };
        let hasHydrated = false;
        const hydrationListeners = /* @__PURE__ */ new Set();
        const finishHydrationListeners = /* @__PURE__ */ new Set();
        let storage = options.storage;
        if (!storage) {
          return config(
            (...args) => {
              console.warn(
                `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
              );
              set(...args);
            },
            get,
            api
          );
        }
        const setItem = () => {
          const state = options.partialize({ ...get() });
          return storage.setItem(options.name, {
            state,
            version: options.version
          });
        };
        const savedSetState = api.setState;
        api.setState = (state, replace) => {
          savedSetState(state, replace);
          void setItem();
        };
        const configResult = config(
          (...args) => {
            set(...args);
            void setItem();
          },
          get,
          api
        );
        api.getInitialState = () => configResult;
        let stateFromStorage;
        const hydrate = () => {
          var _a, _b;
          if (!storage) return;
          hasHydrated = false;
          hydrationListeners.forEach((cb) => {
            var _a2;
            return cb((_a2 = get()) != null ? _a2 : configResult);
          });
          const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;
          return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
            if (deserializedStorageValue) {
              if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
                if (options.migrate) {
                  return [
                    true,
                    options.migrate(
                      deserializedStorageValue.state,
                      deserializedStorageValue.version
                    )
                  ];
                }
                console.error(
                  `State loaded from storage couldn't be migrated since no migrate function was provided`
                );
              } else {
                return [false, deserializedStorageValue.state];
              }
            }
            return [false, void 0];
          }).then((migrationResult) => {
            var _a2;
            const [migrated, migratedState] = migrationResult;
            stateFromStorage = options.merge(
              migratedState,
              (_a2 = get()) != null ? _a2 : configResult
            );
            set(stateFromStorage, true);
            if (migrated) {
              return setItem();
            }
          }).then(() => {
            postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
            stateFromStorage = get();
            hasHydrated = true;
            finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
          }).catch((e) => {
            postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
          });
        };
        api.persist = {
          setOptions: (newOptions) => {
            options = {
              ...options,
              ...newOptions
            };
            if (newOptions.storage) {
              storage = newOptions.storage;
            }
          },
          clearStorage: () => {
            storage == null ? void 0 : storage.removeItem(options.name);
          },
          getOptions: () => options,
          rehydrate: () => hydrate(),
          hasHydrated: () => hasHydrated,
          onHydrate: (cb) => {
            hydrationListeners.add(cb);
            return () => {
              hydrationListeners.delete(cb);
            };
          },
          onFinishHydration: (cb) => {
            finishHydrationListeners.add(cb);
            return () => {
              finishHydrationListeners.delete(cb);
            };
          }
        };
        if (!options.skipHydration) {
          hydrate();
        }
        return stateFromStorage || configResult;
      };
      const persistImpl = (config, baseOptions) => {
        if ("getStorage" in baseOptions || "serialize" in baseOptions || "deserialize" in baseOptions) {
          {
            console.warn(
              "[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."
            );
          }
          return oldImpl(config, baseOptions);
        }
        return newImpl(config, baseOptions);
      };
      const persist = exports("persist", persistImpl);

    })
  };
}));
System.register([],function(b){"use strict";return{execute:function(){b("createJSONStorage",E);const k=b("redux",(d,c)=>(s,o,n)=>(n.dispatch=e=>(s(g=>d(g,e),!1,e),e),n.dispatchFromDevtools=!0,{dispatch:(...e)=>n.dispatch(...e),...c})),I=new Map,w=d=>{const c=I.get(d);return c?Object.fromEntries(Object.entries(c.stores).map(([s,o])=>[s,o.getState()])):{}},T=(d,c,s)=>{if(d===void 0)return{type:"untracked",connection:c.connect(s)};const o=I.get(s.name);if(o)return{type:"tracked",store:d,...o};const n={connection:c.connect(s),stores:{}};return I.set(s.name,n),{type:"tracked",store:d,...n}},H=b("devtools",(d,c={})=>(s,o,n)=>{const{enabled:e,anonymousActionType:g,store:u,...h}=c;let m;try{m=(e!=null?e:!1)&&window.__REDUX_DEVTOOLS_EXTENSION__}catch(r){}if(!m)return d(s,o,n);const{connection:l,...S}=T(u,m,h);let f=!0;n.setState=(r,a,i)=>{const t=s(r,a);if(!f)return t;const p=i===void 0?{type:g||"anonymous"}:typeof i=="string"?{type:i}:i;return u===void 0?(l==null||l.send(p,o()),t):(l==null||l.send({...p,type:`${u}/${p.type}`},{...w(h.name),[u]:n.getState()}),t)};const v=(...r)=>{const a=f;f=!1,s(...r),f=a},y=d(n.setState,o,n);if(S.type==="untracked"?l==null||l.init(y):(S.stores[S.store]=n,l==null||l.init(Object.fromEntries(Object.entries(S.stores).map(([r,a])=>[r,r===S.store?y:a.getState()])))),n.dispatchFromDevtools&&typeof n.dispatch=="function"){const r=n.dispatch;n.dispatch=(...a)=>{r(...a)}}return l.subscribe(r=>{var a;switch(r.type){case"ACTION":if(typeof r.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return _(r.payload,i=>{if(i.type==="__setState"){if(u===void 0){v(i.state);return}Object.keys(i.state).length!==1&&console.error(`
                    [zustand devtools middleware] Unsupported __setState action format. 
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `);const t=i.state[u];if(t==null)return;JSON.stringify(n.getState())!==JSON.stringify(t)&&v(t);return}n.dispatchFromDevtools&&typeof n.dispatch=="function"&&n.dispatch(i)});case"DISPATCH":switch(r.payload.type){case"RESET":return v(y),u===void 0?l==null?void 0:l.init(n.getState()):l==null?void 0:l.init(w(h.name));case"COMMIT":if(u===void 0){l==null||l.init(n.getState());return}return l==null?void 0:l.init(w(h.name));case"ROLLBACK":return _(r.state,i=>{if(u===void 0){v(i),l==null||l.init(n.getState());return}v(i[u]),l==null||l.init(w(h.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return _(r.state,i=>{if(u===void 0){v(i);return}JSON.stringify(n.getState())!==JSON.stringify(i[u])&&v(i[u])});case"IMPORT_STATE":{const{nextLiftedState:i}=r.payload,t=(a=i.computedStates.slice(-1)[0])==null?void 0:a.state;if(!t)return;v(u===void 0?t:t[u]),l==null||l.send(null,i);return}case"PAUSE_RECORDING":return f=!f}return}}),y}),_=(d,c)=>{let s;try{s=JSON.parse(d)}catch(o){console.error("[zustand devtools middleware] Could not parse the received json",o)}s!==void 0&&c(s)},U=b("subscribeWithSelector",d=>(c,s,o)=>{const n=o.subscribe;return o.subscribe=(e,g,u)=>{let h=e;if(g){const m=(u==null?void 0:u.equalityFn)||Object.is;let l=e(o.getState());h=S=>{const f=e(S);if(!m(l,f)){const v=l;g(l=f,v)}},u!=null&&u.fireImmediately&&g(l,l)}return n(h)},d(c,s,o)}),C=b("combine",(d,c)=>(...s)=>Object.assign({},d,c(...s)));function E(d,c){let s;try{s=d()}catch(o){return}return{getItem:o=>{var n;const e=u=>u===null?null:JSON.parse(u,c==null?void 0:c.reviver),g=(n=s.getItem(o))!=null?n:null;return g instanceof Promise?g.then(e):e(g)},setItem:(o,n)=>s.setItem(o,JSON.stringify(n,c==null?void 0:c.replacer)),removeItem:o=>s.removeItem(o)}}const O=d=>c=>{try{const s=d(c);return s instanceof Promise?s:{then(o){return O(o)(s)},catch(o){return this}}}catch(s){return{then(o){return this},catch(o){return O(o)(s)}}}},N=(d,c)=>(s,o,n)=>{let e={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:a=>a,version:0,merge:(a,i)=>({...i,...a}),...c},g=!1;const u=new Set,h=new Set;let m;try{m=e.getStorage()}catch(a){}if(!m)return d((...a)=>{console.warn(`[zustand persist middleware] Unable to update item '${e.name}', the given storage is currently unavailable.`),s(...a)},o,n);const l=O(e.serialize),S=()=>{const a=e.partialize({...o()});let i;const t=l({state:a,version:e.version}).then(p=>m.setItem(e.name,p)).catch(p=>{i=p});if(i)throw i;return t},f=n.setState;n.setState=(a,i)=>{f(a,i),S()};const v=d((...a)=>{s(...a),S()},o,n);let y;const r=()=>{var a;if(!m)return;g=!1,u.forEach(t=>t(o()));const i=((a=e.onRehydrateStorage)==null?void 0:a.call(e,o()))||void 0;return O(m.getItem.bind(m))(e.name).then(t=>{if(t)return e.deserialize(t)}).then(t=>{if(t)if(typeof t.version=="number"&&t.version!==e.version){if(e.migrate)return e.migrate(t.state,t.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return t.state}).then(t=>{var p;return y=e.merge(t,(p=o())!=null?p:v),s(y,!0),S()}).then(()=>{i==null||i(y,void 0),g=!0,h.forEach(t=>t(y))}).catch(t=>{i==null||i(void 0,t)})};return n.persist={setOptions:a=>{e={...e,...a},a.getStorage&&(m=a.getStorage())},clearStorage:()=>{m==null||m.removeItem(e.name)},getOptions:()=>e,rehydrate:()=>r(),hasHydrated:()=>g,onHydrate:a=>(u.add(a),()=>{u.delete(a)}),onFinishHydration:a=>(h.add(a),()=>{h.delete(a)})},r(),y||v},z=(d,c)=>(s,o,n)=>{let e={storage:E(()=>localStorage),partialize:r=>r,version:0,merge:(r,a)=>({...a,...r}),...c},g=!1;const u=new Set,h=new Set;let m=e.storage;if(!m)return d((...r)=>{console.warn(`[zustand persist middleware] Unable to update item '${e.name}', the given storage is currently unavailable.`),s(...r)},o,n);const l=()=>{const r=e.partialize({...o()});return m.setItem(e.name,{state:r,version:e.version})},S=n.setState;n.setState=(r,a)=>{S(r,a),l()};const f=d((...r)=>{s(...r),l()},o,n);n.getInitialState=()=>f;let v;const y=()=>{var r,a;if(!m)return;g=!1,u.forEach(t=>{var p;return t((p=o())!=null?p:f)});const i=((a=e.onRehydrateStorage)==null?void 0:a.call(e,(r=o())!=null?r:f))||void 0;return O(m.getItem.bind(m))(e.name).then(t=>{if(t)if(typeof t.version=="number"&&t.version!==e.version){if(e.migrate)return[!0,e.migrate(t.state,t.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,t.state];return[!1,void 0]}).then(t=>{var p;const[J,A]=t;if(v=e.merge(A,(p=o())!=null?p:f),s(v,!0),J)return l()}).then(()=>{i==null||i(v,void 0),v=o(),g=!0,h.forEach(t=>t(v))}).catch(t=>{i==null||i(void 0,t)})};return n.persist={setOptions:r=>{e={...e,...r},r.storage&&(m=r.storage)},clearStorage:()=>{m==null||m.removeItem(e.name)},getOptions:()=>e,rehydrate:()=>y(),hasHydrated:()=>g,onHydrate:r=>(u.add(r),()=>{u.delete(r)}),onFinishHydration:r=>(h.add(r),()=>{h.delete(r)})},e.skipHydration||y(),v||f},$=b("persist",(d,c)=>"getStorage"in c||"serialize"in c||"deserialize"in c?N(d,c):z(d,c))}}});
System.register([], (function (exports) {
  'use strict';
  return {
    execute: (function () {

      exports("shallow", shallow$1);

      function shallow$1(objA, objB) {
        if (Object.is(objA, objB)) {
          return true;
        }
        if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
          return false;
        }
        if (objA instanceof Map && objB instanceof Map) {
          if (objA.size !== objB.size) return false;
          for (const [key, value] of objA) {
            if (!Object.is(value, objB.get(key))) {
              return false;
            }
          }
          return true;
        }
        if (objA instanceof Set && objB instanceof Set) {
          if (objA.size !== objB.size) return false;
          for (const value of objA) {
            if (!objB.has(value)) {
              return false;
            }
          }
          return true;
        }
        const keysA = Object.keys(objA);
        if (keysA.length !== Object.keys(objB).length) {
          return false;
        }
        for (const keyA of keysA) {
          if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
            return false;
          }
        }
        return true;
      }

      var shallow = exports("default", (objA, objB) => {
        {
          console.warn(
            "[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`."
          );
        }
        return shallow$1(objA, objB);
      });

    })
  };
}));
System.register([],function(n){"use strict";return{execute:function(){n("shallow",f);function f(t,r){if(Object.is(t,r))return!0;if(typeof t!="object"||t===null||typeof r!="object"||r===null)return!1;if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(const[e,o]of t)if(!Object.is(o,r.get(e)))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(const e of t)if(!r.has(e))return!1;return!0}const i=Object.keys(t);if(i.length!==Object.keys(r).length)return!1;for(const e of i)if(!Object.prototype.hasOwnProperty.call(r,e)||!Object.is(t[e],r[e]))return!1;return!0}var s=n("default",(t,r)=>f(t,r))}}});
System.register(['react', 'use-sync-external-store/shim/with-selector', 'zustand/vanilla'], (function (exports) {
  'use strict';
  var ReactExports, useSyncExternalStoreExports, createStore;
  return {
    setters: [function (module) {
      ReactExports = module.default;
    }, function (module) {
      useSyncExternalStoreExports = module.default;
    }, function (module) {
      createStore = module.createStore;
    }],
    execute: (function () {

      exports("useStoreWithEqualityFn", useStoreWithEqualityFn);

      const { useDebugValue } = ReactExports;
      const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
      const identity = (arg) => arg;
      function useStoreWithEqualityFn(api, selector = identity, equalityFn) {
        const slice = useSyncExternalStoreWithSelector(
          api.subscribe,
          api.getState,
          api.getServerState || api.getInitialState,
          selector,
          equalityFn
        );
        useDebugValue(slice);
        return slice;
      }
      const createWithEqualityFnImpl = (createState, defaultEqualityFn) => {
        const api = createStore(createState);
        const useBoundStoreWithEqualityFn = (selector, equalityFn = defaultEqualityFn) => useStoreWithEqualityFn(api, selector, equalityFn);
        Object.assign(useBoundStoreWithEqualityFn, api);
        return useBoundStoreWithEqualityFn;
      };
      const createWithEqualityFn = exports("createWithEqualityFn", (createState, defaultEqualityFn) => createState ? createWithEqualityFnImpl(createState, defaultEqualityFn) : createWithEqualityFnImpl);

    })
  };
}));
System.register(["react","use-sync-external-store/shim/with-selector","zustand/vanilla"],function(a){"use strict";var c,s,i;return{setters:[function(e){c=e.default},function(e){s=e.default},function(e){i=e.createStore}],execute:function(){a("useStoreWithEqualityFn",o);const{useDebugValue:e}=c,{useSyncExternalStoreWithSelector:S}=s,f=t=>t;function o(t,n=f,u){const r=S(t.subscribe,t.getState,t.getServerState||t.getInitialState,n,u);return e(r),r}const l=(t,n)=>{const u=i(t),r=(y,h=n)=>o(u,y,h);return Object.assign(r,u),r},g=a("createWithEqualityFn",(t,n)=>t?l(t,n):l)}}});
System.register([], (function (exports) {
  'use strict';
  return {
    execute: (function () {

      const createStoreImpl = (createState) => {
        let state;
        const listeners = /* @__PURE__ */ new Set();
        const setState = (partial, replace) => {
          const nextState = typeof partial === "function" ? partial(state) : partial;
          if (!Object.is(nextState, state)) {
            const previousState = state;
            state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
            listeners.forEach((listener) => listener(state, previousState));
          }
        };
        const getState = () => state;
        const getInitialState = () => initialState;
        const subscribe = (listener) => {
          listeners.add(listener);
          return () => listeners.delete(listener);
        };
        const destroy = () => {
          {
            console.warn(
              "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
            );
          }
          listeners.clear();
        };
        const api = { setState, getState, getInitialState, subscribe, destroy };
        const initialState = state = createState(setState, getState, api);
        return api;
      };
      const createStore = exports("createStore", (createState) => createState ? createStoreImpl(createState) : createStoreImpl);
      var vanilla = exports("default", (createState) => {
        {
          console.warn(
            "[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'."
          );
        }
        return createStore(createState);
      });

    })
  };
}));
System.register([],function(a){"use strict";return{execute:function(){const o=e=>{let t;const s=new Set,i=(c,l)=>{const n=typeof c=="function"?c(t):c;if(!Object.is(n,t)){const b=t;t=(l!=null?l:typeof n!="object"||n===null)?n:Object.assign({},t,n),s.forEach(d=>d(t,b))}},r=()=>t,u={setState:i,getState:r,getInitialState:()=>S,subscribe:c=>(s.add(c),()=>s.delete(c)),destroy:()=>{s.clear()}},S=t=e(i,r,u);return u},f=a("createStore",e=>e?o(e):o);var g=a("default",e=>f(e))}}});
System.register([], (function (exports) {
  'use strict';
  return {
    execute: (function () {

      exports("shallow", shallow);

      function shallow(objA, objB) {
        if (Object.is(objA, objB)) {
          return true;
        }
        if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
          return false;
        }
        if (objA instanceof Map && objB instanceof Map) {
          if (objA.size !== objB.size) return false;
          for (const [key, value] of objA) {
            if (!Object.is(value, objB.get(key))) {
              return false;
            }
          }
          return true;
        }
        if (objA instanceof Set && objB instanceof Set) {
          if (objA.size !== objB.size) return false;
          for (const value of objA) {
            if (!objB.has(value)) {
              return false;
            }
          }
          return true;
        }
        const keysA = Object.keys(objA);
        if (keysA.length !== Object.keys(objB).length) {
          return false;
        }
        for (const keyA of keysA) {
          if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
            return false;
          }
        }
        return true;
      }

    })
  };
}));
System.register([],function(f){"use strict";return{execute:function(){f("shallow",i);function i(t,r){if(Object.is(t,r))return!0;if(typeof t!="object"||t===null||typeof r!="object"||r===null)return!1;if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(const[e,o]of t)if(!Object.is(o,r.get(e)))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(const e of t)if(!r.has(e))return!1;return!0}const n=Object.keys(t);if(n.length!==Object.keys(r).length)return!1;for(const e of n)if(!Object.prototype.hasOwnProperty.call(r,e)||!Object.is(t[e],r[e]))return!1;return!0}}}});
System.register(['react'], (function (exports) {
  'use strict';
  var ReactExports;
  return {
    setters: [function (module) {
      ReactExports = module.default;
    }],
    execute: (function () {

      exports("useShallow", useShallow);

      function shallow(objA, objB) {
        if (Object.is(objA, objB)) {
          return true;
        }
        if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
          return false;
        }
        if (objA instanceof Map && objB instanceof Map) {
          if (objA.size !== objB.size) return false;
          for (const [key, value] of objA) {
            if (!Object.is(value, objB.get(key))) {
              return false;
            }
          }
          return true;
        }
        if (objA instanceof Set && objB instanceof Set) {
          if (objA.size !== objB.size) return false;
          for (const value of objA) {
            if (!objB.has(value)) {
              return false;
            }
          }
          return true;
        }
        const keysA = Object.keys(objA);
        if (keysA.length !== Object.keys(objB).length) {
          return false;
        }
        for (const keyA of keysA) {
          if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
            return false;
          }
        }
        return true;
      }

      const { useRef } = ReactExports;
      function useShallow(selector) {
        const prev = useRef();
        return (state) => {
          const next = selector(state);
          return shallow(prev.current, next) ? prev.current : prev.current = next;
        };
      }

    })
  };
}));
System.register(["react"],function(o){"use strict";var c;return{setters:[function(s){c=s.default}],execute:function(){o("useShallow",u);function s(r,t){if(Object.is(r,t))return!0;if(typeof r!="object"||r===null||typeof t!="object"||t===null)return!1;if(r instanceof Map&&t instanceof Map){if(r.size!==t.size)return!1;for(const[e,i]of r)if(!Object.is(i,t.get(e)))return!1;return!0}if(r instanceof Set&&t instanceof Set){if(r.size!==t.size)return!1;for(const e of r)if(!t.has(e))return!1;return!0}const n=Object.keys(r);if(n.length!==Object.keys(t).length)return!1;for(const e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],t[e]))return!1;return!0}const{useRef:f}=c;function u(r){const t=f();return n=>{const e=r(n);return s(t.current,e)?t.current:t.current=e}}}}});
System.register(['immer'], (function (exports) {
  'use strict';
  var produce;
  return {
    setters: [function (module) {
      produce = module.produce;
    }],
    execute: (function () {

      const immerImpl = (initializer) => (set, get, store) => {
        store.setState = (updater, replace, ...a) => {
          const nextState = typeof updater === "function" ? produce(updater) : updater;
          return set(nextState, replace, ...a);
        };
        return initializer(store.setState, get, store);
      };
      const immer = exports("immer", immerImpl);

    })
  };
}));
System.register(["immer"],function(c){"use strict";var r;return{setters:[function(n){r=n.produce}],execute:function(){const S=c("immer",s=>(o,u,t)=>(t.setState=(e,i,...m)=>{const f=typeof e=="function"?r(e):e;return o(f,i,...m)},s(t.setState,u,t)))}}});
'use strict';

var ReactExports = require('react');

function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _createForOfIteratorHelperLoose(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (t) return (t = t.call(r)).next.bind(t);
  if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
    t && (r = t);
    var o = 0;
    return function () {
      return o >= r.length ? {
        done: !0
      } : {
        done: !1,
        value: r[o++]
      };
    };
  }
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}

function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (var _iterator = _createForOfIteratorHelperLoose(objA), _step; !(_step = _iterator()).done;) {
      var _step$value = _step.value,
        key = _step$value[0],
        value = _step$value[1];
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (var _iterator2 = _createForOfIteratorHelperLoose(objA), _step2; !(_step2 = _iterator2()).done;) {
      var _value = _step2.value;
      if (!objB.has(_value)) {
        return false;
      }
    }
    return true;
  }
  var keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (var _i = 0, _keysA = keysA; _i < _keysA.length; _i++) {
    var keyA = _keysA[_i];
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

var useRef = ReactExports.useRef;
function useShallow(selector) {
  var prev = useRef();
  return function (state) {
    var next = selector(state);
    return shallow(prev.current, next) ? prev.current : prev.current = next;
  };
}

exports.useShallow = useShallow;
'use strict';

var immer$1 = require('immer');

var immerImpl = function immerImpl(initializer) {
  return function (set, get, store) {
    store.setState = function (updater, replace) {
      var nextState = typeof updater === 'function' ? immer$1.produce(updater) : updater;
      for (var _len = arguments.length, a = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
        a[_key - 2] = arguments[_key];
      }
      return set.apply(void 0, [nextState, replace].concat(a));
    };
    return initializer(store.setState, get, store);
  };
};
var immer = immerImpl;

exports.immer = immer;
import ReactExports from 'react';
import type { ReactNode } from 'react';
import type { StoreApi } from 'zustand';
type UseContextStore<S extends StoreApi<unknown>> = {
    (): ExtractState<S>;
    <U>(selector: (state: ExtractState<S>) => U, equalityFn?: (a: U, b: U) => boolean): U;
};
type ExtractState<S> = S extends {
    getState: () => infer T;
} ? T : never;
type WithoutCallSignature<T> = {
    [K in keyof T]: T[K];
};
/**
 * @deprecated Use `createStore` and `useStore` for context usage
 */
declare function createContext<S extends StoreApi<unknown>>(): {
    Provider: ({ createStore, children, }: {
        createStore: () => S;
        children: ReactNode;
    }) => ReactExports.FunctionComponentElement<ReactExports.ProviderProps<S | undefined>>;
    useStore: UseContextStore<S>;
    useStoreApi: () => WithoutCallSignature<S>;
};
export default createContext;
import ReactExports from 'react';
import { useStoreWithEqualityFn } from 'zustand/traditional';

const {
  createElement,
  createContext: reactCreateContext,
  useContext,
  useMemo,
  useRef
} = ReactExports;
function createContext() {
  if (process.env.NODE_ENV !== "production") {
    console.warn(
      "[DEPRECATED] `context` will be removed in a future version. Instead use `import { createStore, useStore } from 'zustand'`. See: https://github.com/pmndrs/zustand/discussions/1180."
    );
  }
  const ZustandContext = reactCreateContext(void 0);
  const Provider = ({
    createStore,
    children
  }) => {
    const storeRef = useRef();
    if (!storeRef.current) {
      storeRef.current = createStore();
    }
    return createElement(
      ZustandContext.Provider,
      { value: storeRef.current },
      children
    );
  };
  const useContextStore = (selector, equalityFn) => {
    const store = useContext(ZustandContext);
    if (!store) {
      throw new Error(
        "Seems like you have not used zustand provider as an ancestor."
      );
    }
    return useStoreWithEqualityFn(
      store,
      selector,
      equalityFn
    );
  };
  const useStoreApi = () => {
    const store = useContext(ZustandContext);
    if (!store) {
      throw new Error(
        "Seems like you have not used zustand provider as an ancestor."
      );
    }
    return useMemo(() => ({ ...store }), [store]);
  };
  return {
    Provider,
    useStore: useContextStore,
    useStoreApi
  };
}

export { createContext as default };
import ReactExports from 'react';
import { useStoreWithEqualityFn } from 'zustand/traditional';

const {
  createElement,
  createContext: reactCreateContext,
  useContext,
  useMemo,
  useRef
} = ReactExports;
function createContext() {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] `context` will be removed in a future version. Instead use `import { createStore, useStore } from 'zustand'`. See: https://github.com/pmndrs/zustand/discussions/1180."
    );
  }
  const ZustandContext = reactCreateContext(void 0);
  const Provider = ({
    createStore,
    children
  }) => {
    const storeRef = useRef();
    if (!storeRef.current) {
      storeRef.current = createStore();
    }
    return createElement(
      ZustandContext.Provider,
      { value: storeRef.current },
      children
    );
  };
  const useContextStore = (selector, equalityFn) => {
    const store = useContext(ZustandContext);
    if (!store) {
      throw new Error(
        "Seems like you have not used zustand provider as an ancestor."
      );
    }
    return useStoreWithEqualityFn(
      store,
      selector,
      equalityFn
    );
  };
  const useStoreApi = () => {
    const store = useContext(ZustandContext);
    if (!store) {
      throw new Error(
        "Seems like you have not used zustand provider as an ancestor."
      );
    }
    return useMemo(() => ({ ...store }), [store]);
  };
  return {
    Provider,
    useStore: useContextStore,
    useStoreApi
  };
}

export { createContext as default };
export * from './vanilla.mjs';
export * from './react.mjs';
export { default } from './react.mjs';
import { createStore } from 'zustand/vanilla';
export * from 'zustand/vanilla';
import ReactExports from 'react';
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector.js';

const { useDebugValue } = ReactExports;
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
let didWarnAboutEqualityFn = false;
const identity = (arg) => arg;
function useStore(api, selector = identity, equalityFn) {
  if (process.env.NODE_ENV !== "production" && equalityFn && !didWarnAboutEqualityFn) {
    console.warn(
      "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"
    );
    didWarnAboutEqualityFn = true;
  }
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getServerState || api.getInitialState,
    selector,
    equalityFn
  );
  useDebugValue(slice);
  return slice;
}
const createImpl = (createState) => {
  if (process.env.NODE_ENV !== "production" && typeof createState !== "function") {
    console.warn(
      "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`."
    );
  }
  const api = typeof createState === "function" ? createStore(createState) : createState;
  const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);
  Object.assign(useBoundStore, api);
  return useBoundStore;
};
const create = (createState) => createState ? createImpl(createState) : createImpl;
var react = (createState) => {
  if (process.env.NODE_ENV !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`."
    );
  }
  return create(createState);
};

export { create, react as default, useStore };
import { createStore } from 'zustand/vanilla';
export * from 'zustand/vanilla';
import ReactExports from 'react';
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector.js';

const { useDebugValue } = ReactExports;
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
let didWarnAboutEqualityFn = false;
const identity = (arg) => arg;
function useStore(api, selector = identity, equalityFn) {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && equalityFn && !didWarnAboutEqualityFn) {
    console.warn(
      "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"
    );
    didWarnAboutEqualityFn = true;
  }
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getServerState || api.getInitialState,
    selector,
    equalityFn
  );
  useDebugValue(slice);
  return slice;
}
const createImpl = (createState) => {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && typeof createState !== "function") {
    console.warn(
      "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`."
    );
  }
  const api = typeof createState === "function" ? createStore(createState) : createState;
  const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);
  Object.assign(useBoundStore, api);
  return useBoundStore;
};
const create = (createState) => createState ? createImpl(createState) : createImpl;
var react = (createState) => {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`."
    );
  }
  return create(createState);
};

export { create, react as default, useStore };
export * from './middleware/redux.mjs';
export * from './middleware/devtools.mjs';
export * from './middleware/subscribeWithSelector.mjs';
export * from './middleware/combine.mjs';
export * from './middleware/persist.mjs';
const reduxImpl = (reducer, initial) => (set, _get, api) => {
  api.dispatch = (action) => {
    set((state) => reducer(state, action), false, action);
    return action;
  };
  api.dispatchFromDevtools = true;
  return { dispatch: (...a) => api.dispatch(...a), ...initial };
};
const redux = reduxImpl;

const trackedConnections = /* @__PURE__ */ new Map();
const getTrackedConnectionState = (name) => {
  const api = trackedConnections.get(name);
  if (!api) return {};
  return Object.fromEntries(
    Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])
  );
};
const extractConnectionInformation = (store, extensionConnector, options) => {
  if (store === void 0) {
    return {
      type: "untracked",
      connection: extensionConnector.connect(options)
    };
  }
  const existingConnection = trackedConnections.get(options.name);
  if (existingConnection) {
    return { type: "tracked", store, ...existingConnection };
  }
  const newConnection = {
    connection: extensionConnector.connect(options),
    stores: {}
  };
  trackedConnections.set(options.name, newConnection);
  return { type: "tracked", store, ...newConnection };
};
const devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {
  const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;
  let extensionConnector;
  try {
    extensionConnector = (enabled != null ? enabled : process.env.NODE_ENV !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
  } catch (_e) {
  }
  if (!extensionConnector) {
    if (process.env.NODE_ENV !== "production" && enabled) {
      console.warn(
        "[zustand devtools middleware] Please install/enable Redux devtools extension"
      );
    }
    return fn(set, get, api);
  }
  const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);
  let isRecording = true;
  api.setState = (state, replace, nameOrAction) => {
    const r = set(state, replace);
    if (!isRecording) return r;
    const action = nameOrAction === void 0 ? { type: anonymousActionType || "anonymous" } : typeof nameOrAction === "string" ? { type: nameOrAction } : nameOrAction;
    if (store === void 0) {
      connection == null ? void 0 : connection.send(action, get());
      return r;
    }
    connection == null ? void 0 : connection.send(
      {
        ...action,
        type: `${store}/${action.type}`
      },
      {
        ...getTrackedConnectionState(options.name),
        [store]: api.getState()
      }
    );
    return r;
  };
  const setStateFromDevtools = (...a) => {
    const originalIsRecording = isRecording;
    isRecording = false;
    set(...a);
    isRecording = originalIsRecording;
  };
  const initialState = fn(api.setState, get, api);
  if (connectionInformation.type === "untracked") {
    connection == null ? void 0 : connection.init(initialState);
  } else {
    connectionInformation.stores[connectionInformation.store] = api;
    connection == null ? void 0 : connection.init(
      Object.fromEntries(
        Object.entries(connectionInformation.stores).map(([key, store2]) => [
          key,
          key === connectionInformation.store ? initialState : store2.getState()
        ])
      )
    );
  }
  if (api.dispatchFromDevtools && typeof api.dispatch === "function") {
    let didWarnAboutReservedActionType = false;
    const originalDispatch = api.dispatch;
    api.dispatch = (...a) => {
      if (process.env.NODE_ENV !== "production" && a[0].type === "__setState" && !didWarnAboutReservedActionType) {
        console.warn(
          '[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'
        );
        didWarnAboutReservedActionType = true;
      }
      originalDispatch(...a);
    };
  }
  connection.subscribe((message) => {
    var _a;
    switch (message.type) {
      case "ACTION":
        if (typeof message.payload !== "string") {
          console.error(
            "[zustand devtools middleware] Unsupported action format"
          );
          return;
        }
        return parseJsonThen(
          message.payload,
          (action) => {
            if (action.type === "__setState") {
              if (store === void 0) {
                setStateFromDevtools(action.state);
                return;
              }
              if (Object.keys(action.state).length !== 1) {
                console.error(
                  `
                    [zustand devtools middleware] Unsupported __setState action format. 
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `
                );
              }
              const stateFromDevtools = action.state[store];
              if (stateFromDevtools === void 0 || stateFromDevtools === null) {
                return;
              }
              if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {
                setStateFromDevtools(stateFromDevtools);
              }
              return;
            }
            if (!api.dispatchFromDevtools) return;
            if (typeof api.dispatch !== "function") return;
            api.dispatch(action);
          }
        );
      case "DISPATCH":
        switch (message.payload.type) {
          case "RESET":
            setStateFromDevtools(initialState);
            if (store === void 0) {
              return connection == null ? void 0 : connection.init(api.getState());
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "COMMIT":
            if (store === void 0) {
              connection == null ? void 0 : connection.init(api.getState());
              return;
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "ROLLBACK":
            return parseJsonThen(message.state, (state) => {
              if (store === void 0) {
                setStateFromDevtools(state);
                connection == null ? void 0 : connection.init(api.getState());
                return;
              }
              setStateFromDevtools(state[store]);
              connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
            });
          case "JUMP_TO_STATE":
          case "JUMP_TO_ACTION":
            return parseJsonThen(message.state, (state) => {
              if (store === void 0) {
                setStateFromDevtools(state);
                return;
              }
              if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {
                setStateFromDevtools(state[store]);
              }
            });
          case "IMPORT_STATE": {
            const { nextLiftedState } = message.payload;
            const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;
            if (!lastComputedState) return;
            if (store === void 0) {
              setStateFromDevtools(lastComputedState);
            } else {
              setStateFromDevtools(lastComputedState[store]);
            }
            connection == null ? void 0 : connection.send(
              null,
              // FIXME no-any
              nextLiftedState
            );
            return;
          }
          case "PAUSE_RECORDING":
            return isRecording = !isRecording;
        }
        return;
    }
  });
  return initialState;
};
const devtools = devtoolsImpl;
const parseJsonThen = (stringified, f) => {
  let parsed;
  try {
    parsed = JSON.parse(stringified);
  } catch (e) {
    console.error(
      "[zustand devtools middleware] Could not parse the received json",
      e
    );
  }
  if (parsed !== void 0) f(parsed);
};

const subscribeWithSelectorImpl = (fn) => (set, get, api) => {
  const origSubscribe = api.subscribe;
  api.subscribe = (selector, optListener, options) => {
    let listener = selector;
    if (optListener) {
      const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
      let currentSlice = selector(api.getState());
      listener = (state) => {
        const nextSlice = selector(state);
        if (!equalityFn(currentSlice, nextSlice)) {
          const previousSlice = currentSlice;
          optListener(currentSlice = nextSlice, previousSlice);
        }
      };
      if (options == null ? void 0 : options.fireImmediately) {
        optListener(currentSlice, currentSlice);
      }
    }
    return origSubscribe(listener);
  };
  const initialState = fn(set, get, api);
  return initialState;
};
const subscribeWithSelector = subscribeWithSelectorImpl;

const combine = (initialState, create) => (...a) => Object.assign({}, initialState, create(...a));

function createJSONStorage(getStorage, options) {
  let storage;
  try {
    storage = getStorage();
  } catch (_e) {
    return;
  }
  const persistStorage = {
    getItem: (name) => {
      var _a;
      const parse = (str2) => {
        if (str2 === null) {
          return null;
        }
        return JSON.parse(str2, options == null ? void 0 : options.reviver);
      };
      const str = (_a = storage.getItem(name)) != null ? _a : null;
      if (str instanceof Promise) {
        return str.then(parse);
      }
      return parse(str);
    },
    setItem: (name, newValue) => storage.setItem(
      name,
      JSON.stringify(newValue, options == null ? void 0 : options.replacer)
    ),
    removeItem: (name) => storage.removeItem(name)
  };
  return persistStorage;
}
const toThenable = (fn) => (input) => {
  try {
    const result = fn(input);
    if (result instanceof Promise) {
      return result;
    }
    return {
      then(onFulfilled) {
        return toThenable(onFulfilled)(result);
      },
      catch(_onRejected) {
        return this;
      }
    };
  } catch (e) {
    return {
      then(_onFulfilled) {
        return this;
      },
      catch(onRejected) {
        return toThenable(onRejected)(e);
      }
    };
  }
};
const oldImpl = (config, baseOptions) => (set, get, api) => {
  let options = {
    getStorage: () => localStorage,
    serialize: JSON.stringify,
    deserialize: JSON.parse,
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage;
  try {
    storage = options.getStorage();
  } catch (_e) {
  }
  if (!storage) {
    return config(
      (...args) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
        );
        set(...args);
      },
      get,
      api
    );
  }
  const thenableSerialize = toThenable(options.serialize);
  const setItem = () => {
    const state = options.partialize({ ...get() });
    let errorInSync;
    const thenable = thenableSerialize({ state, version: options.version }).then(
      (serializedValue) => storage.setItem(options.name, serializedValue)
    ).catch((e) => {
      errorInSync = e;
    });
    if (errorInSync) {
      throw errorInSync;
    }
    return thenable;
  };
  const savedSetState = api.setState;
  api.setState = (state, replace) => {
    savedSetState(state, replace);
    void setItem();
  };
  const configResult = config(
    (...args) => {
      set(...args);
      void setItem();
    },
    get,
    api
  );
  let stateFromStorage;
  const hydrate = () => {
    var _a;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => cb(get()));
    const postRehydrationCallback = ((_a = options.onRehydrateStorage) == null ? void 0 : _a.call(options, get())) || void 0;
    return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => {
      if (storageValue) {
        return options.deserialize(storageValue);
      }
    }).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
          if (options.migrate) {
            return options.migrate(
              deserializedStorageValue.state,
              deserializedStorageValue.version
            );
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return deserializedStorageValue.state;
        }
      }
    }).then((migratedState) => {
      var _a2;
      stateFromStorage = options.merge(
        migratedState,
        (_a2 = get()) != null ? _a2 : configResult
      );
      set(stateFromStorage, true);
      return setItem();
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
    });
  };
  api.persist = {
    setOptions: (newOptions) => {
      options = {
        ...options,
        ...newOptions
      };
      if (newOptions.getStorage) {
        storage = newOptions.getStorage();
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options.name);
    },
    getOptions: () => options,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  hydrate();
  return stateFromStorage || configResult;
};
const newImpl = (config, baseOptions) => (set, get, api) => {
  let options = {
    storage: createJSONStorage(() => localStorage),
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage = options.storage;
  if (!storage) {
    return config(
      (...args) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
        );
        set(...args);
      },
      get,
      api
    );
  }
  const setItem = () => {
    const state = options.partialize({ ...get() });
    return storage.setItem(options.name, {
      state,
      version: options.version
    });
  };
  const savedSetState = api.setState;
  api.setState = (state, replace) => {
    savedSetState(state, replace);
    void setItem();
  };
  const configResult = config(
    (...args) => {
      set(...args);
      void setItem();
    },
    get,
    api
  );
  api.getInitialState = () => configResult;
  let stateFromStorage;
  const hydrate = () => {
    var _a, _b;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => {
      var _a2;
      return cb((_a2 = get()) != null ? _a2 : configResult);
    });
    const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;
    return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
          if (options.migrate) {
            return [
              true,
              options.migrate(
                deserializedStorageValue.state,
                deserializedStorageValue.version
              )
            ];
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return [false, deserializedStorageValue.state];
        }
      }
      return [false, void 0];
    }).then((migrationResult) => {
      var _a2;
      const [migrated, migratedState] = migrationResult;
      stateFromStorage = options.merge(
        migratedState,
        (_a2 = get()) != null ? _a2 : configResult
      );
      set(stateFromStorage, true);
      if (migrated) {
        return setItem();
      }
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      stateFromStorage = get();
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
    });
  };
  api.persist = {
    setOptions: (newOptions) => {
      options = {
        ...options,
        ...newOptions
      };
      if (newOptions.storage) {
        storage = newOptions.storage;
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options.name);
    },
    getOptions: () => options,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  if (!options.skipHydration) {
    hydrate();
  }
  return stateFromStorage || configResult;
};
const persistImpl = (config, baseOptions) => {
  if ("getStorage" in baseOptions || "serialize" in baseOptions || "deserialize" in baseOptions) {
    if (process.env.NODE_ENV !== "production") {
      console.warn(
        "[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."
      );
    }
    return oldImpl(config, baseOptions);
  }
  return newImpl(config, baseOptions);
};
const persist = persistImpl;

export { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector };
const reduxImpl = (reducer, initial) => (set, _get, api) => {
  api.dispatch = (action) => {
    set((state) => reducer(state, action), false, action);
    return action;
  };
  api.dispatchFromDevtools = true;
  return { dispatch: (...a) => api.dispatch(...a), ...initial };
};
const redux = reduxImpl;

const trackedConnections = /* @__PURE__ */ new Map();
const getTrackedConnectionState = (name) => {
  const api = trackedConnections.get(name);
  if (!api) return {};
  return Object.fromEntries(
    Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])
  );
};
const extractConnectionInformation = (store, extensionConnector, options) => {
  if (store === void 0) {
    return {
      type: "untracked",
      connection: extensionConnector.connect(options)
    };
  }
  const existingConnection = trackedConnections.get(options.name);
  if (existingConnection) {
    return { type: "tracked", store, ...existingConnection };
  }
  const newConnection = {
    connection: extensionConnector.connect(options),
    stores: {}
  };
  trackedConnections.set(options.name, newConnection);
  return { type: "tracked", store, ...newConnection };
};
const devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {
  const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;
  let extensionConnector;
  try {
    extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
  } catch (_e) {
  }
  if (!extensionConnector) {
    if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && enabled) {
      console.warn(
        "[zustand devtools middleware] Please install/enable Redux devtools extension"
      );
    }
    return fn(set, get, api);
  }
  const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);
  let isRecording = true;
  api.setState = (state, replace, nameOrAction) => {
    const r = set(state, replace);
    if (!isRecording) return r;
    const action = nameOrAction === void 0 ? { type: anonymousActionType || "anonymous" } : typeof nameOrAction === "string" ? { type: nameOrAction } : nameOrAction;
    if (store === void 0) {
      connection == null ? void 0 : connection.send(action, get());
      return r;
    }
    connection == null ? void 0 : connection.send(
      {
        ...action,
        type: `${store}/${action.type}`
      },
      {
        ...getTrackedConnectionState(options.name),
        [store]: api.getState()
      }
    );
    return r;
  };
  const setStateFromDevtools = (...a) => {
    const originalIsRecording = isRecording;
    isRecording = false;
    set(...a);
    isRecording = originalIsRecording;
  };
  const initialState = fn(api.setState, get, api);
  if (connectionInformation.type === "untracked") {
    connection == null ? void 0 : connection.init(initialState);
  } else {
    connectionInformation.stores[connectionInformation.store] = api;
    connection == null ? void 0 : connection.init(
      Object.fromEntries(
        Object.entries(connectionInformation.stores).map(([key, store2]) => [
          key,
          key === connectionInformation.store ? initialState : store2.getState()
        ])
      )
    );
  }
  if (api.dispatchFromDevtools && typeof api.dispatch === "function") {
    let didWarnAboutReservedActionType = false;
    const originalDispatch = api.dispatch;
    api.dispatch = (...a) => {
      if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && a[0].type === "__setState" && !didWarnAboutReservedActionType) {
        console.warn(
          '[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'
        );
        didWarnAboutReservedActionType = true;
      }
      originalDispatch(...a);
    };
  }
  connection.subscribe((message) => {
    var _a;
    switch (message.type) {
      case "ACTION":
        if (typeof message.payload !== "string") {
          console.error(
            "[zustand devtools middleware] Unsupported action format"
          );
          return;
        }
        return parseJsonThen(
          message.payload,
          (action) => {
            if (action.type === "__setState") {
              if (store === void 0) {
                setStateFromDevtools(action.state);
                return;
              }
              if (Object.keys(action.state).length !== 1) {
                console.error(
                  `
                    [zustand devtools middleware] Unsupported __setState action format. 
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `
                );
              }
              const stateFromDevtools = action.state[store];
              if (stateFromDevtools === void 0 || stateFromDevtools === null) {
                return;
              }
              if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {
                setStateFromDevtools(stateFromDevtools);
              }
              return;
            }
            if (!api.dispatchFromDevtools) return;
            if (typeof api.dispatch !== "function") return;
            api.dispatch(action);
          }
        );
      case "DISPATCH":
        switch (message.payload.type) {
          case "RESET":
            setStateFromDevtools(initialState);
            if (store === void 0) {
              return connection == null ? void 0 : connection.init(api.getState());
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "COMMIT":
            if (store === void 0) {
              connection == null ? void 0 : connection.init(api.getState());
              return;
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "ROLLBACK":
            return parseJsonThen(message.state, (state) => {
              if (store === void 0) {
                setStateFromDevtools(state);
                connection == null ? void 0 : connection.init(api.getState());
                return;
              }
              setStateFromDevtools(state[store]);
              connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
            });
          case "JUMP_TO_STATE":
          case "JUMP_TO_ACTION":
            return parseJsonThen(message.state, (state) => {
              if (store === void 0) {
                setStateFromDevtools(state);
                return;
              }
              if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {
                setStateFromDevtools(state[store]);
              }
            });
          case "IMPORT_STATE": {
            const { nextLiftedState } = message.payload;
            const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;
            if (!lastComputedState) return;
            if (store === void 0) {
              setStateFromDevtools(lastComputedState);
            } else {
              setStateFromDevtools(lastComputedState[store]);
            }
            connection == null ? void 0 : connection.send(
              null,
              // FIXME no-any
              nextLiftedState
            );
            return;
          }
          case "PAUSE_RECORDING":
            return isRecording = !isRecording;
        }
        return;
    }
  });
  return initialState;
};
const devtools = devtoolsImpl;
const parseJsonThen = (stringified, f) => {
  let parsed;
  try {
    parsed = JSON.parse(stringified);
  } catch (e) {
    console.error(
      "[zustand devtools middleware] Could not parse the received json",
      e
    );
  }
  if (parsed !== void 0) f(parsed);
};

const subscribeWithSelectorImpl = (fn) => (set, get, api) => {
  const origSubscribe = api.subscribe;
  api.subscribe = (selector, optListener, options) => {
    let listener = selector;
    if (optListener) {
      const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
      let currentSlice = selector(api.getState());
      listener = (state) => {
        const nextSlice = selector(state);
        if (!equalityFn(currentSlice, nextSlice)) {
          const previousSlice = currentSlice;
          optListener(currentSlice = nextSlice, previousSlice);
        }
      };
      if (options == null ? void 0 : options.fireImmediately) {
        optListener(currentSlice, currentSlice);
      }
    }
    return origSubscribe(listener);
  };
  const initialState = fn(set, get, api);
  return initialState;
};
const subscribeWithSelector = subscribeWithSelectorImpl;

const combine = (initialState, create) => (...a) => Object.assign({}, initialState, create(...a));

function createJSONStorage(getStorage, options) {
  let storage;
  try {
    storage = getStorage();
  } catch (_e) {
    return;
  }
  const persistStorage = {
    getItem: (name) => {
      var _a;
      const parse = (str2) => {
        if (str2 === null) {
          return null;
        }
        return JSON.parse(str2, options == null ? void 0 : options.reviver);
      };
      const str = (_a = storage.getItem(name)) != null ? _a : null;
      if (str instanceof Promise) {
        return str.then(parse);
      }
      return parse(str);
    },
    setItem: (name, newValue) => storage.setItem(
      name,
      JSON.stringify(newValue, options == null ? void 0 : options.replacer)
    ),
    removeItem: (name) => storage.removeItem(name)
  };
  return persistStorage;
}
const toThenable = (fn) => (input) => {
  try {
    const result = fn(input);
    if (result instanceof Promise) {
      return result;
    }
    return {
      then(onFulfilled) {
        return toThenable(onFulfilled)(result);
      },
      catch(_onRejected) {
        return this;
      }
    };
  } catch (e) {
    return {
      then(_onFulfilled) {
        return this;
      },
      catch(onRejected) {
        return toThenable(onRejected)(e);
      }
    };
  }
};
const oldImpl = (config, baseOptions) => (set, get, api) => {
  let options = {
    getStorage: () => localStorage,
    serialize: JSON.stringify,
    deserialize: JSON.parse,
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage;
  try {
    storage = options.getStorage();
  } catch (_e) {
  }
  if (!storage) {
    return config(
      (...args) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
        );
        set(...args);
      },
      get,
      api
    );
  }
  const thenableSerialize = toThenable(options.serialize);
  const setItem = () => {
    const state = options.partialize({ ...get() });
    let errorInSync;
    const thenable = thenableSerialize({ state, version: options.version }).then(
      (serializedValue) => storage.setItem(options.name, serializedValue)
    ).catch((e) => {
      errorInSync = e;
    });
    if (errorInSync) {
      throw errorInSync;
    }
    return thenable;
  };
  const savedSetState = api.setState;
  api.setState = (state, replace) => {
    savedSetState(state, replace);
    void setItem();
  };
  const configResult = config(
    (...args) => {
      set(...args);
      void setItem();
    },
    get,
    api
  );
  let stateFromStorage;
  const hydrate = () => {
    var _a;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => cb(get()));
    const postRehydrationCallback = ((_a = options.onRehydrateStorage) == null ? void 0 : _a.call(options, get())) || void 0;
    return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => {
      if (storageValue) {
        return options.deserialize(storageValue);
      }
    }).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
          if (options.migrate) {
            return options.migrate(
              deserializedStorageValue.state,
              deserializedStorageValue.version
            );
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return deserializedStorageValue.state;
        }
      }
    }).then((migratedState) => {
      var _a2;
      stateFromStorage = options.merge(
        migratedState,
        (_a2 = get()) != null ? _a2 : configResult
      );
      set(stateFromStorage, true);
      return setItem();
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
    });
  };
  api.persist = {
    setOptions: (newOptions) => {
      options = {
        ...options,
        ...newOptions
      };
      if (newOptions.getStorage) {
        storage = newOptions.getStorage();
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options.name);
    },
    getOptions: () => options,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  hydrate();
  return stateFromStorage || configResult;
};
const newImpl = (config, baseOptions) => (set, get, api) => {
  let options = {
    storage: createJSONStorage(() => localStorage),
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage = options.storage;
  if (!storage) {
    return config(
      (...args) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
        );
        set(...args);
      },
      get,
      api
    );
  }
  const setItem = () => {
    const state = options.partialize({ ...get() });
    return storage.setItem(options.name, {
      state,
      version: options.version
    });
  };
  const savedSetState = api.setState;
  api.setState = (state, replace) => {
    savedSetState(state, replace);
    void setItem();
  };
  const configResult = config(
    (...args) => {
      set(...args);
      void setItem();
    },
    get,
    api
  );
  api.getInitialState = () => configResult;
  let stateFromStorage;
  const hydrate = () => {
    var _a, _b;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => {
      var _a2;
      return cb((_a2 = get()) != null ? _a2 : configResult);
    });
    const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;
    return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
          if (options.migrate) {
            return [
              true,
              options.migrate(
                deserializedStorageValue.state,
                deserializedStorageValue.version
              )
            ];
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return [false, deserializedStorageValue.state];
        }
      }
      return [false, void 0];
    }).then((migrationResult) => {
      var _a2;
      const [migrated, migratedState] = migrationResult;
      stateFromStorage = options.merge(
        migratedState,
        (_a2 = get()) != null ? _a2 : configResult
      );
      set(stateFromStorage, true);
      if (migrated) {
        return setItem();
      }
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      stateFromStorage = get();
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
    });
  };
  api.persist = {
    setOptions: (newOptions) => {
      options = {
        ...options,
        ...newOptions
      };
      if (newOptions.storage) {
        storage = newOptions.storage;
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options.name);
    },
    getOptions: () => options,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  if (!options.skipHydration) {
    hydrate();
  }
  return stateFromStorage || configResult;
};
const persistImpl = (config, baseOptions) => {
  if ("getStorage" in baseOptions || "serialize" in baseOptions || "deserialize" in baseOptions) {
    if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
      console.warn(
        "[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."
      );
    }
    return oldImpl(config, baseOptions);
  }
  return newImpl(config, baseOptions);
};
const persist = persistImpl;

export { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector };
import type { Mutate, StateCreator, StoreApi, StoreMutatorIdentifier } from './vanilla.mjs';
type ExtractState<S> = S extends {
    getState: () => infer T;
} ? T : never;
type ReadonlyStoreApi<T> = Pick<StoreApi<T>, 'getState' | 'getInitialState' | 'subscribe'>;
type WithReact<S extends ReadonlyStoreApi<unknown>> = S & {
    /** @deprecated please use api.getInitialState() */
    getServerState?: () => ExtractState<S>;
};
export declare function useStore<S extends WithReact<ReadonlyStoreApi<unknown>>>(api: S): ExtractState<S>;
export declare function useStore<S extends WithReact<ReadonlyStoreApi<unknown>>, U>(api: S, selector: (state: ExtractState<S>) => U): U;
/**
 * @deprecated The usage with three arguments is deprecated. Use `useStoreWithEqualityFn` from 'zustand/traditional'. The usage with one or two arguments is not deprecated.
 * https://github.com/pmndrs/zustand/discussions/1937
 */
export declare function useStore<S extends WithReact<ReadonlyStoreApi<unknown>>, U>(api: S, selector: (state: ExtractState<S>) => U, equalityFn: ((a: U, b: U) => boolean) | undefined): U;
export type UseBoundStore<S extends WithReact<ReadonlyStoreApi<unknown>>> = {
    (): ExtractState<S>;
    <U>(selector: (state: ExtractState<S>) => U): U;
    /**
     * @deprecated Use `createWithEqualityFn` from 'zustand/traditional'
     */
    <U>(selector: (state: ExtractState<S>) => U, equalityFn: (a: U, b: U) => boolean): U;
} & S;
type Create = {
    <T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>): UseBoundStore<Mutate<StoreApi<T>, Mos>>;
    <T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>) => UseBoundStore<Mutate<StoreApi<T>, Mos>>;
    /**
     * @deprecated Use `useStore` hook to bind store
     */
    <S extends StoreApi<unknown>>(store: S): UseBoundStore<S>;
};
export declare const create: Create;
/**
 * @deprecated Use `import { create } from 'zustand'`
 */
declare const _default: Create;
export default _default;
import { shallow } from './vanilla/shallow.mjs';
/**
 * @deprecated Use `import { shallow } from 'zustand/shallow'`
 */
declare const _default: typeof shallow;
export default _default;
export { shallow };
function shallow$1(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

var shallow = (objA, objB) => {
  if (process.env.NODE_ENV !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`."
    );
  }
  return shallow$1(objA, objB);
};

export { shallow as default, shallow$1 as shallow };
function shallow$1(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

var shallow = (objA, objB) => {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`."
    );
  }
  return shallow$1(objA, objB);
};

export { shallow as default, shallow$1 as shallow };
import type { Mutate, StateCreator, StoreApi, StoreMutatorIdentifier } from './vanilla.mjs';
type ExtractState<S> = S extends {
    getState: () => infer T;
} ? T : never;
type ReadonlyStoreApi<T> = Pick<StoreApi<T>, 'getState' | 'getInitialState' | 'subscribe'>;
type WithReact<S extends ReadonlyStoreApi<unknown>> = S & {
    /** @deprecated please use api.getInitialState() */
    getServerState?: () => ExtractState<S>;
};
export declare function useStoreWithEqualityFn<S extends WithReact<ReadonlyStoreApi<unknown>>>(api: S): ExtractState<S>;
export declare function useStoreWithEqualityFn<S extends WithReact<ReadonlyStoreApi<unknown>>, U>(api: S, selector: (state: ExtractState<S>) => U, equalityFn?: (a: U, b: U) => boolean): U;
export type UseBoundStoreWithEqualityFn<S extends WithReact<ReadonlyStoreApi<unknown>>> = {
    (): ExtractState<S>;
    <U>(selector: (state: ExtractState<S>) => U, equalityFn?: (a: U, b: U) => boolean): U;
} & S;
type CreateWithEqualityFn = {
    <T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>, defaultEqualityFn?: <U>(a: U, b: U) => boolean): UseBoundStoreWithEqualityFn<Mutate<StoreApi<T>, Mos>>;
    <T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>, defaultEqualityFn?: <U>(a: U, b: U) => boolean) => UseBoundStoreWithEqualityFn<Mutate<StoreApi<T>, Mos>>;
};
export declare const createWithEqualityFn: CreateWithEqualityFn;
export {};
import ReactExports from 'react';
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector.js';
import { createStore } from 'zustand/vanilla';

const { useDebugValue } = ReactExports;
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
const identity = (arg) => arg;
function useStoreWithEqualityFn(api, selector = identity, equalityFn) {
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getServerState || api.getInitialState,
    selector,
    equalityFn
  );
  useDebugValue(slice);
  return slice;
}
const createWithEqualityFnImpl = (createState, defaultEqualityFn) => {
  const api = createStore(createState);
  const useBoundStoreWithEqualityFn = (selector, equalityFn = defaultEqualityFn) => useStoreWithEqualityFn(api, selector, equalityFn);
  Object.assign(useBoundStoreWithEqualityFn, api);
  return useBoundStoreWithEqualityFn;
};
const createWithEqualityFn = (createState, defaultEqualityFn) => createState ? createWithEqualityFnImpl(createState, defaultEqualityFn) : createWithEqualityFnImpl;

export { createWithEqualityFn, useStoreWithEqualityFn };
import ReactExports from 'react';
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector.js';
import { createStore } from 'zustand/vanilla';

const { useDebugValue } = ReactExports;
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
const identity = (arg) => arg;
function useStoreWithEqualityFn(api, selector = identity, equalityFn) {
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getServerState || api.getInitialState,
    selector,
    equalityFn
  );
  useDebugValue(slice);
  return slice;
}
const createWithEqualityFnImpl = (createState, defaultEqualityFn) => {
  const api = createStore(createState);
  const useBoundStoreWithEqualityFn = (selector, equalityFn = defaultEqualityFn) => useStoreWithEqualityFn(api, selector, equalityFn);
  Object.assign(useBoundStoreWithEqualityFn, api);
  return useBoundStoreWithEqualityFn;
};
const createWithEqualityFn = (createState, defaultEqualityFn) => createState ? createWithEqualityFnImpl(createState, defaultEqualityFn) : createWithEqualityFnImpl;

export { createWithEqualityFn, useStoreWithEqualityFn };
type SetStateInternal<T> = {
    _(partial: T | Partial<T> | {
        _(state: T): T | Partial<T>;
    }['_'], replace?: boolean | undefined): void;
}['_'];
export interface StoreApi<T> {
    setState: SetStateInternal<T>;
    getState: () => T;
    getInitialState: () => T;
    subscribe: (listener: (state: T, prevState: T) => void) => () => void;
    /**
     * @deprecated Use `unsubscribe` returned by `subscribe`
     */
    destroy: () => void;
}
type Get<T, K, F> = K extends keyof T ? T[K] : F;
export type Mutate<S, Ms> = number extends Ms['length' & keyof Ms] ? S : Ms extends [] ? S : Ms extends [[infer Mi, infer Ma], ...infer Mrs] ? Mutate<StoreMutators<S, Ma>[Mi & StoreMutatorIdentifier], Mrs> : never;
export type StateCreator<T, Mis extends [StoreMutatorIdentifier, unknown][] = [], Mos extends [StoreMutatorIdentifier, unknown][] = [], U = T> = ((setState: Get<Mutate<StoreApi<T>, Mis>, 'setState', never>, getState: Get<Mutate<StoreApi<T>, Mis>, 'getState', never>, store: Mutate<StoreApi<T>, Mis>) => U) & {
    $$storeMutators?: Mos;
};
export interface StoreMutators<S, A> {
}
export type StoreMutatorIdentifier = keyof StoreMutators<unknown, unknown>;
type CreateStore = {
    <T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>): Mutate<StoreApi<T>, Mos>;
    <T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [], Mos>) => Mutate<StoreApi<T>, Mos>;
};
export declare const createStore: CreateStore;
/**
 * @deprecated Use `import { createStore } from 'zustand/vanilla'`
 */
declare const _default: CreateStore;
export default _default;
/**
 * @deprecated Use `unknown` instead of `State`
 */
export type State = unknown;
/**
 * @deprecated Use `Partial<T> | ((s: T) => Partial<T>)` instead of `PartialState<T>`
 */
export type PartialState<T extends State> = Partial<T> | ((state: T) => Partial<T>);
/**
 * @deprecated Use `(s: T) => U` instead of `StateSelector<T, U>`
 */
export type StateSelector<T extends State, U> = (state: T) => U;
/**
 * @deprecated Use `(a: T, b: T) => boolean` instead of `EqualityChecker<T>`
 */
export type EqualityChecker<T> = (state: T, newState: T) => boolean;
/**
 * @deprecated Use `(state: T, previousState: T) => void` instead of `StateListener<T>`
 */
export type StateListener<T> = (state: T, previousState: T) => void;
/**
 * @deprecated Use `(slice: T, previousSlice: T) => void` instead of `StateSliceListener<T>`.
 */
export type StateSliceListener<T> = (slice: T, previousSlice: T) => void;
/**
 * @deprecated Use `(listener: (state: T) => void) => void` instead of `Subscribe<T>`.
 */
export type Subscribe<T extends State> = {
    (listener: (state: T, previousState: T) => void): () => void;
};
/**
 * @deprecated You might be looking for `StateCreator`, if not then
 * use `StoreApi<T>['setState']` instead of `SetState<T>`.
 */
export type SetState<T extends State> = {
    _(partial: T | Partial<T> | {
        _(state: T): T | Partial<T>;
    }['_'], replace?: boolean | undefined): void;
}['_'];
/**
 * @deprecated You might be looking for `StateCreator`, if not then
 * use `StoreApi<T>['getState']` instead of `GetState<T>`.
 */
export type GetState<T extends State> = () => T;
/**
 * @deprecated Use `StoreApi<T>['destroy']` instead of `Destroy`.
 */
export type Destroy = () => void;
const createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const destroy = () => {
    if (process.env.NODE_ENV !== "production") {
      console.warn(
        "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
      );
    }
    listeners.clear();
  };
  const api = { setState, getState, getInitialState, subscribe, destroy };
  const initialState = state = createState(setState, getState, api);
  return api;
};
const createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
var vanilla = (createState) => {
  if (process.env.NODE_ENV !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'."
    );
  }
  return createStore(createState);
};

export { createStore, vanilla as default };
const createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const destroy = () => {
    if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
      console.warn(
        "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
      );
    }
    listeners.clear();
  };
  const api = { setState, getState, getInitialState, subscribe, destroy };
  const initialState = state = createState(setState, getState, api);
  return api;
};
const createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
var vanilla = (createState) => {
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'."
    );
  }
  return createStore(createState);
};

export { createStore, vanilla as default };
export declare function shallow<T>(objA: T, objB: T): boolean;
function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

export { shallow };
function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

export { shallow };
export declare function useShallow<S, U>(selector: (state: S) => U): (state: S) => U;
import ReactExports from 'react';

function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

const { useRef } = ReactExports;
function useShallow(selector) {
  const prev = useRef();
  return (state) => {
    const next = selector(state);
    return shallow(prev.current, next) ? prev.current : prev.current = next;
  };
}

export { useShallow };
import ReactExports from 'react';

function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [key, value] of objA) {
      if (!Object.is(value, objB.get(key))) {
        return false;
      }
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const value of objA) {
      if (!objB.has(value)) {
        return false;
      }
    }
    return true;
  }
  const keysA = Object.keys(objA);
  if (keysA.length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, keyA) || !Object.is(objA[keyA], objB[keyA])) {
      return false;
    }
  }
  return true;
}

const { useRef } = ReactExports;
function useShallow(selector) {
  const prev = useRef();
  return (state) => {
    const next = selector(state);
    return shallow(prev.current, next) ? prev.current : prev.current = next;
  };
}

export { useShallow };
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.mjs';
type Write<T, U> = Omit<T, keyof U> & U;
type Combine = <T extends object, U extends object, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initialState: T, additionalStateCreator: StateCreator<T, Mps, Mcs, U>) => StateCreator<Write<T, U>, Mps, Mcs>;
export declare const combine: Combine;
export {};
import type { StateCreator, StoreApi, StoreMutatorIdentifier } from '../vanilla.mjs';
type Config = Parameters<(Window extends {
    __REDUX_DEVTOOLS_EXTENSION__?: infer T;
} ? T : {
    connect: (param: any) => any;
})['connect']>[0];
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        'zustand/devtools': WithDevtools<S>;
    }
}
type Cast<T, U> = T extends U ? T : U;
type Write<T, U> = Omit<T, keyof U> & U;
type TakeTwo<T> = T extends {
    length: 0;
} ? [undefined, undefined] : T extends {
    length: 1;
} ? [...a0: Cast<T, unknown[]>, a1: undefined] : T extends {
    length: 0 | 1;
} ? [...a0: Cast<T, unknown[]>, a1: undefined] : T extends {
    length: 2;
} ? T : T extends {
    length: 1 | 2;
} ? T : T extends {
    length: 0 | 1 | 2;
} ? T : T extends [infer A0, infer A1, ...unknown[]] ? [A0, A1] : T extends [infer A0, (infer A1)?, ...unknown[]] ? [A0, A1?] : T extends [(infer A0)?, (infer A1)?, ...unknown[]] ? [A0?, A1?] : never;
type WithDevtools<S> = Write<S, StoreDevtools<S>>;
type StoreDevtools<S> = S extends {
    setState: (...a: infer Sa) => infer Sr;
} ? {
    setState<A extends string | {
        type: string;
    }>(...a: [...a: TakeTwo<Sa>, action?: A]): Sr;
} : never;
export interface DevtoolsOptions extends Config {
    name?: string;
    enabled?: boolean;
    anonymousActionType?: string;
    store?: string;
}
type Devtools = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [...Mps, ['zustand/devtools', never]], Mcs>, devtoolsOptions?: DevtoolsOptions) => StateCreator<T, Mps, [['zustand/devtools', never], ...Mcs]>;
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        'zustand/devtools': WithDevtools<S>;
    }
}
export type NamedSet<T> = WithDevtools<StoreApi<T>>['setState'];
export declare const devtools: Devtools;
export {};
import type { Draft } from 'immer';
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.mjs';
type Immer = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [...Mps, ['zustand/immer', never]], Mcs>) => StateCreator<T, Mps, [['zustand/immer', never], ...Mcs]>;
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        ['zustand/immer']: WithImmer<S>;
    }
}
type Write<T, U> = Omit<T, keyof U> & U;
type SkipTwo<T> = T extends {
    length: 0;
} ? [] : T extends {
    length: 1;
} ? [] : T extends {
    length: 0 | 1;
} ? [] : T extends [unknown, unknown, ...infer A] ? A : T extends [unknown, unknown?, ...infer A] ? A : T extends [unknown?, unknown?, ...infer A] ? A : never;
type WithImmer<S> = Write<S, StoreImmer<S>>;
type StoreImmer<S> = S extends {
    getState: () => infer T;
    setState: infer SetState;
} ? SetState extends (...a: infer A) => infer Sr ? {
    setState(nextStateOrUpdater: T | Partial<T> | ((state: Draft<T>) => void), shouldReplace?: boolean | undefined, ...a: SkipTwo<A>): Sr;
} : never : never;
export declare const immer: Immer;
export {};
import { produce } from 'immer';

const immerImpl = (initializer) => (set, get, store) => {
  store.setState = (updater, replace, ...a) => {
    const nextState = typeof updater === "function" ? produce(updater) : updater;
    return set(nextState, replace, ...a);
  };
  return initializer(store.setState, get, store);
};
const immer = immerImpl;

export { immer };
import { produce } from 'immer';

const immerImpl = (initializer) => (set, get, store) => {
  store.setState = (updater, replace, ...a) => {
    const nextState = typeof updater === "function" ? produce(updater) : updater;
    return set(nextState, replace, ...a);
  };
  return initializer(store.setState, get, store);
};
const immer = immerImpl;

export { immer };
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.mjs';
export interface StateStorage {
    getItem: (name: string) => string | null | Promise<string | null>;
    setItem: (name: string, value: string) => unknown | Promise<unknown>;
    removeItem: (name: string) => unknown | Promise<unknown>;
}
export type StorageValue<S> = {
    state: S;
    version?: number;
};
export interface PersistStorage<S> {
    getItem: (name: string) => StorageValue<S> | null | Promise<StorageValue<S> | null>;
    setItem: (name: string, value: StorageValue<S>) => unknown | Promise<unknown>;
    removeItem: (name: string) => unknown | Promise<unknown>;
}
type JsonStorageOptions = {
    reviver?: (key: string, value: unknown) => unknown;
    replacer?: (key: string, value: unknown) => unknown;
};
export declare function createJSONStorage<S>(getStorage: () => StateStorage, options?: JsonStorageOptions): PersistStorage<S> | undefined;
export interface PersistOptions<S, PersistedState = S> {
    /** Name of the storage (must be unique) */
    name: string;
    /**
     * @deprecated Use `storage` instead.
     * A function returning a storage.
     * The storage must fit `window.localStorage`'s api (or an async version of it).
     * For example the storage could be `AsyncStorage` from React Native.
     *
     * @default () => localStorage
     */
    getStorage?: () => StateStorage;
    /**
     * @deprecated Use `storage` instead.
     * Use a custom serializer.
     * The returned string will be stored in the storage.
     *
     * @default JSON.stringify
     */
    serialize?: (state: StorageValue<S>) => string | Promise<string>;
    /**
     * @deprecated Use `storage` instead.
     * Use a custom deserializer.
     * Must return an object matching StorageValue<S>
     *
     * @param str The storage's current value.
     * @default JSON.parse
     */
    deserialize?: (str: string) => StorageValue<PersistedState> | Promise<StorageValue<PersistedState>>;
    /**
     * Use a custom persist storage.
     *
     * Combining `createJSONStorage` helps creating a persist storage
     * with JSON.parse and JSON.stringify.
     *
     * @default createJSONStorage(() => localStorage)
     */
    storage?: PersistStorage<PersistedState> | undefined;
    /**
     * Filter the persisted value.
     *
     * @params state The state's value
     */
    partialize?: (state: S) => PersistedState;
    /**
     * A function returning another (optional) function.
     * The main function will be called before the state rehydration.
     * The returned function will be called after the state rehydration or when an error occurred.
     */
    onRehydrateStorage?: (state: S) => ((state?: S, error?: unknown) => void) | void;
    /**
     * If the stored state's version mismatch the one specified here, the storage will not be used.
     * This is useful when adding a breaking change to your store.
     */
    version?: number;
    /**
     * A function to perform persisted state migration.
     * This function will be called when persisted state versions mismatch with the one specified here.
     */
    migrate?: (persistedState: unknown, version: number) => PersistedState | Promise<PersistedState>;
    /**
     * A function to perform custom hydration merges when combining the stored state with the current one.
     * By default, this function does a shallow merge.
     */
    merge?: (persistedState: unknown, currentState: S) => S;
    /**
     * An optional boolean that will prevent the persist middleware from triggering hydration on initialization,
     * This allows you to call `rehydrate()` at a specific point in your apps rendering life-cycle.
     *
     * This is useful in SSR application.
     *
     * @default false
     */
    skipHydration?: boolean;
}
type PersistListener<S> = (state: S) => void;
type StorePersist<S, Ps> = {
    persist: {
        setOptions: (options: Partial<PersistOptions<S, Ps>>) => void;
        clearStorage: () => void;
        rehydrate: () => Promise<void> | void;
        hasHydrated: () => boolean;
        onHydrate: (fn: PersistListener<S>) => () => void;
        onFinishHydration: (fn: PersistListener<S>) => () => void;
        getOptions: () => Partial<PersistOptions<S, Ps>>;
    };
};
type Persist = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = [], U = T>(initializer: StateCreator<T, [...Mps, ['zustand/persist', unknown]], Mcs>, options: PersistOptions<T, U>) => StateCreator<T, Mps, [['zustand/persist', U], ...Mcs]>;
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        'zustand/persist': WithPersist<S, A>;
    }
}
type Write<T, U> = Omit<T, keyof U> & U;
type WithPersist<S, A> = S extends {
    getState: () => infer T;
} ? Write<S, StorePersist<T, A>> : never;
export declare const persist: Persist;
export {};
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.mjs';
type Write<T, U> = Omit<T, keyof U> & U;
type Action = {
    type: string;
};
type StoreRedux<A> = {
    dispatch: (a: A) => A;
    dispatchFromDevtools: true;
};
type ReduxState<A> = {
    dispatch: StoreRedux<A>['dispatch'];
};
type WithRedux<S, A> = Write<S, StoreRedux<A>>;
type Redux = <T, A extends Action, Cms extends [StoreMutatorIdentifier, unknown][] = []>(reducer: (state: T, action: A) => T, initialState: T) => StateCreator<Write<T, ReduxState<A>>, Cms, [['zustand/redux', A]]>;
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        'zustand/redux': WithRedux<S, A>;
    }
}
export declare const redux: Redux;
export {};
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.mjs';
type SubscribeWithSelector = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, [
    ...Mps,
    ['zustand/subscribeWithSelector', never]
], Mcs>) => StateCreator<T, Mps, [['zustand/subscribeWithSelector', never], ...Mcs]>;
type Write<T, U> = Omit<T, keyof U> & U;
type WithSelectorSubscribe<S> = S extends {
    getState: () => infer T;
} ? Write<S, StoreSubscribeWithSelector<T>> : never;
declare module '../vanilla.mjs' {
    interface StoreMutators<S, A> {
        ['zustand/subscribeWithSelector']: WithSelectorSubscribe<S>;
    }
}
type StoreSubscribeWithSelector<T> = {
    subscribe: {
        (listener: (selectedState: T, previousSelectedState: T) => void): () => void;
        <U>(selector: (state: T) => U, listener: (selectedState: U, previousSelectedState: U) => void, options?: {
            equalityFn?: (a: U, b: U) => boolean;
            fireImmediately?: boolean;
        }): () => void;
    };
};
export declare const subscribeWithSelector: SubscribeWithSelector;
export {};
const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  required: ["foo", "bar"],
  additionalProperties: false,
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}
The MIT License (MIT)

Copyright (c) 2015-2021 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

{
  "name": "ajv",
  "version": "8.20.0",
  "description": "Another JSON Schema Validator",
  "main": "dist/ajv.js",
  "types": "dist/ajv.d.ts",
  "files": [
    "lib/",
    "dist/",
    ".runkit_example.js"
  ],
  "sideEffects": false,
  "repository": "ajv-validator/ajv",
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://ajv.js.org",
  "runkitExampleFilename": ".runkit_example.js",
  "dependencies": {
    "fast-deep-equal": "^3.1.3",
    "fast-uri": "^3.0.1",
    "json-schema-traverse": "^1.0.0",
    "require-from-string": "^2.0.2"
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.5.0",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-typescript": "^11.1.6",
    "@types/chai": "^4.3.11",
    "@types/mocha": "^10.0.6",
    "@types/node": "^20.11.30",
    "@types/require-from-string": "^1.2.3",
    "@typescript-eslint/eslint-plugin": "^7.3.1",
    "@typescript-eslint/parser": "^7.3.1",
    "ajv-formats": "^3.0.1",
    "browserify": "^17.0.0",
    "chai": "^4.4.1",
    "cross-env": "^7.0.3",
    "dayjs": "^1.11.10",
    "dayjs-plugin-utc": "^0.1.2",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "glob": "^10.3.10",
    "husky": "^9.0.11",
    "jimp": "^0.22.10",
    "js-beautify": "^1.15.1",
    "json-schema-test": "^2.0.0",
    "karma": "^6.4.2",
    "karma-chrome-launcher": "^3.2.0",
    "karma-mocha": "^2.0.1",
    "lint-staged": "^15.2.2",
    "mocha": "^10.3.0",
    "module-from-string": "^3.3.0",
    "node-fetch": "^3.3.2",
    "nyc": "^15.1.0",
    "prettier": "3.0.3",
    "re2": "^1.20.9",
    "rollup": "^2.79.1",
    "rollup-plugin-terser": "^7.0.2",
    "ts-node": "^10.9.2",
    "tsify": "^5.0.4",
    "typescript": "5.3.3",
    "uri-js": "^4.4.1"
  },
  "collective": {
    "type": "opencollective",
    "url": "https://opencollective.com/ajv"
  },
  "funding": {
    "type": "github",
    "url": "https://github.com/sponsors/epoberezkin"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{json,yaml,js,ts}": "prettier --write"
  }
}import type {AnySchemaObject} from "./types"
import AjvCore, {Options} from "./core"

import draft7Vocabularies from "./vocabularies/draft7"
import dynamicVocabulary from "./vocabularies/dynamic"
import nextVocabulary from "./vocabularies/next"
import unevaluatedVocabulary from "./vocabularies/unevaluated"
import discriminator from "./vocabularies/discriminator"
import addMetaSchema2019 from "./refs/json-schema-2019-09"

const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"

export class Ajv2019 extends AjvCore {
  constructor(opts: Options = {}) {
    super({
      ...opts,
      dynamicRef: true,
      next: true,
      unevaluated: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    this.addVocabulary(dynamicVocabulary)
    draft7Vocabularies.forEach((v) => this.addVocabulary(v))
    this.addVocabulary(nextVocabulary)
    this.addVocabulary(unevaluatedVocabulary)
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    const {$data, meta} = this.opts
    if (!meta) return
    addMetaSchema2019.call(this, $data)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv2019
module.exports.Ajv2019 = Ajv2019
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv2019

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchemaObject} from "./types"
import AjvCore, {Options} from "./core"

import draft2020Vocabularies from "./vocabularies/draft2020"
import discriminator from "./vocabularies/discriminator"
import addMetaSchema2020 from "./refs/json-schema-2020-12"

const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"

export class Ajv2020 extends AjvCore {
  constructor(opts: Options = {}) {
    super({
      ...opts,
      dynamicRef: true,
      next: true,
      unevaluated: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    draft2020Vocabularies.forEach((v) => this.addVocabulary(v))
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    const {$data, meta} = this.opts
    if (!meta) return
    addMetaSchema2020.call(this, $data)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv2020
module.exports.Ajv2020 = Ajv2020
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv2020

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchemaObject} from "./types"
import AjvCore from "./core"
import draft7Vocabularies from "./vocabularies/draft7"
import discriminator from "./vocabularies/discriminator"
import * as draft7MetaSchema from "./refs/json-schema-draft-07.json"

const META_SUPPORT_DATA = ["/properties"]

const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"

export class Ajv extends AjvCore {
  _addVocabularies(): void {
    super._addVocabularies()
    draft7Vocabularies.forEach((v) => this.addVocabulary(v))
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    if (!this.opts.meta) return
    const metaSchema = this.opts.$data
      ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
      : draft7MetaSchema
    this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv
module.exports.Ajv = Ajv
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  SchemaValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  AnyValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {SchemaCxt, SchemaObjCxt} from "./compile"
export interface Plugin<Opts> {
  (ajv: Ajv, options?: Opts): Ajv
  [prop: string]: any
}

export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

import type {
  Schema,
  AnySchema,
  AnySchemaObject,
  SchemaObject,
  AsyncSchema,
  Vocabulary,
  KeywordDefinition,
  AddedKeywordDefinition,
  AnyValidateFunction,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  Format,
  AddedFormat,
  RegExpEngine,
  UriResolver,
} from "./types"
import type {JSONSchemaType} from "./types/json-schema"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import ValidationError from "./runtime/validation_error"
import MissingRefError from "./compile/ref_error"
import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
import {Code, ValueScope} from "./compile/codegen"
import {normalizeId, getSchemaRefs} from "./compile/resolve"
import {getJSONTypes} from "./compile/validate/dataType"
import {eachItem} from "./compile/util"
import * as $dataRefSchema from "./refs/data.json"

import DefaultUriResolver from "./runtime/uri"

const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
defaultRegExp.code = "new RegExp"

const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
const EXT_SCOPE_NAMES = new Set([
  "validate",
  "serialize",
  "parse",
  "wrapper",
  "root",
  "schema",
  "keyword",
  "pattern",
  "formats",
  "validate$data",
  "func",
  "obj",
  "Error",
])

export type Options = CurrentOptions & DeprecatedOptions

export interface CurrentOptions {
  // strict mode options (NEW)
  strict?: boolean | "log"
  strictSchema?: boolean | "log"
  strictNumbers?: boolean | "log"
  strictTypes?: boolean | "log"
  strictTuples?: boolean | "log"
  strictRequired?: boolean | "log"
  allowMatchingProperties?: boolean // disables a strict mode restriction
  allowUnionTypes?: boolean
  validateFormats?: boolean
  // validation and reporting options:
  $data?: boolean
  allErrors?: boolean
  verbose?: boolean
  discriminator?: boolean
  unicodeRegExp?: boolean
  timestamp?: "string" | "date" // JTD only
  parseDate?: boolean // JTD only
  allowDate?: boolean // JTD only
  specialNumbers?: "fast" | "null" // JTD only
  $comment?:
    | true
    | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
  formats?: {[Name in string]?: Format}
  keywords?: Vocabulary
  schemas?: AnySchema[] | {[Key in string]?: AnySchema}
  logger?: Logger | false
  loadSchema?: (uri: string) => Promise<AnySchemaObject>
  // options to modify validated data:
  removeAdditional?: boolean | "all" | "failing"
  useDefaults?: boolean | "empty"
  coerceTypes?: boolean | "array"
  // advanced options:
  next?: boolean // NEW
  unevaluated?: boolean // NEW
  dynamicRef?: boolean // NEW
  schemaId?: "id" | "$id"
  jtd?: boolean // NEW
  meta?: SchemaObject | boolean
  defaultMeta?: string | AnySchemaObject
  validateSchema?: boolean | "log"
  addUsedSchema?: boolean
  inlineRefs?: boolean | number
  passContext?: boolean
  loopRequired?: number
  loopEnum?: number // NEW
  ownProperties?: boolean
  multipleOfPrecision?: number
  int32range?: boolean // JTD only
  messages?: boolean
  code?: CodeOptions // NEW
  uriResolver?: UriResolver
}

export interface CodeOptions {
  es5?: boolean
  esm?: boolean
  lines?: boolean
  optimize?: boolean | number
  formats?: Code // code to require (or construct) map of available formats - for standalone code
  source?: boolean
  process?: (code: string, schema?: SchemaEnv) => string
  regExp?: RegExpEngine
}

interface InstanceCodeOptions extends CodeOptions {
  regExp: RegExpEngine
  optimize: number
}

interface DeprecatedOptions {
  /** @deprecated */
  ignoreKeywordsWithRef?: boolean
  /** @deprecated */
  jsPropertySyntax?: boolean // added instead of jsonPointers
  /** @deprecated */
  unicode?: boolean
}

interface RemovedOptions {
  format?: boolean
  errorDataPath?: "object" | "property"
  nullable?: boolean // "nullable" keyword is supported by default
  jsonPointers?: boolean
  extendRefs?: true | "ignore" | "fail"
  missingRefs?: true | "ignore" | "fail"
  processCode?: (code: string, schema?: SchemaEnv) => string
  sourceCode?: boolean
  strictDefaults?: boolean
  strictKeywords?: boolean
  uniqueItems?: boolean
  unknownFormats?: true | string[] | "ignore"
  cache?: any
  serialize?: (schema: AnySchema) => unknown
  ajvErrors?: boolean
}

type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
  [K in keyof T]-?: string | undefined
}

const removedOptions: OptionsInfo<RemovedOptions> = {
  errorDataPath: "",
  format: "`validateFormats: false` can be used instead.",
  nullable: '"nullable" keyword is supported by default.',
  jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
  extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
  missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
  processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
  sourceCode: "Use option `code: {source: true}`",
  strictDefaults: "It is default now, see option `strict`.",
  strictKeywords: "It is default now, see option `strict`.",
  uniqueItems: '"uniqueItems" keyword is always validated.',
  unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
  cache: "Map is used as cache, schema object as key.",
  serialize: "Map is used as cache, schema object as key.",
  ajvErrors: "It is default now.",
}

const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
  ignoreKeywordsWithRef: "",
  jsPropertySyntax: "",
  unicode: '"minLength"/"maxLength" account for unicode characters by default.',
}

type RequiredInstanceOptions = {
  [K in
    | "strictSchema"
    | "strictNumbers"
    | "strictTypes"
    | "strictTuples"
    | "strictRequired"
    | "inlineRefs"
    | "loopRequired"
    | "loopEnum"
    | "meta"
    | "messages"
    | "schemaId"
    | "addUsedSchema"
    | "validateSchema"
    | "validateFormats"
    | "int32range"
    | "unicodeRegExp"
    | "uriResolver"]: NonNullable<Options[K]>
} & {code: InstanceCodeOptions}

export type InstanceOptions = Options & RequiredInstanceOptions

const MAX_EXPRESSION = 200

// eslint-disable-next-line complexity
function requiredOptions(o: Options): RequiredInstanceOptions {
  const s = o.strict
  const _optz = o.code?.optimize
  const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
  const regExp = o.code?.regExp ?? defaultRegExp
  const uriResolver = o.uriResolver ?? DefaultUriResolver
  return {
    strictSchema: o.strictSchema ?? s ?? true,
    strictNumbers: o.strictNumbers ?? s ?? true,
    strictTypes: o.strictTypes ?? s ?? "log",
    strictTuples: o.strictTuples ?? s ?? "log",
    strictRequired: o.strictRequired ?? s ?? false,
    code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
    loopRequired: o.loopRequired ?? MAX_EXPRESSION,
    loopEnum: o.loopEnum ?? MAX_EXPRESSION,
    meta: o.meta ?? true,
    messages: o.messages ?? true,
    inlineRefs: o.inlineRefs ?? true,
    schemaId: o.schemaId ?? "$id",
    addUsedSchema: o.addUsedSchema ?? true,
    validateSchema: o.validateSchema ?? true,
    validateFormats: o.validateFormats ?? true,
    unicodeRegExp: o.unicodeRegExp ?? true,
    int32range: o.int32range ?? true,
    uriResolver: uriResolver,
  }
}

export interface Logger {
  log(...args: unknown[]): unknown
  warn(...args: unknown[]): unknown
  error(...args: unknown[]): unknown
}

export default class Ajv {
  opts: InstanceOptions
  errors?: ErrorObject[] | null // errors from the last validation
  logger: Logger
  // shared external scope values for compiled functions
  readonly scope: ValueScope
  readonly schemas: {[Key in string]?: SchemaEnv} = {}
  readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
  readonly formats: {[Name in string]?: AddedFormat} = Object.create(null)
  readonly RULES: ValidationRules
  readonly _compilations: Set<SchemaEnv> = new Set()
  private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
  private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
  private readonly _metaOpts: InstanceOptions

  static ValidationError = ValidationError
  static MissingRefError = MissingRefError

  constructor(opts: Options = {}) {
    opts = this.opts = {...opts, ...requiredOptions(opts)}
    const {es5, lines} = this.opts.code

    this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
    this.logger = getLogger(opts.logger)
    const formatOpt = opts.validateFormats
    opts.validateFormats = false

    this.RULES = getRules()
    checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
    checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
    this._metaOpts = getMetaSchemaOptions.call(this)

    if (opts.formats) addInitialFormats.call(this)
    this._addVocabularies()
    this._addDefaultMetaSchema()
    if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
    if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
    addInitialSchemas.call(this)
    opts.validateFormats = formatOpt
  }

  _addVocabularies(): void {
    this.addKeyword("$async")
  }

  _addDefaultMetaSchema(): void {
    const {$data, meta, schemaId} = this.opts
    let _dataRefSchema: SchemaObject = $dataRefSchema
    if (schemaId === "id") {
      _dataRefSchema = {...$dataRefSchema}
      _dataRefSchema.id = _dataRefSchema.$id
      delete _dataRefSchema.$id
    }
    if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    const {meta, schemaId} = this.opts
    return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
  }

  // Validate data using schema
  // AnySchema will be compiled and cached using schema itself as a key for Map
  validate(schema: Schema | string, data: unknown): boolean
  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
  validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  validate<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    data: unknown
  ): data is JTDDataType<T>
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
  validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
  validate<T>(
    schemaKeyRef: AnySchema | string, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data: unknown | T // to be validated
  ): boolean | Promise<T> {
    let v: AnyValidateFunction | undefined
    if (typeof schemaKeyRef == "string") {
      v = this.getSchema<T>(schemaKeyRef)
      if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
    } else {
      v = this.compile<T>(schemaKeyRef)
    }

    const valid = v(data)
    if (!("$async" in v)) this.errors = v.errors
    return valid
  }

  // Create validation function for passed schema
  // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
  compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  compile<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    _meta?: boolean
  ): ValidateFunction<JTDDataType<T>>
  compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
    const sch = this._addSchema(schema, _meta)
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
  }

  // Creates validating function for passed schema with asynchronous loading of missing schemas.
  // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  // TODO allow passing schema URI
  // meta - optional true to compile meta-schema
  compileAsync<T = unknown>(
    schema: SchemaObject | JSONSchemaType<T>,
    _meta?: boolean
  ): Promise<ValidateFunction<T>>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
  compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>>
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>> {
    if (typeof this.opts.loadSchema != "function") {
      throw new Error("options.loadSchema should be a function")
    }
    const {loadSchema} = this.opts
    return runCompileAsync.call(this, schema, meta)

    async function runCompileAsync(
      this: Ajv,
      _schema: AnySchemaObject,
      _meta?: boolean
    ): Promise<AnyValidateFunction> {
      await loadMetaSchema.call(this, _schema.$schema)
      const sch = this._addSchema(_schema, _meta)
      return sch.validate || _compileAsync.call(this, sch)
    }

    async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
      if ($ref && !this.getSchema($ref)) {
        await runCompileAsync.call(this, {$ref}, true)
      }
    }

    async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
      try {
        return this._compileSchemaEnv(sch)
      } catch (e) {
        if (!(e instanceof MissingRefError)) throw e
        checkLoaded.call(this, e)
        await loadMissingSchema.call(this, e.missingSchema)
        return _compileAsync.call(this, sch)
      }
    }

    function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
      if (this.refs[ref]) {
        throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
      }
    }

    async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
      const _schema = await _loadSchema.call(this, ref)
      if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
      if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
    }

    async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
      const p = this._loading[ref]
      if (p) return p
      try {
        return await (this._loading[ref] = loadSchema(ref))
      } finally {
        delete this._loading[ref]
      }
    }
  }

  // Adds schema to the instance
  addSchema(
    schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
    key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
  ): Ajv {
    if (Array.isArray(schema)) {
      for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
      return this
    }
    let id: string | undefined
    if (typeof schema === "object") {
      const {schemaId} = this.opts
      id = schema[schemaId]
      if (id !== undefined && typeof id != "string") {
        throw new Error(`schema ${schemaId} must be string`)
      }
    }
    key = normalizeId(key || id)
    this._checkUnique(key)
    this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
    return this
  }

  // Add schema that will be used to validate other schemas
  // options in META_IGNORE_OPTIONS are alway set to false
  addMetaSchema(
    schema: AnySchemaObject,
    key?: string, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
  ): Ajv {
    this.addSchema(schema, key, true, _validateSchema)
    return this
  }

  //  Validate schema against its meta-schema
  validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
    if (typeof schema == "boolean") return true
    let $schema: string | AnySchemaObject | undefined
    $schema = schema.$schema
    if ($schema !== undefined && typeof $schema != "string") {
      throw new Error("$schema must be a string")
    }
    $schema = $schema || this.opts.defaultMeta || this.defaultMeta()
    if (!$schema) {
      this.logger.warn("meta-schema not available")
      this.errors = null
      return true
    }
    const valid = this.validate($schema, schema)
    if (!valid && throwOrLogError) {
      const message = "schema is invalid: " + this.errorsText()
      if (this.opts.validateSchema === "log") this.logger.error(message)
      else throw new Error(message)
    }
    return valid
  }

  // Get compiled schema by `key` or `ref`.
  // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    let sch
    while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
    if (sch === undefined) {
      const {schemaId} = this.opts
      const root = new SchemaEnv({schema: {}, schemaId})
      sch = resolveSchema.call(this, root, keyRef)
      if (!sch) return
      this.refs[keyRef] = sch
    }
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
  }

  // Remove cached schema(s).
  // If no parameter is passed all schemas but meta-schemas are removed.
  // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
    if (schemaKeyRef instanceof RegExp) {
      this._removeAllSchemas(this.schemas, schemaKeyRef)
      this._removeAllSchemas(this.refs, schemaKeyRef)
      return this
    }
    switch (typeof schemaKeyRef) {
      case "undefined":
        this._removeAllSchemas(this.schemas)
        this._removeAllSchemas(this.refs)
        this._cache.clear()
        return this
      case "string": {
        const sch = getSchEnv.call(this, schemaKeyRef)
        if (typeof sch == "object") this._cache.delete(sch.schema)
        delete this.schemas[schemaKeyRef]
        delete this.refs[schemaKeyRef]
        return this
      }
      case "object": {
        const cacheKey = schemaKeyRef
        this._cache.delete(cacheKey)
        let id = schemaKeyRef[this.opts.schemaId]
        if (id) {
          id = normalizeId(id)
          delete this.schemas[id]
          delete this.refs[id]
        }
        return this
      }
      default:
        throw new Error("ajv.removeSchema: invalid parameter")
    }
  }

  // add "vocabulary" - a collection of keywords
  addVocabulary(definitions: Vocabulary): Ajv {
    for (const def of definitions) this.addKeyword(def)
    return this
  }

  addKeyword(
    kwdOrDef: string | KeywordDefinition,
    def?: KeywordDefinition // deprecated
  ): Ajv {
    let keyword: string | string[]
    if (typeof kwdOrDef == "string") {
      keyword = kwdOrDef
      if (typeof def == "object") {
        this.logger.warn("these parameters are deprecated, see docs for addKeyword")
        def.keyword = keyword
      }
    } else if (typeof kwdOrDef == "object" && def === undefined) {
      def = kwdOrDef
      keyword = def.keyword
      if (Array.isArray(keyword) && !keyword.length) {
        throw new Error("addKeywords: keyword must be string or non-empty array")
      }
    } else {
      throw new Error("invalid addKeywords parameters")
    }

    checkKeyword.call(this, keyword, def)
    if (!def) {
      eachItem(keyword, (kwd) => addRule.call(this, kwd))
      return this
    }
    keywordMetaschema.call(this, def)
    const definition: AddedKeywordDefinition = {
      ...def,
      type: getJSONTypes(def.type),
      schemaType: getJSONTypes(def.schemaType),
    }
    eachItem(
      keyword,
      definition.type.length === 0
        ? (k) => addRule.call(this, k, definition)
        : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
    )
    return this
  }

  getKeyword(keyword: string): AddedKeywordDefinition | boolean {
    const rule = this.RULES.all[keyword]
    return typeof rule == "object" ? rule.definition : !!rule
  }

  // Remove keyword
  removeKeyword(keyword: string): Ajv {
    // TODO return type should be Ajv
    const {RULES} = this
    delete RULES.keywords[keyword]
    delete RULES.all[keyword]
    for (const group of RULES.rules) {
      const i = group.rules.findIndex((rule) => rule.keyword === keyword)
      if (i >= 0) group.rules.splice(i, 1)
    }
    return this
  }

  // Add format
  addFormat(name: string, format: Format): Ajv {
    if (typeof format == "string") format = new RegExp(format)
    this.formats[name] = format
    return this
  }

  errorsText(
    errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
    {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
  ): string {
    if (!errors || errors.length === 0) return "No errors"
    return errors
      .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
      .reduce((text, msg) => text + separator + msg)
  }

  $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
    const rules = this.RULES.all
    metaSchema = JSON.parse(JSON.stringify(metaSchema))
    for (const jsonPointer of keywordsJsonPointers) {
      const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
      let keywords = metaSchema
      for (const seg of segments) keywords = keywords[seg] as AnySchemaObject

      for (const key in rules) {
        const rule = rules[key]
        if (typeof rule != "object") continue
        const {$data} = rule.definition
        const schema = keywords[key] as AnySchemaObject | undefined
        if ($data && schema) keywords[key] = schemaOrData(schema)
      }
    }

    return metaSchema
  }

  private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
    for (const keyRef in schemas) {
      const sch = schemas[keyRef]
      if (!regex || regex.test(keyRef)) {
        if (typeof sch == "string") {
          delete schemas[keyRef]
        } else if (sch && !sch.meta) {
          this._cache.delete(sch.schema)
          delete schemas[keyRef]
        }
      }
    }
  }

  _addSchema(
    schema: AnySchema,
    meta?: boolean,
    baseId?: string,
    validateSchema = this.opts.validateSchema,
    addSchema = this.opts.addUsedSchema
  ): SchemaEnv {
    let id: string | undefined
    const {schemaId} = this.opts
    if (typeof schema == "object") {
      id = schema[schemaId]
    } else {
      if (this.opts.jtd) throw new Error("schema must be object")
      else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
    }
    let sch = this._cache.get(schema)
    if (sch !== undefined) return sch

    baseId = normalizeId(id || baseId)
    const localRefs = getSchemaRefs.call(this, schema, baseId)
    sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
    this._cache.set(sch.schema, sch)
    if (addSchema && !baseId.startsWith("#")) {
      // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
      if (baseId) this._checkUnique(baseId)
      this.refs[baseId] = sch
    }
    if (validateSchema) this.validateSchema(schema, true)
    return sch
  }

  private _checkUnique(id: string): void {
    if (this.schemas[id] || this.refs[id]) {
      throw new Error(`schema with key or id "${id}" already exists`)
    }
  }

  private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
    if (sch.meta) this._compileMetaSchema(sch)
    else compileSchema.call(this, sch)

    /* istanbul ignore if */
    if (!sch.validate) throw new Error("ajv implementation error")
    return sch.validate
  }

  private _compileMetaSchema(sch: SchemaEnv): void {
    const currentOpts = this.opts
    this.opts = this._metaOpts
    try {
      compileSchema.call(this, sch)
    } finally {
      this.opts = currentOpts
    }
  }
}

export interface ErrorsTextOptions {
  separator?: string
  dataVar?: string
}

function checkOptions(
  this: Ajv,
  checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
  options: Options & RemovedOptions,
  msg: string,
  log: "warn" | "error" = "error"
): void {
  for (const key in checkOpts) {
    const opt = key as keyof typeof checkOpts
    if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
  }
}

function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
  keyRef = normalizeId(keyRef) // TODO tests fail without this line
  return this.schemas[keyRef] || this.refs[keyRef]
}

function addInitialSchemas(this: Ajv): void {
  const optsSchemas = this.opts.schemas
  if (!optsSchemas) return
  if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
  else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
}

function addInitialFormats(this: Ajv): void {
  for (const name in this.opts.formats) {
    const format = this.opts.formats[name]
    if (format) this.addFormat(name, format)
  }
}

function addInitialKeywords(
  this: Ajv,
  defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
  if (Array.isArray(defs)) {
    this.addVocabulary(defs)
    return
  }
  this.logger.warn("keywords option as map is deprecated, pass array")
  for (const keyword in defs) {
    const def = defs[keyword] as KeywordDefinition
    if (!def.keyword) def.keyword = keyword
    this.addKeyword(def)
  }
}

function getMetaSchemaOptions(this: Ajv): InstanceOptions {
  const metaOpts = {...this.opts}
  for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
  return metaOpts
}

const noLogs = {log() {}, warn() {}, error() {}}

function getLogger(logger?: Partial<Logger> | false): Logger {
  if (logger === false) return noLogs
  if (logger === undefined) return console
  if (logger.log && logger.warn && logger.error) return logger as Logger
  throw new Error("logger must implement log, warn and error methods")
}

const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i

function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
  const {RULES} = this
  eachItem(keyword, (kwd) => {
    if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
    if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
  })
  if (!def) return
  if (def.$data && !("code" in def || "validate" in def)) {
    throw new Error('$data keyword must have "code" or "validate" function')
  }
}

function addRule(
  this: Ajv,
  keyword: string,
  definition?: AddedKeywordDefinition,
  dataType?: JSONType
): void {
  const post = definition?.post
  if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
  const {RULES} = this
  let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
  if (!ruleGroup) {
    ruleGroup = {type: dataType, rules: []}
    RULES.rules.push(ruleGroup)
  }
  RULES.keywords[keyword] = true
  if (!definition) return

  const rule: Rule = {
    keyword,
    definition: {
      ...definition,
      type: getJSONTypes(definition.type),
      schemaType: getJSONTypes(definition.schemaType),
    },
  }
  if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
  else ruleGroup.rules.push(rule)
  RULES.all[keyword] = rule
  definition.implements?.forEach((kwd) => this.addKeyword(kwd))
}

function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
  const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
  if (i >= 0) {
    ruleGroup.rules.splice(i, 0, rule)
  } else {
    ruleGroup.rules.push(rule)
    this.logger.warn(`rule ${before} is not defined`)
  }
}

function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
  let {metaSchema} = def
  if (metaSchema === undefined) return
  if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
  def.validateSchema = this.compile(metaSchema, true)
}

const $dataRef = {
  $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
}

function schemaOrData(schema: AnySchema): AnySchemaObject {
  return {anyOf: [schema, $dataRef]}
}
import type {AnySchemaObject, SchemaObject, JTDParser} from "./types"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import AjvCore, {CurrentOptions} from "./core"
import jtdVocabulary from "./vocabularies/jtd"
import jtdMetaSchema from "./refs/jtd-schema"
import compileSerializer from "./compile/jtd/serialize"
import compileParser from "./compile/jtd/parse"
import {SchemaEnv} from "./compile"

const META_SCHEMA_ID = "JTD-meta-schema"

type JTDOptions = CurrentOptions & {
  // strict mode options not supported with JTD:
  strict?: never
  allowMatchingProperties?: never
  allowUnionTypes?: never
  validateFormats?: never
  // validation and reporting options not supported with JTD:
  $data?: never
  verbose?: boolean
  $comment?: never
  formats?: never
  loadSchema?: never
  // options to modify validated data:
  useDefaults?: never
  coerceTypes?: never
  // advanced options:
  next?: never
  unevaluated?: never
  dynamicRef?: never
  meta?: boolean
  defaultMeta?: never
  inlineRefs?: boolean
  loopRequired?: never
  multipleOfPrecision?: never
}

export class Ajv extends AjvCore {
  constructor(opts: JTDOptions = {}) {
    super({
      ...opts,
      jtd: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    this.addVocabulary(jtdVocabulary)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    if (!this.opts.meta) return
    this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }

  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string
  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string {
    const sch = this._addSchema(schema)
    return sch.serialize || this._compileSerializer(sch)
  }

  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>
  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> {
    const sch = this._addSchema(schema)
    return (sch.parse || this._compileParser(sch)) as JTDParser<T>
  }

  private _compileSerializer<T>(sch: SchemaEnv): (data: T) => string {
    compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.serialize) throw new Error("ajv implementation error")
    return sch.serialize
  }

  private _compileParser(sch: SchemaEnv): JTDParser {
    compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.parse) throw new Error("ajv implementation error")
    return sch.parse
  }
}

module.exports = exports = Ajv
module.exports.Ajv = Ajv
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
  JTDParser,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {JTDErrorObject} from "./vocabularies/jtd"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

export {JTDSchemaType, SomeJTDSchemaType, JTDDataType}
export {JTDOptions}
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchema, SchemaMap} from "../types"
import type {SchemaCxt} from "../compile"
import type {KeywordCxt} from "../compile/validate"
import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen"
import {alwaysValidSchema, Type} from "../compile/util"
import N from "../compile/names"
import {useFunc} from "../compile/util"
export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {
  const {gen, data, it} = cxt
  gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
    cxt.setParams({missingProperty: _`${prop}`}, true)
    cxt.error()
  })
}

export function checkMissingProp(
  {gen, data, it: {opts}}: KeywordCxt,
  properties: string[],
  missing: Name
): Code {
  return or(
    ...properties.map((prop) =>
      and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)
    )
  )
}

export function reportMissingProp(cxt: KeywordCxt, missing: Name): void {
  cxt.setParams({missingProperty: missing}, true)
  cxt.error()
}

export function hasPropFunc(gen: CodeGen): Name {
  return gen.scopeValue("func", {
    // eslint-disable-next-line @typescript-eslint/unbound-method
    ref: Object.prototype.hasOwnProperty,
    code: _`Object.prototype.hasOwnProperty`,
  })
}

export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {
  return _`${hasPropFunc(gen)}.call(${data}, ${property})`
}

export function propertyInData(
  gen: CodeGen,
  data: Name,
  property: Name | string,
  ownProperties?: boolean
): Code {
  const cond = _`${data}${getProperty(property)} !== undefined`
  return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond
}

export function noPropertyInData(
  gen: CodeGen,
  data: Name,
  property: Name | string,
  ownProperties?: boolean
): Code {
  const cond = _`${data}${getProperty(property)} === undefined`
  return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond
}

export function allSchemaProperties(schemaMap?: SchemaMap): string[] {
  return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []
}

export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {
  return allSchemaProperties(schemaMap).filter(
    (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)
  )
}

export function callValidateCode(
  {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,
  func: Code,
  context: Code,
  passSchema?: boolean
): Code {
  const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data
  const valCxt: [Name, Code | number][] = [
    [N.instancePath, strConcat(N.instancePath, errorPath)],
    [N.parentData, it.parentData],
    [N.parentDataProperty, it.parentDataProperty],
    [N.rootData, N.rootData],
  ]
  if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])
  const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`
  return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`
}

const newRegExp = _`new RegExp`

export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {
  const u = opts.unicodeRegExp ? "u" : ""
  const {regExp} = opts.code
  const rx = regExp(pattern, u)

  return gen.scopeValue("pattern", {
    key: rx.toString(),
    ref: rx,
    code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,
  })
}

export function validateArray(cxt: KeywordCxt): Name {
  const {gen, data, keyword, it} = cxt
  const valid = gen.name("valid")
  if (it.allErrors) {
    const validArr = gen.let("valid", true)
    validateItems(() => gen.assign(validArr, false))
    return validArr
  }
  gen.var(valid, true)
  validateItems(() => gen.break())
  return valid

  function validateItems(notValid: () => void): void {
    const len = gen.const("len", _`${data}.length`)
    gen.forRange("i", 0, len, (i) => {
      cxt.subschema(
        {
          keyword,
          dataProp: i,
          dataPropType: Type.Num,
        },
        valid
      )
      gen.if(not(valid), notValid)
    })
  }
}

export function validateUnion(cxt: KeywordCxt): void {
  const {gen, schema, keyword, it} = cxt
  /* istanbul ignore if */
  if (!Array.isArray(schema)) throw new Error("ajv implementation error")
  const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))
  if (alwaysValid && !it.opts.unevaluated) return

  const valid = gen.let("valid", false)
  const schValid = gen.name("_valid")

  gen.block(() =>
    schema.forEach((_sch: AnySchema, i: number) => {
      const schCxt = cxt.subschema(
        {
          keyword,
          schemaProp: i,
          compositeRule: true,
        },
        schValid
      )
      gen.assign(valid, _`${valid} || ${schValid}`)
      const merged = cxt.mergeValidEvaluated(schCxt, schValid)
      // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
      // or if all properties and items were evaluated (it.props === true && it.items === true)
      if (!merged) gen.if(not(valid))
    })
  )

  cxt.result(
    valid,
    () => cxt.reset(),
    () => cxt.error(true)
  )
}
import type {Vocabulary} from "../types"
import coreVocabulary from "./core"
import validationVocabulary from "./validation"
import getApplicatorVocabulary from "./applicator"
import dynamicVocabulary from "./dynamic"
import nextVocabulary from "./next"
import unevaluatedVocabulary from "./unevaluated"
import formatVocabulary from "./format"
import {metadataVocabulary, contentVocabulary} from "./metadata"

const draft2020Vocabularies: Vocabulary[] = [
  dynamicVocabulary,
  coreVocabulary,
  validationVocabulary,
  getApplicatorVocabulary(true),
  formatVocabulary,
  metadataVocabulary,
  contentVocabulary,
  nextVocabulary,
  unevaluatedVocabulary,
]

export default draft2020Vocabularies
import type {Vocabulary} from "../types"
import coreVocabulary from "./core"
import validationVocabulary from "./validation"
import getApplicatorVocabulary from "./applicator"
import formatVocabulary from "./format"
import {metadataVocabulary, contentVocabulary} from "./metadata"

const draft7Vocabularies: Vocabulary[] = [
  coreVocabulary,
  validationVocabulary,
  getApplicatorVocabulary(),
  formatVocabulary,
  metadataVocabulary,
  contentVocabulary,
]

export default draft7Vocabularies
import type {TypeError} from "../compile/validate/dataType"
import type {ApplicatorKeywordError} from "./applicator"
import type {ValidationKeywordError} from "./validation"
import type {FormatError} from "./format/format"
import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties"
import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems"
import type {DependentRequiredError} from "./validation/dependentRequired"
import type {DiscriminatorError} from "./discriminator"

export type DefinedError =
  | TypeError
  | ApplicatorKeywordError
  | ValidationKeywordError
  | FormatError
  | UnevaluatedPropertiesError
  | UnevaluatedItemsError
  | DependentRequiredError
  | DiscriminatorError
import type {Vocabulary} from "../types"

export const metadataVocabulary: Vocabulary = [
  "title",
  "description",
  "default",
  "deprecated",
  "readOnly",
  "writeOnly",
  "examples",
]

export const contentVocabulary: Vocabulary = [
  "contentMediaType",
  "contentEncoding",
  "contentSchema",
]
import type {Vocabulary} from "../types"
import dependentRequired from "./validation/dependentRequired"
import dependentSchemas from "./applicator/dependentSchemas"
import limitContains from "./validation/limitContains"

const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains]

export default next
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type ConstError = ErrorObject<"const", {allowedValue: any}>

const error: KeywordErrorDefinition = {
  message: "must be equal to constant",
  params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "const",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schemaCode, schema} = cxt
    if ($data || (schema && typeof schema == "object")) {
      cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)
    } else {
      cxt.fail(_`${schema} !== ${data}`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject} from "../../types"
import {
  validatePropertyDeps,
  error,
  DependenciesErrorParams,
  PropertyDependencies,
} from "../applicator/dependencies"

export type DependentRequiredError = ErrorObject<
  "dependentRequired",
  DependenciesErrorParams,
  PropertyDependencies
>

const def: CodeKeywordDefinition = {
  keyword: "dependentRequired",
  type: "object",
  schemaType: "object",
  error,
  code: (cxt) => validatePropertyDeps(cxt),
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, or, Name, Code} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}>

const error: KeywordErrorDefinition = {
  message: "must be equal to one of the allowed values",
  params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "enum",
  schemaType: "array",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    if (!$data && schema.length === 0) throw new Error("enum must have non-empty array")
    const useLoop = schema.length >= it.opts.loopEnum
    let eql: Name | undefined
    const getEql = (): Name => (eql ??= useFunc(gen, equal))

    let valid: Code
    if (useLoop || $data) {
      valid = gen.let("valid")
      cxt.block$data(valid, loopEnum)
    } else {
      /* istanbul ignore if */
      if (!Array.isArray(schema)) throw new Error("ajv implementation error")
      const vSchema = gen.const("vSchema", schemaCode)
      valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))
    }
    cxt.pass(valid)

    function loopEnum(): void {
      gen.assign(valid, false)
      gen.forOf("v", schemaCode as Code, (v) =>
        gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())
      )
    }

    function equalCode(vSchema: Name, i: number): Code {
      const sch = schema[i]
      return typeof sch === "object" && sch !== null
        ? _`${getEql()}(${data}, ${vSchema}[${i}])`
        : _`${data} === ${sch}`
    }
  },
}

export default def
import type {ErrorObject, Vocabulary} from "../../types"
import limitNumber, {LimitNumberError} from "./limitNumber"
import multipleOf, {MultipleOfError} from "./multipleOf"
import limitLength from "./limitLength"
import pattern, {PatternError} from "./pattern"
import limitProperties from "./limitProperties"
import required, {RequiredError} from "./required"
import limitItems from "./limitItems"
import uniqueItems, {UniqueItemsError} from "./uniqueItems"
import constKeyword, {ConstError} from "./const"
import enumKeyword, {EnumError} from "./enum"

const validation: Vocabulary = [
  // number
  limitNumber,
  multipleOf,
  // string
  limitLength,
  pattern,
  // object
  limitProperties,
  required,
  // array
  limitItems,
  uniqueItems,
  // any
  {keyword: "type", schemaType: ["string", "array"]},
  {keyword: "nullable", schemaType: "boolean"},
  constKeyword,
  enumKeyword,
]

export default validation

type LimitError = ErrorObject<
  "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength",
  {limit: number},
  number | {$data: string}
>

export type ValidationKeywordError =
  | LimitError
  | LimitNumberError
  | MultipleOfError
  | PatternError
  | RequiredError
  | UniqueItemsError
  | ConstError
  | EnumError
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: ["maxContains", "minContains"],
  type: "array",
  schemaType: "number",
  code({keyword, parentSchema, it}: KeywordCxt) {
    if (parentSchema.contains === undefined) {
      checkStrictMode(it, `"${keyword}" without "contains" is ignored`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxItems" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} items`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxItems", "minItems"],
  type: "array",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    const op = keyword === "maxItems" ? operators.GT : operators.LT
    cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import ucs2length from "../../runtime/ucs2length"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxLength" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} characters`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxLength", "minLength"],
  type: "string",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode, it} = cxt
    const op = keyword === "maxLength" ? operators.GT : operators.LT
    const len =
      it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`
    cxt.fail$data(_`${len} ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators, Code} from "../../compile/codegen"

const ops = operators

type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum"

type Comparison = "<=" | ">=" | "<" | ">"

const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {
  maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT},
  minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT},
  exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE},
  exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE},
}

export type LimitNumberError = ErrorObject<
  Kwd,
  {limit: number; comparison: Comparison},
  number | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,
  params: ({keyword, schemaCode}) =>
    _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: Object.keys(KWDs),
  type: "number",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxProperties" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} properties`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxProperties", "minProperties"],
  type: "object",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    const op = keyword === "maxProperties" ? operators.GT : operators.LT
    cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"

export type MultipleOfError = ErrorObject<
  "multipleOf",
  {multipleOf: number},
  number | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,
  params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "multipleOf",
  type: "number",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, schemaCode, it} = cxt
    // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
    const prec = it.opts.multipleOfPrecision
    const res = gen.let("res")
    const invalid = prec
      ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
      : _`${res} !== parseInt(${res})`
    cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {usePattern} from "../code"
import {useFunc} from "../../compile/util"
import {_, str} from "../../compile/codegen"

export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must match pattern "${schemaCode}"`,
  params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "pattern",
  type: "string",
  schemaType: "string",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    const u = it.opts.unicodeRegExp ? "u" : ""
    if ($data) {
      const {regExp} = it.opts.code
      const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp)
      const valid = gen.let("valid")
      gen.try(
        () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),
        () => gen.assign(valid, false)
      )
      cxt.fail$data(_`!${valid}`)
    } else {
      const regExp = usePattern(cxt, schema)
      cxt.fail$data(_`!${regExp}.test(${data})`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {
  checkReportMissingProp,
  checkMissingProp,
  reportMissingProp,
  propertyInData,
  noPropertyInData,
} from "../code"
import {_, str, nil, not, Name, Code} from "../../compile/codegen"
import {checkStrictMode} from "../../compile/util"

export type RequiredError = ErrorObject<
  "required",
  {missingProperty: string},
  string[] | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,
  params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "required",
  type: "object",
  schemaType: "array",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, schemaCode, data, $data, it} = cxt
    const {opts} = it
    if (!$data && schema.length === 0) return
    const useLoop = schema.length >= opts.loopRequired
    if (it.allErrors) allErrorsMode()
    else exitOnErrorMode()

    if (opts.strictRequired) {
      const props = cxt.parentSchema.properties
      const {definedProperties} = cxt.it
      for (const requiredKey of schema) {
        if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {
          const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
          const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`
          checkStrictMode(it, msg, it.opts.strictRequired)
        }
      }
    }

    function allErrorsMode(): void {
      if (useLoop || $data) {
        cxt.block$data(nil, loopAllRequired)
      } else {
        for (const prop of schema) {
          checkReportMissingProp(cxt, prop)
        }
      }
    }

    function exitOnErrorMode(): void {
      const missing = gen.let("missing")
      if (useLoop || $data) {
        const valid = gen.let("valid", true)
        cxt.block$data(valid, () => loopUntilMissing(missing, valid))
        cxt.ok(valid)
      } else {
        gen.if(checkMissingProp(cxt, schema, missing))
        reportMissingProp(cxt, missing)
        gen.else()
      }
    }

    function loopAllRequired(): void {
      gen.forOf("prop", schemaCode as Code, (prop) => {
        cxt.setParams({missingProperty: prop})
        gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())
      })
    }

    function loopUntilMissing(missing: Name, valid: Name): void {
      cxt.setParams({missingProperty: missing})
      gen.forOf(
        missing,
        schemaCode as Code,
        () => {
          gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))
          gen.if(not(valid), () => {
            cxt.error()
            gen.break()
          })
        },
        nil
      )
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType"
import {_, str, Name} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type UniqueItemsError = ErrorObject<
  "uniqueItems",
  {i: number; j: number},
  boolean | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({params: {i, j}}) =>
    str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
  params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "uniqueItems",
  type: "array",
  schemaType: "boolean",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt
    if (!$data && !schema) return
    const valid = gen.let("valid")
    const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []
    cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)
    cxt.ok(valid)

    function validateUniqueItems(): void {
      const i = gen.let("i", _`${data}.length`)
      const j = gen.let("j")
      cxt.setParams({i, j})
      gen.assign(valid, true)
      gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))
    }

    function canOptimize(): boolean {
      return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array")
    }

    function loopN(i: Name, j: Name): void {
      const item = gen.name("item")
      const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)
      const indices = gen.const("indices", _`{}`)
      gen.for(_`;${i}--;`, () => {
        gen.let(item, _`${data}[${i}]`)
        gen.if(wrongType, _`continue`)
        if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`)
        gen
          .if(_`typeof ${indices}[${item}] == "number"`, () => {
            gen.assign(j, _`${indices}[${item}]`)
            cxt.error()
            gen.assign(valid, false).break()
          })
          .code(_`${indices}[${item}] = ${i}`)
      })
    }

    function loopN2(i: Name, j: Name): void {
      const eql = useFunc(gen, equal)
      const outer = gen.name("outer")
      gen.label(outer).for(_`;${i}--;`, () =>
        gen.for(_`${j} = ${i}; ${j}--;`, () =>
          gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {
            cxt.error()
            gen.assign(valid, false).break(outer)
          })
        )
      )
    }
  },
}

export default def
import type {Vocabulary} from "../../types"
import unevaluatedProperties from "./unevaluatedProperties"
import unevaluatedItems from "./unevaluatedItems"

const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems]

export default unevaluated
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, Type} from "../../compile/util"

export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "unevaluatedItems",
  type: "array",
  schemaType: ["boolean", "object"],
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, data, it} = cxt
    const items = it.items || 0
    if (items === true) return
    const len = gen.const("len", _`${data}.length`)
    if (schema === false) {
      cxt.setParams({len: items})
      cxt.fail(_`${len} > ${items}`)
    } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
      const valid = gen.var("valid", _`${len} <= ${items}`)
      gen.if(not(valid), () => validateItems(valid, items))
      cxt.ok(valid)
    }
    it.items = true

    function validateItems(valid: Name, from: Name | number): void {
      gen.forRange("i", from, len, (i) => {
        cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid)
        if (!it.allErrors) gen.if(not(valid), () => gen.break())
      })
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import {_, not, and, Name, Code} from "../../compile/codegen"
import {alwaysValidSchema, Type} from "../../compile/util"
import N from "../../compile/names"

export type UnevaluatedPropertiesError = ErrorObject<
  "unevaluatedProperties",
  {unevaluatedProperty: string},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: "must NOT have unevaluated properties",
  params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "unevaluatedProperties",
  type: "object",
  schemaType: ["boolean", "object"],
  trackErrors: true,
  error,
  code(cxt) {
    const {gen, schema, data, errsCount, it} = cxt
    /* istanbul ignore if */
    if (!errsCount) throw new Error("ajv implementation error")
    const {allErrors, props} = it
    if (props instanceof Name) {
      gen.if(_`${props} !== true`, () =>
        gen.forIn("key", data, (key: Name) =>
          gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))
        )
      )
    } else if (props !== true) {
      gen.forIn("key", data, (key: Name) =>
        props === undefined
          ? unevaluatedPropCode(key)
          : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))
      )
    }
    it.props = true
    cxt.ok(_`${errsCount} === ${N.errors}`)

    function unevaluatedPropCode(key: Name): void {
      if (schema === false) {
        cxt.setParams({unevaluatedProperty: key})
        cxt.error()
        if (!allErrors) gen.break()
        return
      }

      if (!alwaysValidSchema(it, schema)) {
        const valid = gen.name("valid")
        cxt.subschema(
          {
            keyword: "unevaluatedProperties",
            dataProp: key,
            dataPropType: Type.Str,
          },
          valid
        )
        if (!allErrors) gen.if(not(valid), () => gen.break())
      }
    }

    function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code {
      return _`!${evaluatedProps} || !${evaluatedProps}[${key}]`
    }

    function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code {
      const ps: Code[] = []
      for (const p in evaluatedProps) {
        if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`)
      }
      return and(...ps)
    }
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, not, getProperty, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
import {DiscrError, DiscrErrorObj} from "../discriminator/types"

export type JTDDiscriminatorError =
  | _JTDTypeError<"discriminator", "object", string>
  | DiscrErrorObj<DiscrError.Tag>
  | DiscrErrorObj<DiscrError.Mapping>

const error: KeywordErrorDefinition = {
  message: (cxt) => {
    const {schema, params} = cxt
    return params.discrError
      ? params.discrError === DiscrError.Tag
        ? `tag "${schema}" must be string`
        : `value of tag "${schema}" must be in mapping`
      : typeErrorMessage(cxt, "object")
  },
  params: (cxt) => {
    const {schema, params} = cxt
    return params.discrError
      ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
      : typeErrorParams(cxt, "object")
  },
}

const def: CodeKeywordDefinition = {
  keyword: "discriminator",
  schemaType: "string",
  implements: ["mapping"],
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, parentSchema} = cxt
    const [valid, cond] = checkNullableObject(cxt, data)

    gen.if(cond)
    validateDiscriminator()
    gen.elseIf(not(valid))
    cxt.error()
    gen.endIf()
    cxt.ok(valid)

    function validateDiscriminator(): void {
      const tag = gen.const("tag", _`${data}${getProperty(schema)}`)
      gen.if(_`${tag} === undefined`)
      cxt.error(false, {discrError: DiscrError.Tag, tag})
      gen.elseIf(_`typeof ${tag} == "string"`)
      validateMapping(tag)
      gen.else()
      cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema})
      gen.endIf()
    }

    function validateMapping(tag: Name): void {
      gen.if(false)
      for (const tagValue in parentSchema.mapping) {
        gen.elseIf(_`${tag} === ${tagValue}`)
        gen.assign(valid, applyTagSchema(tagValue))
      }
      gen.else()
      cxt.error(
        false,
        {discrError: DiscrError.Mapping, tag},
        {instancePath: schema, schemaPath: "mapping", parentSchema: true}
      )
      gen.endIf()
    }

    function applyTagSchema(schemaProp: string): Name {
      const _valid = gen.name("valid")
      cxt.subschema(
        {
          keyword: "mapping",
          schemaProp,
          jtdDiscriminator: schema,
        },
        _valid
      )
      return _valid
    }
  },
}

export default def
import type {CodeKeywordDefinition, SchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"
import {validateArray} from "../code"
import {_, not} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullable} from "./nullable"
import {typeError, _JTDTypeError} from "./error"

export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject>

const def: CodeKeywordDefinition = {
  keyword: "elements",
  schemaType: "object",
  error: typeError("array"),
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const [valid] = checkNullable(cxt)
    gen.if(not(valid), () =>
      gen.if(
        _`Array.isArray(${data})`,
        () => gen.assign(valid, validateArray(cxt)),
        () => cxt.error()
      )
    )
    cxt.ok(valid)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, or, and, Code} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullable} from "./nullable"

export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]>

const error: KeywordErrorDefinition = {
  message: "must be equal to one of the allowed values",
  params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "enum",
  schemaType: "array",
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, schemaValue, parentSchema, it} = cxt
    if (schema.length === 0) throw new Error("enum must have non-empty array")
    if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique")
    let valid: Code
    const isString = _`typeof ${data} == "string"`
    if (schema.length >= it.opts.loopEnum) {
      let cond: Code
      ;[valid, cond] = checkNullable(cxt, isString)
      gen.if(cond, loopEnum)
    } else {
      /* istanbul ignore if */
      if (!Array.isArray(schema)) throw new Error("ajv implementation error")
      valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`)))
      if (parentSchema.nullable) valid = or(_`${data} === null`, valid)
    }
    cxt.pass(valid)

    function loopEnum(): void {
      gen.forOf("v", schemaValue as Code, (v) =>
        gen.if(_`${valid} = ${data} === ${v}`, () => gen.break())
      )
    }
  },
}

export default def
import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types"
import {_, Code} from "../../compile/codegen"

export type _JTDTypeError<K extends string, T extends string, S> = ErrorObject<
  K,
  {type: T; nullable: boolean},
  S
>

export function typeError(t: string): KeywordErrorDefinition {
  return {
    message: (cxt) => typeErrorMessage(cxt, t),
    params: (cxt) => typeErrorParams(cxt, t),
  }
}

export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string {
  return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}`
}

export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code {
  return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}`
}
import type {Vocabulary} from "../../types"
import refKeyword from "./ref"
import typeKeyword, {JTDTypeError} from "./type"
import enumKeyword, {JTDEnumError} from "./enum"
import elements, {JTDElementsError} from "./elements"
import properties, {JTDPropertiesError} from "./properties"
import optionalProperties from "./optionalProperties"
import discriminator, {JTDDiscriminatorError} from "./discriminator"
import values, {JTDValuesError} from "./values"
import union from "./union"
import metadata from "./metadata"

const jtdVocabulary: Vocabulary = [
  "definitions",
  refKeyword,
  typeKeyword,
  enumKeyword,
  elements,
  properties,
  optionalProperties,
  discriminator,
  values,
  union,
  metadata,
  {keyword: "additionalProperties", schemaType: "boolean"},
  {keyword: "nullable", schemaType: "boolean"},
]

export default jtdVocabulary

export type JTDErrorObject =
  | JTDTypeError
  | JTDEnumError
  | JTDElementsError
  | JTDPropertiesError
  | JTDDiscriminatorError
  | JTDValuesError
import {KeywordCxt} from "../../ajv"
import type {CodeKeywordDefinition} from "../../types"
import {alwaysValidSchema} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "metadata",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const valid = gen.name("valid")
    cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid)
    cxt.ok(valid)
  },
}

export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void {
  if (it.jtdMetadata !== metadata) {
    throw new Error(`JTD: "${keyword}" cannot be used in this schema location`)
  }
}

export default def
import type {KeywordCxt} from "../../compile/validate"
import {_, not, nil, Code, Name} from "../../compile/codegen"

export function checkNullable(
  {gen, data, parentSchema}: KeywordCxt,
  cond: Code = nil
): [Name, Code] {
  const valid = gen.name("valid")
  if (parentSchema.nullable) {
    gen.let(valid, _`${data} === null`)
    cond = not(valid)
  } else {
    gen.let(valid, false)
  }
  return [valid, cond]
}

export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] {
  const [valid, cond_] = checkNullable(cxt, cond)
  return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]
}
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {validateProperties, error} from "./properties"

const def: CodeKeywordDefinition = {
  keyword: "optionalProperties",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    if (cxt.parentSchema.properties) return
    validateProperties(cxt)
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  SchemaObject,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {propertyInData, allSchemaProperties, isOwnProperty} from "../code"
import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util"
import {_, and, not, Code, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"

enum PropError {
  Additional = "additional",
  Missing = "missing",
}

type PropKeyword = "properties" | "optionalProperties"

type PropSchema = {[P in string]?: SchemaObject}

export type JTDPropertiesError =
  | _JTDTypeError<PropKeyword, "object", PropSchema>
  | ErrorObject<PropKeyword, {error: PropError.Additional; additionalProperty: string}, PropSchema>
  | ErrorObject<PropKeyword, {error: PropError.Missing; missingProperty: string}, PropSchema>

export const error: KeywordErrorDefinition = {
  message: (cxt) => {
    const {params} = cxt
    return params.propError
      ? params.propError === PropError.Additional
        ? "must NOT have additional properties"
        : `must have property '${params.missingProperty}'`
      : typeErrorMessage(cxt, "object")
  },
  params: (cxt) => {
    const {params} = cxt
    return params.propError
      ? params.propError === PropError.Additional
        ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
        : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
      : typeErrorParams(cxt, "object")
  },
}

const def: CodeKeywordDefinition = {
  keyword: "properties",
  schemaType: "object",
  error,
  code: validateProperties,
}

// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }

export function validateProperties(cxt: KeywordCxt): void {
  checkMetadata(cxt)
  const {gen, data, parentSchema, it} = cxt
  const {additionalProperties, nullable} = parentSchema
  if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping")
  if (commonProperties()) {
    throw new Error("JTD: properties and optionalProperties have common members")
  }
  const [allProps, properties] = schemaProperties("properties")
  const [allOptProps, optProperties] = schemaProperties("optionalProperties")
  if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
    return
  }

  const [valid, cond] =
    it.jtdDiscriminator === undefined
      ? checkNullableObject(cxt, data)
      : [gen.let("valid", false), true]
  gen.if(cond, () =>
    gen.assign(valid, true).block(() => {
      validateProps(properties, "properties", true)
      validateProps(optProperties, "optionalProperties")
      if (!additionalProperties) validateAdditional()
    })
  )
  cxt.pass(valid)

  function commonProperties(): boolean {
    const props = parentSchema.properties as Record<string, any> | undefined
    const optProps = parentSchema.optionalProperties as Record<string, any> | undefined
    if (!(props && optProps)) return false
    for (const p in props) {
      if (Object.prototype.hasOwnProperty.call(optProps, p)) return true
    }
    return false
  }

  function schemaProperties(keyword: string): [string[], string[]] {
    const schema = parentSchema[keyword]
    const allPs = schema ? allSchemaProperties(schema) : []
    if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
      throw new Error(`JTD: discriminator tag used in ${keyword}`)
    }
    const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p]))
    return [allPs, ps]
  }

  function validateProps(props: string[], keyword: string, required?: boolean): void {
    const _valid = gen.var("valid")
    for (const prop of props) {
      gen.if(
        propertyInData(gen, data, prop, it.opts.ownProperties),
        () => applyPropertySchema(prop, keyword, _valid),
        () => missingProperty(prop)
      )
      cxt.ok(_valid)
    }

    function missingProperty(prop: string): void {
      if (required) {
        gen.assign(_valid, false)
        cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop})
      } else {
        gen.assign(_valid, true)
      }
    }
  }

  function applyPropertySchema(prop: string, keyword: string, _valid: Name): void {
    cxt.subschema(
      {
        keyword,
        schemaProp: prop,
        dataProp: prop,
      },
      _valid
    )
  }

  function validateAdditional(): void {
    gen.forIn("key", data, (key: Name) => {
      const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator)
      const addOptProp = isAdditional(key, allOptProps, "optionalProperties")
      const extra =
        addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp)
      gen.if(extra, () => {
        if (it.opts.removeAdditional) {
          gen.code(_`delete ${data}[${key}]`)
        } else {
          cxt.error(
            false,
            {propError: PropError.Additional, additionalProperty: key},
            {instancePath: key, parentSchema: true}
          )
          if (!it.opts.allErrors) gen.break()
        }
      })
    })
  }

  function isAdditional(
    key: Name,
    props: string[],
    keyword: string,
    jtdDiscriminator?: string
  ): Code | true {
    let additional: Code | boolean
    if (props.length > 8) {
      // TODO maybe an option instead of hard-coded 8?
      const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword)
      additional = not(isOwnProperty(gen, propsSchema as Code, key))
      if (jtdDiscriminator !== undefined) {
        additional = and(additional, _`${key} !== ${jtdDiscriminator}`)
      }
    } else if (props.length || jtdDiscriminator !== undefined) {
      const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props)
      additional = and(...ps.map((p) => _`${key} !== ${p}`))
    } else {
      additional = true
    }
    return additional
  }
}

export default def
import type {CodeKeywordDefinition, AnySchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {compileSchema, SchemaEnv} from "../../compile"
import {_, not, nil, stringify} from "../../compile/codegen"
import MissingRefError from "../../compile/ref_error"
import N from "../../compile/names"
import {getValidate, callRef} from "../core/ref"
import {checkMetadata} from "./metadata"

const def: CodeKeywordDefinition = {
  keyword: "ref",
  schemaType: "string",
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema: ref, parentSchema, it} = cxt
    const {
      schemaEnv: {root},
    } = it
    const valid = gen.name("valid")
    if (parentSchema.nullable) {
      gen.var(valid, _`${data} === null`)
      gen.if(not(valid), validateJtdRef)
    } else {
      gen.var(valid, false)
      validateJtdRef()
    }
    cxt.ok(valid)

    function validateJtdRef(): void {
      const refSchema = (root.schema as AnySchemaObject).definitions?.[ref]
      if (!refSchema) {
        throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`)
      }
      if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema)
      else inlineRefSchema(refSchema)
    }

    function callValidate(schema: AnySchemaObject): void {
      const sch = compileSchema.call(
        it.self,
        new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
      )
      const v = getValidate(cxt, sch)
      const errsCount = gen.const("_errs", N.errors)
      callRef(cxt, v, sch, sch.$async)
      gen.assign(valid, _`${errsCount} === ${N.errors}`)
    }

    function inlineRefSchema(schema: AnySchemaObject): void {
      const schName = gen.scopeValue(
        "schema",
        it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
      )
      cxt.subschema(
        {
          schema,
          dataTypes: [],
          schemaPath: nil,
          topSchemaRef: schName,
          errSchemaPath: `/definitions/${ref}`,
        },
        valid
      )
    }
  },
}

export function hasRef(schema: AnySchemaObject): boolean {
  for (const key in schema) {
    let sch: AnySchemaObject
    if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true
  }
  return false
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, nil, or, Code} from "../../compile/codegen"
import validTimestamp from "../../runtime/timestamp"
import {useFunc} from "../../compile/util"
import {checkMetadata} from "./metadata"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"

export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>

export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"

export const intRange: {[T in IntType]: [number, number, number]} = {
  int8: [-128, 127, 3],
  uint8: [0, 255, 3],
  int16: [-32768, 32767, 5],
  uint16: [0, 65535, 5],
  int32: [-2147483648, 2147483647, 10],
  uint32: [0, 4294967295, 10],
}

export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType

const error: KeywordErrorDefinition = {
  message: (cxt) => typeErrorMessage(cxt, cxt.schema),
  params: (cxt) => typeErrorParams(cxt, cxt.schema),
}

function timestampCode(cxt: KeywordCxt): Code {
  const {gen, data, it} = cxt
  const {timestamp, allowDate} = it.opts
  if (timestamp === "date") return _`${data} instanceof Date `
  const vts = useFunc(gen, validTimestamp)
  const allowDateArg = allowDate ? _`, true` : nil
  const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`
  return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString)
}

const def: CodeKeywordDefinition = {
  keyword: "type",
  schemaType: "string",
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {data, schema, parentSchema, it} = cxt
    let cond: Code
    switch (schema) {
      case "boolean":
      case "string":
        cond = _`typeof ${data} == ${schema}`
        break
      case "timestamp": {
        cond = timestampCode(cxt)
        break
      }
      case "float32":
      case "float64":
        cond = _`typeof ${data} == "number"`
        break
      default: {
        const sch = schema as IntType
        cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`
        if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
          if (sch === "uint32") cond = _`${cond} && ${data} >= 0`
        } else {
          const [min, max] = intRange[sch]
          cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}`
        }
      }
    }
    cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateUnion} from "../code"

const def: CodeKeywordDefinition = {
  keyword: "union",
  schemaType: "array",
  trackErrors: true,
  code: validateUnion,
  error: {message: "must match a schema in union"},
}

export default def
import type {CodeKeywordDefinition, SchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema, Type} from "../../compile/util"
import {not, or, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeError, _JTDTypeError} from "./error"

export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject>

const def: CodeKeywordDefinition = {
  keyword: "values",
  schemaType: "object",
  error: typeError("object"),
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, it} = cxt
    const [valid, cond] = checkNullableObject(cxt, data)
    if (alwaysValidSchema(it, schema)) {
      gen.if(not(or(cond, valid)), () => cxt.error())
    } else {
      gen.if(cond)
      gen.assign(valid, validateMap())
      gen.elseIf(not(valid))
      cxt.error()
      gen.endIf()
    }
    cxt.ok(valid)

    function validateMap(): Name | boolean {
      const _valid = gen.name("valid")
      if (it.allErrors) {
        const validMap = gen.let("valid", true)
        validateValues(() => gen.assign(validMap, false))
        return validMap
      }
      gen.var(_valid, true)
      validateValues(() => gen.break())
      return _valid

      function validateValues(notValid: () => void): void {
        gen.forIn("key", data, (key) => {
          cxt.subschema(
            {
              keyword: "values",
              dataProp: key,
              dataPropType: Type.Str,
            },
            _valid
          )
          gen.if(not(_valid), notValid)
        })
      }
    }
  },
}

export default def
import type {
  AddedFormat,
  FormatValidator,
  AsyncFormatValidator,
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen"

type FormatValidate =
  | FormatValidator<string>
  | FormatValidator<number>
  | AsyncFormatValidator<string>
  | AsyncFormatValidator<number>
  | RegExp
  | string
  | true

export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must match format "${schemaCode}"`,
  params: ({schemaCode}) => _`{format: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "format",
  type: ["number", "string"],
  schemaType: "string",
  $data: true,
  error,
  code(cxt: KeywordCxt, ruleType?: string) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    const {opts, errSchemaPath, schemaEnv, self} = it
    if (!opts.validateFormats) return

    if ($data) validate$DataFormat()
    else validateFormat()

    function validate$DataFormat(): void {
      const fmts = gen.scopeValue("formats", {
        ref: self.formats,
        code: opts.code.formats,
      })
      const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`)
      const fType = gen.let("fType")
      const format = gen.let("format")
      // TODO simplify
      gen.if(
        _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,
        () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`),
        () => gen.assign(fType, _`"string"`).assign(format, fDef)
      )
      cxt.fail$data(or(unknownFmt(), invalidFmt()))

      function unknownFmt(): Code {
        if (opts.strictSchema === false) return nil
        return _`${schemaCode} && !${format}`
      }

      function invalidFmt(): Code {
        const callFormat = schemaEnv.$async
          ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
          : _`${format}(${data})`
        const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`
        return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`
      }
    }

    function validateFormat(): void {
      const formatDef: AddedFormat | undefined = self.formats[schema]
      if (!formatDef) {
        unknownFormat()
        return
      }
      if (formatDef === true) return
      const [fmtType, format, fmtRef] = getFormat(formatDef)
      if (fmtType === ruleType) cxt.pass(validCondition())

      function unknownFormat(): void {
        if (opts.strictSchema === false) {
          self.logger.warn(unknownMsg())
          return
        }
        throw new Error(unknownMsg())

        function unknownMsg(): string {
          return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"`
        }
      }

      function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {
        const code =
          fmtDef instanceof RegExp
            ? regexpCode(fmtDef)
            : opts.code.formats
            ? _`${opts.code.formats}${getProperty(schema)}`
            : undefined
        const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code})
        if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
          return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`]
        }

        return ["string", fmtDef, fmt]
      }

      function validCondition(): Code {
        if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
          if (!schemaEnv.$async) throw new Error("async format in sync schema")
          return _`await ${fmtRef}(${data})`
        }
        return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`
      }
    }
  },
}

export default def
import type {Vocabulary} from "../../types"
import formatKeyword from "./format"

const format: Vocabulary = [formatKeyword]

export default format
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Code} from "../../compile/codegen"
import N from "../../compile/names"
import {SchemaEnv, compileSchema} from "../../compile"
import {getValidate} from "../core/ref"

const def: CodeKeywordDefinition = {
  keyword: "$dynamicAnchor",
  schemaType: "string",
  code: (cxt) => dynamicAnchor(cxt, cxt.schema),
}

export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void {
  const {gen, it} = cxt
  it.schemaEnv.root.dynamicAnchors[anchor] = true
  const v = _`${N.dynamicAnchors}${getProperty(anchor)}`
  const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt)
  gen.if(_`!${v}`, () => gen.assign(v, validate))
}

function _getValidate(cxt: KeywordCxt): Code {
  const {schemaEnv, schema, self} = cxt.it
  const {root, baseId, localRefs, meta} = schemaEnv.root
  const {schemaId} = self.opts
  const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})
  compileSchema.call(self, sch)
  return getValidate(cxt, sch)
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import {callRef} from "../core/ref"

const def: CodeKeywordDefinition = {
  keyword: "$dynamicRef",
  schemaType: "string",
  code: (cxt) => dynamicRef(cxt, cxt.schema),
}

export function dynamicRef(cxt: KeywordCxt, ref: string): void {
  const {gen, keyword, it} = cxt
  if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`)
  const anchor = ref.slice(1)
  if (it.allErrors) {
    _dynamicRef()
  } else {
    const valid = gen.let("valid", false)
    _dynamicRef(valid)
    cxt.ok(valid)
  }

  function _dynamicRef(valid?: Name): void {
    // TODO the assumption here is that `recursiveRef: #` always points to the root
    // of the schema object, which is not correct, because there may be $id that
    // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
    // Because of that 2 tests in recursiveRef.json fail.
    // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
    // (This problem is not tested in JSON-Schema-Test-Suite)
    if (it.schemaEnv.root.dynamicAnchors[anchor]) {
      const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`)
      gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid))
    } else {
      _callRef(it.validateName, valid)()
    }
  }

  function _callRef(validate: Code, valid?: Name): () => void {
    return valid
      ? () =>
          gen.block(() => {
            callRef(cxt, validate)
            gen.let(valid, true)
          })
      : () => callRef(cxt, validate)
  }
}

export default def
import type {Vocabulary} from "../../types"
import dynamicAnchor from "./dynamicAnchor"
import dynamicRef from "./dynamicRef"
import recursiveAnchor from "./recursiveAnchor"
import recursiveRef from "./recursiveRef"

const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef]

export default dynamic
import type {CodeKeywordDefinition} from "../../types"
import {dynamicAnchor} from "./dynamicAnchor"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "$recursiveAnchor",
  schemaType: "boolean",
  code(cxt) {
    if (cxt.schema) dynamicAnchor(cxt, "")
    else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored")
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {dynamicRef} from "./dynamicRef"

const def: CodeKeywordDefinition = {
  keyword: "$recursiveRef",
  schemaType: "string",
  code: (cxt) => dynamicRef(cxt, cxt.schema),
}

export default def
import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Name} from "../../compile/codegen"
import {DiscrError, DiscrErrorObj} from "../discriminator/types"
import {resolveRef, SchemaEnv} from "../../compile"
import MissingRefError from "../../compile/ref_error"
import {schemaHasRulesButRef} from "../../compile/util"

export type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>

const error: KeywordErrorDefinition = {
  message: ({params: {discrError, tagName}}) =>
    discrError === DiscrError.Tag
      ? `tag "${tagName}" must be string`
      : `value of tag "${tagName}" must be in oneOf`,
  params: ({params: {discrError, tag, tagName}}) =>
    _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "discriminator",
  type: "object",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, schema, parentSchema, it} = cxt
    const {oneOf} = parentSchema
    if (!it.opts.discriminator) {
      throw new Error("discriminator: requires discriminator option")
    }
    const tagName = schema.propertyName
    if (typeof tagName != "string") throw new Error("discriminator: requires propertyName")
    if (schema.mapping) throw new Error("discriminator: mapping is not supported")
    if (!oneOf) throw new Error("discriminator: requires oneOf keyword")
    const valid = gen.let("valid", false)
    const tag = gen.const("tag", _`${data}${getProperty(tagName)}`)
    gen.if(
      _`typeof ${tag} == "string"`,
      () => validateMapping(),
      () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})
    )
    cxt.ok(valid)

    function validateMapping(): void {
      const mapping = getMapping()
      gen.if(false)
      for (const tagValue in mapping) {
        gen.elseIf(_`${tag} === ${tagValue}`)
        gen.assign(valid, applyTagSchema(mapping[tagValue]))
      }
      gen.else()
      cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})
      gen.endIf()
    }

    function applyTagSchema(schemaProp?: number): Name {
      const _valid = gen.name("valid")
      const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid)
      cxt.mergeEvaluated(schCxt, Name)
      return _valid
    }

    function getMapping(): {[T in string]?: number} {
      const oneOfMapping: {[T in string]?: number} = {}
      const topRequired = hasRequired(parentSchema)
      let tagRequired = true
      for (let i = 0; i < oneOf.length; i++) {
        let sch = oneOf[i]
        if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {
          const ref = sch.$ref
          sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)
          if (sch instanceof SchemaEnv) sch = sch.schema
          if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)
        }
        const propSch = sch?.properties?.[tagName]
        if (typeof propSch != "object") {
          throw new Error(
            `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`
          )
        }
        tagRequired = tagRequired && (topRequired || hasRequired(sch))
        addMappings(propSch, i)
      }
      if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`)
      return oneOfMapping

      function hasRequired({required}: AnySchemaObject): boolean {
        return Array.isArray(required) && required.includes(tagName)
      }

      function addMappings(sch: AnySchemaObject, i: number): void {
        if (sch.const) {
          addMapping(sch.const, i)
        } else if (sch.enum) {
          for (const tagValue of sch.enum) {
            addMapping(tagValue, i)
          }
        } else {
          throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)
        }
      }

      function addMapping(tagValue: unknown, i: number): void {
        if (typeof tagValue != "string" || tagValue in oneOfMapping) {
          throw new Error(`discriminator: "${tagName}" values must be unique strings`)
        }
        oneOfMapping[tagValue] = i
      }
    }
  },
}

export default def
import type {ErrorObject} from "../../types"

export enum DiscrError {
  Tag = "tag",
  Mapping = "mapping",
}

export type DiscrErrorObj<E extends DiscrError> = ErrorObject<
  "discriminator",
  {error: E; tag: string; tagValue: unknown},
  string
>
import type {CodeKeywordDefinition} from "../../types"

const def: CodeKeywordDefinition = {
  keyword: "id",
  code() {
    throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')
  },
}

export default def
import type {Vocabulary} from "../../types"
import idKeyword from "./id"
import refKeyword from "./ref"

const core: Vocabulary = [
  "$schema",
  "$id",
  "$defs",
  "$vocabulary",
  {keyword: "$comment"},
  "definitions",
  idKeyword,
  refKeyword,
]

export default core
import type {CodeKeywordDefinition, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import MissingRefError from "../../compile/ref_error"
import {callValidateCode} from "../code"
import {_, nil, stringify, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import {SchemaEnv, resolveRef} from "../../compile"
import {mergeEvaluated} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "$ref",
  schemaType: "string",
  code(cxt: KeywordCxt): void {
    const {gen, schema: $ref, it} = cxt
    const {baseId, schemaEnv: env, validateName, opts, self} = it
    const {root} = env
    if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef()
    const schOrEnv = resolveRef.call(self, root, baseId, $ref)
    if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)
    if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)
    return inlineRefSchema(schOrEnv)

    function callRootRef(): void {
      if (env === root) return callRef(cxt, validateName, env, env.$async)
      const rootName = gen.scopeValue("root", {ref: root})
      return callRef(cxt, _`${rootName}.validate`, root, root.$async)
    }

    function callValidate(sch: SchemaEnv): void {
      const v = getValidate(cxt, sch)
      callRef(cxt, v, sch, sch.$async)
    }

    function inlineRefSchema(sch: AnySchema): void {
      const schName = gen.scopeValue(
        "schema",
        opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}
      )
      const valid = gen.name("valid")
      const schCxt = cxt.subschema(
        {
          schema: sch,
          dataTypes: [],
          schemaPath: nil,
          topSchemaRef: schName,
          errSchemaPath: $ref,
        },
        valid
      )
      cxt.mergeEvaluated(schCxt)
      cxt.ok(valid)
    }
  },
}

export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {
  const {gen} = cxt
  return sch.validate
    ? gen.scopeValue("validate", {ref: sch.validate})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.validate`
}

export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {
  const {gen, it} = cxt
  const {allErrors, schemaEnv: env, opts} = it
  const passCxt = opts.passContext ? N.this : nil
  if ($async) callAsyncRef()
  else callSyncRef()

  function callAsyncRef(): void {
    if (!env.$async) throw new Error("async schema referenced by sync schema")
    const valid = gen.let("valid")
    gen.try(
      () => {
        gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)
        addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result
        if (!allErrors) gen.assign(valid, true)
      },
      (e) => {
        gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))
        addErrorsFrom(e)
        if (!allErrors) gen.assign(valid, false)
      }
    )
    cxt.ok(valid)
  }

  function callSyncRef(): void {
    cxt.result(
      callValidateCode(cxt, v, passCxt),
      () => addEvaluatedFrom(v),
      () => addErrorsFrom(v)
    )
  }

  function addErrorsFrom(source: Code): void {
    const errs = _`${source}.errors`
    gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged
    gen.assign(N.errors, _`${N.vErrors}.length`)
  }

  function addEvaluatedFrom(source: Code): void {
    if (!it.opts.unevaluated) return
    const schEvaluated = sch?.validate?.evaluated
    // TODO refactor
    if (it.props !== true) {
      if (schEvaluated && !schEvaluated.dynamicProps) {
        if (schEvaluated.props !== undefined) {
          it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)
        }
      } else {
        const props = gen.var("props", _`${source}.evaluated.props`)
        it.props = mergeEvaluated.props(gen, props, it.props, Name)
      }
    }
    if (it.items !== true) {
      if (schEvaluated && !schEvaluated.dynamicItems) {
        if (schEvaluated.items !== undefined) {
          it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)
        }
      } else {
        const items = gen.var("items", _`${source}.evaluated.items`)
        it.items = mergeEvaluated.items(gen, items, it.items, Name)
      }
    }
  }
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util"

export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "additionalItems" as const,
  type: "array",
  schemaType: ["boolean", "object"],
  before: "uniqueItems",
  error,
  code(cxt: KeywordCxt) {
    const {parentSchema, it} = cxt
    const {items} = parentSchema
    if (!Array.isArray(items)) {
      checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas')
      return
    }
    validateAdditionalItems(cxt, items)
  },
}

export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {
  const {gen, schema, data, keyword, it} = cxt
  it.items = true
  const len = gen.const("len", _`${data}.length`)
  if (schema === false) {
    cxt.setParams({len: items.length})
    cxt.pass(_`${len} <= ${items.length}`)
  } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
    const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var
    gen.if(not(valid), () => validateItems(valid))
    cxt.ok(valid)
  }

  function validateItems(valid: Name): void {
    gen.forRange("i", items.length, len, (i) => {
      cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)
      if (!it.allErrors) gen.if(not(valid), () => gen.break())
    })
  }
}

export default def
import type {
  CodeKeywordDefinition,
  AddedKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import {allSchemaProperties, usePattern, isOwnProperty} from "../code"
import {_, nil, or, not, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import type {SubschemaArgs} from "../../compile/validate/subschema"
import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util"

export type AdditionalPropertiesError = ErrorObject<
  "additionalProperties",
  {additionalProperty: string},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: "must NOT have additional properties",
  params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
}

const def: CodeKeywordDefinition & AddedKeywordDefinition = {
  keyword: "additionalProperties",
  type: ["object"],
  schemaType: ["boolean", "object"],
  allowUndefined: true,
  trackErrors: true,
  error,
  code(cxt) {
    const {gen, schema, parentSchema, data, errsCount, it} = cxt
    /* istanbul ignore if */
    if (!errsCount) throw new Error("ajv implementation error")
    const {allErrors, opts} = it
    it.props = true
    if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return
    const props = allSchemaProperties(parentSchema.properties)
    const patProps = allSchemaProperties(parentSchema.patternProperties)
    checkAdditionalProperties()
    cxt.ok(_`${errsCount} === ${N.errors}`)

    function checkAdditionalProperties(): void {
      gen.forIn("key", data, (key: Name) => {
        if (!props.length && !patProps.length) additionalPropertyCode(key)
        else gen.if(isAdditional(key), () => additionalPropertyCode(key))
      })
    }

    function isAdditional(key: Name): Code {
      let definedProp: Code
      if (props.length > 8) {
        // TODO maybe an option instead of hard-coded 8?
        const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties")
        definedProp = isOwnProperty(gen, propsSchema as Code, key)
      } else if (props.length) {
        definedProp = or(...props.map((p) => _`${key} === ${p}`))
      } else {
        definedProp = nil
      }
      if (patProps.length) {
        definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))
      }
      return not(definedProp)
    }

    function deleteAdditional(key: Name): void {
      gen.code(_`delete ${data}[${key}]`)
    }

    function additionalPropertyCode(key: Name): void {
      if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
        deleteAdditional(key)
        return
      }

      if (schema === false) {
        cxt.setParams({additionalProperty: key})
        cxt.error()
        if (!allErrors) gen.break()
        return
      }

      if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
        const valid = gen.name("valid")
        if (opts.removeAdditional === "failing") {
          applyAdditionalSchema(key, valid, false)
          gen.if(not(valid), () => {
            cxt.reset()
            deleteAdditional(key)
          })
        } else {
          applyAdditionalSchema(key, valid)
          if (!allErrors) gen.if(not(valid), () => gen.break())
        }
      }
    }

    function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {
      const subschema: SubschemaArgs = {
        keyword: "additionalProperties",
        dataProp: key,
        dataPropType: Type.Str,
      }
      if (errors === false) {
        Object.assign(subschema, {
          compositeRule: true,
          createErrors: false,
          allErrors: false,
        })
      }
      cxt.subschema(subschema, valid)
    }
  },
}

export default def
import type {CodeKeywordDefinition, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "allOf",
  schemaType: "array",
  code(cxt: KeywordCxt) {
    const {gen, schema, it} = cxt
    /* istanbul ignore if */
    if (!Array.isArray(schema)) throw new Error("ajv implementation error")
    const valid = gen.name("valid")
    schema.forEach((sch: AnySchema, i: number) => {
      if (alwaysValidSchema(it, sch)) return
      const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid)
      cxt.ok(valid)
      cxt.mergeEvaluated(schCxt)
    })
  },
}

export default def
import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types"
import {validateUnion} from "../code"

export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]>

const def: CodeKeywordDefinition = {
  keyword: "anyOf",
  schemaType: "array",
  trackErrors: true,
  code: validateUnion,
  error: {message: "must match a schema in anyOf"},
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util"

export type ContainsError = ErrorObject<
  "contains",
  {minContains: number; maxContains?: number},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: ({params: {min, max}}) =>
    max === undefined
      ? str`must contain at least ${min} valid item(s)`
      : str`must contain at least ${min} and no more than ${max} valid item(s)`,
  params: ({params: {min, max}}) =>
    max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "contains",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, data, it} = cxt
    let min: number
    let max: number | undefined
    const {minContains, maxContains} = parentSchema
    if (it.opts.next) {
      min = minContains === undefined ? 1 : minContains
      max = maxContains
    } else {
      min = 1
    }
    const len = gen.const("len", _`${data}.length`)
    cxt.setParams({min, max})
    if (max === undefined && min === 0) {
      checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`)
      return
    }
    if (max !== undefined && min > max) {
      checkStrictMode(it, `"minContains" > "maxContains" is always invalid`)
      cxt.fail()
      return
    }
    if (alwaysValidSchema(it, schema)) {
      let cond = _`${len} >= ${min}`
      if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`
      cxt.pass(cond)
      return
    }

    it.items = true
    const valid = gen.name("valid")
    if (max === undefined && min === 1) {
      validateItems(valid, () => gen.if(valid, () => gen.break()))
    } else if (min === 0) {
      gen.let(valid, true)
      if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)
    } else {
      gen.let(valid, false)
      validateItemsWithCount()
    }
    cxt.result(valid, () => cxt.reset())

    function validateItemsWithCount(): void {
      const schValid = gen.name("_valid")
      const count = gen.let("count", 0)
      validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))
    }

    function validateItems(_valid: Name, block: () => void): void {
      gen.forRange("i", 0, len, (i) => {
        cxt.subschema(
          {
            keyword: "contains",
            dataProp: i,
            dataPropType: Type.Num,
            compositeRule: true,
          },
          _valid
        )
        block()
      })
    }

    function checkLimits(count: Name): void {
      gen.code(_`${count}++`)
      if (max === undefined) {
        gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())
      } else {
        gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())
        if (min === 1) gen.assign(valid, true)
        else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))
      }
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  SchemaMap,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code"

export type PropertyDependencies = {[K in string]?: string[]}

export interface DependenciesErrorParams {
  property: string
  missingProperty: string
  depsCount: number
  deps: string // TODO change to string[]
}

type SchemaDependencies = SchemaMap

export type DependenciesError = ErrorObject<
  "dependencies",
  DependenciesErrorParams,
  {[K in string]?: string[] | AnySchema}
>

export const error: KeywordErrorDefinition = {
  message: ({params: {property, depsCount, deps}}) => {
    const property_ies = depsCount === 1 ? "property" : "properties"
    return str`must have ${property_ies} ${deps} when property ${property} is present`
  },
  params: ({params: {property, depsCount, deps, missingProperty}}) =>
    _`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
}

const def: CodeKeywordDefinition = {
  keyword: "dependencies",
  type: "object",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    const [propDeps, schDeps] = splitDependencies(cxt)
    validatePropertyDeps(cxt, propDeps)
    validateSchemaDeps(cxt, schDeps)
  },
}

function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {
  const propertyDeps: PropertyDependencies = {}
  const schemaDeps: SchemaDependencies = {}
  for (const key in schema) {
    if (key === "__proto__") continue
    const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps
    deps[key] = schema[key]
  }
  return [propertyDeps, schemaDeps]
}

export function validatePropertyDeps(
  cxt: KeywordCxt,
  propertyDeps: {[K in string]?: string[]} = cxt.schema
): void {
  const {gen, data, it} = cxt
  if (Object.keys(propertyDeps).length === 0) return
  const missing = gen.let("missing")
  for (const prop in propertyDeps) {
    const deps = propertyDeps[prop] as string[]
    if (deps.length === 0) continue
    const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)
    cxt.setParams({
      property: prop,
      depsCount: deps.length,
      deps: deps.join(", "),
    })
    if (it.allErrors) {
      gen.if(hasProperty, () => {
        for (const depProp of deps) {
          checkReportMissingProp(cxt, depProp)
        }
      })
    } else {
      gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)
      reportMissingProp(cxt, missing)
      gen.else()
    }
  }
}

export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {
  const {gen, data, keyword, it} = cxt
  const valid = gen.name("valid")
  for (const prop in schemaDeps) {
    if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue
    gen.if(
      propertyInData(gen, data, prop, it.opts.ownProperties),
      () => {
        const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)
        cxt.mergeValidEvaluated(schCxt, valid)
      },
      () => gen.var(valid, true) // TODO var
    )
    cxt.ok(valid)
  }
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateSchemaDeps} from "./dependencies"

const def: CodeKeywordDefinition = {
  keyword: "dependentSchemas",
  type: "object",
  schemaType: "object",
  code: (cxt) => validateSchemaDeps(cxt),
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {SchemaObjCxt} from "../../compile"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode} from "../../compile/util"

export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params}) => str`must match "${params.ifClause}" schema`,
  params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "if",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, parentSchema, it} = cxt
    if (parentSchema.then === undefined && parentSchema.else === undefined) {
      checkStrictMode(it, '"if" without "then" and "else" is ignored')
    }
    const hasThen = hasSchema(it, "then")
    const hasElse = hasSchema(it, "else")
    if (!hasThen && !hasElse) return

    const valid = gen.let("valid", true)
    const schValid = gen.name("_valid")
    validateIf()
    cxt.reset()

    if (hasThen && hasElse) {
      const ifClause = gen.let("ifClause")
      cxt.setParams({ifClause})
      gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause))
    } else if (hasThen) {
      gen.if(schValid, validateClause("then"))
    } else {
      gen.if(not(schValid), validateClause("else"))
    }

    cxt.pass(valid, () => cxt.error(true))

    function validateIf(): void {
      const schCxt = cxt.subschema(
        {
          keyword: "if",
          compositeRule: true,
          createErrors: false,
          allErrors: false,
        },
        schValid
      )
      cxt.mergeEvaluated(schCxt)
    }

    function validateClause(keyword: string, ifClause?: Name): () => void {
      return () => {
        const schCxt = cxt.subschema({keyword}, schValid)
        gen.assign(valid, schValid)
        cxt.mergeValidEvaluated(schCxt, valid)
        if (ifClause) gen.assign(ifClause, _`${keyword}`)
        else cxt.setParams({ifClause: keyword})
      }
    }
  },
}

function hasSchema(it: SchemaObjCxt, keyword: string): boolean {
  const schema = it.schema[keyword]
  return schema !== undefined && !alwaysValidSchema(it, schema)
}

export default def
import type {ErrorNoParams, Vocabulary} from "../../types"
import additionalItems, {AdditionalItemsError} from "./additionalItems"
import prefixItems from "./prefixItems"
import items from "./items"
import items2020, {ItemsError} from "./items2020"
import contains, {ContainsError} from "./contains"
import dependencies, {DependenciesError} from "./dependencies"
import propertyNames, {PropertyNamesError} from "./propertyNames"
import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties"
import properties from "./properties"
import patternProperties from "./patternProperties"
import notKeyword, {NotKeywordError} from "./not"
import anyOf, {AnyOfError} from "./anyOf"
import oneOf, {OneOfError} from "./oneOf"
import allOf from "./allOf"
import ifKeyword, {IfKeywordError} from "./if"
import thenElse from "./thenElse"

export default function getApplicator(draft2020 = false): Vocabulary {
  const applicator = [
    // any
    notKeyword,
    anyOf,
    oneOf,
    allOf,
    ifKeyword,
    thenElse,
    // object
    propertyNames,
    additionalProperties,
    dependencies,
    properties,
    patternProperties,
  ]
  // array
  if (draft2020) applicator.push(prefixItems, items2020)
  else applicator.push(additionalItems, items)
  applicator.push(contains)
  return applicator
}

export type ApplicatorKeywordError =
  | ErrorNoParams<"false schema">
  | AdditionalItemsError
  | ItemsError
  | ContainsError
  | AdditionalPropertiesError
  | DependenciesError
  | IfKeywordError
  | AnyOfError
  | OneOfError
  | NotKeywordError
  | PropertyNamesError
import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_} from "../../compile/codegen"
import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util"
import {validateArray} from "../code"

const def: CodeKeywordDefinition = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "array", "boolean"],
  before: "uniqueItems",
  code(cxt: KeywordCxt) {
    const {schema, it} = cxt
    if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema)
    it.items = true
    if (alwaysValidSchema(it, schema)) return
    cxt.ok(validateArray(cxt))
  },
}

export function validateTuple(
  cxt: KeywordCxt,
  extraItems: string,
  schArr: AnySchema[] = cxt.schema
): void {
  const {gen, parentSchema, data, keyword, it} = cxt
  checkStrictTuple(parentSchema)
  if (it.opts.unevaluated && schArr.length && it.items !== true) {
    it.items = mergeEvaluated.items(gen, schArr.length, it.items)
  }
  const valid = gen.name("valid")
  const len = gen.const("len", _`${data}.length`)
  schArr.forEach((sch: AnySchema, i: number) => {
    if (alwaysValidSchema(it, sch)) return
    gen.if(_`${len} > ${i}`, () =>
      cxt.subschema(
        {
          keyword,
          schemaProp: i,
          dataProp: i,
        },
        valid
      )
    )
    cxt.ok(valid)
  })

  function checkStrictTuple(sch: AnySchemaObject): void {
    const {opts, errSchemaPath} = it
    const l = schArr.length
    const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)
    if (opts.strictTuples && !fullTuple) {
      const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`
      checkStrictMode(it, msg, opts.strictTuples)
    }
  }
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {validateArray} from "../code"
import {validateAdditionalItems} from "./additionalItems"

export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  error,
  code(cxt: KeywordCxt) {
    const {schema, parentSchema, it} = cxt
    const {prefixItems} = parentSchema
    it.items = true
    if (alwaysValidSchema(it, schema)) return
    if (prefixItems) validateAdditionalItems(cxt, prefixItems)
    else cxt.ok(validateArray(cxt))
  },
}

export default def
import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"

export type NotKeywordError = ErrorNoParams<"not", AnySchema>

const def: CodeKeywordDefinition = {
  keyword: "not",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  code(cxt: KeywordCxt) {
    const {gen, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) {
      cxt.fail()
      return
    }

    const valid = gen.name("valid")
    cxt.subschema(
      {
        keyword: "not",
        compositeRule: true,
        createErrors: false,
        allErrors: false,
      },
      valid
    )

    cxt.failResult(
      valid,
      () => cxt.reset(),
      () => cxt.error()
    )
  },
  error: {message: "must NOT be valid"},
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, Name} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {SchemaCxt} from "../../compile"

export type OneOfError = ErrorObject<
  "oneOf",
  {passingSchemas: [number, number] | null},
  AnySchema[]
>

const error: KeywordErrorDefinition = {
  message: "must match exactly one schema in oneOf",
  params: ({params}) => _`{passingSchemas: ${params.passing}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "oneOf",
  schemaType: "array",
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, it} = cxt
    /* istanbul ignore if */
    if (!Array.isArray(schema)) throw new Error("ajv implementation error")
    if (it.opts.discriminator && parentSchema.discriminator) return
    const schArr: AnySchema[] = schema
    const valid = gen.let("valid", false)
    const passing = gen.let("passing", null)
    const schValid = gen.name("_valid")
    cxt.setParams({passing})
    // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas

    gen.block(validateOneOf)

    cxt.result(
      valid,
      () => cxt.reset(),
      () => cxt.error(true)
    )

    function validateOneOf(): void {
      schArr.forEach((sch: AnySchema, i: number) => {
        let schCxt: SchemaCxt | undefined
        if (alwaysValidSchema(it, sch)) {
          gen.var(schValid, true)
        } else {
          schCxt = cxt.subschema(
            {
              keyword: "oneOf",
              schemaProp: i,
              compositeRule: true,
            },
            schValid
          )
        }

        if (i > 0) {
          gen
            .if(_`${schValid} && ${valid}`)
            .assign(valid, false)
            .assign(passing, _`[${passing}, ${i}]`)
            .else()
        }

        gen.if(schValid, () => {
          gen.assign(valid, true)
          gen.assign(passing, i)
          if (schCxt) cxt.mergeEvaluated(schCxt, Name)
        })
      })
    }
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {allSchemaProperties, usePattern} from "../code"
import {_, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode} from "../../compile/util"
import {evaluatedPropsToName, Type} from "../../compile/util"
import {AnySchema} from "../../types"

const def: CodeKeywordDefinition = {
  keyword: "patternProperties",
  type: "object",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    const {gen, schema, data, parentSchema, it} = cxt
    const {opts} = it
    const patterns = allSchemaProperties(schema)
    const alwaysValidPatterns = patterns.filter((p) =>
      alwaysValidSchema(it, schema[p] as AnySchema)
    )

    if (
      patterns.length === 0 ||
      (alwaysValidPatterns.length === patterns.length &&
        (!it.opts.unevaluated || it.props === true))
    ) {
      return
    }

    const checkProperties =
      opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties
    const valid = gen.name("valid")
    if (it.props !== true && !(it.props instanceof Name)) {
      it.props = evaluatedPropsToName(gen, it.props)
    }
    const {props} = it
    validatePatternProperties()

    function validatePatternProperties(): void {
      for (const pat of patterns) {
        if (checkProperties) checkMatchingProperties(pat)
        if (it.allErrors) {
          validateProperties(pat)
        } else {
          gen.var(valid, true) // TODO var
          validateProperties(pat)
          gen.if(valid)
        }
      }
    }

    function checkMatchingProperties(pat: string): void {
      for (const prop in checkProperties) {
        if (new RegExp(pat).test(prop)) {
          checkStrictMode(
            it,
            `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`
          )
        }
      }
    }

    function validateProperties(pat: string): void {
      gen.forIn("key", data, (key) => {
        gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {
          const alwaysValid = alwaysValidPatterns.includes(pat)
          if (!alwaysValid) {
            cxt.subschema(
              {
                keyword: "patternProperties",
                schemaProp: pat,
                dataProp: key,
                dataPropType: Type.Str,
              },
              valid
            )
          }

          if (it.opts.unevaluated && props !== true) {
            gen.assign(_`${props}[${key}]`, true)
          } else if (!alwaysValid && !it.allErrors) {
            // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
            // or if all properties were evaluated (props === true)
            gen.if(not(valid), () => gen.break())
          }
        })
      })
    }
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateTuple} from "./items"

const def: CodeKeywordDefinition = {
  keyword: "prefixItems",
  type: "array",
  schemaType: ["array"],
  before: "uniqueItems",
  code: (cxt) => validateTuple(cxt, "items"),
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {KeywordCxt} from "../../compile/validate"
import {propertyInData, allSchemaProperties} from "../code"
import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util"
import apDef from "./additionalProperties"

const def: CodeKeywordDefinition = {
  keyword: "properties",
  type: "object",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, data, it} = cxt
    if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
      apDef.code(new KeywordCxt(it, apDef, "additionalProperties"))
    }
    const allProps = allSchemaProperties(schema)
    for (const prop of allProps) {
      it.definedProperties.add(prop)
    }
    if (it.opts.unevaluated && allProps.length && it.props !== true) {
      it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)
    }
    const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))
    if (properties.length === 0) return
    const valid = gen.name("valid")

    for (const prop of properties) {
      if (hasDefault(prop)) {
        applyPropertySchema(prop)
      } else {
        gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))
        applyPropertySchema(prop)
        if (!it.allErrors) gen.else().var(valid, true)
        gen.endIf()
      }
      cxt.it.definedProperties.add(prop)
      cxt.ok(valid)
    }

    function hasDefault(prop: string): boolean | undefined {
      return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined
    }

    function applyPropertySchema(prop: string): void {
      cxt.subschema(
        {
          keyword: "properties",
          schemaProp: prop,
          dataProp: prop,
        },
        valid
      )
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, not} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"

export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema>

const error: KeywordErrorDefinition = {
  message: "property name must be valid",
  params: ({params}) => _`{propertyName: ${params.propertyName}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "propertyNames",
  type: "object",
  schemaType: ["object", "boolean"],
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, data, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const valid = gen.name("valid")

    gen.forIn("key", data, (key) => {
      cxt.setParams({propertyName: key})
      cxt.subschema(
        {
          keyword: "propertyNames",
          data: key,
          dataTypes: ["string"],
          propertyName: key,
          compositeRule: true,
        },
        valid
      )
      gen.if(not(valid), () => {
        cxt.error(true)
        if (!it.allErrors) gen.break()
      })
    })

    cxt.ok(valid)
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: ["then", "else"],
  schemaType: ["object", "boolean"],
  code({keyword, parentSchema, it}: KeywordCxt) {
    if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`)
  },
}

export default def
import {URIComponent} from "fast-uri"
import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen"
import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile"
import type {JSONType} from "../compile/rules"
import type {KeywordCxt} from "../compile/validate"
import type Ajv from "../core"

interface _SchemaObject {
  id?: string
  $id?: string
  $schema?: string
  [x: string]: any // TODO
}

export interface SchemaObject extends _SchemaObject {
  id?: string
  $id?: string
  $schema?: string
  $async?: false
  [x: string]: any // TODO
}

export interface AsyncSchema extends _SchemaObject {
  $async: true
}

export type AnySchemaObject = SchemaObject | AsyncSchema

export type Schema = SchemaObject | boolean

export type AnySchema = Schema | AsyncSchema

export type SchemaMap = {[Key in string]?: AnySchema}

export interface SourceCode {
  validateName: ValueScopeName
  validateCode: string
  scopeValues: ScopeValueSets
  evaluated?: Code
}

export interface DataValidationCxt<T extends string | number = string | number> {
  instancePath: string
  parentData: {[K in T]: any} // object or array
  parentDataProperty: T // string or number
  rootData: Record<string, any> | any[]
  dynamicAnchors: {[Ref in string]?: ValidateFunction}
}

export interface ValidateFunction<T = unknown> {
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T
  errors?: null | ErrorObject[]
  evaluated?: Evaluated
  schema: AnySchema
  schemaEnv: SchemaEnv
  source?: SourceCode
}

export interface JTDParser<T = unknown> {
  (json: string): T | undefined
  message?: string
  position?: number
}

export type EvaluatedProperties = {[K in string]?: true} | true

export type EvaluatedItems = number | true

export interface Evaluated {
  // determined at compile time if staticProps/Items is true
  props?: EvaluatedProperties
  items?: EvaluatedItems
  // whether props/items determined at compile time
  dynamicProps: boolean
  dynamicItems: boolean
}

export interface AsyncValidateFunction<T = unknown> extends ValidateFunction<T> {
  (...args: Parameters<ValidateFunction<T>>): Promise<T>
  $async: true
}

export type AnyValidateFunction<T = any> = ValidateFunction<T> | AsyncValidateFunction<T>

export interface ErrorObject<K extends string = string, P = Record<string, any>, S = unknown> {
  keyword: K
  instancePath: string
  schemaPath: string
  params: P
  // Added to validation errors of "propertyNames" keyword schema
  propertyName?: string
  // Excluded if option `messages` set to false.
  message?: string
  // These are added with the `verbose` option.
  schema?: S
  parentSchema?: AnySchemaObject
  data?: unknown
}

export type ErrorNoParams<K extends string, S = unknown> = ErrorObject<K, Record<string, never>, S>

interface _KeywordDef {
  keyword: string | string[]
  type?: JSONType | JSONType[] // data types that keyword applies to
  schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema
  allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema
  $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference)
  implements?: string[] // other schema keywords that this keyword implements
  before?: string // keyword should be executed before this keyword (should be applicable to the same type)
  post?: boolean // keyword should be executed after other keywords without post flag
  metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable
  validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed
  dependencies?: string[] // keywords that must be present in the same schema
  error?: KeywordErrorDefinition
  $dataError?: KeywordErrorDefinition
}

export interface CodeKeywordDefinition extends _KeywordDef {
  code: (cxt: KeywordCxt, ruleType?: string) => void
  trackErrors?: boolean
}

export type MacroKeywordFunc = (
  schema: any,
  parentSchema: AnySchemaObject,
  it: SchemaCxt
) => AnySchema

export type CompileKeywordFunc = (
  schema: any,
  parentSchema: AnySchemaObject,
  it: SchemaObjCxt
) => DataValidateFunction

export interface DataValidateFunction {
  (...args: Parameters<ValidateFunction>): boolean | Promise<any>
  errors?: Partial<ErrorObject>[]
}

export interface SchemaValidateFunction {
  (
    schema: any,
    data: any,
    parentSchema?: AnySchemaObject,
    dataCxt?: DataValidationCxt
  ): boolean | Promise<any>
  errors?: Partial<ErrorObject>[]
}

export interface FuncKeywordDefinition extends _KeywordDef {
  validate?: SchemaValidateFunction | DataValidateFunction
  compile?: CompileKeywordFunc
  // schema: false makes validate not to expect schema (DataValidateFunction)
  schema?: boolean // requires "validate"
  modifying?: boolean
  async?: boolean
  valid?: boolean
  errors?: boolean | "full"
}

export interface MacroKeywordDefinition extends FuncKeywordDefinition {
  macro: MacroKeywordFunc
}

export type KeywordDefinition =
  | CodeKeywordDefinition
  | FuncKeywordDefinition
  | MacroKeywordDefinition

export type AddedKeywordDefinition = KeywordDefinition & {
  type: JSONType[]
  schemaType: JSONType[]
}

export interface KeywordErrorDefinition {
  message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
  params?: Code | ((cxt: KeywordErrorCxt) => Code)
}

export type Vocabulary = (KeywordDefinition | string)[]

export interface KeywordErrorCxt {
  gen: CodeGen
  keyword: string
  data: Name
  $data?: string | false
  schema: any // TODO
  parentSchema?: AnySchemaObject
  schemaCode: Code | number | boolean
  schemaValue: Code | number | boolean
  schemaType?: JSONType[]
  errsCount?: Name
  params: KeywordCxtParams
  it: SchemaCxt
}

export type KeywordCxtParams = {[P in string]?: Code | string | number}

export type FormatValidator<T extends string | number> = (data: T) => boolean

export type FormatCompare<T extends string | number> = (data1: T, data2: T) => number | undefined

export type AsyncFormatValidator<T extends string | number> = (data: T) => Promise<boolean>

export interface FormatDefinition<T extends string | number> {
  type?: T extends string ? "string" | undefined : "number"
  validate: FormatValidator<T> | (T extends string ? string | RegExp : never)
  async?: false | undefined
  compare?: FormatCompare<T>
}

export interface AsyncFormatDefinition<T extends string | number> {
  type?: T extends string ? "string" | undefined : "number"
  validate: AsyncFormatValidator<T>
  async: true
  compare?: FormatCompare<T>
}

export type AddedFormat =
  | true
  | RegExp
  | FormatValidator<string>
  | FormatDefinition<string>
  | FormatDefinition<number>
  | AsyncFormatDefinition<string>
  | AsyncFormatDefinition<number>

export type Format = AddedFormat | string

export interface RegExpEngine {
  (pattern: string, u: string): RegExpLike
  code: string
}

export interface RegExpLike {
  test: (s: string) => boolean
}

export interface UriResolver {
  parse(uri: string): URIComponent
  resolve(base: string, path: string): string
  serialize(component: URIComponent): string
}
/* eslint-disable @typescript-eslint/no-empty-interface */
type StrictNullChecksWrapper<Name extends string, Type> = undefined extends null
  ? `strictNullChecks must be true in tsconfig to use ${Name}`
  : Type

type UnionToIntersection<U> = (U extends any ? (_: U) => void : never) extends (_: infer I) => void
  ? I
  : never

export type SomeJSONSchema = UncheckedJSONSchemaType<Known, true>

type UncheckedPartialSchema<T> = Partial<UncheckedJSONSchemaType<T, true>>

export type PartialSchema<T> = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema<T>>

type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
  ? T | undefined
  : T

interface NumberKeywords {
  minimum?: number
  maximum?: number
  exclusiveMinimum?: number
  exclusiveMaximum?: number
  multipleOf?: number
  format?: string
}

interface StringKeywords {
  minLength?: number
  maxLength?: number
  pattern?: string
  format?: string
}

type UncheckedJSONSchemaType<T, IsPartial extends boolean> = (
  | // these two unions allow arbitrary unions of types
  {
      anyOf: readonly UncheckedJSONSchemaType<T, IsPartial>[]
    }
  | {
      oneOf: readonly UncheckedJSONSchemaType<T, IsPartial>[]
    }
  // this union allows for { type: (primitive)[] } style schemas
  | ({
      type: readonly (T extends number
        ? JSONType<"number" | "integer", IsPartial>
        : T extends string
        ? JSONType<"string", IsPartial>
        : T extends boolean
        ? JSONType<"boolean", IsPartial>
        : never)[]
    } & UnionToIntersection<
      T extends number
        ? NumberKeywords
        : T extends string
        ? StringKeywords
        : T extends boolean
        ? // eslint-disable-next-line @typescript-eslint/ban-types
          {}
        : never
    >)
  // this covers "normal" types; it's last so typescript looks to it first for errors
  | ((T extends number
      ? {
          type: JSONType<"number" | "integer", IsPartial>
        } & NumberKeywords
      : T extends string
      ? {
          type: JSONType<"string", IsPartial>
        } & StringKeywords
      : T extends boolean
      ? {
          type: JSONType<"boolean", IsPartial>
        }
      : T extends readonly [any, ...any[]]
      ? {
          // JSON AnySchema for tuple
          type: JSONType<"array", IsPartial>
          items: {
            readonly [K in keyof T]-?: UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>
          } & {length: T["length"]}
          minItems: T["length"]
        } & ({maxItems: T["length"]} | {additionalItems: false})
      : T extends readonly any[]
      ? {
          type: JSONType<"array", IsPartial>
          items: UncheckedJSONSchemaType<T[0], false>
          contains?: UncheckedPartialSchema<T[0]>
          minItems?: number
          maxItems?: number
          minContains?: number
          maxContains?: number
          uniqueItems?: true
          additionalItems?: never
        }
      : T extends Record<string, any>
      ? {
          // JSON AnySchema for records and dictionaries
          // "required" is not optional because it is often forgotten
          // "properties" are optional for more concise dictionary schemas
          // "patternProperties" and can be only used with interfaces that have string index
          type: JSONType<"object", IsPartial>
          additionalProperties?: boolean | UncheckedJSONSchemaType<T[string], false>
          unevaluatedProperties?: boolean | UncheckedJSONSchemaType<T[string], false>
          properties?: IsPartial extends true
            ? Partial<UncheckedPropertiesSchema<T>>
            : UncheckedPropertiesSchema<T>
          patternProperties?: Record<string, UncheckedJSONSchemaType<T[string], false>>
          propertyNames?: Omit<UncheckedJSONSchemaType<string, false>, "type"> & {type?: "string"}
          dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema<T>}
          dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]}
          dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema<T>}
          minProperties?: number
          maxProperties?: number
        } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties
          ? {required: readonly (keyof T)[]}
          : [UncheckedRequiredMembers<T>] extends [never]
          ? {required?: readonly UncheckedRequiredMembers<T>[]}
          : {required: readonly UncheckedRequiredMembers<T>[]})
      : T extends null
      ? {
          type: JSONType<"null", IsPartial>
          nullable: true
        }
      : never) & {
      allOf?: readonly UncheckedPartialSchema<T>[]
      anyOf?: readonly UncheckedPartialSchema<T>[]
      oneOf?: readonly UncheckedPartialSchema<T>[]
      if?: UncheckedPartialSchema<T>
      then?: UncheckedPartialSchema<T>
      else?: UncheckedPartialSchema<T>
      not?: UncheckedPartialSchema<T>
    })
) & {
  [keyword: string]: any
  $id?: string
  $ref?: string
  $defs?: Record<string, UncheckedJSONSchemaType<Known, true>>
  definitions?: Record<string, UncheckedJSONSchemaType<Known, true>>
}

export type JSONSchemaType<T> = StrictNullChecksWrapper<
  "JSONSchemaType",
  UncheckedJSONSchemaType<T, false>
>

type Known =
  | {[key: string]: Known}
  | [Known, ...Known[]]
  | Known[]
  | number
  | string
  | boolean
  | null

type UncheckedPropertiesSchema<T> = {
  [K in keyof T]-?: (UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>) | {$ref: string}
}

export type PropertiesSchema<T> = StrictNullChecksWrapper<
  "PropertiesSchema",
  UncheckedPropertiesSchema<T>
>

type UncheckedRequiredMembers<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T]

export type RequiredMembers<T> = StrictNullChecksWrapper<
  "RequiredMembers",
  UncheckedRequiredMembers<T>
>

type Nullable<T> = undefined extends T
  ? {
      nullable: true
      const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const
      enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass
      default?: T | null
    }
  : {
      nullable?: false
      const?: T
      enum?: readonly T[]
      default?: T
    }
/** numeric strings */
type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"

/** string strings */
type StringType = "string" | "timestamp"

/** Generic JTD Schema without inference of the represented type */
export type SomeJTDSchemaType = (
  | // ref
  {ref: string}
  // primitives
  | {type: NumberType | StringType | "boolean"}
  // enum
  | {enum: string[]}
  // elements
  | {elements: SomeJTDSchemaType}
  // values
  | {values: SomeJTDSchemaType}
  // properties
  | {
      properties: Record<string, SomeJTDSchemaType>
      optionalProperties?: Record<string, SomeJTDSchemaType>
      additionalProperties?: boolean
    }
  | {
      properties?: Record<string, SomeJTDSchemaType>
      optionalProperties: Record<string, SomeJTDSchemaType>
      additionalProperties?: boolean
    }
  // discriminator
  | {discriminator: string; mapping: Record<string, SomeJTDSchemaType>}
  // empty
  // NOTE see the end of
  // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492
  // eslint-disable-next-line @typescript-eslint/ban-types
  | {}
) & {
  nullable?: boolean
  metadata?: Record<string, unknown>
  definitions?: Record<string, SomeJTDSchemaType>
}

/** required keys of an object, not undefined */
type RequiredKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T]

/** optional or undifined-able keys of an object */
type OptionalKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? K : never
}[keyof T]

/** type is true if T is a union type */
type IsUnion_<T, U extends T = T> = false extends (
  T extends unknown ? ([U] extends [T] ? false : true) : never
)
  ? false
  : true
type IsUnion<T> = IsUnion_<T>

/** type is true if T is identically E */
type TypeEquality<T, E> = [T] extends [E] ? ([E] extends [T] ? true : false) : false

/** type is true if T or null is identically E or null*/
type NullTypeEquality<T, E> = TypeEquality<T | null, E | null>

/** gets only the string literals of a type or null if a type isn't a string literal */
type EnumString<T> = [T] extends [never]
  ? null
  : T extends string
  ? string extends T
    ? null
    : T
  : null

/** true if type is a union of string literals */
type IsEnum<T> = null extends EnumString<T> ? false : true

/** true only if all types are array types (not tuples) */
// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays
// have an index at every number
type IsElements<T> = false extends IsUnion<T>
  ? [T] extends [readonly unknown[]]
    ? undefined extends T[0.5]
      ? false
      : true
    : false
  : false

/** true if the the type is a values type */
type IsValues<T> = false extends IsUnion<T> ? TypeEquality<keyof T, string> : false

/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */
type IsRecord<T, Union extends boolean> = Union extends IsUnion<T>
  ? null extends EnumString<keyof T>
    ? false
    : true
  : false

/** true if type represents an empty record */
type IsEmptyRecord<T> = [T] extends [Record<string, never>]
  ? [T] extends [never]
    ? false
    : true
  : false

/** actual schema */
export type JTDSchemaType<T, D extends Record<string, unknown> = Record<string, never>> = (
  | // refs - where null wasn't specified, must match exactly
  (null extends EnumString<keyof D>
      ? never
      :
          | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false})
          // nulled refs - if ref is nullable and nullable is specified, then it can
          // match either null or non-null definitions
          | (null extends T
              ? {
                  [K in keyof D]: [Exclude<T, null>] extends [Exclude<D[K], null>]
                    ? {ref: K}
                    : never
                }[keyof D] & {nullable: true}
              : never))
  // empty - empty schemas also treat nullable differently in that it's now fully ignored
  | (unknown extends T ? {nullable?: boolean} : never)
  // all other types // numbers - only accepts the type number
  | ((true extends NullTypeEquality<T, number>
      ? {type: NumberType}
      : // booleans - accepts the type boolean
      true extends NullTypeEquality<T, boolean>
      ? {type: "boolean"}
      : // strings - only accepts the type string
      true extends NullTypeEquality<T, string>
      ? {type: StringType}
      : // strings - only accepts the type Date
      true extends NullTypeEquality<T, Date>
      ? {type: "timestamp"}
      : // enums - only accepts union of string literals
      // TODO we can't actually check that everything in the union was specified
      true extends IsEnum<Exclude<T, null>>
      ? {enum: EnumString<Exclude<T, null>>[]}
      : // arrays - only accepts arrays, could be array of unions to be resolved later
      true extends IsElements<Exclude<T, null>>
      ? T extends readonly (infer E)[]
        ? {
            elements: JTDSchemaType<E, D>
          }
        : never
      : // empty properties
      true extends IsEmptyRecord<Exclude<T, null>>
      ?
          | {properties: Record<string, never>; optionalProperties?: Record<string, never>}
          | {optionalProperties: Record<string, never>}
      : // values
      true extends IsValues<Exclude<T, null>>
      ? T extends Record<string, infer V>
        ? {
            values: JTDSchemaType<V, D>
          }
        : never
      : // properties
      true extends IsRecord<Exclude<T, null>, false>
      ? ([RequiredKeys<Exclude<T, null>>] extends [never]
          ? {
              properties?: Record<string, never>
            }
          : {
              properties: {[K in RequiredKeys<T>]: JTDSchemaType<T[K], D>}
            }) &
          ([OptionalKeys<Exclude<T, null>>] extends [never]
            ? {
                optionalProperties?: Record<string, never>
              }
            : {
                optionalProperties: {
                  [K in OptionalKeys<T>]: JTDSchemaType<Exclude<T[K], undefined>, D>
                }
              }) & {
            additionalProperties?: boolean
          }
      : // discriminator
      true extends IsRecord<Exclude<T, null>, true>
      ? {
          [K in keyof Exclude<T, null>]-?: Exclude<T, null>[K] extends string
            ? {
                discriminator: K
                mapping: {
                  // TODO currently allows descriminator to be present in schema
                  [M in Exclude<T, null>[K]]: JTDSchemaType<
                    Omit<T extends Record<K, M> ? T : never, K>,
                    D
                  >
                }
              }
            : never
        }[keyof Exclude<T, null>]
      : never) &
      (null extends T
        ? {
            nullable: true
          }
        : {nullable?: false}))
) & {
  // extra properties
  metadata?: Record<string, unknown>
  // TODO these should only be allowed at the top level
  definitions?: {[K in keyof D]: JTDSchemaType<D[K], D>}
}

type JTDDataDef<S, D extends Record<string, unknown>> =
  | // ref
  (S extends {ref: string}
      ? D extends {[K in S["ref"]]: infer V}
        ? JTDDataDef<V, D>
        : never
      : // type
      S extends {type: NumberType}
      ? number
      : S extends {type: "boolean"}
      ? boolean
      : S extends {type: "string"}
      ? string
      : S extends {type: "timestamp"}
      ? string | Date
      : // enum
      S extends {enum: readonly (infer E)[]}
      ? string extends E
        ? never
        : [E] extends [string]
        ? E
        : never
      : // elements
      S extends {elements: infer E}
      ? JTDDataDef<E, D>[]
      : // properties
      S extends {
          properties: Record<string, unknown>
          optionalProperties?: Record<string, unknown>
          additionalProperties?: boolean
        }
      ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>} & {
          -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<
            S["optionalProperties"][K],
            D
          >
        } & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown)
      : S extends {
          properties?: Record<string, unknown>
          optionalProperties: Record<string, unknown>
          additionalProperties?: boolean
        }
      ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>} & {
          -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<
            S["optionalProperties"][K],
            D
          >
        } & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown)
      : // values
      S extends {values: infer V}
      ? Record<string, JTDDataDef<V, D>>
      : // discriminator
      S extends {discriminator: infer M; mapping: Record<string, unknown>}
      ? [M] extends [string]
        ? {
            [K in keyof S["mapping"]]: JTDDataDef<S["mapping"][K], D> & {[KM in M]: K}
          }[keyof S["mapping"]]
        : never
      : // empty
        unknown)
  | (S extends {nullable: true} ? null : never)

export type JTDDataType<S> = S extends {definitions: Record<string, unknown>}
  ? JTDDataDef<S, S["definitions"]>
  : JTDDataDef<S, Record<string, never>>
import type AjvCore from "../core"
import type {AnyValidateFunction, SourceCode} from "../types"
import type {SchemaEnv} from "../compile"
import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope"
import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code"

function standaloneCode(
  ajv: AjvCore,
  refsOrFunc?: {[K in string]?: string} | AnyValidateFunction
): string {
  if (!ajv.opts.code.source) {
    throw new Error("moduleCode: ajv instance must have code.source option")
  }
  const {_n} = ajv.scope.opts
  return typeof refsOrFunc == "function"
    ? funcExportCode(refsOrFunc.source)
    : refsOrFunc !== undefined
    ? multiExportsCode<string>(refsOrFunc, getValidate)
    : multiExportsCode<SchemaEnv>(ajv.schemas, (sch) =>
        sch.meta ? undefined : ajv.compile(sch.schema)
      )

  function getValidate(id: string): AnyValidateFunction {
    const v = ajv.getSchema(id)
    if (!v) throw new Error(`moduleCode: no schema with id ${id}`)
    return v
  }

  function funcExportCode(source?: SourceCode): string {
    const usedValues: UsedScopeValues = {}
    const n = source?.validateName
    const vCode = validateCode(usedValues, source)
    if (ajv.opts.code.esm) {
      // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
      return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`
    }
    return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`
  }

  function multiExportsCode<T extends SchemaEnv | string>(
    schemas: {[K in string]?: T},
    getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined
  ): string {
    const usedValues: UsedScopeValues = {}
    let code = _`"use strict";`
    for (const name in schemas) {
      const v = getValidateFunc(schemas[name] as T)
      if (v) {
        const vCode = validateCode(usedValues, v.source)
        const exportSyntax = ajv.opts.code.esm
          ? _`export const ${getEsmExportName(name)}`
          : _`exports${getProperty(name)}`
        code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}`
      }
    }
    return `${code}`
  }

  function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code {
    if (!s) throw new Error('moduleCode: function does not have "source" property')
    if (usedState(s.validateName) === UsedValueState.Completed) return nil
    setUsedState(s.validateName, UsedValueState.Started)

    const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode)
    const code = new _Code(`${scopeCode}${_n}${s.validateCode}`)
    return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code

    function refValidateCode(n: ValueScopeName): Code | undefined {
      const vRef = n.value?.ref
      if (n.prefix === "validate" && typeof vRef == "function") {
        const v = vRef as AnyValidateFunction
        return validateCode(usedValues, v.source)
      } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
        const {validate, validateName} = vRef as SchemaEnv
        if (!validateName) throw new Error("ajv internal error")
        const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
        const wrapper = _`${def} ${n} = {validate: ${validateName}};`
        if (usedState(validateName) === UsedValueState.Started) return wrapper
        const vCode = validateCode(usedValues, validate?.source)
        return _`${wrapper}${_n}${vCode}`
      }
      return undefined
    }

    function usedState(name: ValueScopeName): UsedValueState | undefined {
      return usedValues[name.prefix]?.get(name)
    }

    function setUsedState(name: ValueScopeName, state: UsedValueState): void {
      const {prefix} = name
      const names = (usedValues[prefix] = usedValues[prefix] || new Map())
      names.set(name, state)
    }
  }
}

module.exports = exports = standaloneCode
Object.defineProperty(exports, "__esModule", {value: true})

export default standaloneCode
import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core"
import standaloneCode from "."
import * as requireFromString from "require-from-string"

export default class AjvPack {
  errors?: ErrorObject[] | null // errors from the last validation
  constructor(readonly ajv: Ajv) {}

  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown> {
    return Ajv.prototype.validate.call(this, schemaKeyRef, data)
  }

  compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T> {
    return this.getStandalone(this.ajv.compile<T>(schema, meta))
  }

  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    const v = this.ajv.getSchema<T>(keyRef)
    if (!v) return undefined
    return this.getStandalone(v)
  }

  private getStandalone<T = unknown>(v: AnyValidateFunction<T>): AnyValidateFunction<T> {
    return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction<T>
  }

  addSchema(...args: Parameters<typeof Ajv.prototype.addSchema>): AjvPack {
    this.ajv.addSchema.call(this.ajv, ...args)
    return this
  }

  addKeyword(...args: Parameters<typeof Ajv.prototype.addKeyword>): AjvPack {
    this.ajv.addKeyword.call(this.ajv, ...args)
    return this
  }
}
// https://github.com/ajv-validator/ajv/issues/889
import * as equal from "fast-deep-equal"

type Equal = typeof equal & {code: string}
;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default'

export default equal as Equal
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/

export function parseJson(s: string, pos: number): unknown {
  let endPos: number | undefined
  parseJson.message = undefined
  let matches: RegExpExecArray | null
  if (pos) s = s.slice(pos)
  try {
    parseJson.position = pos + s.length
    return JSON.parse(s)
  } catch (e) {
    matches = rxParseJson.exec((e as Error).message)
    if (!matches) {
      parseJson.message = "unexpected end"
      return undefined
    }
    endPos = +matches[1]
    const c = s[endPos]
    s = s.slice(0, endPos)
    parseJson.position = pos + endPos
    try {
      return JSON.parse(s)
    } catch (e1) {
      parseJson.message = `unexpected token ${c}`
      return undefined
    }
  }
}

parseJson.message = undefined as string | undefined
parseJson.position = 0 as number
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'

export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined {
  let numStr = ""
  let c: string
  parseJsonNumber.message = undefined
  if (s[pos] === "-") {
    numStr += "-"
    pos++
  }
  if (s[pos] === "0") {
    numStr += "0"
    pos++
  } else {
    if (!parseDigits(maxDigits)) {
      errorMessage()
      return undefined
    }
  }
  if (maxDigits) {
    parseJsonNumber.position = pos
    return +numStr
  }
  if (s[pos] === ".") {
    numStr += "."
    pos++
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  if (((c = s[pos]), c === "e" || c === "E")) {
    numStr += "e"
    pos++
    if (((c = s[pos]), c === "+" || c === "-")) {
      numStr += c
      pos++
    }
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  parseJsonNumber.position = pos
  return +numStr

  function parseDigits(maxLen?: number): boolean {
    let digit = false
    while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
      digit = true
      numStr += c
      pos++
    }
    return digit
  }

  function errorMessage(): void {
    parseJsonNumber.position = pos
    parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"
  }
}

parseJsonNumber.message = undefined as string | undefined
parseJsonNumber.position = 0 as number
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'

const escapedChars: {[X in string]?: string} = {
  b: "\b",
  f: "\f",
  n: "\n",
  r: "\r",
  t: "\t",
  '"': '"',
  "/": "/",
  "\\": "\\",
}

const CODE_A: number = "a".charCodeAt(0)
const CODE_0: number = "0".charCodeAt(0)

export function parseJsonString(s: string, pos: number): string | undefined {
  let str = ""
  let c: string | undefined
  parseJsonString.message = undefined
  // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
  while (true) {
    c = s[pos++]
    if (c === '"') break
    if (c === "\\") {
      c = s[pos]
      if (c in escapedChars) {
        str += escapedChars[c]
        pos++
      } else if (c === "u") {
        pos++
        let count = 4
        let code = 0
        while (count--) {
          code <<= 4
          c = s[pos]
          // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
          if (c === undefined) {
            errorMessage("unexpected end")
            return undefined
          }
          c = c.toLowerCase()
          if (c >= "a" && c <= "f") {
            code += c.charCodeAt(0) - CODE_A + 10
          } else if (c >= "0" && c <= "9") {
            code += c.charCodeAt(0) - CODE_0
          } else {
            errorMessage(`unexpected token ${c}`)
            return undefined
          }
          pos++
        }
        str += String.fromCharCode(code)
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    } else if (c === undefined) {
      errorMessage("unexpected end")
      return undefined
    } else {
      if (c.charCodeAt(0) >= 0x20) {
        str += c
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
    }
  }
  parseJsonString.position = pos
  return str

  function errorMessage(msg: string): void {
    parseJsonString.position = pos
    parseJsonString.message = msg
  }
}

parseJsonString.message = undefined as string | undefined
parseJsonString.position = 0 as number
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'
const rxEscapable =
  // eslint-disable-next-line no-control-regex, no-misleading-character-class
  /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g

const escaped: {[K in string]?: string} = {
  "\b": "\\b",
  "\t": "\\t",
  "\n": "\\n",
  "\f": "\\f",
  "\r": "\\r",
  '"': '\\"',
  "\\": "\\\\",
}

export default function quote(s: string): string {
  rxEscapable.lastIndex = 0
  return (
    '"' +
    (rxEscapable.test(s)
      ? s.replace(rxEscapable, (a) => {
          const c = escaped[a]
          return typeof c === "string"
            ? c
            : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
        })
      : s) +
    '"'
  )
}

quote.code = 'require("ajv/dist/runtime/quote").default'
import * as re2 from "re2"

type Re2 = typeof re2 & {code: string}
;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default'

export default re2 as Re2
const DT_SEPARATOR = /t|\s/i
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

export default function validTimestamp(str: string, allowDate: boolean): boolean {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  const dt: string[] = str.split(DT_SEPARATOR)
  return (
    (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
    (allowDate && dt.length === 1 && validDate(dt[0]))
  )
}

function validDate(str: string): boolean {
  const matches: string[] | null = DATE.exec(str)
  if (!matches) return false
  const y: number = +matches[1]
  const m: number = +matches[2]
  const d: number = +matches[3]
  return (
    m >= 1 &&
    m <= 12 &&
    d >= 1 &&
    (d <= DAYS[m] ||
      // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
      (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))
  )
}

function validTime(str: string): boolean {
  const matches: string[] | null = TIME.exec(str)
  if (!matches) return false
  const hr: number = +matches[1]
  const min: number = +matches[2]
  const sec: number = +matches[3]
  const tzH: number = +(matches[4] || 0)
  const tzM: number = +(matches[5] || 0)
  return (
    (hr <= 23 && min <= 59 && sec <= 59) ||
    // leap second
    (hr - tzH === 23 && min - tzM === 59 && sec === 60)
  )
}

validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
export default function ucs2length(str: string): number {
  const len = str.length
  let length = 0
  let pos = 0
  let value: number
  while (pos < len) {
    length++
    value = str.charCodeAt(pos++)
    if (value >= 0xd800 && value <= 0xdbff && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos)
      if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate
    }
  }
  return length
}

ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'
import * as uri from "fast-uri"

type URI = typeof uri & {code: string}
;(uri as URI).code = 'require("ajv/dist/runtime/uri").default'

export default uri as URI
import type {ErrorObject} from "../types"

export default class ValidationError extends Error {
  readonly errors: Partial<ErrorObject>[]
  readonly ajv: true
  readonly validation: true

  constructor(errors: Partial<ErrorObject>[]) {
    super("validation failed")
    this.errors = errors
    this.ajv = this.validation = true
  }
}
{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
import {SchemaObject} from "../types"

type MetaSchema = (root: boolean) => SchemaObject

const shared: MetaSchema = (root) => {
  const sch: SchemaObject = {
    nullable: {type: "boolean"},
    metadata: {
      optionalProperties: {
        union: {elements: {ref: "schema"}},
      },
      additionalProperties: true,
    },
  }
  if (root) sch.definitions = {values: {ref: "schema"}}
  return sch
}

const emptyForm: MetaSchema = (root) => ({
  optionalProperties: shared(root),
})

const refForm: MetaSchema = (root) => ({
  properties: {
    ref: {type: "string"},
  },
  optionalProperties: shared(root),
})

const typeForm: MetaSchema = (root) => ({
  properties: {
    type: {
      enum: [
        "boolean",
        "timestamp",
        "string",
        "float32",
        "float64",
        "int8",
        "uint8",
        "int16",
        "uint16",
        "int32",
        "uint32",
      ],
    },
  },
  optionalProperties: shared(root),
})

const enumForm: MetaSchema = (root) => ({
  properties: {
    enum: {elements: {type: "string"}},
  },
  optionalProperties: shared(root),
})

const elementsForm: MetaSchema = (root) => ({
  properties: {
    elements: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const propertiesForm: MetaSchema = (root) => ({
  properties: {
    properties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    optionalProperties: {values: {ref: "schema"}},
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const optionalPropertiesForm: MetaSchema = (root) => ({
  properties: {
    optionalProperties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const discriminatorForm: MetaSchema = (root) => ({
  properties: {
    discriminator: {type: "string"},
    mapping: {
      values: {
        metadata: {
          union: [propertiesForm(false), optionalPropertiesForm(false)],
        },
      },
    },
  },
  optionalProperties: shared(root),
})

const valuesForm: MetaSchema = (root) => ({
  properties: {
    values: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const schema: MetaSchema = (root) => ({
  metadata: {
    union: [
      emptyForm,
      refForm,
      typeForm,
      enumForm,
      elementsForm,
      propertiesForm,
      optionalPropertiesForm,
      discriminatorForm,
      valuesForm,
    ].map((s) => s(root)),
  },
})

const jtdMetaSchema: SchemaObject = {
  definitions: {
    schema: schema(false),
  },
  ...schema(true),
}

export default jtdMetaSchema
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as unevaluated from "./meta/unevaluated.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format-annotation.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    unevaluated,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types"
import type {SchemaCxt} from "./index"
import {CodeGen, _, str, strConcat, Code, Name} from "./codegen"
import {SafeExpr} from "./codegen/code"
import {getErrorPath, Type} from "./util"
import N from "./names"

export const keywordError: KeywordErrorDefinition = {
  message: ({keyword}) => str`must pass "${keyword}" keyword validation`,
}

export const keyword$DataError: KeywordErrorDefinition = {
  message: ({keyword, schemaType}) =>
    schemaType
      ? str`"${keyword}" keyword must be ${schemaType} ($data)`
      : str`"${keyword}" keyword is invalid ($data)`,
}

export interface ErrorPaths {
  instancePath?: Code
  schemaPath?: string
  parentSchema?: boolean
}

export function reportError(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition = keywordError,
  errorPaths?: ErrorPaths,
  overrideAllErrors?: boolean
): void {
  const {it} = cxt
  const {gen, compositeRule, allErrors} = it
  const errObj = errorObjectCode(cxt, error, errorPaths)
  if (overrideAllErrors ?? (compositeRule || allErrors)) {
    addError(gen, errObj)
  } else {
    returnErrors(it, _`[${errObj}]`)
  }
}

export function reportExtraError(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition = keywordError,
  errorPaths?: ErrorPaths
): void {
  const {it} = cxt
  const {gen, compositeRule, allErrors} = it
  const errObj = errorObjectCode(cxt, error, errorPaths)
  addError(gen, errObj)
  if (!(compositeRule || allErrors)) {
    returnErrors(it, N.vErrors)
  }
}

export function resetErrorsCount(gen: CodeGen, errsCount: Name): void {
  gen.assign(N.errors, errsCount)
  gen.if(_`${N.vErrors} !== null`, () =>
    gen.if(
      errsCount,
      () => gen.assign(_`${N.vErrors}.length`, errsCount),
      () => gen.assign(N.vErrors, null)
    )
  )
}

export function extendErrors({
  gen,
  keyword,
  schemaValue,
  data,
  errsCount,
  it,
}: KeywordErrorCxt): void {
  /* istanbul ignore if */
  if (errsCount === undefined) throw new Error("ajv implementation error")
  const err = gen.name("err")
  gen.forRange("i", errsCount, N.errors, (i) => {
    gen.const(err, _`${N.vErrors}[${i}]`)
    gen.if(_`${err}.instancePath === undefined`, () =>
      gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))
    )
    gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)
    if (it.opts.verbose) {
      gen.assign(_`${err}.schema`, schemaValue)
      gen.assign(_`${err}.data`, data)
    }
  })
}

function addError(gen: CodeGen, errObj: Code): void {
  const err = gen.const("err", errObj)
  gen.if(
    _`${N.vErrors} === null`,
    () => gen.assign(N.vErrors, _`[${err}]`),
    _`${N.vErrors}.push(${err})`
  )
  gen.code(_`${N.errors}++`)
}

function returnErrors(it: SchemaCxt, errs: Code): void {
  const {gen, validateName, schemaEnv} = it
  if (schemaEnv.$async) {
    gen.throw(_`new ${it.ValidationError as Name}(${errs})`)
  } else {
    gen.assign(_`${validateName}.errors`, errs)
    gen.return(false)
  }
}

const E = {
  keyword: new Name("keyword"),
  schemaPath: new Name("schemaPath"), // also used in JTD errors
  params: new Name("params"),
  propertyName: new Name("propertyName"),
  message: new Name("message"),
  schema: new Name("schema"),
  parentSchema: new Name("parentSchema"),
}

function errorObjectCode(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition,
  errorPaths?: ErrorPaths
): Code {
  const {createErrors} = cxt.it
  if (createErrors === false) return _`{}`
  return errorObject(cxt, error, errorPaths)
}

function errorObject(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition,
  errorPaths: ErrorPaths = {}
): Code {
  const {gen, it} = cxt
  const keyValues: [Name, SafeExpr | string][] = [
    errorInstancePath(it, errorPaths),
    errorSchemaPath(cxt, errorPaths),
  ]
  extraErrorProps(cxt, error, keyValues)
  return gen.object(...keyValues)
}

function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {
  const instPath = instancePath
    ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`
    : errorPath
  return [N.instancePath, strConcat(N.instancePath, instPath)]
}

function errorSchemaPath(
  {keyword, it: {errSchemaPath}}: KeywordErrorCxt,
  {schemaPath, parentSchema}: ErrorPaths
): [Name, string | Code] {
  let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`
  if (schemaPath) {
    schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`
  }
  return [E.schemaPath, schPath]
}

function extraErrorProps(
  cxt: KeywordErrorCxt,
  {params, message}: KeywordErrorDefinition,
  keyValues: [Name, SafeExpr | string][]
): void {
  const {keyword, data, schemaValue, it} = cxt
  const {opts, propertyName, topSchemaRef, schemaPath} = it
  keyValues.push(
    [E.keyword, keyword],
    [E.params, typeof params == "function" ? params(cxt) : params || _`{}`]
  )
  if (opts.messages) {
    keyValues.push([E.message, typeof message == "function" ? message(cxt) : message])
  }
  if (opts.verbose) {
    keyValues.push(
      [E.schema, schemaValue],
      [E.parentSchema, _`${topSchemaRef}${schemaPath}`],
      [N.data, data]
    )
  }
  if (propertyName) keyValues.push([E.propertyName, propertyName])
}
import type {
  AnySchema,
  AnySchemaObject,
  AnyValidateFunction,
  AsyncValidateFunction,
  EvaluatedProperties,
  EvaluatedItems,
} from "../types"
import type Ajv from "../core"
import type {InstanceOptions} from "../core"
import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
import ValidationError from "../runtime/validation_error"
import N from "./names"
import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
import {schemaHasRulesButRef, unescapeFragment} from "./util"
import {validateFunctionCode} from "./validate"
import {URIComponent} from "fast-uri"
import {JSONType} from "./rules"

export type SchemaRefs = {
  [Ref in string]?: SchemaEnv | AnySchema
}

export interface SchemaCxt {
  readonly gen: CodeGen
  readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
  readonly data: Name // Name with reference to the current part of data instance
  readonly parentData: Name // should be used in keywords modifying data
  readonly parentDataProperty: Code | number // should be used in keywords modifying data
  readonly dataNames: Name[]
  readonly dataPathArr: (Code | number)[]
  readonly dataLevel: number // the level of the currently validated data,
  // it can be used to access both the property names and the data on all levels from the top.
  dataTypes: JSONType[] // data types applied to the current part of data instance
  definedProperties: Set<string> // set of properties to keep track of for required checks
  readonly topSchemaRef: Code
  readonly validateName: Name
  evaluated?: Name
  readonly ValidationError?: Name
  readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
  readonly schemaEnv: SchemaEnv
  readonly rootId: string
  baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
  readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
  readonly errSchemaPath: string // this is actual string, should not be changed to Code
  readonly errorPath: Code
  readonly propertyName?: Name
  readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
  // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
  // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
  // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
  props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
  items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
  jtdDiscriminator?: string
  jtdMetadata?: boolean
  readonly createErrors?: boolean
  readonly opts: InstanceOptions // Ajv instance option.
  readonly self: Ajv // current Ajv instance
}

export interface SchemaObjCxt extends SchemaCxt {
  readonly schema: AnySchemaObject
}
interface SchemaEnvArgs {
  readonly schema: AnySchema
  readonly schemaId?: "$id" | "id"
  readonly root?: SchemaEnv
  readonly baseId?: string
  readonly schemaPath?: string
  readonly localRefs?: LocalRefs
  readonly meta?: boolean
}

export class SchemaEnv implements SchemaEnvArgs {
  readonly schema: AnySchema
  readonly schemaId?: "$id" | "id"
  readonly root: SchemaEnv
  baseId: string // TODO possibly, it should be readonly
  schemaPath?: string
  localRefs?: LocalRefs
  readonly meta?: boolean
  readonly $async?: boolean // true if the current schema is asynchronous.
  readonly refs: SchemaRefs = {}
  readonly dynamicAnchors: {[Ref in string]?: true} = {}
  validate?: AnyValidateFunction
  validateName?: ValueScopeName
  serialize?: (data: unknown) => string
  serializeName?: ValueScopeName
  parse?: (data: string) => unknown
  parseName?: ValueScopeName

  constructor(env: SchemaEnvArgs) {
    let schema: AnySchemaObject | undefined
    if (typeof env.schema == "object") schema = env.schema
    this.schema = env.schema
    this.schemaId = env.schemaId
    this.root = env.root || this
    this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
    this.schemaPath = env.schemaPath
    this.localRefs = env.localRefs
    this.meta = env.meta
    this.$async = schema?.$async
    this.refs = {}
  }
}

// let codeSize = 0
// let nodeCount = 0

// Compiles schema in SchemaEnv
export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
  // TODO refactor - remove compilations
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  let _ValidationError
  if (sch.$async) {
    _ValidationError = gen.scopeValue("Error", {
      ref: ValidationError,
      code: _`require("ajv/dist/runtime/validation_error").default`,
    })
  }

  const validateName = gen.scopeName("validate")
  sch.validateName = validateName

  const schemaCxt: SchemaCxt = {
    gen,
    allErrors: this.opts.allErrors,
    data: N.data,
    parentData: N.parentData,
    parentDataProperty: N.parentDataProperty,
    dataNames: [N.data],
    dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
    dataLevel: 0,
    dataTypes: [],
    definedProperties: new Set<string>(),
    topSchemaRef: gen.scopeValue(
      "schema",
      this.opts.code.source === true
        ? {ref: sch.schema, code: stringify(sch.schema)}
        : {ref: sch.schema}
    ),
    validateName,
    ValidationError: _ValidationError,
    schema: sch.schema,
    schemaEnv: sch,
    rootId,
    baseId: sch.baseId || rootId,
    schemaPath: nil,
    errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
    errorPath: _`""`,
    opts: this.opts,
    self: this,
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    validateFunctionCode(schemaCxt)
    gen.optimize(this.opts.code.optimize)
    // gen.optimize(1)
    const validateCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
    // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
    if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
    // console.log("\n\n\n *** \n", sourceCode)
    const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
    const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
    this.scope.value(validateName, {ref: validate})

    validate.errors = null
    validate.schema = sch.schema
    validate.schemaEnv = sch
    if (sch.$async) (validate as AsyncValidateFunction).$async = true
    if (this.opts.code.source === true) {
      validate.source = {validateName, validateCode, scopeValues: gen._values}
    }
    if (this.opts.unevaluated) {
      const {props, items} = schemaCxt
      validate.evaluated = {
        props: props instanceof Name ? undefined : props,
        items: items instanceof Name ? undefined : items,
        dynamicProps: props instanceof Name,
        dynamicItems: items instanceof Name,
      }
      if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
    }
    sch.validate = validate
    return sch
  } catch (e) {
    delete sch.validate
    delete sch.validateName
    if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
    // console.log("\n\n\n *** \n", sourceCode, this.opts)
    throw e
  } finally {
    this._compilations.delete(sch)
  }
}

export function resolveRef(
  this: Ajv,
  root: SchemaEnv,
  baseId: string,
  ref: string
): AnySchema | SchemaEnv | undefined {
  ref = resolveUrl(this.opts.uriResolver, baseId, ref)
  const schOrFunc = root.refs[ref]
  if (schOrFunc) return schOrFunc

  let _sch = resolve.call(this, root, ref)
  if (_sch === undefined) {
    const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
    const {schemaId} = this.opts
    if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})
  }

  if (_sch === undefined) return
  return (root.refs[ref] = inlineOrCompile.call(this, _sch))
}

function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
  if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
  return sch.validate ? sch : compileSchema.call(this, sch)
}

// Index of schema compilation in the currently compiled list
export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
  for (const sch of this._compilations) {
    if (sameSchemaEnv(sch, schEnv)) return sch
  }
}

function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
}

// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(
  this: Ajv,
  root: SchemaEnv, // information about the root schema for the current schema
  ref: string // reference to resolve
): SchemaEnv | undefined {
  let sch
  while (typeof (sch = this.refs[ref]) == "string") ref = sch
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
}

// Resolve schema, its root and baseId
export function resolveSchema(
  this: Ajv,
  root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
  ref: string // reference to resolve
): SchemaEnv | undefined {
  const p = this.opts.uriResolver.parse(ref)
  const refPath = _getFullPath(this.opts.uriResolver, p)
  let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
  // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
  if (Object.keys(root.schema).length > 0 && refPath === baseId) {
    return getJsonPointer.call(this, p, root)
  }

  const id = normalizeId(refPath)
  const schOrRef = this.refs[id] || this.schemas[id]
  if (typeof schOrRef == "string") {
    const sch = resolveSchema.call(this, root, schOrRef)
    if (typeof sch?.schema !== "object") return
    return getJsonPointer.call(this, p, sch)
  }

  if (typeof schOrRef?.schema !== "object") return
  if (!schOrRef.validate) compileSchema.call(this, schOrRef)
  if (id === normalizeId(ref)) {
    const {schema} = schOrRef
    const {schemaId} = this.opts
    const schId = schema[schemaId]
    if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
    return new SchemaEnv({schema, schemaId, root, baseId})
  }
  return getJsonPointer.call(this, p, schOrRef)
}

const PREVENT_SCOPE_CHANGE = new Set([
  "properties",
  "patternProperties",
  "enum",
  "dependencies",
  "definitions",
])

function getJsonPointer(
  this: Ajv,
  parsedRef: URIComponent,
  {baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
  if (parsedRef.fragment?.[0] !== "/") return
  for (const part of parsedRef.fragment.slice(1).split("/")) {
    if (typeof schema === "boolean") return
    const partSchema = schema[unescapeFragment(part)]
    if (partSchema === undefined) return
    schema = partSchema
    // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
    const schId = typeof schema === "object" && schema[this.opts.schemaId]
    if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
      baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
    }
  }
  let env: SchemaEnv | undefined
  if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
    const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
    env = resolveSchema.call(this, root, $ref)
  }
  // even though resolution failed we need to return SchemaEnv to throw exception
  // so that compileAsync loads missing schema.
  const {schemaId} = this.opts
  env = env || new SchemaEnv({schema, schemaId, root, baseId})
  if (env.schema !== env.root.schema) return env
  return undefined
}
import {Name} from "./codegen"

const names = {
  // validation function arguments
  data: new Name("data"), // data passed to validation function
  // args passed from referencing schema
  valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
  instancePath: new Name("instancePath"),
  parentData: new Name("parentData"),
  parentDataProperty: new Name("parentDataProperty"),
  rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function
  dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
  // function scoped variables
  vErrors: new Name("vErrors"), // null or array of validation errors
  errors: new Name("errors"), // counter of validation errors
  this: new Name("this"),
  // "globals"
  self: new Name("self"),
  scope: new Name("scope"),
  // JTD serialize/parse name for JSON string and position
  json: new Name("json"),
  jsonPos: new Name("jsonPos"),
  jsonLen: new Name("jsonLen"),
  jsonPart: new Name("jsonPart"),
}

export default names
import {resolveUrl, normalizeId, getFullPath} from "./resolve"
import type {UriResolver} from "../types"

export default class MissingRefError extends Error {
  readonly missingRef: string
  readonly missingSchema: string

  constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {
    super(msg || `can't resolve reference ${ref} from id ${baseId}`)
    this.missingRef = resolveUrl(resolver, baseId, ref)
    this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))
  }
}
import type {AnySchema, AnySchemaObject, UriResolver} from "../types"
import type Ajv from "../ajv"
import type {URIComponent} from "fast-uri"
import {eachItem} from "./util"
import * as equal from "fast-deep-equal"
import * as traverse from "json-schema-traverse"

// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution
export type LocalRefs = {[Ref in string]?: AnySchemaObject}

// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
  "type",
  "format",
  "pattern",
  "maxLength",
  "minLength",
  "maxProperties",
  "minProperties",
  "maxItems",
  "minItems",
  "maximum",
  "minimum",
  "uniqueItems",
  "multipleOf",
  "required",
  "enum",
  "const",
])

export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {
  if (typeof schema == "boolean") return true
  if (limit === true) return !hasRef(schema)
  if (!limit) return false
  return countKeys(schema) <= limit
}

const REF_KEYWORDS = new Set([
  "$ref",
  "$recursiveRef",
  "$recursiveAnchor",
  "$dynamicRef",
  "$dynamicAnchor",
])

function hasRef(schema: AnySchemaObject): boolean {
  for (const key in schema) {
    if (REF_KEYWORDS.has(key)) return true
    const sch = schema[key]
    if (Array.isArray(sch) && sch.some(hasRef)) return true
    if (typeof sch == "object" && hasRef(sch)) return true
  }
  return false
}

function countKeys(schema: AnySchemaObject): number {
  let count = 0
  for (const key in schema) {
    if (key === "$ref") return Infinity
    count++
    if (SIMPLE_INLINED.has(key)) continue
    if (typeof schema[key] == "object") {
      eachItem(schema[key], (sch) => (count += countKeys(sch)))
    }
    if (count === Infinity) return Infinity
  }
  return count
}

export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string {
  if (normalize !== false) id = normalizeId(id)
  const p = resolver.parse(id)
  return _getFullPath(resolver, p)
}

export function _getFullPath(resolver: UriResolver, p: URIComponent): string {
  const serialized = resolver.serialize(p)
  return serialized.split("#")[0] + "#"
}

const TRAILING_SLASH_HASH = /#\/?$/
export function normalizeId(id: string | undefined): string {
  return id ? id.replace(TRAILING_SLASH_HASH, "") : ""
}

export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {
  id = normalizeId(id)
  return resolver.resolve(baseId, id)
}

const ANCHOR = /^[a-z_][-a-z0-9._]*$/i

export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
  if (typeof schema == "boolean") return {}
  const {schemaId, uriResolver} = this.opts
  const schId = normalizeId(schema[schemaId] || baseId)
  const baseIds: {[JsonPtr in string]?: string} = {"": schId}
  const pathPrefix = getFullPath(uriResolver, schId, false)
  const localRefs: LocalRefs = {}
  const schemaRefs: Set<string> = new Set()

  traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
    if (parentJsonPtr === undefined) return
    const fullPath = pathPrefix + jsonPtr
    let innerBaseId = baseIds[parentJsonPtr]
    if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId])
    addAnchor.call(this, sch.$anchor)
    addAnchor.call(this, sch.$dynamicAnchor)
    baseIds[jsonPtr] = innerBaseId

    function addRef(this: Ajv, ref: string): string {
      // eslint-disable-next-line @typescript-eslint/unbound-method
      const _resolve = this.opts.uriResolver.resolve
      ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)
      if (schemaRefs.has(ref)) throw ambiguos(ref)
      schemaRefs.add(ref)
      let schOrRef = this.refs[ref]
      if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
      if (typeof schOrRef == "object") {
        checkAmbiguosRef(sch, schOrRef.schema, ref)
      } else if (ref !== normalizeId(fullPath)) {
        if (ref[0] === "#") {
          checkAmbiguosRef(sch, localRefs[ref], ref)
          localRefs[ref] = sch
        } else {
          this.refs[ref] = fullPath
        }
      }
      return ref
    }

    function addAnchor(this: Ajv, anchor: unknown): void {
      if (typeof anchor == "string") {
        if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
        addRef.call(this, `#${anchor}`)
      }
    }
  })

  return localRefs

  function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
    if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
  }

  function ambiguos(ref: string): Error {
    return new Error(`reference "${ref}" resolves to more than one schema`)
  }
}
import type {AddedKeywordDefinition} from "../types"

const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const

export type JSONType = (typeof _jsonTypes)[number]

const jsonTypes: Set<string> = new Set(_jsonTypes)

export function isJSONType(x: unknown): x is JSONType {
  return typeof x == "string" && jsonTypes.has(x)
}

type ValidationTypes = {
  [K in JSONType]: boolean | RuleGroup | undefined
}

export interface ValidationRules {
  rules: RuleGroup[]
  post: RuleGroup
  all: {[Key in string]?: boolean | Rule} // rules that have to be validated
  keywords: {[Key in string]?: boolean} // all known keywords (superset of "all")
  types: ValidationTypes
}

export interface RuleGroup {
  type?: JSONType
  rules: Rule[]
}

// This interface wraps KeywordDefinition because definition can have multiple keywords
export interface Rule {
  keyword: string
  definition: AddedKeywordDefinition
}

export function getRules(): ValidationRules {
  const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = {
    number: {type: "number", rules: []},
    string: {type: "string", rules: []},
    array: {type: "array", rules: []},
    object: {type: "object", rules: []},
  }
  return {
    types: {...groups, integer: true, boolean: true, null: true},
    rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],
    post: {rules: []},
    all: {},
    keywords: {},
  }
}
import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"

// TODO refactor to use Set
export function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {
  const hash: {[K in T]?: true} = {}
  for (const item of arr) hash[item] = true
  return hash
}

export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {
  if (typeof schema == "boolean") return schema
  if (Object.keys(schema).length === 0) return true
  checkUnknownRules(it, schema)
  return !schemaHasRules(schema, it.self.RULES.all)
}

export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
  const {opts, self} = it
  if (!opts.strictSchema) return
  if (typeof schema === "boolean") return
  const rules = self.RULES.keywords
  for (const key in schema) {
    if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
  }
}

export function schemaHasRules(
  schema: AnySchema,
  rules: {[Key in string]?: boolean | Rule}
): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (rules[key]) return true
  return false
}

export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true
  return false
}

export function schemaRefOrVal(
  {topSchemaRef, schemaPath}: SchemaObjCxt,
  schema: unknown,
  keyword: string,
  $data?: string | false
): Code | number | boolean {
  if (!$data) {
    if (typeof schema == "number" || typeof schema == "boolean") return schema
    if (typeof schema == "string") return _`${schema}`
  }
  return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`
}

export function unescapeFragment(str: string): string {
  return unescapeJsonPointer(decodeURIComponent(str))
}

export function escapeFragment(str: string | number): string {
  return encodeURIComponent(escapeJsonPointer(str))
}

export function escapeJsonPointer(str: string | number): string {
  if (typeof str == "number") return `${str}`
  return str.replace(/~/g, "~0").replace(/\//g, "~1")
}

export function unescapeJsonPointer(str: string): string {
  return str.replace(/~1/g, "/").replace(/~0/g, "~")
}

export function eachItem<T>(xs: T | T[], f: (x: T) => void): void {
  if (Array.isArray(xs)) {
    for (const x of xs) f(x)
  } else {
    f(xs)
  }
}

type SomeEvaluated = EvaluatedProperties | EvaluatedItems

type MergeEvaluatedFunc<T extends SomeEvaluated> = (
  gen: CodeGen,
  from: Name | T,
  to: Name | Exclude<T, true> | undefined,
  toName?: typeof Name
) => Name | T

interface MakeMergeFuncArgs<T extends SomeEvaluated> {
  mergeNames: (gen: CodeGen, from: Name, to: Name) => void
  mergeToName: (gen: CodeGen, from: T, to: Name) => void
  mergeValues: (from: T, to: Exclude<T, true>) => T
  resultToName: (gen: CodeGen, res?: T) => Name
}

function makeMergeEvaluated<T extends SomeEvaluated>({
  mergeNames,
  mergeToName,
  mergeValues,
  resultToName,
}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {
  return (gen, from, to, toName) => {
    const res =
      to === undefined
        ? from
        : to instanceof Name
        ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
        : from instanceof Name
        ? (mergeToName(gen, to, from), from)
        : mergeValues(from, to)
    return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res
  }
}

interface MergeEvaluated {
  props: MergeEvaluatedFunc<EvaluatedProperties>
  items: MergeEvaluatedFunc<EvaluatedItems>
}

export const mergeEvaluated: MergeEvaluated = {
  props: makeMergeEvaluated({
    mergeNames: (gen, from, to) =>
      gen.if(_`${to} !== true && ${from} !== undefined`, () => {
        gen.if(
          _`${from} === true`,
          () => gen.assign(to, true),
          () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)
        )
      }),
    mergeToName: (gen, from, to) =>
      gen.if(_`${to} !== true`, () => {
        if (from === true) {
          gen.assign(to, true)
        } else {
          gen.assign(to, _`${to} || {}`)
          setEvaluated(gen, to, from)
        }
      }),
    mergeValues: (from, to) => (from === true ? true : {...from, ...to}),
    resultToName: evaluatedPropsToName,
  }),
  items: makeMergeEvaluated({
    mergeNames: (gen, from, to) =>
      gen.if(_`${to} !== true && ${from} !== undefined`, () =>
        gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)
      ),
    mergeToName: (gen, from, to) =>
      gen.if(_`${to} !== true`, () =>
        gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)
      ),
    mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
    resultToName: (gen, items) => gen.var("items", items),
  }),
}

export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {
  if (ps === true) return gen.var("props", true)
  const props = gen.var("props", _`{}`)
  if (ps !== undefined) setEvaluated(gen, props, ps)
  return props
}

export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
  Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
}

const snippets: {[S in string]?: _Code} = {}

export function useFunc(gen: CodeGen, f: {code: string}): Name {
  return gen.scopeValue("func", {
    ref: f,
    code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),
  })
}

export enum Type {
  Num,
  Str,
}

export function getErrorPath(
  dataProp: Name | string | number,
  dataPropType?: Type,
  jsPropertySyntax?: boolean
): Code | string {
  // let path
  if (dataProp instanceof Name) {
    const isNumber = dataPropType === Type.Num
    return jsPropertySyntax
      ? isNumber
        ? _`"[" + ${dataProp} + "]"`
        : _`"['" + ${dataProp} + "']"`
      : isNumber
      ? _`"/" + ${dataProp}`
      : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer
  }
  return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp)
}

export function checkStrictMode(
  it: SchemaCxt,
  msg: string,
  mode: boolean | "log" = it.opts.strictSchema
): void {
  if (!mode) return
  msg = `strict mode: ${msg}`
  if (mode === true) throw new Error(msg)
  it.self.logger.warn(msg)
}
import type {AnySchemaObject} from "../../types"
import type {SchemaObjCxt} from ".."
import type {JSONType, RuleGroup, Rule} from "../rules"

export function schemaHasRulesForType(
  {schema, self}: SchemaObjCxt,
  type: JSONType
): boolean | undefined {
  const group = self.RULES.types[type]
  return group && group !== true && shouldUseGroup(schema, group)
}

export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
  return group.rules.some((rule) => shouldUseRule(schema, rule))
}

export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
  return (
    schema[rule.keyword] !== undefined ||
    rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
  )
}
import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types"
import type {SchemaCxt} from ".."
import {reportError} from "../errors"
import {_, Name} from "../codegen"
import N from "../names"

const boolError: KeywordErrorDefinition = {
  message: "boolean schema is false",
}

export function topBoolOrEmptySchema(it: SchemaCxt): void {
  const {gen, schema, validateName} = it
  if (schema === false) {
    falseSchemaError(it, false)
  } else if (typeof schema == "object" && schema.$async === true) {
    gen.return(N.data)
  } else {
    gen.assign(_`${validateName}.errors`, null)
    gen.return(true)
  }
}

export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {
  const {gen, schema} = it
  if (schema === false) {
    gen.var(valid, false) // TODO var
    falseSchemaError(it)
  } else {
    gen.var(valid, true) // TODO var
  }
}

function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {
  const {gen, data} = it
  // TODO maybe some other interface should be used for non-keyword validation errors...
  const cxt: KeywordErrorCxt = {
    gen,
    keyword: "false schema",
    data,
    schema: false,
    schemaCode: false,
    schemaValue: false,
    params: {},
    it,
  }
  reportError(cxt, boolError, undefined, overrideAllErrors)
}
import type {
  KeywordErrorDefinition,
  KeywordErrorCxt,
  ErrorObject,
  AnySchemaObject,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {isJSONType, JSONType} from "../rules"
import {schemaHasRulesForType} from "./applicability"
import {reportError} from "../errors"
import {_, nil, and, not, operators, Code, Name} from "../codegen"
import {toHash, schemaRefOrVal} from "../util"

export enum DataType {
  Correct,
  Wrong,
}

export function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
  const types = getJSONTypes(schema.type)
  const hasNull = types.includes("null")
  if (hasNull) {
    if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
  } else {
    if (!types.length && schema.nullable !== undefined) {
      throw new Error('"nullable" cannot be used without "type"')
    }
    if (schema.nullable === true) types.push("null")
  }
  return types
}

// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
export function getJSONTypes(ts: unknown | unknown[]): JSONType[] {
  const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []
  if (types.every(isJSONType)) return types
  throw new Error("type must be JSONType or JSONType[]: " + types.join(","))
}

export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
  const {gen, data, opts} = it
  const coerceTo = coerceToTypes(types, opts.coerceTypes)
  const checkTypes =
    types.length > 0 &&
    !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
  if (checkTypes) {
    const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
    gen.if(wrongType, () => {
      if (coerceTo.length) coerceData(it, types, coerceTo)
      else reportTypeError(it)
    })
  }
  return checkTypes
}

const COERCIBLE: Set<JSONType> = new Set(["string", "number", "integer", "boolean", "null"])
function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] {
  return coerceTypes
    ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
    : []
}

function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
  const {gen, data, opts} = it
  const dataType = gen.let("dataType", _`typeof ${data}`)
  const coerced = gen.let("coerced", _`undefined`)
  if (opts.coerceTypes === "array") {
    gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
      gen
        .assign(data, _`${data}[0]`)
        .assign(dataType, _`typeof ${data}`)
        .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
    )
  }
  gen.if(_`${coerced} !== undefined`)
  for (const t of coerceTo) {
    if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
      coerceSpecificType(t)
    }
  }
  gen.else()
  reportTypeError(it)
  gen.endIf()

  gen.if(_`${coerced} !== undefined`, () => {
    gen.assign(data, coerced)
    assignParentData(it, coerced)
  })

  function coerceSpecificType(t: string): void {
    switch (t) {
      case "string":
        gen
          .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
          .assign(coerced, _`"" + ${data}`)
          .elseIf(_`${data} === null`)
          .assign(coerced, _`""`)
        return
      case "number":
        gen
          .elseIf(
            _`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`
          )
          .assign(coerced, _`+${data}`)
        return
      case "integer":
        gen
          .elseIf(
            _`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
          )
          .assign(coerced, _`+${data}`)
        return
      case "boolean":
        gen
          .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
          .assign(coerced, false)
          .elseIf(_`${data} === "true" || ${data} === 1`)
          .assign(coerced, true)
        return
      case "null":
        gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
        gen.assign(coerced, null)
        return

      case "array":
        gen
          .elseIf(
            _`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`
          )
          .assign(coerced, _`[${data}]`)
    }
  }
}

function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
  // TODO use gen.property
  gen.if(_`${parentData} !== undefined`, () =>
    gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
  )
}

export function checkDataType(
  dataType: JSONType,
  data: Name,
  strictNums?: boolean | "log",
  correct = DataType.Correct
): Code {
  const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
  let cond: Code
  switch (dataType) {
    case "null":
      return _`${data} ${EQ} null`
    case "array":
      cond = _`Array.isArray(${data})`
      break
    case "object":
      cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
      break
    case "integer":
      cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
      break
    case "number":
      cond = numCond()
      break
    default:
      return _`typeof ${data} ${EQ} ${dataType}`
  }
  return correct === DataType.Correct ? cond : not(cond)

  function numCond(_cond: Code = nil): Code {
    return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
  }
}

export function checkDataTypes(
  dataTypes: JSONType[],
  data: Name,
  strictNums?: boolean | "log",
  correct?: DataType
): Code {
  if (dataTypes.length === 1) {
    return checkDataType(dataTypes[0], data, strictNums, correct)
  }
  let cond: Code
  const types = toHash(dataTypes)
  if (types.array && types.object) {
    const notObj = _`typeof ${data} != "object"`
    cond = types.null ? notObj : _`!${data} || ${notObj}`
    delete types.null
    delete types.array
    delete types.object
  } else {
    cond = nil
  }
  if (types.number) delete types.integer
  for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))
  return cond
}

export type TypeError = ErrorObject<"type", {type: string}>

const typeError: KeywordErrorDefinition = {
  message: ({schema}) => `must be ${schema}`,
  params: ({schema, schemaValue}) =>
    typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,
}

export function reportTypeError(it: SchemaObjCxt): void {
  const cxt = getTypeErrorContext(it)
  reportError(cxt, typeError)
}

function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
  const {gen, data, schema} = it
  const schemaCode = schemaRefOrVal(it, schema, "type")
  return {
    gen,
    keyword: "type",
    data,
    schema: schema.type,
    schemaCode,
    schemaValue: schemaCode,
    parentSchema: schema,
    params: {},
    it,
  }
}
import type {SchemaObjCxt} from ".."
import {_, getProperty, stringify} from "../codegen"
import {checkStrictMode} from "../util"

export function assignDefaults(it: SchemaObjCxt, ty?: string): void {
  const {properties, items} = it.schema
  if (ty === "object" && properties) {
    for (const key in properties) {
      assignDefault(it, key, properties[key].default)
    }
  } else if (ty === "array" && Array.isArray(items)) {
    items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
  }
}

function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
  const {gen, compositeRule, data, opts} = it
  if (defaultValue === undefined) return
  const childData = _`${data}${getProperty(prop)}`
  if (compositeRule) {
    checkStrictMode(it, `default is ignored for: ${childData}`)
    return
  }

  let condition = _`${childData} === undefined`
  if (opts.useDefaults === "empty") {
    condition = _`${condition} || ${childData} === null || ${childData} === ""`
  }
  // `${childData} === undefined` +
  // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
  gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
}
import type {
  AddedKeywordDefinition,
  AnySchema,
  AnySchemaObject,
  KeywordErrorCxt,
  KeywordCxtParams,
} from "../../types"
import type {SchemaCxt, SchemaObjCxt} from ".."
import type {InstanceOptions} from "../../core"
import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
import {shouldUseGroup, shouldUseRule} from "./applicability"
import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
import {assignDefaults} from "./defaults"
import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import {resolveUrl} from "../resolve"
import {
  schemaRefOrVal,
  schemaHasRulesButRef,
  checkUnknownRules,
  checkStrictMode,
  unescapeJsonPointer,
  mergeEvaluated,
} from "../util"
import type {JSONType, Rule, RuleGroup} from "../rules"
import {
  ErrorPaths,
  reportError,
  reportExtraError,
  resetErrorsCount,
  keyword$DataError,
} from "../errors"

// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
export function validateFunctionCode(it: SchemaCxt): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      topSchemaObjCode(it)
      return
    }
  }
  validateFunction(it, () => topBoolOrEmptySchema(it))
}

function validateFunction(
  {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
  body: Block
): void {
  if (opts.code.es5) {
    gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
      gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
      destructureValCxtES5(gen, opts)
      gen.code(body)
    })
  } else {
    gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
      gen.code(funcSourceUrl(schema, opts)).code(body)
    )
  }
}

function destructureValCxt(opts: InstanceOptions): Code {
  return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
    N.data
  }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
}

function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
  gen.if(
    N.valCxt,
    () => {
      gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
      gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
      gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
      gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
    },
    () => {
      gen.var(N.instancePath, _`""`)
      gen.var(N.parentData, _`undefined`)
      gen.var(N.parentDataProperty, _`undefined`)
      gen.var(N.rootData, N.data)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
    }
  )
}

function topSchemaObjCode(it: SchemaObjCxt): void {
  const {schema, opts, gen} = it
  validateFunction(it, () => {
    if (opts.$comment && schema.$comment) commentKeyword(it)
    checkNoDefault(it)
    gen.let(N.vErrors, null)
    gen.let(N.errors, 0)
    if (opts.unevaluated) resetEvaluated(it)
    typeAndKeywords(it)
    returnResults(it)
  })
  return
}

function resetEvaluated(it: SchemaObjCxt): void {
  // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
  const {gen, validateName} = it
  it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
  gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
  gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
}

function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
  const schId = typeof schema == "object" && schema[opts.schemaId]
  return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
}

// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it: SchemaCxt, valid: Name): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      subSchemaObjCode(it, valid)
      return
    }
  }
  boolOrEmptySchema(it, valid)
}

function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (self.RULES.all[key]) return true
  return false
}

function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
  return typeof it.schema != "boolean"
}

function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
  const {schema, gen, opts} = it
  if (opts.$comment && schema.$comment) commentKeyword(it)
  updateContext(it)
  checkAsyncSchema(it)
  const errsCount = gen.const("_errs", N.errors)
  typeAndKeywords(it, errsCount)
  // TODO var
  gen.var(valid, _`${errsCount} === ${N.errors}`)
}

function checkKeywords(it: SchemaObjCxt): void {
  checkUnknownRules(it)
  checkRefsAndKeywords(it)
}

function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
  if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
  const types = getSchemaTypes(it.schema)
  const checkedTypes = coerceAndCheckDataType(it, types)
  schemaKeywords(it, types, !checkedTypes, errsCount)
}

function checkRefsAndKeywords(it: SchemaObjCxt): void {
  const {schema, errSchemaPath, opts, self} = it
  if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
    self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
  }
}

function checkNoDefault(it: SchemaObjCxt): void {
  const {schema, opts} = it
  if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
    checkStrictMode(it, "default is ignored in the schema root")
  }
}

function updateContext(it: SchemaObjCxt): void {
  const schId = it.schema[it.opts.schemaId]
  if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
}

function checkAsyncSchema(it: SchemaObjCxt): void {
  if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
}

function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
  const msg = schema.$comment
  if (opts.$comment === true) {
    gen.code(_`${N.self}.logger.log(${msg})`)
  } else if (typeof opts.$comment == "function") {
    const schemaPath = str`${errSchemaPath}/$comment`
    const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
    gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
  }
}

function returnResults(it: SchemaCxt): void {
  const {gen, schemaEnv, validateName, ValidationError, opts} = it
  if (schemaEnv.$async) {
    // TODO assign unevaluated
    gen.if(
      _`${N.errors} === 0`,
      () => gen.return(N.data),
      () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
    )
  } else {
    gen.assign(_`${validateName}.errors`, N.vErrors)
    if (opts.unevaluated) assignEvaluated(it)
    gen.return(_`${N.errors} === 0`)
  }
}

function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
  if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
  if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
}

function schemaKeywords(
  it: SchemaObjCxt,
  types: JSONType[],
  typeErrors: boolean,
  errsCount?: Name
): void {
  const {gen, schema, data, allErrors, opts, self} = it
  const {RULES} = self
  if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
    gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
    return
  }
  if (!opts.jtd) checkStrictTypes(it, types)
  gen.block(() => {
    for (const group of RULES.rules) groupKeywords(group)
    groupKeywords(RULES.post)
  })

  function groupKeywords(group: RuleGroup): void {
    if (!shouldUseGroup(schema, group)) return
    if (group.type) {
      gen.if(checkDataType(group.type, data, opts.strictNumbers))
      iterateKeywords(it, group)
      if (types.length === 1 && types[0] === group.type && typeErrors) {
        gen.else()
        reportTypeError(it)
      }
      gen.endIf()
    } else {
      iterateKeywords(it, group)
    }
    // TODO make it "ok" call?
    if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
  }
}

function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
  const {
    gen,
    schema,
    opts: {useDefaults},
  } = it
  if (useDefaults) assignDefaults(it, group.type)
  gen.block(() => {
    for (const rule of group.rules) {
      if (shouldUseRule(schema, rule)) {
        keywordCode(it, rule.keyword, rule.definition, group.type)
      }
    }
  })
}

function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (it.schemaEnv.meta || !it.opts.strictTypes) return
  checkContextTypes(it, types)
  if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
  checkKeywordTypes(it, it.dataTypes)
}

function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (!types.length) return
  if (!it.dataTypes.length) {
    it.dataTypes = types
    return
  }
  types.forEach((t) => {
    if (!includesType(it.dataTypes, t)) {
      strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
    }
  })
  narrowSchemaTypes(it, types)
}

function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
    strictTypesError(it, "use allowUnionTypes to allow union type keyword")
  }
}

function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  const rules = it.self.RULES.all
  for (const keyword in rules) {
    const rule = rules[keyword]
    if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
      const {type} = rule.definition
      if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
        strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
      }
    }
  }
}

function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
  return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
}

function includesType(ts: JSONType[], t: JSONType): boolean {
  return ts.includes(t) || (t === "integer" && ts.includes("number"))
}

function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
  const ts: JSONType[] = []
  for (const t of it.dataTypes) {
    if (includesType(withTypes, t)) ts.push(t)
    else if (withTypes.includes("integer") && t === "number") ts.push("integer")
  }
  it.dataTypes = ts
}

function strictTypesError(it: SchemaObjCxt, msg: string): void {
  const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
  msg += ` at "${schemaPath}" (strictTypes)`
  checkStrictMode(it, msg, it.opts.strictTypes)
}

export class KeywordCxt implements KeywordErrorCxt {
  readonly gen: CodeGen
  readonly allErrors?: boolean
  readonly keyword: string
  readonly data: Name // Name referencing the current level of the data instance
  readonly $data?: string | false
  schema: any // keyword value in the schema
  readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
  readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
  readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
  readonly parentSchema: AnySchemaObject
  readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
  // requires option trackErrors in keyword definition
  params: KeywordCxtParams // object to pass parameters to error messages from keyword code
  readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
  readonly def: AddedKeywordDefinition

  constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
    validateKeywordUsage(it, def, keyword)
    this.gen = it.gen
    this.allErrors = it.allErrors
    this.keyword = keyword
    this.data = it.data
    this.schema = it.schema[keyword]
    this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
    this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
    this.schemaType = def.schemaType
    this.parentSchema = it.schema
    this.params = {}
    this.it = it
    this.def = def

    if (this.$data) {
      this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
    } else {
      this.schemaCode = this.schemaValue
      if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
        throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
      }
    }

    if ("code" in def ? def.trackErrors : def.errors !== false) {
      this.errsCount = it.gen.const("_errs", N.errors)
    }
  }

  result(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.failResult(not(condition), successAction, failAction)
  }

  failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.gen.if(condition)
    if (failAction) failAction()
    else this.error()
    if (successAction) {
      this.gen.else()
      successAction()
      if (this.allErrors) this.gen.endIf()
    } else {
      if (this.allErrors) this.gen.endIf()
      else this.gen.else()
    }
  }

  pass(condition: Code, failAction?: () => void): void {
    this.failResult(not(condition), undefined, failAction)
  }

  fail(condition?: Code): void {
    if (condition === undefined) {
      this.error()
      if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
      return
    }
    this.gen.if(condition)
    this.error()
    if (this.allErrors) this.gen.endIf()
    else this.gen.else()
  }

  fail$data(condition: Code): void {
    if (!this.$data) return this.fail(condition)
    const {schemaCode} = this
    this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
  }

  error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
    if (errorParams) {
      this.setParams(errorParams)
      this._error(append, errorPaths)
      this.setParams({})
      return
    }
    this._error(append, errorPaths)
  }

  private _error(append?: boolean, errorPaths?: ErrorPaths): void {
    ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
  }

  $dataError(): void {
    reportError(this, this.def.$dataError || keyword$DataError)
  }

  reset(): void {
    if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
    resetErrorsCount(this.gen, this.errsCount)
  }

  ok(cond: Code | boolean): void {
    if (!this.allErrors) this.gen.if(cond)
  }

  setParams(obj: KeywordCxtParams, assign?: true): void {
    if (assign) Object.assign(this.params, obj)
    else this.params = obj
  }

  block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
    this.gen.block(() => {
      this.check$data(valid, $dataValid)
      codeBlock()
    })
  }

  check$data(valid: Name = nil, $dataValid: Code = nil): void {
    if (!this.$data) return
    const {gen, schemaCode, schemaType, def} = this
    gen.if(or(_`${schemaCode} === undefined`, $dataValid))
    if (valid !== nil) gen.assign(valid, true)
    if (schemaType.length || def.validateSchema) {
      gen.elseIf(this.invalid$data())
      this.$dataError()
      if (valid !== nil) gen.assign(valid, false)
    }
    gen.else()
  }

  invalid$data(): Code {
    const {gen, schemaCode, schemaType, def, it} = this
    return or(wrong$DataType(), invalid$DataSchema())

    function wrong$DataType(): Code {
      if (schemaType.length) {
        /* istanbul ignore if */
        if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
        const st = Array.isArray(schemaType) ? schemaType : [schemaType]
        return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
      }
      return nil
    }

    function invalid$DataSchema(): Code {
      if (def.validateSchema) {
        const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
        return _`!${validateSchemaRef}(${schemaCode})`
      }
      return nil
    }
  }

  subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
    const subschema = getSubschema(this.it, appl)
    extendSubschemaData(subschema, this.it, appl)
    extendSubschemaMode(subschema, appl)
    const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
    subschemaCode(nextContext, valid)
    return nextContext
  }

  mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
    const {it, gen} = this
    if (!it.opts.unevaluated) return
    if (it.props !== true && schemaCxt.props !== undefined) {
      it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
    }
    if (it.items !== true && schemaCxt.items !== undefined) {
      it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
    }
  }

  mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
    const {it, gen} = this
    if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
      gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
      return true
    }
  }
}

function keywordCode(
  it: SchemaObjCxt,
  keyword: string,
  def: AddedKeywordDefinition,
  ruleType?: JSONType
): void {
  const cxt = new KeywordCxt(it, def, keyword)
  if ("code" in def) {
    def.code(cxt, ruleType)
  } else if (cxt.$data && def.validate) {
    funcKeywordCode(cxt, def)
  } else if ("macro" in def) {
    macroKeywordCode(cxt, def)
  } else if (def.compile || def.validate) {
    funcKeywordCode(cxt, def)
  }
}

const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
export function getData(
  $data: string,
  {dataLevel, dataNames, dataPathArr}: SchemaCxt
): Code | number {
  let jsonPointer
  let data: Code
  if ($data === "") return N.rootData
  if ($data[0] === "/") {
    if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
    jsonPointer = $data
    data = N.rootData
  } else {
    const matches = RELATIVE_JSON_POINTER.exec($data)
    if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
    const up: number = +matches[1]
    jsonPointer = matches[2]
    if (jsonPointer === "#") {
      if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
      return dataPathArr[dataLevel - up]
    }
    if (up > dataLevel) throw new Error(errorMsg("data", up))
    data = dataNames[dataLevel - up]
    if (!jsonPointer) return data
  }

  let expr = data
  const segments = jsonPointer.split("/")
  for (const segment of segments) {
    if (segment) {
      data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
      expr = _`${expr} && ${data}`
    }
  }
  return expr

  function errorMsg(pointerType: string, up: number): string {
    return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
  }
}
import type {KeywordCxt} from "."
import type {
  AnySchema,
  SchemaValidateFunction,
  AnyValidateFunction,
  AddedKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import type {JSONType} from "../rules"
import {callValidateCode} from "../../vocabularies/code"
import {extendErrors} from "../errors"

type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction

export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, it} = cxt
  const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
  const schemaRef = useKeyword(gen, keyword, macroSchema)
  if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)

  const valid = gen.name("valid")
  cxt.subschema(
    {
      schema: macroSchema,
      schemaPath: nil,
      errSchemaPath: `${it.errSchemaPath}/${keyword}`,
      topSchemaRef: schemaRef,
      compositeRule: true,
    },
    valid
  )
  cxt.pass(valid, () => cxt.error(true))
}

export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, $data, it} = cxt
  checkAsyncKeyword(it, def)
  const validate =
    !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
  const validateRef = useKeyword(gen, keyword, validate)
  const valid = gen.let("valid")
  cxt.block$data(valid, validateKeyword)
  cxt.ok(def.valid ?? valid)

  function validateKeyword(): void {
    if (def.errors === false) {
      assignValid()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => cxt.error())
    } else {
      const ruleErrs = def.async ? validateAsync() : validateSync()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => addErrs(cxt, ruleErrs))
    }
  }

  function validateAsync(): Name {
    const ruleErrs = gen.let("ruleErrs", null)
    gen.try(
      () => assignValid(_`await `),
      (e) =>
        gen.assign(valid, false).if(
          _`${e} instanceof ${it.ValidationError as Name}`,
          () => gen.assign(ruleErrs, _`${e}.errors`),
          () => gen.throw(e)
        )
    )
    return ruleErrs
  }

  function validateSync(): Code {
    const validateErrs = _`${validateRef}.errors`
    gen.assign(validateErrs, null)
    assignValid(nil)
    return validateErrs
  }

  function assignValid(_await: Code = def.async ? _`await ` : nil): void {
    const passCxt = it.opts.passContext ? N.this : N.self
    const passSchema = !(("compile" in def && !$data) || def.schema === false)
    gen.assign(
      valid,
      _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
      def.modifying
    )
  }

  function reportErrs(errors: () => void): void {
    gen.if(not(def.valid ?? valid), errors)
  }
}

function modifyData(cxt: KeywordCxt): void {
  const {gen, data, it} = cxt
  gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))
}

function addErrs(cxt: KeywordCxt, errs: Code): void {
  const {gen} = cxt
  gen.if(
    _`Array.isArray(${errs})`,
    () => {
      gen
        .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
        .assign(N.errors, _`${N.vErrors}.length`)
      extendErrors(cxt)
    },
    () => cxt.error()
  )
}

function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
  if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
}

function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
  if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
  return gen.scopeValue(
    "keyword",
    typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
  )
}

export function validSchemaType(
  schema: unknown,
  schemaType: JSONType[],
  allowUndefined = false
): boolean {
  // TODO add tests
  return (
    !schemaType.length ||
    schemaType.some((st) =>
      st === "array"
        ? Array.isArray(schema)
        : st === "object"
        ? schema && typeof schema == "object" && !Array.isArray(schema)
        : typeof schema == st || (allowUndefined && typeof schema == "undefined")
    )
  )
}

export function validateKeywordUsage(
  {schema, opts, self, errSchemaPath}: SchemaObjCxt,
  def: AddedKeywordDefinition,
  keyword: string
): void {
  /* istanbul ignore if */
  if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
    throw new Error("ajv implementation error")
  }

  const deps = def.dependencies
  if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
    throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
  }

  if (def.validateSchema) {
    const valid = def.validateSchema(schema[keyword])
    if (!valid) {
      const msg =
        `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
        self.errorsText(def.validateSchema.errors)
      if (opts.validateSchema === "log") self.logger.error(msg)
      else throw new Error(msg)
    }
  }
}
import type {AnySchema} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, str, getProperty, Code, Name} from "../codegen"
import {escapeFragment, getErrorPath, Type} from "../util"
import type {JSONType} from "../rules"

export interface SubschemaContext {
  // TODO use Optional? align with SchemCxt property types
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef?: Code
  errorPath?: Code
  dataLevel?: number
  dataTypes?: JSONType[]
  data?: Name
  parentData?: Name
  parentDataProperty?: Code | number
  dataNames?: Name[]
  dataPathArr?: (Code | number)[]
  propertyName?: Name
  jtdDiscriminator?: string
  jtdMetadata?: boolean
  compositeRule?: true
  createErrors?: boolean
  allErrors?: boolean
}

export type SubschemaArgs = Partial<{
  keyword: string
  schemaProp: string | number
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef: Code
  data: Name | Code
  dataProp: Code | string | number
  dataTypes: JSONType[]
  definedProperties: Set<string>
  propertyName: Name
  dataPropType: Type
  jtdDiscriminator: string
  jtdMetadata: boolean
  compositeRule: true
  createErrors: boolean
  allErrors: boolean
}>

export function getSubschema(
  it: SchemaObjCxt,
  {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
): SubschemaContext {
  if (keyword !== undefined && schema !== undefined) {
    throw new Error('both "keyword" and "schema" passed, only one allowed')
  }

  if (keyword !== undefined) {
    const sch = it.schema[keyword]
    return schemaProp === undefined
      ? {
          schema: sch,
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        }
      : {
          schema: sch[schemaProp],
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
        }
  }

  if (schema !== undefined) {
    if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
      throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
    }
    return {
      schema,
      schemaPath,
      topSchemaRef,
      errSchemaPath,
    }
  }

  throw new Error('either "keyword" or "schema" must be passed')
}

export function extendSubschemaData(
  subschema: SubschemaContext,
  it: SchemaObjCxt,
  {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
  if (data !== undefined && dataProp !== undefined) {
    throw new Error('both "data" and "dataProp" passed, only one allowed')
  }

  const {gen} = it

  if (dataProp !== undefined) {
    const {errorPath, dataPathArr, opts} = it
    const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
    dataContextProps(nextData)
    subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
    subschema.parentDataProperty = _`${dataProp}`
    subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
  }

  if (data !== undefined) {
    const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
    dataContextProps(nextData)
    if (propertyName !== undefined) subschema.propertyName = propertyName
    // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
  }

  if (dataTypes) subschema.dataTypes = dataTypes

  function dataContextProps(_nextData: Name): void {
    subschema.data = _nextData
    subschema.dataLevel = it.dataLevel + 1
    subschema.dataTypes = []
    it.definedProperties = new Set<string>()
    subschema.parentData = it.data
    subschema.dataNames = [...it.dataNames, _nextData]
  }
}

export function extendSubschemaMode(
  subschema: SubschemaContext,
  {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
): void {
  if (compositeRule !== undefined) subschema.compositeRule = compositeRule
  if (createErrors !== undefined) subschema.createErrors = createErrors
  if (allErrors !== undefined) subschema.allErrors = allErrors
  subschema.jtdDiscriminator = jtdDiscriminator // not inherited
  subschema.jtdMetadata = jtdMetadata // not inherited
}
import type Ajv from "../../core"
import type {SchemaObject} from "../../types"
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
import {SchemaEnv, getCompilingSchema} from ".."
import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen"
import MissingRefError from "../ref_error"
import N from "../names"
import {hasPropFunc} from "../../vocabularies/code"
import {hasRef} from "../../vocabularies/jtd/ref"
import {intRange, IntType} from "../../vocabularies/jtd/type"
import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson"
import {useFunc} from "../util"
import validTimestamp from "../../runtime/timestamp"

type GenParse = (cxt: ParseCxt) => void

const genParse: {[F in JTDForm]: GenParse} = {
  elements: parseElements,
  values: parseValues,
  discriminator: parseDiscriminator,
  properties: parseProperties,
  optionalProperties: parseProperties,
  enum: parseEnum,
  type: parseType,
  ref: parseRef,
}

interface ParseCxt {
  readonly gen: CodeGen
  readonly self: Ajv // current Ajv instance
  readonly schemaEnv: SchemaEnv
  readonly definitions: SchemaObjectMap
  schema: SchemaObject
  data: Code
  parseName: Name
  char: Name
}

export default function compileParser(
  this: Ajv,
  sch: SchemaEnv,
  definitions: SchemaObjectMap
): SchemaEnv {
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  const parseName = gen.scopeName("parse")
  const cxt: ParseCxt = {
    self: this,
    gen,
    schema: sch.schema as SchemaObject,
    schemaEnv: sch,
    definitions,
    data: N.data,
    parseName,
    char: gen.name("c"),
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    sch.parseName = parseName
    parserFunction(cxt)
    gen.optimize(this.opts.code.optimize)
    const parseFuncCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
    const makeParse = new Function(`${N.scope}`, sourceCode)
    const parse: (json: string) => unknown = makeParse(this.scope.get())
    this.scope.value(parseName, {ref: parse})
    sch.parse = parse
  } catch (e) {
    if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
    delete sch.parse
    delete sch.parseName
    throw e
  } finally {
    this._compilations.delete(sch)
  }
  return sch
}

const undef = _`undefined`

function parserFunction(cxt: ParseCxt): void {
  const {gen, parseName, char} = cxt
  gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => {
    gen.let(N.data)
    gen.let(char)
    gen.assign(_`${parseName}.message`, undef)
    gen.assign(_`${parseName}.position`, undef)
    gen.assign(N.jsonPos, _`${N.jsonPos} || 0`)
    gen.const(N.jsonLen, _`${N.json}.length`)
    parseCode(cxt)
    skipWhitespace(cxt)
    gen.if(N.jsonPart, () => {
      gen.assign(_`${parseName}.position`, N.jsonPos)
      gen.return(N.data)
    })
    gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data))
    jsonSyntaxError(cxt)
  })
}

function parseCode(cxt: ParseCxt): void {
  let form: JTDForm | undefined
  for (const key of jtdForms) {
    if (key in cxt.schema) {
      form = key
      break
    }
  }
  if (form) parseNullable(cxt, genParse[form])
  else parseEmpty(cxt)
}

const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError))

function parseNullable(cxt: ParseCxt, parseForm: GenParse): void {
  const {gen, schema, data} = cxt
  if (!schema.nullable) return parseForm(cxt)
  tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null))
}

function parseElements(cxt: ParseCxt): void {
  const {gen, schema, data} = cxt
  parseToken(cxt, "[")
  const ix = gen.let("i", 0)
  gen.assign(data, _`[]`)
  parseItems(cxt, "]", () => {
    const el = gen.let("el")
    parseCode({...cxt, schema: schema.elements, data: el})
    gen.assign(_`${data}[${ix}++]`, el)
  })
}

function parseValues(cxt: ParseCxt): void {
  const {gen, schema, data} = cxt
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values))
}

function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
  tryParseItems(cxt, endToken, block)
  parseToken(cxt, endToken)
}

function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
  const {gen} = cxt
  gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
    block()
    tryParseToken(cxt, ",", () => gen.break(), hasItem)
  })

  function hasItem(): void {
    tryParseToken(cxt, endToken, () => {}, jsonSyntaxError)
  }
}

function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void {
  const {gen} = cxt
  const key = gen.let("key")
  parseString({...cxt, data: key})
  parseToken(cxt, ":")
  parsePropertyValue(cxt, key, schema)
}

function parseDiscriminator(cxt: ParseCxt): void {
  const {gen, data, schema} = cxt
  const {discriminator, mapping} = schema
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  const startPos = gen.const("pos", N.jsonPos)
  const value = gen.let("value")
  const tag = gen.let("tag")
  tryParseItems(cxt, "}", () => {
    const key = gen.let("key")
    parseString({...cxt, data: key})
    parseToken(cxt, ":")
    gen.if(
      _`${key} === ${discriminator}`,
      () => {
        parseString({...cxt, data: tag})
        gen.assign(_`${data}[${key}]`, tag)
        gen.break()
      },
      () => parseEmpty({...cxt, data: value}) // can be discarded/skipped
    )
  })
  gen.assign(N.jsonPos, startPos)
  gen.if(_`${tag} === undefined`)
  parsingError(cxt, str`discriminator tag not found`)
  for (const tagValue in mapping) {
    gen.elseIf(_`${tag} === ${tagValue}`)
    parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator)
  }
  gen.else()
  parsingError(cxt, str`discriminator value not in schema`)
  gen.endIf()
}

function parseProperties(cxt: ParseCxt): void {
  const {gen, data} = cxt
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  parseSchemaProperties(cxt)
}

function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void {
  const {gen, schema, data} = cxt
  const {properties, optionalProperties, additionalProperties} = schema
  parseItems(cxt, "}", () => {
    const key = gen.let("key")
    parseString({...cxt, data: key})
    parseToken(cxt, ":")
    gen.if(false)
    parseDefinedProperty(cxt, key, properties)
    parseDefinedProperty(cxt, key, optionalProperties)
    if (discriminator) {
      gen.elseIf(_`${key} === ${discriminator}`)
      const tag = gen.let("tag")
      parseString({...cxt, data: tag}) // can be discarded, it is already assigned
    }
    gen.else()
    if (additionalProperties) {
      parseEmpty({...cxt, data: _`${data}[${key}]`})
    } else {
      parsingError(cxt, str`property ${key} not allowed`)
    }
    gen.endIf()
  })
  if (properties) {
    const hasProp = hasPropFunc(gen)
    const allProps: Code = and(
      ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`)
    )
    gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`))
  }
}

function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
  const {gen} = cxt
  for (const prop in schemas) {
    gen.elseIf(_`${key} === ${prop}`)
    parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
  }
}

function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void {
  parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`})
}

function parseType(cxt: ParseCxt): void {
  const {gen, schema, data, self} = cxt
  switch (schema.type) {
    case "boolean":
      parseBoolean(cxt)
      break
    case "string":
      parseString(cxt)
      break
    case "timestamp": {
      parseString(cxt)
      const vts = useFunc(gen, validTimestamp)
      const {allowDate, parseDate} = self.opts
      const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})`
      const fail: Code = parseDate
        ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`)
        : notValid
      gen.if(fail, () => parsingError(cxt, str`invalid timestamp`))
      break
    }
    case "float32":
    case "float64":
      parseNumber(cxt)
      break
    default: {
      const t = schema.type as IntType
      if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
        parseNumber(cxt, 16) // 2 ** 53 - max safe integer
        if (t === "uint32") {
          gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`))
        }
      } else {
        const [min, max, maxDigits] = intRange[t]
        parseNumber(cxt, maxDigits)
        gen.if(_`${data} < ${min} || ${data} > ${max}`, () =>
          parsingError(cxt, str`integer out of range`)
        )
      }
    }
  }
}

function parseString(cxt: ParseCxt): void {
  parseToken(cxt, '"')
  parseWith(cxt, parseJsonString)
}

function parseEnum(cxt: ParseCxt): void {
  const {gen, data, schema} = cxt
  const enumSch = schema.enum
  parseToken(cxt, '"')
  // TODO loopEnum
  gen.if(false)
  for (const value of enumSch) {
    const valueStr = JSON.stringify(value).slice(1) // remove starting quote
    gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`)
    gen.assign(data, str`${value}`)
    gen.add(N.jsonPos, valueStr.length)
  }
  gen.else()
  jsonSyntaxError(cxt)
  gen.endIf()
}

function parseNumber(cxt: ParseCxt, maxDigits?: number): void {
  const {gen} = cxt
  skipWhitespace(cxt)
  gen.if(
    _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`,
    () => jsonSyntaxError(cxt),
    () => parseWith(cxt, parseJsonNumber, maxDigits)
  )
}

function parseBooleanToken(bool: boolean, fail: GenParse): GenParse {
  return (cxt) => {
    const {gen, data} = cxt
    tryParseToken(
      cxt,
      `${bool}`,
      () => fail(cxt),
      () => gen.assign(data, bool)
    )
  }
}

function parseRef(cxt: ParseCxt): void {
  const {gen, self, definitions, schema, schemaEnv} = cxt
  const {ref} = schema
  const refSchema = definitions[ref]
  if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
  if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema})
  const {root} = schemaEnv
  const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
  partialParse(cxt, getParser(gen, sch), true)
}

function getParser(gen: CodeGen, sch: SchemaEnv): Code {
  return sch.parse
    ? gen.scopeValue("parse", {ref: sch.parse})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.parse`
}

function parseEmpty(cxt: ParseCxt): void {
  parseWith(cxt, parseJson)
}

function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void {
  partialParse(cxt, useFunc(cxt.gen, parseFunc), args)
}

function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void {
  const {gen, data} = cxt
  gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`)
  gen.assign(N.jsonPos, _`${parseFunc}.position`)
  gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`))
}

function parseToken(cxt: ParseCxt, tok: string): void {
  tryParseToken(cxt, tok, jsonSyntaxError)
}

function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void {
  const {gen} = cxt
  const n = tok.length
  skipWhitespace(cxt)
  gen.if(
    _`${jsonSlice(n)} === ${tok}`,
    () => {
      gen.add(N.jsonPos, n)
      success?.(cxt)
    },
    () => fail(cxt)
  )
}

function skipWhitespace({gen, char: c}: ParseCxt): void {
  gen.code(
    _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;`
  )
}

function jsonSlice(len: number | Name): Code {
  return len === 1
    ? _`${N.json}[${N.jsonPos}]`
    : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})`
}

function jsonSyntaxError(cxt: ParseCxt): void {
  parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`)
}

function parsingError({gen, parseName}: ParseCxt, msg: Code): void {
  gen.assign(_`${parseName}.message`, msg)
  gen.assign(_`${parseName}.position`, N.jsonPos)
  gen.return(undef)
}
import type Ajv from "../../core"
import type {SchemaObject} from "../../types"
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
import {SchemaEnv, getCompilingSchema} from ".."
import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen"
import MissingRefError from "../ref_error"
import N from "../names"
import {isOwnProperty} from "../../vocabularies/code"
import {hasRef} from "../../vocabularies/jtd/ref"
import {useFunc} from "../util"
import quote from "../../runtime/quote"

const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = {
  elements: serializeElements,
  values: serializeValues,
  discriminator: serializeDiscriminator,
  properties: serializeProperties,
  optionalProperties: serializeProperties,
  enum: serializeString,
  type: serializeType,
  ref: serializeRef,
}

interface SerializeCxt {
  readonly gen: CodeGen
  readonly self: Ajv // current Ajv instance
  readonly schemaEnv: SchemaEnv
  readonly definitions: SchemaObjectMap
  schema: SchemaObject
  data: Code
}

export default function compileSerializer(
  this: Ajv,
  sch: SchemaEnv,
  definitions: SchemaObjectMap
): SchemaEnv {
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  const serializeName = gen.scopeName("serialize")
  const cxt: SerializeCxt = {
    self: this,
    gen,
    schema: sch.schema as SchemaObject,
    schemaEnv: sch,
    definitions,
    data: N.data,
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    sch.serializeName = serializeName
    gen.func(serializeName, N.data, false, () => {
      gen.let(N.json, str``)
      serializeCode(cxt)
      gen.return(N.json)
    })
    gen.optimize(this.opts.code.optimize)
    const serializeFuncCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}`
    const makeSerialize = new Function(`${N.scope}`, sourceCode)
    const serialize: (data: unknown) => string = makeSerialize(this.scope.get())
    this.scope.value(serializeName, {ref: serialize})
    sch.serialize = serialize
  } catch (e) {
    if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode)
    delete sch.serialize
    delete sch.serializeName
    throw e
  } finally {
    this._compilations.delete(sch)
  }
  return sch
}

function serializeCode(cxt: SerializeCxt): void {
  let form: JTDForm | undefined
  for (const key of jtdForms) {
    if (key in cxt.schema) {
      form = key
      break
    }
  }
  serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty)
}

function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void {
  const {gen, schema, data} = cxt
  if (!schema.nullable) return serializeForm(cxt)
  gen.if(
    _`${data} === undefined || ${data} === null`,
    () => gen.add(N.json, _`"null"`),
    () => serializeForm(cxt)
  )
}

function serializeElements(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  gen.add(N.json, str`[`)
  const first = gen.let("first", true)
  gen.forOf("el", data, (el) => {
    addComma(cxt, first)
    serializeCode({...cxt, schema: schema.elements, data: el})
  })
  gen.add(N.json, str`]`)
}

function serializeValues(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  gen.add(N.json, str`{`)
  const first = gen.let("first", true)
  gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first))
  gen.add(N.json, str`}`)
}

function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void {
  const {gen, data} = cxt
  addComma(cxt, first)
  serializeString({...cxt, data: key})
  gen.add(N.json, str`:`)
  const value = gen.const("value", _`${data}${getProperty(key)}`)
  serializeCode({...cxt, schema, data: value})
}

function serializeDiscriminator(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  const {discriminator} = schema
  gen.add(N.json, str`{${JSON.stringify(discriminator)}:`)
  const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`)
  serializeString({...cxt, data: tag})
  gen.if(false)
  for (const tagValue in schema.mapping) {
    gen.elseIf(_`${tag} === ${tagValue}`)
    const sch = schema.mapping[tagValue]
    serializeSchemaProperties({...cxt, schema: sch}, discriminator)
  }
  gen.endIf()
  gen.add(N.json, str`}`)
}

function serializeProperties(cxt: SerializeCxt): void {
  const {gen} = cxt
  gen.add(N.json, str`{`)
  serializeSchemaProperties(cxt)
  gen.add(N.json, str`}`)
}

function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void {
  const {gen, schema, data} = cxt
  const {properties, optionalProperties} = schema
  const props = keys(properties)
  const optProps = keys(optionalProperties)
  const allProps = allProperties(props.concat(optProps))
  let first = !discriminator
  let firstProp: Name | undefined

  for (const key of props) {
    if (first) first = false
    else gen.add(N.json, str`,`)
    serializeProperty(key, properties[key], keyValue(key))
  }
  if (first) firstProp = gen.let("first", true)
  for (const key of optProps) {
    const value = keyValue(key)
    gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => {
      addComma(cxt, firstProp)
      serializeProperty(key, optionalProperties[key], value)
    })
  }
  if (schema.additionalProperties) {
    gen.forIn("key", data, (key) =>
      gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))
    )
  }

  function keys(ps?: SchemaObjectMap): string[] {
    return ps ? Object.keys(ps) : []
  }

  function allProperties(ps: string[]): string[] {
    if (discriminator) ps.push(discriminator)
    if (new Set(ps).size !== ps.length) {
      throw new Error("JTD: properties/optionalProperties/disciminator overlap")
    }
    return ps
  }

  function keyValue(key: string): Name {
    return gen.const("value", _`${data}${getProperty(key)}`)
  }

  function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void {
    gen.add(N.json, str`${JSON.stringify(key)}:`)
    serializeCode({...cxt, schema: propSchema, data: value})
  }

  function isAdditional(key: Name, ps: string[]): Code | true {
    return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true
  }
}

function serializeType(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  switch (schema.type) {
    case "boolean":
      gen.add(N.json, _`${data} ? "true" : "false"`)
      break
    case "string":
      serializeString(cxt)
      break
    case "timestamp":
      gen.if(
        _`${data} instanceof Date`,
        () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
        () => serializeString(cxt)
      )
      break
    default:
      serializeNumber(cxt)
  }
}

function serializeString({gen, data}: SerializeCxt): void {
  gen.add(N.json, _`${useFunc(gen, quote)}(${data})`)
}

function serializeNumber({gen, data, self}: SerializeCxt): void {
  const condition = _`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`

  if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
    gen.add(N.json, _`"" + ${data}`)
  } else {
    // specialNumbers === "null"
    gen.if(
      condition,
      () => gen.add(N.json, _`null`),
      () => gen.add(N.json, _`"" + ${data}`)
    )
  }
}

function serializeRef(cxt: SerializeCxt): void {
  const {gen, self, data, definitions, schema, schemaEnv} = cxt
  const {ref} = schema
  const refSchema = definitions[ref]
  if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
  if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema})
  const {root} = schemaEnv
  const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
  gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`)
}

function getSerialize(gen: CodeGen, sch: SchemaEnv): Code {
  return sch.serialize
    ? gen.scopeValue("serialize", {ref: sch.serialize})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize`
}

function serializeEmpty({gen, data}: SerializeCxt): void {
  gen.add(N.json, _`JSON.stringify(${data})`)
}

function addComma({gen}: SerializeCxt, first?: Name): void {
  if (first) {
    gen.if(
      first,
      () => gen.assign(first, false),
      () => gen.add(N.json, str`,`)
    )
  } else {
    gen.add(N.json, str`,`)
  }
}
import type {SchemaObject} from "../../types"

export type SchemaObjectMap = {[Ref in string]?: SchemaObject}

export const jtdForms = [
  "elements",
  "values",
  "discriminator",
  "properties",
  "optionalProperties",
  "enum",
  "type",
  "ref",
] as const

export type JTDForm = (typeof jtdForms)[number]
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export abstract class _CodeOrName {
  abstract readonly str: string
  abstract readonly names: UsedNames
  abstract toString(): string
  abstract emptyStr(): boolean
}

export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i

export class Name extends _CodeOrName {
  readonly str: string
  constructor(s: string) {
    super()
    if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
    this.str = s
  }

  toString(): string {
    return this.str
  }

  emptyStr(): boolean {
    return false
  }

  get names(): UsedNames {
    return {[this.str]: 1}
  }
}

export class _Code extends _CodeOrName {
  readonly _items: readonly CodeItem[]
  private _str?: string
  private _names?: UsedNames

  constructor(code: string | readonly CodeItem[]) {
    super()
    this._items = typeof code === "string" ? [code] : code
  }

  toString(): string {
    return this.str
  }

  emptyStr(): boolean {
    if (this._items.length > 1) return false
    const item = this._items[0]
    return item === "" || item === '""'
  }

  get str(): string {
    return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, ""))
  }

  get names(): UsedNames {
    return (this._names ??= this._items.reduce((names: UsedNames, c) => {
      if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1
      return names
    }, {}))
  }
}

export type CodeItem = Name | string | number | boolean | null

export type UsedNames = Record<string, number | undefined>

export type Code = _Code | Name

export type SafeExpr = Code | number | boolean | null

export const nil = new _Code("")

type CodeArg = SafeExpr | string | undefined

export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {
  const code: CodeItem[] = [strs[0]]
  let i = 0
  while (i < args.length) {
    addCodeArg(code, args[i])
    code.push(strs[++i])
  }
  return new _Code(code)
}

const plus = new _Code("+")

export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {
  const expr: CodeItem[] = [safeStringify(strs[0])]
  let i = 0
  while (i < args.length) {
    expr.push(plus)
    addCodeArg(expr, args[i])
    expr.push(plus, safeStringify(strs[++i]))
  }
  optimize(expr)
  return new _Code(expr)
}

export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {
  if (arg instanceof _Code) code.push(...arg._items)
  else if (arg instanceof Name) code.push(arg)
  else code.push(interpolate(arg))
}

function optimize(expr: CodeItem[]): void {
  let i = 1
  while (i < expr.length - 1) {
    if (expr[i] === plus) {
      const res = mergeExprItems(expr[i - 1], expr[i + 1])
      if (res !== undefined) {
        expr.splice(i - 1, 3, res)
        continue
      }
      expr[i++] = "+"
    }
    i++
  }
}

function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {
  if (b === '""') return a
  if (a === '""') return b
  if (typeof a == "string") {
    if (b instanceof Name || a[a.length - 1] !== '"') return
    if (typeof b != "string") return `${a.slice(0, -1)}${b}"`
    if (b[0] === '"') return a.slice(0, -1) + b.slice(1)
    return
  }
  if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`
  return
}

export function strConcat(c1: Code, c2: Code): Code {
  return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`
}

// TODO do not allow arrays here
function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {
  return typeof x == "number" || typeof x == "boolean" || x === null
    ? x
    : safeStringify(Array.isArray(x) ? x.join(",") : x)
}

export function stringify(x: unknown): Code {
  return new _Code(safeStringify(x))
}

export function safeStringify(x: unknown): string {
  return JSON.stringify(x)
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029")
}

export function getProperty(key: Code | string | number): Code {
  return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`
}

//Does best effort to format the name properly
export function getEsmExportName(key: Code | string | number): Code {
  if (typeof key == "string" && IDENTIFIER.test(key)) {
    return new _Code(`${key}`)
  }
  throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)
}

export function regexpCode(rx: RegExp): Code {
  return new _Code(rx.toString())
}
import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope"
import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code"
import {Scope, varKinds} from "./scope"

export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"

// type for expressions that can be safely inserted in code without quotes
export type SafeExpr = Code | number | boolean | null

// type that is either Code of function that adds code to CodeGen instance using its methods
export type Block = Code | (() => void)

export const operators = {
  GT: new _Code(">"),
  GTE: new _Code(">="),
  LT: new _Code("<"),
  LTE: new _Code("<="),
  EQ: new _Code("==="),
  NEQ: new _Code("!=="),
  NOT: new _Code("!"),
  OR: new _Code("||"),
  AND: new _Code("&&"),
  ADD: new _Code("+"),
}

abstract class Node {
  abstract readonly names: UsedNames

  optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
    return this
  }

  optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
    return this
  }

  // get count(): number {
  //   return 1
  // }
}

class Def extends Node {
  constructor(
    private readonly varKind: Name,
    private readonly name: Name,
    private rhs?: SafeExpr
  ) {
    super()
  }

  render({es5, _n}: CGOptions): string {
    const varKind = es5 ? varKinds.var : this.varKind
    const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`
    return `${varKind} ${this.name}${rhs};` + _n
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!names[this.name.str]) return
    if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)
    return this
  }

  get names(): UsedNames {
    return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
  }
}

class Assign extends Node {
  constructor(
    readonly lhs: Code,
    public rhs: SafeExpr,
    private readonly sideEffects?: boolean
  ) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.lhs} = ${this.rhs};` + _n
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return
    this.rhs = optimizeExpr(this.rhs, names, constants)
    return this
  }

  get names(): UsedNames {
    const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
    return addExprNames(names, this.rhs)
  }
}

class AssignOp extends Assign {
  constructor(
    lhs: Code,
    private readonly op: Code,
    rhs: SafeExpr,
    sideEffects?: boolean
  ) {
    super(lhs, rhs, sideEffects)
  }

  render({_n}: CGOptions): string {
    return `${this.lhs} ${this.op}= ${this.rhs};` + _n
  }
}

class Label extends Node {
  readonly names: UsedNames = {}
  constructor(readonly label: Name) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.label}:` + _n
  }
}

class Break extends Node {
  readonly names: UsedNames = {}
  constructor(readonly label?: Code) {
    super()
  }

  render({_n}: CGOptions): string {
    const label = this.label ? ` ${this.label}` : ""
    return `break${label};` + _n
  }
}

class Throw extends Node {
  constructor(readonly error: Code) {
    super()
  }

  render({_n}: CGOptions): string {
    return `throw ${this.error};` + _n
  }

  get names(): UsedNames {
    return this.error.names
  }
}

class AnyCode extends Node {
  constructor(private code: SafeExpr) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.code};` + _n
  }

  optimizeNodes(): this | undefined {
    return `${this.code}` ? this : undefined
  }

  optimizeNames(names: UsedNames, constants: Constants): this {
    this.code = optimizeExpr(this.code, names, constants)
    return this
  }

  get names(): UsedNames {
    return this.code instanceof _CodeOrName ? this.code.names : {}
  }
}

abstract class ParentNode extends Node {
  constructor(readonly nodes: ChildNode[] = []) {
    super()
  }

  render(opts: CGOptions): string {
    return this.nodes.reduce((code, n) => code + n.render(opts), "")
  }

  optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
    const {nodes} = this
    let i = nodes.length
    while (i--) {
      const n = nodes[i].optimizeNodes()
      if (Array.isArray(n)) nodes.splice(i, 1, ...n)
      else if (n) nodes[i] = n
      else nodes.splice(i, 1)
    }
    return nodes.length > 0 ? this : undefined
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    const {nodes} = this
    let i = nodes.length
    while (i--) {
      // iterating backwards improves 1-pass optimization
      const n = nodes[i]
      if (n.optimizeNames(names, constants)) continue
      subtractNames(names, n.names)
      nodes.splice(i, 1)
    }
    return nodes.length > 0 ? this : undefined
  }

  get names(): UsedNames {
    return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
  }

  // get count(): number {
  //   return this.nodes.reduce((c, n) => c + n.count, 1)
  // }
}

abstract class BlockNode extends ParentNode {
  render(opts: CGOptions): string {
    return "{" + opts._n + super.render(opts) + "}" + opts._n
  }
}

class Root extends ParentNode {}

class Else extends BlockNode {
  static readonly kind = "else"
}

class If extends BlockNode {
  static readonly kind = "if"
  else?: If | Else
  constructor(
    private condition: Code | boolean,
    nodes?: ChildNode[]
  ) {
    super(nodes)
  }

  render(opts: CGOptions): string {
    let code = `if(${this.condition})` + super.render(opts)
    if (this.else) code += "else " + this.else.render(opts)
    return code
  }

  optimizeNodes(): If | ChildNode[] | undefined {
    super.optimizeNodes()
    const cond = this.condition
    if (cond === true) return this.nodes // else is ignored here
    let e = this.else
    if (e) {
      const ns = e.optimizeNodes()
      e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
    }
    if (e) {
      if (cond === false) return e instanceof If ? e : e.nodes
      if (this.nodes.length) return this
      return new If(not(cond), e instanceof If ? [e] : e.nodes)
    }
    if (cond === false || !this.nodes.length) return undefined
    return this
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    this.else = this.else?.optimizeNames(names, constants)
    if (!(super.optimizeNames(names, constants) || this.else)) return
    this.condition = optimizeExpr(this.condition, names, constants)
    return this
  }

  get names(): UsedNames {
    const names = super.names
    addExprNames(names, this.condition)
    if (this.else) addNames(names, this.else.names)
    return names
  }

  // get count(): number {
  //   return super.count + (this.else?.count || 0)
  // }
}

abstract class For extends BlockNode {
  static readonly kind = "for"
}

class ForLoop extends For {
  constructor(private iteration: Code) {
    super()
  }

  render(opts: CGOptions): string {
    return `for(${this.iteration})` + super.render(opts)
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!super.optimizeNames(names, constants)) return
    this.iteration = optimizeExpr(this.iteration, names, constants)
    return this
  }

  get names(): UsedNames {
    return addNames(super.names, this.iteration.names)
  }
}

class ForRange extends For {
  constructor(
    private readonly varKind: Name,
    private readonly name: Name,
    private readonly from: SafeExpr,
    private readonly to: SafeExpr
  ) {
    super()
  }

  render(opts: CGOptions): string {
    const varKind = opts.es5 ? varKinds.var : this.varKind
    const {name, from, to} = this
    return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)
  }

  get names(): UsedNames {
    const names = addExprNames(super.names, this.from)
    return addExprNames(names, this.to)
  }
}

class ForIter extends For {
  constructor(
    private readonly loop: "of" | "in",
    private readonly varKind: Name,
    private readonly name: Name,
    private iterable: Code
  ) {
    super()
  }

  render(opts: CGOptions): string {
    return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!super.optimizeNames(names, constants)) return
    this.iterable = optimizeExpr(this.iterable, names, constants)
    return this
  }

  get names(): UsedNames {
    return addNames(super.names, this.iterable.names)
  }
}

class Func extends BlockNode {
  static readonly kind = "func"
  constructor(
    public name: Name,
    public args: Code,
    public async?: boolean
  ) {
    super()
  }

  render(opts: CGOptions): string {
    const _async = this.async ? "async " : ""
    return `${_async}function ${this.name}(${this.args})` + super.render(opts)
  }
}

class Return extends ParentNode {
  static readonly kind = "return"

  render(opts: CGOptions): string {
    return "return " + super.render(opts)
  }
}

class Try extends BlockNode {
  catch?: Catch
  finally?: Finally

  render(opts: CGOptions): string {
    let code = "try" + super.render(opts)
    if (this.catch) code += this.catch.render(opts)
    if (this.finally) code += this.finally.render(opts)
    return code
  }

  optimizeNodes(): this {
    super.optimizeNodes()
    this.catch?.optimizeNodes() as Catch | undefined
    this.finally?.optimizeNodes() as Finally | undefined
    return this
  }

  optimizeNames(names: UsedNames, constants: Constants): this {
    super.optimizeNames(names, constants)
    this.catch?.optimizeNames(names, constants)
    this.finally?.optimizeNames(names, constants)
    return this
  }

  get names(): UsedNames {
    const names = super.names
    if (this.catch) addNames(names, this.catch.names)
    if (this.finally) addNames(names, this.finally.names)
    return names
  }

  // get count(): number {
  //   return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
  // }
}

class Catch extends BlockNode {
  static readonly kind = "catch"
  constructor(readonly error: Name) {
    super()
  }

  render(opts: CGOptions): string {
    return `catch(${this.error})` + super.render(opts)
  }
}

class Finally extends BlockNode {
  static readonly kind = "finally"
  render(opts: CGOptions): string {
    return "finally" + super.render(opts)
  }
}

type StartBlockNode = If | For | Func | Return | Try

type LeafNode = Def | Assign | Label | Break | Throw | AnyCode

type ChildNode = StartBlockNode | LeafNode

type EndBlockNodeType =
  | typeof If
  | typeof Else
  | typeof For
  | typeof Func
  | typeof Return
  | typeof Catch
  | typeof Finally

type Constants = Record<string, SafeExpr | undefined>

export interface CodeGenOptions {
  es5?: boolean
  lines?: boolean
  ownProperties?: boolean
}

interface CGOptions extends CodeGenOptions {
  _n: "\n" | ""
}

export class CodeGen {
  readonly _scope: Scope
  readonly _extScope: ValueScope
  readonly _values: ScopeValueSets = {}
  private readonly _nodes: ParentNode[]
  private readonly _blockStarts: number[] = []
  private readonly _constants: Constants = {}
  private readonly opts: CGOptions

  constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
    this.opts = {...opts, _n: opts.lines ? "\n" : ""}
    this._extScope = extScope
    this._scope = new Scope({parent: extScope})
    this._nodes = [new Root()]
  }

  toString(): string {
    return this._root.render(this.opts)
  }

  // returns unique name in the internal scope
  name(prefix: string): Name {
    return this._scope.name(prefix)
  }

  // reserves unique name in the external scope
  scopeName(prefix: string): ValueScopeName {
    return this._extScope.name(prefix)
  }

  // reserves unique name in the external scope and assigns value to it
  scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
    const name = this._extScope.value(prefixOrName, value)
    const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
    vs.add(name)
    return name
  }

  getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
    return this._extScope.getValue(prefix, keyOrRef)
  }

  // return code that assigns values in the external scope to the names that are used internally
  // (same names that were returned by gen.scopeName or gen.scopeValue)
  scopeRefs(scopeName: Name): Code {
    return this._extScope.scopeRefs(scopeName, this._values)
  }

  scopeCode(): Code {
    return this._extScope.scopeCode(this._values)
  }

  private _def(
    varKind: Name,
    nameOrPrefix: Name | string,
    rhs?: SafeExpr,
    constant?: boolean
  ): Name {
    const name = this._scope.toName(nameOrPrefix)
    if (rhs !== undefined && constant) this._constants[name.str] = rhs
    this._leafNode(new Def(varKind, name, rhs))
    return name
  }

  // `const` declaration (`var` in es5 mode)
  const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
  }

  // `let` declaration with optional assignment (`var` in es5 mode)
  let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
  }

  // `var` declaration with optional assignment
  var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
  }

  // assignment code
  assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
    return this._leafNode(new Assign(lhs, rhs, sideEffects))
  }

  // `+=` code
  add(lhs: Code, rhs: SafeExpr): CodeGen {
    return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
  }

  // appends passed SafeExpr to code or executes Block
  code(c: Block | SafeExpr): CodeGen {
    if (typeof c == "function") c()
    else if (c !== nil) this._leafNode(new AnyCode(c))
    return this
  }

  // returns code for object literal for the passed argument list of key-value pairs
  object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
    const code: CodeItem[] = ["{"]
    for (const [key, value] of keyValues) {
      if (code.length > 1) code.push(",")
      code.push(key)
      if (key !== value || this.opts.es5) {
        code.push(":")
        addCodeArg(code, value)
      }
    }
    code.push("}")
    return new _Code(code)
  }

  // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
  if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
    this._blockNode(new If(condition))

    if (thenBody && elseBody) {
      this.code(thenBody).else().code(elseBody).endIf()
    } else if (thenBody) {
      this.code(thenBody).endIf()
    } else if (elseBody) {
      throw new Error('CodeGen: "else" body without "then" body')
    }
    return this
  }

  // `else if` clause - invalid without `if` or after `else` clauses
  elseIf(condition: Code | boolean): CodeGen {
    return this._elseNode(new If(condition))
  }

  // `else` clause - only valid after `if` or `else if` clauses
  else(): CodeGen {
    return this._elseNode(new Else())
  }

  // end `if` statement (needed if gen.if was used only with condition)
  endIf(): CodeGen {
    return this._endBlockNode(If, Else)
  }

  private _for(node: For, forBody?: Block): CodeGen {
    this._blockNode(node)
    if (forBody) this.code(forBody).endFor()
    return this
  }

  // a generic `for` clause (or statement if `forBody` is passed)
  for(iteration: Code, forBody?: Block): CodeGen {
    return this._for(new ForLoop(iteration), forBody)
  }

  // `for` statement for a range of values
  forRange(
    nameOrPrefix: Name | string,
    from: SafeExpr,
    to: SafeExpr,
    forBody: (index: Name) => void,
    varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
  ): CodeGen {
    const name = this._scope.toName(nameOrPrefix)
    return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
  }

  // `for-of` statement (in es5 mode replace with a normal for loop)
  forOf(
    nameOrPrefix: Name | string,
    iterable: Code,
    forBody: (item: Name) => void,
    varKind: Code = varKinds.const
  ): CodeGen {
    const name = this._scope.toName(nameOrPrefix)
    if (this.opts.es5) {
      const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
      return this.forRange("_i", 0, _`${arr}.length`, (i) => {
        this.var(name, _`${arr}[${i}]`)
        forBody(name)
      })
    }
    return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
  }

  // `for-in` statement.
  // With option `ownProperties` replaced with a `for-of` loop for object keys
  forIn(
    nameOrPrefix: Name | string,
    obj: Code,
    forBody: (item: Name) => void,
    varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
  ): CodeGen {
    if (this.opts.ownProperties) {
      return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
    }
    const name = this._scope.toName(nameOrPrefix)
    return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
  }

  // end `for` loop
  endFor(): CodeGen {
    return this._endBlockNode(For)
  }

  // `label` statement
  label(label: Name): CodeGen {
    return this._leafNode(new Label(label))
  }

  // `break` statement
  break(label?: Code): CodeGen {
    return this._leafNode(new Break(label))
  }

  // `return` statement
  return(value: Block | SafeExpr): CodeGen {
    const node = new Return()
    this._blockNode(node)
    this.code(value)
    if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
    return this._endBlockNode(Return)
  }

  // `try` statement
  try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
    if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
    const node = new Try()
    this._blockNode(node)
    this.code(tryBody)
    if (catchCode) {
      const error = this.name("e")
      this._currNode = node.catch = new Catch(error)
      catchCode(error)
    }
    if (finallyCode) {
      this._currNode = node.finally = new Finally()
      this.code(finallyCode)
    }
    return this._endBlockNode(Catch, Finally)
  }

  // `throw` statement
  throw(error: Code): CodeGen {
    return this._leafNode(new Throw(error))
  }

  // start self-balancing block
  block(body?: Block, nodeCount?: number): CodeGen {
    this._blockStarts.push(this._nodes.length)
    if (body) this.code(body).endBlock(nodeCount)
    return this
  }

  // end the current self-balancing block
  endBlock(nodeCount?: number): CodeGen {
    const len = this._blockStarts.pop()
    if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
    const toClose = this._nodes.length - len
    if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
      throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
    }
    this._nodes.length = len
    return this
  }

  // `function` heading (or definition if funcBody is passed)
  func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
    this._blockNode(new Func(name, args, async))
    if (funcBody) this.code(funcBody).endFunc()
    return this
  }

  // end function definition
  endFunc(): CodeGen {
    return this._endBlockNode(Func)
  }

  optimize(n = 1): void {
    while (n-- > 0) {
      this._root.optimizeNodes()
      this._root.optimizeNames(this._root.names, this._constants)
    }
  }

  private _leafNode(node: LeafNode): CodeGen {
    this._currNode.nodes.push(node)
    return this
  }

  private _blockNode(node: StartBlockNode): void {
    this._currNode.nodes.push(node)
    this._nodes.push(node)
  }

  private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
    const n = this._currNode
    if (n instanceof N1 || (N2 && n instanceof N2)) {
      this._nodes.pop()
      return this
    }
    throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
  }

  private _elseNode(node: If | Else): CodeGen {
    const n = this._currNode
    if (!(n instanceof If)) {
      throw new Error('CodeGen: "else" without "if"')
    }
    this._currNode = n.else = node
    return this
  }

  private get _root(): Root {
    return this._nodes[0] as Root
  }

  private get _currNode(): ParentNode {
    const ns = this._nodes
    return ns[ns.length - 1]
  }

  private set _currNode(node: ParentNode) {
    const ns = this._nodes
    ns[ns.length - 1] = node
  }

  // get nodeCount(): number {
  //   return this._root.count
  // }
}

function addNames(names: UsedNames, from: UsedNames): UsedNames {
  for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
  return names
}

function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
  return from instanceof _CodeOrName ? addNames(names, from.names) : names
}

function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T
function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
  if (expr instanceof Name) return replaceName(expr)
  if (!canOptimize(expr)) return expr
  return new _Code(
    expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
      if (c instanceof Name) c = replaceName(c)
      if (c instanceof _Code) items.push(...c._items)
      else items.push(c)
      return items
    }, [])
  )

  function replaceName(n: Name): SafeExpr {
    const c = constants[n.str]
    if (c === undefined || names[n.str] !== 1) return n
    delete names[n.str]
    return c
  }

  function canOptimize(e: SafeExpr): e is _Code {
    return (
      e instanceof _Code &&
      e._items.some(
        (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
      )
    )
  }
}

function subtractNames(names: UsedNames, from: UsedNames): void {
  for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
}

export function not<T extends Code | SafeExpr>(x: T): T
export function not(x: Code | SafeExpr): Code | SafeExpr {
  return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}`
}

const andCode = mappend(operators.AND)

// boolean AND (&&) expression with the passed arguments
export function and(...args: Code[]): Code {
  return args.reduce(andCode)
}

const orCode = mappend(operators.OR)

// boolean OR (||) expression with the passed arguments
export function or(...args: Code[]): Code {
  return args.reduce(orCode)
}

type MAppend = (x: Code, y: Code) => Code

function mappend(op: Code): MAppend {
  return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
}

function par(x: Code): Code {
  return x instanceof Name ? x : _`(${x})`
}
import {_, nil, Code, Name} from "./code"

interface NameGroup {
  prefix: string
  index: number
}

export interface NameValue {
  ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure
  key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used
  code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)
}

export type ValueReference = unknown // possibly make CodeGen parameterized type on this type

class ValueError extends Error {
  readonly value?: NameValue
  constructor(name: ValueScopeName) {
    super(`CodeGen: "code" for ${name} not defined`)
    this.value = name.value
  }
}

interface ScopeOptions {
  prefixes?: Set<string>
  parent?: Scope
}

interface ValueScopeOptions extends ScopeOptions {
  scope: ScopeStore
  es5?: boolean
  lines?: boolean
}

export type ScopeStore = Record<string, ValueReference[] | undefined>

type ScopeValues = {
  [Prefix in string]?: Map<unknown, ValueScopeName>
}

export type ScopeValueSets = {
  [Prefix in string]?: Set<ValueScopeName>
}

export enum UsedValueState {
  Started,
  Completed,
}

export type UsedScopeValues = {
  [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>
}

export const varKinds = {
  const: new Name("const"),
  let: new Name("let"),
  var: new Name("var"),
}

export class Scope {
  protected readonly _names: {[Prefix in string]?: NameGroup} = {}
  protected readonly _prefixes?: Set<string>
  protected readonly _parent?: Scope

  constructor({prefixes, parent}: ScopeOptions = {}) {
    this._prefixes = prefixes
    this._parent = parent
  }

  toName(nameOrPrefix: Name | string): Name {
    return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)
  }

  name(prefix: string): Name {
    return new Name(this._newName(prefix))
  }

  protected _newName(prefix: string): string {
    const ng = this._names[prefix] || this._nameGroup(prefix)
    return `${prefix}${ng.index++}`
  }

  private _nameGroup(prefix: string): NameGroup {
    if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {
      throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`)
    }
    return (this._names[prefix] = {prefix, index: 0})
  }
}

interface ScopePath {
  property: string
  itemIndex: number
}

export class ValueScopeName extends Name {
  readonly prefix: string
  value?: NameValue
  scopePath?: Code

  constructor(prefix: string, nameStr: string) {
    super(nameStr)
    this.prefix = prefix
  }

  setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
    this.value = value
    this.scopePath = _`.${new Name(property)}[${itemIndex}]`
  }
}

interface VSOptions extends ValueScopeOptions {
  _n: Code
}

const line = _`\n`

export class ValueScope extends Scope {
  protected readonly _values: ScopeValues = {}
  protected readonly _scope: ScopeStore
  readonly opts: VSOptions

  constructor(opts: ValueScopeOptions) {
    super(opts)
    this._scope = opts.scope
    this.opts = {...opts, _n: opts.lines ? line : nil}
  }

  get(): ScopeStore {
    return this._scope
  }

  name(prefix: string): ValueScopeName {
    return new ValueScopeName(prefix, this._newName(prefix))
  }

  value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {
    if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value")
    const name = this.toName(nameOrPrefix) as ValueScopeName
    const {prefix} = name
    const valueKey = value.key ?? value.ref
    let vs = this._values[prefix]
    if (vs) {
      const _name = vs.get(valueKey)
      if (_name) return _name
    } else {
      vs = this._values[prefix] = new Map()
    }
    vs.set(valueKey, name)

    const s = this._scope[prefix] || (this._scope[prefix] = [])
    const itemIndex = s.length
    s[itemIndex] = value.ref
    name.setValue(value, {property: prefix, itemIndex})
    return name
  }

  getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
    const vs = this._values[prefix]
    if (!vs) return
    return vs.get(keyOrRef)
  }

  scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {
    return this._reduceValues(values, (name: ValueScopeName) => {
      if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
      return _`${scopeName}${name.scopePath}`
    })
  }

  scopeCode(
    values: ScopeValues | ScopeValueSets = this._values,
    usedValues?: UsedScopeValues,
    getCode?: (n: ValueScopeName) => Code | undefined
  ): Code {
    return this._reduceValues(
      values,
      (name: ValueScopeName) => {
        if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
        return name.value.code
      },
      usedValues,
      getCode
    )
  }

  private _reduceValues(
    values: ScopeValues | ScopeValueSets,
    valueCode: (n: ValueScopeName) => Code | undefined,
    usedValues: UsedScopeValues = {},
    getCode?: (n: ValueScopeName) => Code | undefined
  ): Code {
    let code: Code = nil
    for (const prefix in values) {
      const vs = values[prefix]
      if (!vs) continue
      const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())
      vs.forEach((name: ValueScopeName) => {
        if (nameSet.has(name)) return
        nameSet.set(name, UsedValueState.Started)
        let c = valueCode(name)
        if (c) {
          const def = this.opts.es5 ? varKinds.var : varKinds.const
          code = _`${code}${def} ${name} = ${c};${this.opts._n}`
        } else if ((c = getCode?.(name))) {
          code = _`${code}${c}${this.opts._n}`
        } else {
          throw new ValueError(name)
        }
        nameSet.set(name, UsedValueState.Completed)
      })
    }
    return code
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const dynamic_1 = require("./vocabularies/dynamic");
const next_1 = require("./vocabularies/next");
const unevaluated_1 = require("./vocabularies/unevaluated");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
class Ajv2019 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(dynamic_1.default);
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        this.addVocabulary(next_1.default);
        this.addVocabulary(unevaluated_1.default);
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2019_09_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2019 = Ajv2019;
module.exports = exports = Ajv2019;
module.exports.Ajv2019 = Ajv2019;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2019;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2019.js.map{"version":3,"file":"2019.js","sourceRoot":"","sources":["../lib/2019.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,kDAAsD;AACtD,oDAAsD;AACtD,8CAAgD;AAChD,4DAA8D;AAC9D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ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AIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;
const core_1 = require("./core");
const draft2020_1 = require("./vocabularies/draft2020");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2020_12_1 = require("./refs/json-schema-2020-12");
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
class Ajv2020 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2020_12_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2020 = Ajv2020;
module.exports = exports = Ajv2020;
module.exports.Ajv2020 = Ajv2020;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2020;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2020.js.map{"version":3,"file":"2020.js","sourceRoot":"","sources":["../lib/2020.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,wDAA4D;AAC5D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,mBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAC3D,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa;YAAE,IAAI,CAAC,UAAU,CAAC,uBAAa,CAAC,CAAA;IAC7D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,MAAM,EAAC,KAAK,EAAE,IAAI,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;QAC/B,IAAI,CAAC,IAAI;YAAE,OAAM;QACjB,6BAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACnC,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AA5BD,0BA4BC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAClC,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAA;AAChC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const discriminator_1 = require("./vocabularies/discriminator");
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
    _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        const metaSchema = this.opts.$data
            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
            : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=ajv.js.map{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../lib/ajv.ts"],"names":[],"mappings":";;;AACA,iCAA4B;AAC5B,kDAAsD;AACtD,gEAAwD;AACxD,qEAAoE;AAEp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AC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error",
]);
const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now.",
};
const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver: uriResolver,
    };
}
class Ajv {
    constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = Object.create(null);
        this._compilations = new Set();
        this._loading = {};
        this._cache = new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
            addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
        this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
            _dataRefSchema = { ...$dataRefSchema };
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
        }
        if (meta && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
        const { meta, schemaId } = this.opts;
        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
    }
    validate(schemaKeyRef, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data // to be validated
    ) {
        let v;
        if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        }
        else {
            v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
            this.errors = v.errors;
        return valid;
    }
    compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
            await loadMetaSchema.call(this, _schema.$schema);
            const sch = this._addSchema(_schema, _meta);
            return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
            if ($ref && !this.getSchema($ref)) {
                await runCompileAsync.call(this, { $ref }, true);
            }
        }
        async function _compileAsync(sch) {
            try {
                return this._compileSchemaEnv(sch);
            }
            catch (e) {
                if (!(e instanceof ref_error_1.default))
                    throw e;
                checkLoaded.call(this, e);
                await loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
            }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
            if (this.refs[ref]) {
                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
            }
        }
        async function loadMissingSchema(ref) {
            const _schema = await _loadSchema.call(this, ref);
            if (!this.refs[ref])
                await loadMetaSchema.call(this, _schema.$schema);
            if (!this.refs[ref])
                this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
            const p = this._loading[ref];
            if (p)
                return p;
            try {
                return await (this._loading[ref] = loadSchema(ref));
            }
            finally {
                delete this._loading[ref];
            }
        }
    }
    // Adds schema to the instance
    addSchema(schema, // If array is passed, `key` will be ignored
    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
    ) {
        if (Array.isArray(schema)) {
            for (const sch of schema)
                this.addSchema(sch, undefined, _meta, _validateSchema);
            return this;
        }
        let id;
        if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id = schema[schemaId];
            if (id !== undefined && typeof id != "string") {
                throw new Error(`schema ${schemaId} must be string`);
            }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
    ) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
            return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != "string") {
            throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
        if (sch === undefined) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
                return;
            this.refs[keyRef] = sch;
        }
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case "undefined":
                this._removeAllSchemas(this.schemas);
                this._removeAllSchemas(this.refs);
                this._cache.clear();
                return this;
            case "string": {
                const sch = getSchEnv.call(this, schemaKeyRef);
                if (typeof sch == "object")
                    this._cache.delete(sch.schema);
                delete this.schemas[schemaKeyRef];
                delete this.refs[schemaKeyRef];
                return this;
            }
            case "object": {
                const cacheKey = schemaKeyRef;
                this._cache.delete(cacheKey);
                let id = schemaKeyRef[this.opts.schemaId];
                if (id) {
                    id = (0, resolve_1.normalizeId)(id);
                    delete this.schemas[id];
                    delete this.refs[id];
                }
                return this;
            }
            default:
                throw new Error("ajv.removeSchema: invalid parameter");
        }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions) {
        for (const def of definitions)
            this.addKeyword(def);
        return this;
    }
    addKeyword(kwdOrDef, def // deprecated
    ) {
        let keyword;
        if (typeof kwdOrDef == "string") {
            keyword = kwdOrDef;
            if (typeof def == "object") {
                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
                def.keyword = keyword;
            }
        }
        else if (typeof kwdOrDef == "object" && def === undefined) {
            def = kwdOrDef;
            keyword = def.keyword;
            if (Array.isArray(keyword) && !keyword.length) {
                throw new Error("addKeywords: keyword must be string or non-empty array");
            }
        }
        else {
            throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
            return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
            ...def,
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0
            ? (k) => addRule.call(this, k, definition)
            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        return this;
    }
    getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword) {
        // TODO return type should be Ajv
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
            if (i >= 0)
                group.rules.splice(i, 1);
        }
        return this;
    }
    // Add format
    addFormat(name, format) {
        if (typeof format == "string")
            format = new RegExp(format);
        this.formats[name] = format;
        return this;
    }
    errorsText(errors = this.errors, // optional array of validation errors
    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
    ) {
        if (!errors || errors.length === 0)
            return "No errors";
        return errors
            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
            .reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
            let keywords = metaSchema;
            for (const seg of segments)
                keywords = keywords[seg];
            for (const key in rules) {
                const rule = rules[key];
                if (typeof rule != "object")
                    continue;
                const { $data } = rule.definition;
                const schema = keywords[key];
                if ($data && schema)
                    keywords[key] = schemaOrData(schema);
            }
        }
        return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
                if (typeof sch == "string") {
                    delete schemas[keyRef];
                }
                else if (sch && !sch.meta) {
                    this._cache.delete(sch.schema);
                    delete schemas[keyRef];
                }
            }
        }
    }
    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
            id = schema[schemaId];
        }
        else {
            if (this.opts.jtd)
                throw new Error("schema must be object");
            else if (typeof schema != "boolean")
                throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== undefined)
            return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
            if (baseId)
                this._checkUnique(baseId);
            this.refs[baseId] = sch;
        }
        if (validateSchema)
            this.validateSchema(schema, true);
        return sch;
    }
    _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
            throw new Error(`schema with key or id "${id}" already exists`);
        }
    }
    _compileSchemaEnv(sch) {
        if (sch.meta)
            this._compileMetaSchema(sch);
        else
            compile_1.compileSchema.call(this, sch);
        /* istanbul ignore if */
        if (!sch.validate)
            throw new Error("ajv implementation error");
        return sch.validate;
    }
    _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
            compile_1.compileSchema.call(this, sch);
        }
        finally {
            this.opts = currentOpts;
        }
    }
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
    for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
}
function getSchEnv(keyRef) {
    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
    return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
        return;
    if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
    else
        for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
    for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
            this.addFormat(name, format);
    }
}
function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
            def.keyword = keyword;
        this.addKeyword(def);
    }
}
function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
    return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
    if (logger === false)
        return noLogs;
    if (logger === undefined)
        return console;
    if (logger.log && logger.warn && logger.error)
        return logger;
    throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
    const { RULES } = this;
    (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def)
        return;
    if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
    }
}
function addRule(keyword, definition, dataType) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
    if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword] = true;
    if (!definition)
        return;
    const rule = {
        keyword,
        definition: {
            ...definition,
            type: (0, dataType_1.getJSONTypes)(definition.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
        },
    };
    if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
        ruleGroup.rules.push(rule);
    RULES.all[keyword] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
    }
    else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
    }
}
function keywordMetaschema(def) {
    let { metaSchema } = def;
    if (metaSchema === undefined)
        return;
    if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
    def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map{"version":3,"file":"core.js","sourceRoot":"","sources":["../lib/core.ts"],"names":[],"mappings":";;;AA4BA,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAKl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C,CAAA;IACxE,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACX,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAA;IACpC,CAAC;SAAM,CAAC;QACN,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,MAAM,iBAAiB,CAAC,CAAA;IACnD,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAY,GAAsB;IAC1D,IAAI,EAAC,UAAU,EAAC,GAAG,GAAG,CAAA;IACtB,IAAI,UAAU,KAAK,SAAS;QAAE,OAAM;IACpC,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;QAAE,UAAU,GAAG,YAAY,CAAC,UAAU,CAAC,CAAA;IACvE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACrD,CAAC;AAED,MAAM,QAAQ,GAAG;IACf,IAAI,EAAE,gFAAgF;CACvF,CAAA;AAED,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,EAAC,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAC,CAAA;AACpC,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const jtd_1 = require("./vocabularies/jtd");
const jtd_schema_1 = require("./refs/jtd-schema");
const serialize_1 = require("./compile/jtd/serialize");
const parse_1 = require("./compile/jtd/parse");
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            jtd: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(jtd_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
    compileSerializer(schema) {
        const sch = this._addSchema(schema);
        return sch.serialize || this._compileSerializer(sch);
    }
    compileParser(schema) {
        const sch = this._addSchema(schema);
        return (sch.parse || this._compileParser(sch));
    }
    _compileSerializer(sch) {
        serialize_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.serialize)
            throw new Error("ajv implementation error");
        return sch.serialize;
    }
    _compileParser(sch) {
        parse_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.parse)
            throw new Error("ajv implementation error");
        return sch.parse;
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceM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iB,CAAA;IAChE,CAAC;IAEO,kBAAkB,CAAI,GAAc;QAC1C,mBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAG,GAAG,CAAC,MAA0B,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;QACpF,wBAAwB;QACxB,IAAI,CAAC,GAAG,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC/D,OAAO,GAAG,CAAC,SAAS,CAAA;IACtB,CAAC;IAEO,cAAc,CAAC,GAAc;QACnC,eAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAG,GAAG,CAAC,MAA0B,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;QAChF,wBAAwB;QACxB,IAAI,CAAC,GAAG,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC3D,OAAO,GAAG,CAAC,KAAK,CAAA;IAClB,CAAC;CACF;AAvDD,kBAuDC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,GAAG,CAAA;AAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAA;AACxB,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAElB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAInD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = require("../compile/codegen");
const util_1 = require("../compile/util");
const names_1 = require("../compile/names");
const util_2 = require("../compile/util");
function checkReportMissingProp(cxt, prop) {
    const { gen, data, it } = cxt;
    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
        cxt.error();
    });
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
    return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
    });
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
    const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData],
    ];
    if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
    const u = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern, u);
    return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
    });
}
exports.usePattern = usePattern;
function validateArray(cxt) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
                keyword,
                dataProp: i,
                dataPropType: util_1.Type.Num,
            }, valid);
            gen.if((0, codegen_1.not)(valid), notValid);
        });
    }
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
    const { gen, schema, keyword, it } = cxt;
    /* istanbul ignore if */
    if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
    if (alwaysValid && !it.opts.unevaluated)
        return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
            keyword,
            schemaProp: i,
            compositeRule: true,
        }, schValid);
        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
        // or if all properties and items were evaluated (it.props === true && it.items === true)
        if (!merged)
            gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../lib/vocabularies/code.ts"],"names":[],"mappings":";;;AAGA,gDAAoG;AACpG,0CAAuD;AACvD,4CAAgC;AAChC,0CAAuC;AACvC,SAAgB,sBAAsB,CAAC,GAAe,EAAE,IAAY;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,GAAG,CAAC,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE;QACpE,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,EAAE,EAAC,EAAE,IAAI,CAAC,CAAA;QAClD,GAAG,CAAC,KAAK,EAAE,CAAA;IACb,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AG,CAAC,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACxD,+FAA+F;QAC/F,yFAAyF;QACzF,IAAI,CAAC,MAAM;YAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,CAAC,CAAA;IACjC,CAAC,CAAC,CACH,CAAA;IAED,GAAG,CAAC,MAAM,CACR,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CACtB,CAAA;AACH,CAAC;AAjCD,sCAiCC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const dynamic_1 = require("./dynamic");
const next_1 = require("./next");
const unevaluated_1 = require("./unevaluated");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft2020Vocabularies = [
    dynamic_1.default,
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(true),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
    next_1.default,
    unevaluated_1.default,
];
exports.default = draft2020Vocabularies;
//# sourceMappingURL=draft2020.js.map{"version":3,"file":"draft2020.js","sourceRoot":"","sources":["../../lib/vocabularies/draft2020.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,uCAAyC;AACzC,iCAAmC;AACnC,+CAAiD;AACjD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,qBAAqB,GAAiB;IAC1C,iBAAiB;IACjB,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,EAAC,IAAI,CAAC;IAC7B,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;IACjB,cAAc;IACd,qBAAqB;CACtB,CAAA;AAED,kBAAe,qBAAqB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
];
exports.default = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map{"version":3,"file":"draft7.js","sourceRoot":"","sources":["../../lib/vocabularies/draft7.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,kBAAkB,GAAiB;IACvC,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,GAAE;IACzB,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;CAClB,CAAA;AAED,kBAAe,kBAAkB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/vocabularies/errors.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples",
];
exports.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema",
];
//# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../lib/vocabularies/metadata.ts"],"names":[],"mappings":";;;AAEa,QAAA,kBAAkB,GAAe;IAC5C,OAAO;IACP,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU;IACV,WAAW;IACX,UAAU;CACX,CAAA;AAEY,QAAA,iBAAiB,GAAe;IAC3C,kBAAkB;IAClB,iBAAiB;IACjB,eAAe;CAChB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependentRequired_1 = require("./validation/dependentRequired");
const dependentSchemas_1 = require("./applicator/dependentSchemas");
const limitContains_1 = require("./validation/limitContains");
const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
exports.default = next;
//# sourceMappingURL=next.js.map{"version":3,"file":"next.js","sourceRoot":"","sources":["../../lib/vocabularies/next.ts"],"names":[],"mappings":";;AACA,sEAA8D;AAC9D,oEAA4D;AAC5D,8DAAsD;AAEtD,MAAM,IAAI,GAAe,CAAC,2BAAiB,EAAE,0BAAgB,EAAE,uBAAa,CAAC,CAAA;AAE7E,kBAAe,IAAI,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || (schema && typeof schema == "object")) {
            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        }
        else {
            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=const.js.map{"version":3,"file":"const.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/const.ts"],"names":[],"mappings":";;AAEA,mDAAuC;AACvC,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,2BAA2B;IACpC,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,UAAU,GAAG;CAC3D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAClD,IAAI,KAAK,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,EAAE,CAAC;YACnD,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,IAAI,IAAI,KAAK,UAAU,GAAG,CAAC,CAAA;QACnE,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,QAAQ,IAAI,EAAE,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("../applicator/dependencies");
const def = {
    keyword: "dependentRequired",
    type: "object",
    schemaType: "object",
    error: dependencies_1.error,
    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentRequired.js.map{"version":3,"file":"dependentRequired.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/dependentRequired.ts"],"names":[],"mappings":";;AACA,6DAKmC;AAQnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,oBAAK;IACL,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,mCAAoB,EAAC,GAAG,CAAC;CACzC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
            throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
        let valid;
        if (useLoop || $data) {
            valid = gen.let("valid");
            cxt.block$data(valid, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            const vSchema = gen.const("vSchema", schemaCode);
            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.assign(valid, false);
            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i) {
            const sch = schema[i];
            return typeof sch === "object" && sch !== null
                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
                : (0, codegen_1._) `${data} === ${sch}`;
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/enum.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IA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AK,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC,CAC7E,CAAA;QACH,CAAC;QAED,SAAS,SAAS,CAAC,OAAa,EAAE,CAAS;YACzC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;YACrB,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI;gBAC5C,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,EAAE,IAAI,IAAI,KAAK,OAAO,IAAI,CAAC,IAAI;gBAC3C,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,QAAQ,GAAG,EAAE,CAAA;QAC3B,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const limitNumber_1 = require("./limitNumber");
const multipleOf_1 = require("./multipleOf");
const limitLength_1 = require("./limitLength");
const pattern_1 = require("./pattern");
const limitProperties_1 = require("./limitProperties");
const required_1 = require("./required");
const limitItems_1 = require("./limitItems");
const uniqueItems_1 = require("./uniqueItems");
const const_1 = require("./const");
const enum_1 = require("./enum");
const validation = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default,
];
exports.default = validation;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/index.ts"],"names":[],"mappings":";;AACA,+CAA2D;AAC3D,6CAAwD;AACxD,+CAAuC;AACvC,uCAA+C;AAC/C,uDAA+C;AAC/C,yCAAkD;AAClD,6CAAqC;AACrC,+CAA2D;AAC3D,mCAAgD;AAChD,iCAA6C;AAE7C,MAAM,UAAU,GAAe;IAC7B,SAAS;IACT,qBAAW;IACX,oBAAU;IACV,SAAS;IACT,qBAAW;IACX,iBAAO;IACP,SAAS;IACT,yBAAe;IACf,kBAAQ;IACR,QAAQ;IACR,oBAAU;IACV,qBAAW;IACX,MAAM;IACN,EAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAC;IAClD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;IAC5C,eAAY;IACZ,cAAW;CACZ,CAAA;AAED,kBAAe,UAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["maxContains", "minContains"],
    type: "array",
    schemaType: "number",
    code({ keyword, parentSchema, it }) {
        if (parentSchema.contains === undefined) {
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=limitContains.js.map{"version":3,"file":"limitContains.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitContains.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC;IACvC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACxC,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,iCAAiC,CAAC,CAAA;QACnE,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitItems.js.map{"version":3,"file":"limitItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitItems.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACtD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,QAAQ,CAAA;IAC5D,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;IACjC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAC/D,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACtD,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const ucs2length_1 = require("../../runtime/ucs2length");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitLength.js.map{"version":3,"file":"limitLength.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitLength.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,yDAAiD;AAEjD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACvD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC;IACnC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC3C,MAAM,EAAE,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAChE,MAAM,GAAG,GACP,EAAE,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAA,cAAO,EAAC,GAAG,CAAC,GAAG,EAAE,oBAAU,CAAC,IAAI,IAAI,GAAG,CAAA;QAC7F,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,IAAI,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IAC9C,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
    },
};
exports.default = def;
//# sourceMappingURL=limitNumber.js.map{"version":3,"file":"limitNumber.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitNumber.ts"],"names":[],"mappings":";;AAEA,mDAA6D;AAE7D,MAAM,GAAG,GAAG,mBAAS,CAAA;AAMrB,MAAM,IAAI,GAA4D;IACpE,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IACzD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAC1D,CAAA;AAQD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,WAAW,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,IAAI,UAAU,EAAE;IAC5F,MAAM,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAChC,IAAA,WAAC,EAAA,gBAAgB,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,YAAY,UAAU,GAAG;CACvE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;IAC1B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,IAAI,CAAC,OAAc,CAAC,CAAC,IAAI,IAAI,UAAU,aAAa,IAAI,GAAG,CAAC,CAAA;IACxF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitProperties.js.map{"version":3,"file":"limitProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitProperties.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QAC3D,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC;IAC3C,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QACpE,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,eAAe,IAAI,YAAY,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACnE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec
            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
            : (0, codegen_1._) `${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
    },
};
exports.default = def;
//# sourceMappingURL=multipleOf.js.map{"version":3,"file":"multipleOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/multipleOf.ts"],"names":[],"mappings":";;AAEA,mDAA4C;AAQ5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,EAAE;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,gBAAgB,UAAU,GAAG;CACzD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACvC,sEAAsE;QACtE,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAA;QACxC,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,MAAM,OAAO,GAAG,IAAI;YAClB,CAAC,CAAC,IAAA,WAAC,EAAA,uBAAuB,GAAG,OAAO,GAAG,UAAU,IAAI,EAAE;YACvD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,iBAAiB,GAAG,GAAG,CAAA;QAClC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,UAAU,cAAc,GAAG,MAAM,IAAI,IAAI,UAAU,KAAK,OAAO,IAAI,CAAC,CAAA;IACzF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
            const { regExp } = it.opts.code;
            const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);
            const valid = gen.let("valid");
            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
            cxt.fail$data((0, codegen_1._) `!${valid}`);
        }
        else {
            const regExp = (0, code_1.usePattern)(cxt, schema);
            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=pattern.js.map{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/pattern.ts"],"names":[],"mappings":";;AAEA,kCAAkC;AAClC,6CAA0C;AAC1C,mDAA4C;AAI5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,GAAG;IAClE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,aAAa,UAAU,GAAG;CACtD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;QAC1C,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,EAAC,MAAM,EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAA;YAC7B,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,YAAY,CAAC,CAAC,CAAC,IAAA,cAAO,EAAC,GAAG,EAAE,MAAM,CAAC,CAAA;YACtF,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;YAC9B,GAAG,CAAC,GAAG,CACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,UAAU,IAAI,UAAU,KAAK,CAAC,UAAU,IAAI,GAAG,CAAC,EAC5E,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAC/B,CAAA;YACD,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,KAAK,EAAE,CAAC,CAAA;QAC7B,CAAC;aAAM,CAAC;YACN,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,GAAG,EAAE,MAAM,CAAC,CAAA;YACtC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,MAAM,SAAS,IAAI,GAAG,CAAC,CAAA;QAC5C,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
            return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
            allErrorsMode();
        else
            exitOnErrorMode();
        if (opts.strictRequired) {
            const props = cxt.parentSchema.properties;
            const { definedProperties } = cxt.it;
            for (const requiredKey of schema) {
                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
                }
            }
        }
        function allErrorsMode() {
            if (useLoop || $data) {
                cxt.block$data(codegen_1.nil, loopAllRequired);
            }
            else {
                for (const prop of schema) {
                    (0, code_1.checkReportMissingProp)(cxt, prop);
                }
            }
        }
        function exitOnErrorMode() {
            const missing = gen.let("missing");
            if (useLoop || $data) {
                const valid = gen.let("valid", true);
                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
                cxt.ok(valid);
            }
            else {
                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
                (0, code_1.reportMissingProp)(cxt, missing);
                gen.else();
            }
        }
        function loopAllRequired() {
            gen.forOf("prop", schemaCode, (prop) => {
                cxt.setParams({ missingProperty: prop });
                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
            });
        }
        function loopUntilMissing(missing, valid) {
            cxt.setParams({ missingProperty: missing });
            gen.forOf(missing, schemaCode, () => {
                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
                gen.if((0, codegen_1.not)(valid), () => {
                    cxt.error();
                    gen.break();
                });
            }, codegen_1.nil);
        }
    },
};
exports.default = def;
//# sourceMappingURL=required.js.map{"version":3,"file":"required.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/required.ts"],"names":[],"mappings":";;AAEA,kCAMgB;AAChB,mDAAkE;AAClE,6CAAkD;AAQlD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,gCAAgC,eAAe,GAAG;IAC/F,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EA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CAAC,KAAK,EAAE,CAAC,CAAA;YAClF,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,SAAS,gBAAgB,CAAC,OAAa,EAAE,KAAW;YAClD,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,GAAG,CAAC,KAAK,CACP,OAAO,EACP,UAAkB,EAClB,GAAG,EAAE;gBACH,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAA;gBACzE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;oBACtB,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,KAAK,EAAE,CAAA;gBACb,CAAC,CAAC,CAAA;YACJ,CAAC,EACD,aAAG,CACJ,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dataType_1 = require("../../compile/validate/dataType");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
            return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
            const j = gen.let("j");
            cxt.setParams({ i, j });
            gen.assign(valid, true);
            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        function canOptimize() {
            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i, j) {
            const item = gen.name("item");
            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
            const indices = gen.const("indices", (0, codegen_1._) `{}`);
            gen.for((0, codegen_1._) `;${i}--;`, () => {
                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
                gen.if(wrongType, (0, codegen_1._) `continue`);
                if (itemTypes.length > 1)
                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
                gen
                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
                    cxt.error();
                    gen.assign(valid, false).break();
                })
                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
            });
        }
        function loopN2(i, j) {
            const eql = (0, util_1.useFunc)(gen, equal_1.default);
            const outer = gen.name("outer");
            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
                cxt.error();
                gen.assign(valid, false).break(outer);
            })));
        }
    },
};
exports.default = def;
//# sourceMappingURL=uniqueItems.js.map{"version":3,"file":"uniqueItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/uniqueItems.ts"],"names":[],"mappings":";;AAEA,8DAAwF;AACxF,mDAAkD;AAClD,6CAA0C;AAC1C,+CAAuC;AAQvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,CAAC,EAAE,CAAC,EAAC,EAAC,EAAE,EAAE,CAC5B,IAAA,aAAG,EAAA,2CA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AAe,EAAE,GAAG,EAAE;oBAClD,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,IAAI,IAAI,GAAG,CAAC,CAAA;oBACrC,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,EAAE,CAAA;gBAClC,CAAC,CAAC;qBACD,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,OAAO,IAAI,IAAI,OAAO,CAAC,EAAE,CAAC,CAAA;YACxC,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,SAAS,MAAM,CAAC,CAAO,EAAE,CAAO;YAC9B,MAAM,GAAG,GAAG,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,CAAA;YAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAC/B,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,IAAA,WAAC,EAAA,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CACrC,GAAG,CAAC,GAAG,CAAC,IAAA,WAAC,EAAA,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CACpC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,IAAI,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE;gBACnD,GAAG,CAAC,KAAK,EAAE,CAAA;gBACX,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC,CAAC,CACH,CACF,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unevaluatedProperties_1 = require("./unevaluatedProperties");
const unevaluatedItems_1 = require("./unevaluatedItems");
const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
exports.default = unevaluated;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/index.ts"],"names":[],"mappings":";;AACA,mEAA2D;AAC3D,yDAAiD;AAEjD,MAAM,WAAW,GAAe,CAAC,+BAAqB,EAAE,0BAAgB,CAAC,CAAA;AAEzE,kBAAe,WAAW,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "unevaluatedItems",
    type: "array",
    schemaType: ["boolean", "object"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        const items = it.items || 0;
        if (items === true)
            return;
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        if (schema === false) {
            cxt.setParams({ len: items });
            cxt.fail((0, codegen_1._) `${len} > ${items}`);
        }
        else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`);
            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
            cxt.ok(valid);
        }
        it.items = true;
        function validateItems(valid, from) {
            gen.forRange("i", from, len, (i) => {
                cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
                if (!it.allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedItems.js.map{"version":3,"file":"unevaluatedItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedItems.ts"],"names":[],"mappings":";;AAOA,mDAAuD;AACvD,6CAA0D;AAI1D,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,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AK,EAAE,KAAK,CAAC,CAAC,CAAA;YACrD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACf,CAAC;QACD,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QAEf,SAAS,aAAa,CAAC,KAAW,EAAE,IAAmB;YACrD,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;gBACjC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;gBACxF,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YAC1D,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const names_1 = require("../../compile/names");
const error = {
    message: "must NOT have unevaluated properties",
    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,
};
const def = {
    keyword: "unevaluatedProperties",
    type: "object",
    schemaType: ["boolean", "object"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, props } = it;
        if (props instanceof codegen_1.Name) {
            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
        }
        else if (props !== true) {
            gen.forIn("key", data, (key) => props === undefined
                ? unevaluatedPropCode(key)
                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
        }
        it.props = true;
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function unevaluatedPropCode(key) {
            if (schema === false) {
                cxt.setParams({ unevaluatedProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (!(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                cxt.subschema({
                    keyword: "unevaluatedProperties",
                    dataProp: key,
                    dataPropType: util_1.Type.Str,
                }, valid);
                if (!allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
        }
        function unevaluatedDynamic(evaluatedProps, key) {
            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;
        }
        function unevaluatedStatic(evaluatedProps, key) {
            const ps = [];
            for (const p in evaluatedProps) {
                if (evaluatedProps[p] === true)
                    ps.push((0, codegen_1._) `${key} !== ${p}`);
            }
            return (0, codegen_1.and)(...ps);
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedProperties.js.map{"version":3,"file":"unevaluatedProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedProperties.ts"],"names":[],"mappings":";;AAMA,mDAA6D;AAC7D,6CAA0D;AAC1D,+CAAmC;AAQnC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,sCAAsC;IAC/C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,yBAAyB,MAAM,CAAC,mBAAmB,GAAG;CAC9E,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,uBAAuB;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAG;QACN,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAC,GAAG,GAAG,CAA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GAAG,CAAC,KAAK,EAAE,CAAA;gBAC3B,OAAM;YACR,CAAC;YAED,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;gBACnC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;gBAC/B,GAAG,CAAC,SAAS,CACX;oBACE,OAAO,EAAE,uBAAuB;oBAChC,QAAQ,EAAE,GAAG;oBACb,YAAY,EAAE,WAAI,CAAC,GAAG;iBACvB,EACD,KAAK,CACN,CAAA;gBACD,IAAI,CAAC,SAAS;oBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YACvD,CAAC;QACH,CAAC;QAED,SAAS,kBAAkB,CAAC,cAAoB,EAAE,GAAS;YACzD,OAAO,IAAA,WAAC,EAAA,IAAI,cAAc,QAAQ,cAAc,IAAI,GAAG,GAAG,CAAA;QAC5D,CAAC;QAED,SAAS,iBAAiB,CAAC,cAAsC,EAAE,GAAS;YAC1E,MAAM,EAAE,GAAW,EAAE,CAAA;YACrB,KAAK,MAAM,CAAC,IAAI,cAAc,EAAE,CAAC;gBAC/B,IAAI,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI;oBAAE,EAAE,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAA;YAC7D,CAAC;YACD,OAAO,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,CAAA;QACnB,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const types_1 = require("../discriminator/types");
const error = {
    message: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? params.discrError === types_1.DiscrError.Tag
                ? `tag "${schema}" must be string`
                : `value of tag "${schema}" must be in mapping`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "discriminator",
    schemaType: "string",
    implements: ["mapping"],
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, parentSchema } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        gen.if(cond);
        validateDiscriminator();
        gen.elseIf((0, codegen_1.not)(valid));
        cxt.error();
        gen.endIf();
        cxt.ok(valid);
        function validateDiscriminator() {
            const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`);
            gen.if((0, codegen_1._) `${tag} === undefined`);
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag });
            gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`);
            validateMapping(tag);
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema });
            gen.endIf();
        }
        function validateMapping(tag) {
            gen.if(false);
            for (const tagValue in parentSchema.mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(tagValue));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            cxt.subschema({
                keyword: "mapping",
                schemaProp,
                jtdDiscriminator: schema,
            }, _valid);
            return _valid;
        }
    },
};
exports.default = def;
//# sourceMappingURL=discriminator.js.map{"version":3,"file":"discriminator.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/discriminator.ts"],"names":[],"mappings":";;AAEA,mDA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,EAAE,CAAA;YACV,GAAG,CAAC,KAAK,CACP,KAAK,EACL,EAAC,UAAU,EAAE,kBAAU,CAAC,OAAO,EAAE,GAAG,EAAC,EACrC,EAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAC,CAClE,CAAA;YACD,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,cAAc,CAAC,UAAkB;YACxC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAChC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,SAAS;gBAClB,UAAU;gBACV,gBAAgB,EAAE,MAAM;aACzB,EACD,MAAM,CACP,CAAA;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "elements",
    schemaType: "object",
    error: (0, error_1.typeError)("array"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const [valid] = (0, nullable_1.checkNullable)(cxt);
        gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error()));
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=elements.js.map{"version":3,"file":"elements.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/elements.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AACpD,kCAAqC;AACrC,mDAA4C;AAC5C,yCAAwC;AACxC,yCAAwC;AACxC,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,OAAO,CAAC;IACzB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CACtB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,iBAAiB,IAAI,GAAG,EACzB,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,EAC3C,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
        if (schema.length === 0)
            throw new Error("enum must have non-empty array");
        if (schema.length !== new Set(schema).size)
            throw new Error("enum items must be unique");
        let valid;
        const isString = (0, codegen_1._) `typeof ${data} == "string"`;
        if (schema.length >= it.opts.loopEnum) {
            let cond;
            [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString);
            gen.if(cond, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`)));
            if (parentSchema.nullable)
                valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid);
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break()));
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/enum.ts"],"names":[],"mappings":";;AAEA,mDAAsD;AACtD,yCAAwC;AACxC,yCAAwC;AAIxC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,OAAO;IACnB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC9D,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;QAC1E,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QACxF,IAAI,KAAW,CAAA;QACf,MAAM,QAAQ,GAAG,IAAA,WAAC,EAAA,UAAU,IAAI,cAAc,CAAA;QAC9C,IAAI,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACtC,IAAI,IAAU,CACb;YAAA,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YAC7C,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;QACxB,CAAC;aAAM,CAAC;YACN,wBAAwB;YACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;YACvE,KAAK,GAAG,IAAA,aAAG,EAAC,QAAQ,EAAE,IAAA,YAAE,EAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,CAAA;YACpF,IAAI,YAAY,CAAC,QAAQ;gBAAE,KAAK,GAAG,IAAA,YAAE,EAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,KAAK,CAAC,CAAA;QACnE,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAEf,SAAS,QAAQ;YACf,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,WAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CACxC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,IAAI,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAC1D,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0;
const codegen_1 = require("../../compile/codegen");
function typeError(t) {
    return {
        message: (cxt) => typeErrorMessage(cxt, t),
        params: (cxt) => typeErrorParams(cxt, t),
    };
}
exports.typeError = typeError;
function typeErrorMessage({ parentSchema }, t) {
    return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`;
}
exports.typeErrorMessage = typeErrorMessage;
function typeErrorParams({ parentSchema }, t) {
    return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`;
}
exports.typeErrorParams = typeErrorParams;
//# sourceMappingURL=error.js.map{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/error.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAQ7C,SAAgB,SAAS,CAAC,CAAS;IACjC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;KACzC,CAAA;AACH,CAAC;AALD,8BAKC;AAED,SAAgB,gBAAgB,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACzE,OAAO,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAA;AACzE,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACxE,OAAO,IAAA,WAAC,EAAA,UAAU,CAAC,eAAe,CAAC,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,CAAA,GAAG,CAAA;AAC/D,CAAC;AAFD,0CAEC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ref_1 = require("./ref");
const type_1 = require("./type");
const enum_1 = require("./enum");
const elements_1 = require("./elements");
const properties_1 = require("./properties");
const optionalProperties_1 = require("./optionalProperties");
const discriminator_1 = require("./discriminator");
const values_1 = require("./values");
const union_1 = require("./union");
const metadata_1 = require("./metadata");
const jtdVocabulary = [
    "definitions",
    ref_1.default,
    type_1.default,
    enum_1.default,
    elements_1.default,
    properties_1.default,
    optionalProperties_1.default,
    discriminator_1.default,
    values_1.default,
    union_1.default,
    metadata_1.default,
    { keyword: "additionalProperties", schemaType: "boolean" },
    { keyword: "nullable", schemaType: "boolean" },
];
exports.default = jtdVocabulary;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/index.ts"],"names":[],"mappings":";;AACA,+BAA8B;AAC9B,iCAAgD;AAChD,iCAAgD;AAChD,yCAAqD;AACrD,6CAA2D;AAC3D,6DAAqD;AACrD,mDAAoE;AACpE,qCAA+C;AAC/C,mCAA2B;AAC3B,yCAAiC;AAEjC,MAAM,aAAa,GAAe;IAChC,aAAa;IACb,aAAU;IACV,cAAW;IACX,cAAW;IACX,kBAAQ;IACR,oBAAU;IACV,4BAAkB;IAClB,uBAAa;IACb,gBAAM;IACN,eAAK;IACL,kBAAQ;IACR,EAAC,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,SAAS,EAAC;IACxD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;CAC7C,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkMetadata = void 0;
const util_1 = require("../../compile/util");
const def = {
    keyword: "metadata",
    schemaType: "object",
    code(cxt) {
        checkMetadata(cxt);
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid);
        cxt.ok(valid);
    },
};
function checkMetadata({ it, keyword }, metadata) {
    if (it.jtdMetadata !== metadata) {
        throw new Error(`JTD: "${keyword}" cannot be used in this schema location`);
    }
}
exports.checkMetadata = checkMetadata;
exports.default = def;
//# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/metadata.ts"],"names":[],"mappings":";;;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,aAAa,CAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;QAC9D,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAAC,EAAC,EAAE,EAAE,OAAO,EAAa,EAAE,QAAkB;IACzE,IAAI,EAAE,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,SAAS,OAAO,0CAA0C,CAAC,CAAA;IAC7E,CAAC;AACH,CAAC;AAJD,sCAIC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkNullableObject = exports.checkNullable = void 0;
const codegen_1 = require("../../compile/codegen");
function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) {
    const valid = gen.name("valid");
    if (parentSchema.nullable) {
        gen.let(valid, (0, codegen_1._) `${data} === null`);
        cond = (0, codegen_1.not)(valid);
    }
    else {
        gen.let(valid, false);
    }
    return [valid, cond];
}
exports.checkNullable = checkNullable;
function checkNullableObject(cxt, cond) {
    const [valid, cond_] = checkNullable(cxt, cond);
    return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`];
}
exports.checkNullableObject = checkNullableObject;
//# sourceMappingURL=nullable.js.map{"version":3,"file":"nullable.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/nullable.ts"],"names":[],"mappings":";;;AACA,mDAA6D;AAE7D,SAAgB,aAAa,CAC3B,EAAC,GAAG,EAAE,IAAI,EAAE,YAAY,EAAa,EACrC,OAAa,aAAG;IAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;QACnC,IAAI,GAAG,IAAA,aAAG,EAAC,KAAK,CAAC,CAAA;IACnB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAZD,sCAYC;AAED,SAAgB,mBAAmB,CAAC,GAAe,EAAE,IAAU;IAC7D,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC/C,OAAO,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,KAAK,cAAc,GAAG,CAAC,IAAI,kCAAkC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAA;AAC9F,CAAC;AAHD,kDAGC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const properties_1 = require("./properties");
const def = {
    keyword: "optionalProperties",
    schemaType: "object",
    error: properties_1.error,
    code(cxt) {
        if (cxt.parentSchema.properties)
            return;
        (0, properties_1.validateProperties)(cxt);
    },
};
exports.default = def;
//# sourceMappingURL=optionalProperties.js.map{"version":3,"file":"optionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/optionalProperties.ts"],"names":[],"mappings":";;AAEA,6CAAsD;AAEtD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,oBAAoB;IAC7B,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,kBAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU;YAAE,OAAM;QACvC,IAAA,+BAAkB,EAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperties = exports.error = void 0;
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
var PropError;
(function (PropError) {
    PropError["Additional"] = "additional";
    PropError["Missing"] = "missing";
})(PropError || (PropError = {}));
exports.error = {
    message: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? "must NOT have additional properties"
                : `must have property '${params.missingProperty}'`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
                : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "properties",
    schemaType: "object",
    error: exports.error,
    code: validateProperties,
};
// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }
function validateProperties(cxt) {
    (0, metadata_1.checkMetadata)(cxt);
    const { gen, data, parentSchema, it } = cxt;
    const { additionalProperties, nullable } = parentSchema;
    if (it.jtdDiscriminator && nullable)
        throw new Error("JTD: nullable inside discriminator mapping");
    if (commonProperties()) {
        throw new Error("JTD: properties and optionalProperties have common members");
    }
    const [allProps, properties] = schemaProperties("properties");
    const [allOptProps, optProperties] = schemaProperties("optionalProperties");
    if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
        return;
    }
    const [valid, cond] = it.jtdDiscriminator === undefined
        ? (0, nullable_1.checkNullableObject)(cxt, data)
        : [gen.let("valid", false), true];
    gen.if(cond, () => gen.assign(valid, true).block(() => {
        validateProps(properties, "properties", true);
        validateProps(optProperties, "optionalProperties");
        if (!additionalProperties)
            validateAdditional();
    }));
    cxt.pass(valid);
    function commonProperties() {
        const props = parentSchema.properties;
        const optProps = parentSchema.optionalProperties;
        if (!(props && optProps))
            return false;
        for (const p in props) {
            if (Object.prototype.hasOwnProperty.call(optProps, p))
                return true;
        }
        return false;
    }
    function schemaProperties(keyword) {
        const schema = parentSchema[keyword];
        const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
        if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
            throw new Error(`JTD: discriminator tag used in ${keyword}`);
        }
        const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        return [allPs, ps];
    }
    function validateProps(props, keyword, required) {
        const _valid = gen.var("valid");
        for (const prop of props) {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop));
            cxt.ok(_valid);
        }
        function missingProperty(prop) {
            if (required) {
                gen.assign(_valid, false);
                cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop });
            }
            else {
                gen.assign(_valid, true);
            }
        }
    }
    function applyPropertySchema(prop, keyword, _valid) {
        cxt.subschema({
            keyword,
            schemaProp: prop,
            dataProp: prop,
        }, _valid);
    }
    function validateAdditional() {
        gen.forIn("key", data, (key) => {
            const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator);
            const addOptProp = isAdditional(key, allOptProps, "optionalProperties");
            const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp);
            gen.if(extra, () => {
                if (it.opts.removeAdditional) {
                    gen.code((0, codegen_1._) `delete ${data}[${key}]`);
                }
                else {
                    cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true });
                    if (!it.opts.allErrors)
                        gen.break();
                }
            });
        });
    }
    function isAdditional(key, props, keyword, jtdDiscriminator) {
        let additional;
        if (props.length > 8) {
            // TODO maybe an option instead of hard-coded 8?
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword);
            additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key));
            if (jtdDiscriminator !== undefined) {
                additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`);
            }
        }
        else if (props.length || jtdDiscriminator !== undefined) {
            const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props);
            additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`));
        }
        else {
            additional = true;
        }
        return additional;
    }
}
exports.validateProperties = validateProperties;
exports.default = def;
//# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/properties.ts"],"names":[],"mappings":";;;AAOA,kCAA0E;AAC1E,6CAAoE;AACpE,mDAA6D;AAC7D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AAExE,IAAK,SAGJ;AAHD,WAAK,SAAS;IACZ,sCAAyB,CAAA;IACzB,gCAAmB,CAAA;AACrB,CAAC,EAHI,SAAS,KAAT,SAAS,QAGb;AAWY,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,MAAM,EAAC,MAAM,EAAC,GAAG,GAAG,CAAA;QACpB,OAAO,MAAM,CAA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C,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,IAAI,CAAA;QACnB,CAAC;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;AACH,CAAC;AA1HD,gDA0HC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasRef = void 0;
const compile_1 = require("../../compile");
const codegen_1 = require("../../compile/codegen");
const ref_error_1 = require("../../compile/ref_error");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const metadata_1 = require("./metadata");
const def = {
    keyword: "ref",
    schemaType: "string",
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema: ref, parentSchema, it } = cxt;
        const { schemaEnv: { root }, } = it;
        const valid = gen.name("valid");
        if (parentSchema.nullable) {
            gen.var(valid, (0, codegen_1._) `${data} === null`);
            gen.if((0, codegen_1.not)(valid), validateJtdRef);
        }
        else {
            gen.var(valid, false);
            validateJtdRef();
        }
        cxt.ok(valid);
        function validateJtdRef() {
            var _a;
            const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
            if (!refSchema) {
                throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
            }
            if (hasRef(refSchema) || !it.opts.inlineRefs)
                callValidate(refSchema);
            else
                inlineRefSchema(refSchema);
        }
        function callValidate(schema) {
            const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
            const v = (0, ref_1.getValidate)(cxt, sch);
            const errsCount = gen.const("_errs", names_1.default.errors);
            (0, ref_1.callRef)(cxt, v, sch, sch.$async);
            gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        }
        function inlineRefSchema(schema) {
            const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
            cxt.subschema({
                schema,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: `/definitions/${ref}`,
            }, valid);
        }
    },
};
function hasRef(schema) {
    for (const key in schema) {
        let sch;
        if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
            return true;
    }
    return false;
}
exports.hasRef = hasRef;
exports.default = def;
//# sourceMappingURL=ref.js.map{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/ref.ts"],"names":[],"mappings":";;;AAEA,2CAAsD;AACtD,mDAA4D;AAC5D,uDAAqD;AACrD,+CAAmC;AACnC,qCAAgD;AAChD,yCAAwC;AAExC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EACJ,SAAS,EAAE,EAAC,IAAI,EAAC,GAClB,GAAG,EAAE,CAAA;QACN,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;YACnC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,cAAc,CAAC,CAAA;QACpC,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;YACrB,cAAc,EAAE,CAAA;QAClB,CAAC;QACD,GAAG,CAAC,EAAE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GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAA,mBAAS,EAAC,MAAM,CAAC,EAAC,CAAC,CAAC,CAAC,EAAC,GAAG,EAAE,MAAM,EAAC,CACtF,CAAA;YACD,GAAG,CAAC,SAAS,CACX;gBACE,MAAM;gBACN,SAAS,EAAE,EAAE;gBACb,UAAU,EAAE,aAAG;gBACf,YAAY,EAAE,OAAO;gBACrB,aAAa,EAAE,gBAAgB,GAAG,EAAE;aACrC,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAgB,MAAM,CAAC,MAAuB;IAC5C,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,GAAoB,CAAA;QACxB,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,QAAQ,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAA;IAC3F,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAND,wBAMC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intRange = void 0;
const codegen_1 = require("../../compile/codegen");
const timestamp_1 = require("../../runtime/timestamp");
const util_1 = require("../../compile/util");
const metadata_1 = require("./metadata");
const error_1 = require("./error");
exports.intRange = {
    int8: [-128, 127, 3],
    uint8: [0, 255, 3],
    int16: [-32768, 32767, 5],
    uint16: [0, 65535, 5],
    int32: [-2147483648, 2147483647, 10],
    uint32: [0, 4294967295, 10],
};
const error = {
    message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
    params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
};
function timestampCode(cxt) {
    const { gen, data, it } = cxt;
    const { timestamp, allowDate } = it.opts;
    if (timestamp === "date")
        return (0, codegen_1._) `${data} instanceof Date `;
    const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
    const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
    const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
    return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
}
const def = {
    keyword: "type",
    schemaType: "string",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { data, schema, parentSchema, it } = cxt;
        let cond;
        switch (schema) {
            case "boolean":
            case "string":
                cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
                break;
            case "timestamp": {
                cond = timestampCode(cxt);
                break;
            }
            case "float32":
            case "float64":
                cond = (0, codegen_1._) `typeof ${data} == "number"`;
                break;
            default: {
                const sch = schema;
                cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
                if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
                    if (sch === "uint32")
                        cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
                }
                else {
                    const [min, max] = exports.intRange[sch];
                    cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
                }
            }
        }
        cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
    },
};
exports.default = def;
//# sourceMappingURL=type.js.map{"version":3,"file":"type.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/type.ts"],"names":[],"mappings":";;;AAEA,mDAAsD;AACtD,uDAAoD;AACpD,6CAA0C;AAC1C,yCAAwC;AACxC,mCAAwE;AAM3D,QAAA,QAAQ,GAA+C;IAClE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;IACpB,KAAK,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IAClB,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,C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C,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACxE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "union",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in union" },
};
exports.default = def;
//# sourceMappingURL=union.js.map{"version":3,"file":"union.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/union.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "values",
    schemaType: "object",
    error: (0, error_1.typeError)("object"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error());
        }
        else {
            gen.if(cond);
            gen.assign(valid, validateMap());
            gen.elseIf((0, codegen_1.not)(valid));
            cxt.error();
            gen.endIf();
        }
        cxt.ok(valid);
        function validateMap() {
            const _valid = gen.name("valid");
            if (it.allErrors) {
                const validMap = gen.let("valid", true);
                validateValues(() => gen.assign(validMap, false));
                return validMap;
            }
            gen.var(_valid, true);
            validateValues(() => gen.break());
            return _valid;
            function validateValues(notValid) {
                gen.forIn("key", data, (key) => {
                    cxt.subschema({
                        keyword: "values",
                        dataProp: key,
                        dataPropType: util_1.Type.Str,
                    }, _valid);
                    gen.if((0, codegen_1.not)(_valid), notValid);
                });
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=values.js.map{"version":3,"file":"values.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/values.ts"],"names":[],"mappings":";;AAEA,6CAA0D;AAC1D,mDAAmD;AACnD,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,QAAQ;IACjB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,QAAQ,CAAC;IAC1B,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,IAAA,8BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,CAAA;QACpD,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YAClC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,IAAA,YAAE,EAAC,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QACjD,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAA;YACZ,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,WAAW,EAAE,CAAC,CAAA;YAChC,GAAG,CAAC,MAAM,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,CAAC,CAAA;YACtB,GAAG,CAAC,KAAK,EAAE,CAAA;YACX,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QAEb,SAAS,WAAW;YAClB,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAChC,IAAI,EAAE,CAAC,SAAS,EAAE,CAAC;gBACjB,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;gBACvC,cAAc,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAA;gBACjD,OAAO,QAAQ,CAAA;YACjB,CAAC;YACD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACrB,cAAc,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YACjC,OAAO,MAAM,CAAA;YAEb,SAAS,cAAc,CAAC,QAAoB;gBAC1C,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;oBAC7B,GAAG,CAAC,SAAS,CACX;wBACE,OAAO,EAAE,QAAQ;wBACjB,QAAQ,EAAE,GAAG;wBACb,YAAY,EAAE,WAAI,CAAC,GAAG;qBACvB,EACD,MAAM,CACP,CAAA;oBACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAA;gBAC/B,CAAC,CAAC,CAAA;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self } = it;
        if (!opts.validateFormats)
            return;
        if ($data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
            const fType = gen.let("fType");
            const format = gen.let("format");
            // TODO simplify
            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
            function unknownFmt() {
                if (opts.strictSchema === false)
                    return codegen_1.nil;
                return (0, codegen_1._) `${schemaCode} && !${format}`;
            }
            function invalidFmt() {
                const callFormat = schemaEnv.$async
                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
                    : (0, codegen_1._) `${format}(${data})`;
                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
            }
        }
        function validateFormat() {
            const formatDef = self.formats[schema];
            if (!formatDef) {
                unknownFormat();
                return;
            }
            if (formatDef === true)
                return;
            const [fmtType, format, fmtRef] = getFormat(formatDef);
            if (fmtType === ruleType)
                cxt.pass(validCondition());
            function unknownFormat() {
                if (opts.strictSchema === false) {
                    self.logger.warn(unknownMsg());
                    return;
                }
                throw new Error(unknownMsg());
                function unknownMsg() {
                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
                }
            }
            function getFormat(fmtDef) {
                const code = fmtDef instanceof RegExp
                    ? (0, codegen_1.regexpCode)(fmtDef)
                    : opts.code.formats
                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
                        : undefined;
                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
                }
                return ["string", fmtDef, fmt];
            }
            function validCondition() {
                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
                    if (!schemaEnv.$async)
                        throw new Error("async format in sync schema");
                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
                }
                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=format.js.map{"version":3,"file":"format.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/format.ts"],"names":[],"mappings":";;AASA,mDAAoF;AAapF,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,sBAAsB,UAAU,GAAG;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,YAAY,UAAU,GAAG;CACrD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,QAAQ;IACjB,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC1B,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe,EAAE,QAAiB;QACrC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EAAC,IAAI,EAAE,aAAa,EAAE,SAAS,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;QACjD,IAAI,CAAC,IAAI,CAAC,eAAe;YAAE,OAAM;QAEjC,IAAI,KAAK;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object.defineProperty(exports, "__esModule", { value: true });
const format_1 = require("./format");
const format = [format_1.default];
exports.default = format;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/index.ts"],"names":[],"mappings":";;AACA,qCAAoC;AAEpC,MAAM,MAAM,GAAe,CAAC,gBAAa,CAAC,CAAA;AAE1C,kBAAe,MAAM,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicAnchor = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicAnchor",
    schemaType: "string",
    code: (cxt) => dynamicAnchor(cxt, cxt.schema),
};
function dynamicAnchor(cxt, anchor) {
    const { gen, it } = cxt;
    it.schemaEnv.root.dynamicAnchors[anchor] = true;
    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
    const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));
}
exports.dynamicAnchor = dynamicAnchor;
function _getValidate(cxt) {
    const { schemaEnv, schema, self } = cxt.it;
    const { root, baseId, localRefs, meta } = schemaEnv.root;
    const { schemaId } = self.opts;
    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
    compile_1.compileSchema.call(self, sch);
    return (0, ref_1.getValidate)(cxt, sch);
}
exports.default = def;
//# sourceMappingURL=dynamicAnchor.js.map{"version":3,"file":"dynamicAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicAnchor.ts"],"names":[],"mappings":";;;AAEA,mDAA0D;AAC1D,+CAAmC;AACnC,2CAAsD;AACtD,qCAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,gBAAgB;IACzB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,C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AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicRef = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicRef",
    schemaType: "string",
    code: (cxt) => dynamicRef(cxt, cxt.schema),
};
function dynamicRef(cxt, ref) {
    const { gen, keyword, it } = cxt;
    if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
    const anchor = ref.slice(1);
    if (it.allErrors) {
        _dynamicRef();
    }
    else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
    }
    function _dynamicRef(valid) {
        // TODO the assumption here is that `recursiveRef: #` always points to the root
        // of the schema object, which is not correct, because there may be $id that
        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
        // Because of that 2 tests in recursiveRef.json fail.
        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
        // (This problem is not tested in JSON-Schema-Test-Suite)
        if (it.schemaEnv.root.dynamicAnchors[anchor]) {
            const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
        }
        else {
            _callRef(it.validateName, valid)();
        }
    }
    function _callRef(validate, valid) {
        return valid
            ? () => gen.block(() => {
                (0, ref_1.callRef)(cxt, validate);
                gen.let(valid, true);
            })
            : () => (0, ref_1.callRef)(cxt, validate);
    }
}
exports.dynamicRef = dynamicRef;
exports.default = def;
//# sourceMappingURL=dynamicRef.js.map{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicRef.ts"],"names":[],"mappings":";;;AAEA,mDAAgE;AAChE,+CAAmC;AACnC,qCAAmC;AAEnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,QAAQ;IACpB,IAAI,E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CAAC,EAAE,CAAA;QACpC,CAAC;IACH,CAAC;IAED,SAAS,QAAQ,CAAC,QAAc,EAAE,KAAY;QAC5C,OAAO,KAAK;YACV,CAAC,CAAC,GAAG,EAAE,CACH,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE;gBACb,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBACtB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;YACN,CAAC,CAAC,GAAG,EAAE,CAAC,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IAClC,CAAC;AACH,CAAC;AApCD,gCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const dynamicRef_1 = require("./dynamicRef");
const recursiveAnchor_1 = require("./recursiveAnchor");
const recursiveRef_1 = require("./recursiveRef");
const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/index.ts"],"names":[],"mappings":";;AACA,mDAA2C;AAC3C,6CAAqC;AACrC,uDAA+C;AAC/C,iDAAyC;AAEzC,MAAM,OAAO,GAAe,CAAC,uBAAa,EAAE,oBAAU,EAAE,yBAAe,EAAE,sBAAY,CAAC,CAAA;AAEtF,kBAAe,OAAO,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$recursiveAnchor",
    schemaType: "boolean",
    code(cxt) {
        if (cxt.schema)
            (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
        else
            (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
    },
};
exports.default = def;
//# sourceMappingURL=recursiveAnchor.js.map{"version":3,"file":"recursiveAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveAnchor.ts"],"names":[],"mappings":";;AACA,mDAA6C;AAC7C,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,UAAU,EAAE,SAAS;IACrB,IAAI,CAAC,GAAG;QACN,IAAI,GAAG,CAAC,MAAM;YAAE,IAAA,6BAAa,EAAC,GAAG,EAAE,EAAE,CAAC,CAAA;;YACjC,IAAA,sBAAe,EAAC,GAAG,CAAC,EAAE,EAAE,oCAAoC,CAAC,CAAA;IACpE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicRef_1 = require("./dynamicRef");
const def = {
    keyword: "$recursiveRef",
    schemaType: "string",
    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),
};
exports.default = def;
//# sourceMappingURL=recursiveRef.js.map{"version":3,"file":"recursiveRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveRef.ts"],"names":[],"mappings":";;AACA,6CAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const types_1 = require("../discriminator/types");
const compile_1 = require("../../compile");
const ref_error_1 = require("../../compile/ref_error");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
        ? `tag "${tagName}" must be string`
        : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
            throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
            throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
            throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
            throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
            const mapping = getMapping();
            gen.if(false);
            for (const tagValue in mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(mapping[tagValue]));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
            cxt.mergeEvaluated(schCxt, codegen_1.Name);
            return _valid;
        }
        function getMapping() {
            var _a;
            const oneOfMapping = {};
            const topRequired = hasRequired(parentSchema);
            let tagRequired = true;
            for (let i = 0; i < oneOf.length; i++) {
                let sch = oneOf[i];
                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
                    const ref = sch.$ref;
                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
                    if (sch instanceof compile_1.SchemaEnv)
                        sch = sch.schema;
                    if (sch === undefined)
                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
                }
                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
                if (typeof propSch != "object") {
                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
                }
                tagRequired = tagRequired && (topRequired || hasRequired(sch));
                addMappings(propSch, i);
            }
            if (!tagRequired)
                throw new Error(`discriminator: "${tagName}" must be required`);
            return oneOfMapping;
            function hasRequired({ required }) {
                return Array.isArray(required) && required.includes(tagName);
            }
            function addMappings(sch, i) {
                if (sch.const) {
                    addMapping(sch.const, i);
                }
                else if (sch.enum) {
                    for (const tagValue of sch.enum) {
                        addMapping(tagValue, i);
                    }
                }
                else {
                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
                }
            }
            function addMapping(tagValue, i) {
                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
                }
                oneOfMapping[tagValue] = i;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/index.ts"],"names":[],"mappings":";;AAEA,mDAA0D;AAC1D,kDAAgE;AAChE,2CAAmD;AACnD,uDAAqD;AACrD,6CAAuD;AAIvD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC3C,UAAU,KAAK,kBAAU,CAAC,GAAG;QAC3B,CAAC,CAAC,QAAQ,OAAO,kBAAkB;QACnC,CAAC,CAAC,iBAAiB,OAAO,oBAAoB;IAClD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,GAAG,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC/C,IAAA,WAAC,EAAA,WAAW,UAAU,UAAU,OAAO,eAAe,GAAG,GAAG;CAC/D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,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KAAK,EAAE,CAAC,CAAC,CAAA;gBAC1B,CAAC;qBAAM,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;oBACpB,KAAK,MAAM,QAAQ,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;wBAChC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;oBACzB,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,KAAK,CAAC,8BAA8B,OAAO,+BAA+B,CAAC,CAAA;gBACvF,CAAC;YACH,CAAC;YAED,SAAS,UAAU,CAAC,QAAiB,EAAE,CAAS;gBAC9C,IAAI,OAAO,QAAQ,IAAI,QAAQ,IAAI,QAAQ,IAAI,YAAY,EAAE,CAAC;oBAC5D,MAAM,IAAI,KAAK,CAAC,mBAAmB,OAAO,iCAAiC,CAAC,CAAA;gBAC9E,CAAC;gBACD,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
    DiscrError["Tag"] = "tag";
    DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,yBAAW,CAAA;IACX,iCAAmB,CAAA;AACrB,CAAC,EAHW,UAAU,0BAAV,UAAU,QAGrB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const def = {
    keyword: "id",
    code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    },
};
exports.default = def;
//# sourceMappingURL=id.js.map{"version":3,"file":"id.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/id.ts"],"names":[],"mappings":";;AAEA,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,IAAI;QACF,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const id_1 = require("./id");
const ref_1 = require("./ref");
const core = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default,
];
exports.default = core;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/index.ts"],"names":[],"mappings":";;AACA,6BAA4B;AAC5B,+BAA8B;AAE9B,MAAM,IAAI,GAAe;IACvB,SAAS;IACT,KAAK;IACL,OAAO;IACP,aAAa;IACb,EAAC,OAAO,EAAE,UAAU,EAAC;IACrB,aAAa;IACb,YAAS;IACT,aAAU;CACX,CAAA;AAED,kBAAe,IAAI,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = require("../../compile/ref_error");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
            return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
        if (schOrEnv === undefined)
            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
            return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
            if (env === root)
                return callRef(cxt, validateName, env, env.$async);
            const rootName = gen.scopeValue("root", { ref: root });
            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
            const v = getValidate(cxt, sch);
            callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
            const valid = gen.name("valid");
            const schCxt = cxt.subschema({
                schema: sch,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: $ref,
            }, valid);
            cxt.mergeEvaluated(schCxt);
            cxt.ok(valid);
        }
    },
};
function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate
        ? gen.scopeValue("validate", { ref: sch.validate })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
    const { gen, it } = cxt;
    const { allErrors, schemaEnv: env, opts } = it;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
        callAsyncRef();
    else
        callSyncRef();
    function callAsyncRef() {
        if (!env.$async)
            throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
            if (!allErrors)
                gen.assign(valid, true);
        }, (e) => {
            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
            addErrorsFrom(e);
            if (!allErrors)
                gen.assign(valid, false);
        });
        cxt.ok(valid);
    }
    function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
    }
    function addErrorsFrom(source) {
        const errs = (0, codegen_1._) `${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
        var _a;
        if (!it.opts.unevaluated)
            return;
        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
        // TODO refactor
        if (it.props !== true) {
            if (schEvaluated && !schEvaluated.dynamicProps) {
                if (schEvaluated.props !== undefined) {
                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
                }
            }
            else {
                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
            }
        }
        if (it.items !== true) {
            if (schEvaluated && !schEvaluated.dynamicItems) {
                if (schEvaluated.items !== undefined) {
                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
                }
            }
            else {
                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
            }
        }
    }
}
exports.callRef = callRef;
exports.default = def;
//# sourceMappingURL=ref.js.map{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/ref.ts"],"names":[],"mappings":";;;AAEA,uDAAqD;AACrD,kCAAwC;AACxC,mDAAmE;AACnE,+CAAmC;AACnC,2CAAmD;AACnD,6CAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,EAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;QAC7D,MAAM,EAAC,IAAI,EAAC,GAAG,GAAG,CAAA;QAClB,IAAI,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAA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oBACrC,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAhED,0BAgEC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
            return;
        }
        validateAdditionalItems(cxt, items);
    },
};
function validateAdditionalItems(cxt, items) {
    const { gen, schema, data, keyword, it } = cxt;
    it.items = true;
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
    }
    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
    }
    function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
            if (!it.allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
    }
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
//# sourceMappingURL=additionalItems.js.map{"version":3,"file":"additionalItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalItems.ts"],"names":[],"mappings":";;;AAOA,mDAAuD;AACvD,6CAA2E;AAI3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,iBAA0B;IACnC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC9B,MAAM,EAAC,KAAK,EAAC,GAAG,YAAY,CAAA;QAC5B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,IAAA,sBAAe,EAAC,EAAE,EAAE,sEAAsE,CAAC,CAAA;YAC3F,OAAM;QACR,CAAC;QACD,uBAAuB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACrC,CAAC;CACF,CAAA;AAED,SAAgB,uBAAuB,CAAC,GAAe,EAAE,KAAkB;IACzE,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,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G,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QAC1D,CAAC,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAnBD,0DAmBC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const util_1 = require("../../compile/util");
const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
            return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
            gen.forIn("key", data, (key) => {
                if (!props.length && !patProps.length)
                    additionalPropertyCode(key);
                else
                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
            });
        }
        function isAdditional(key) {
            let definedProp;
            if (props.length > 8) {
                // TODO maybe an option instead of hard-coded 8?
                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
            }
            else if (props.length) {
                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
            }
            else {
                definedProp = codegen_1.nil;
            }
            if (patProps.length) {
                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
            }
            return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
                deleteAdditional(key);
                return;
            }
            if (schema === false) {
                cxt.setParams({ additionalProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                if (opts.removeAdditional === "failing") {
                    applyAdditionalSchema(key, valid, false);
                    gen.if((0, codegen_1.not)(valid), () => {
                        cxt.reset();
                        deleteAdditional(key);
                    });
                }
                else {
                    applyAdditionalSchema(key, valid);
                    if (!allErrors)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                }
            }
        }
        function applyAdditionalSchema(key, valid, errors) {
            const subschema = {
                keyword: "additionalProperties",
                dataProp: key,
                dataPropType: util_1.Type.Str,
            };
            if (errors === false) {
                Object.assign(subschema, {
                    compositeRule: true,
                    createErrors: false,
                    allErrors: false,
                });
            }
            cxt.subschema(subschema, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=additionalProperties.js.map{"version":3,"file":"additionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalProperties.ts"],"names":[],"mappings":";;AAOA,kCAAsE;AACtE,mDAAiE;AACjE,+CAAmC;AAEnC,6CAA0E;AAQ1E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,qCAAqC;IAC9C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,wBAAwB,MAAM,CAAC,kBAAkB,GAAG;CAC5E,CAAA;AAED,MAAM,GAAG,GAAmD;IAC1D,OAAO,EAAE,sBAAsB;IAC/B,IAAI,EAAE,CAAC,QAAQ,CAAC;IAChB,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,cAAc,EAAE,IAAI;IACpB,W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,KAAK;iBACjB,CAAC,CAAA;YACJ,CAAC;YACD,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QACjC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
        const { gen, schema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
            if ((0, util_1.alwaysValidSchema)(it, sch))
                return;
            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
            cxt.ok(valid);
            cxt.mergeEvaluated(schCxt);
        });
    },
};
exports.default = def;
//# sourceMappingURL=allOf.js.map{"version":3,"file":"allOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/allOf.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,wBAAwB;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QACvE,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,MAAM,CAAC,OAAO,CAAC,CAAC,GAAc,EAAE,CAAS,EAAE,EAAE;YAC3C,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;gBAAE,OAAM;YACtC,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAC,EAAE,KAAK,CAAC,CAAA;YACtE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map{"version":3,"file":"anyOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/anyOf.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAIrC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { min, max } }) => max === undefined
        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
            min = minContains === undefined ? 1 : minContains;
            max = maxContains;
        }
        else {
            min = 1;
        }
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        cxt.setParams({ min, max });
        if (max === undefined && min === 0) {
            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
            return;
        }
        if (max !== undefined && min > max) {
            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
            cxt.fail();
            return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            let cond = (0, codegen_1._) `${len} >= ${min}`;
            if (max !== undefined)
                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
            cxt.pass(cond);
            return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === undefined && min === 1) {
            validateItems(valid, () => gen.if(valid, () => gen.break()));
        }
        else if (min === 0) {
            gen.let(valid, true);
            if (max !== undefined)
                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
        }
        else {
            gen.let(valid, false);
            validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
            const schValid = gen.name("_valid");
            const count = gen.let("count", 0);
            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
            gen.forRange("i", 0, len, (i) => {
                cxt.subschema({
                    keyword: "contains",
                    dataProp: i,
                    dataPropType: util_1.Type.Num,
                    compositeRule: true,
                }, _valid);
                block();
            });
        }
        function checkLimits(count) {
            gen.code((0, codegen_1._) `${count}++`);
            if (max === undefined) {
                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
            }
            else {
                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
                if (min === 1)
                    gen.assign(valid, true);
                else
                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=contains.js.map{"version":3,"file":"contains.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/contains.ts"],"names":[],"mappings":";;AAOA,mDAAkD;AAClD,6CAA2E;AAQ3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC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AAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;YACtE,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;gBACpE,IAAI,GAAG,KAAK,CAAC;oBAAE,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;;oBACjC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,OAAO,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;YACnE,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
exports.error = {
    message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
    },
    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
};
const def = {
    keyword: "dependencies",
    type: "object",
    schemaType: "object",
    error: exports.error,
    code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
    },
};
function splitDependencies({ schema }) {
    const propertyDeps = {};
    const schemaDeps = {};
    for (const key in schema) {
        if (key === "__proto__")
            continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
    }
    return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
    const { gen, data, it } = cxt;
    if (Object.keys(propertyDeps).length === 0)
        return;
    const missing = gen.let("missing");
    for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
            continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
            property: prop,
            depsCount: deps.length,
            deps: deps.join(", "),
        });
        if (it.allErrors) {
            gen.if(hasProperty, () => {
                for (const depProp of deps) {
                    (0, code_1.checkReportMissingProp)(cxt, depProp);
                }
            });
        }
        else {
            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
        }
    }
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
            continue;
        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
        }, () => gen.var(valid, true) // TODO var
        );
        cxt.ok(valid);
    }
}
exports.validateSchemaDeps = validateSchemaDeps;
exports.default = def;
//# sourceMappingURL=dependencies.js.map{"version":3,"file":"dependencies.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependencies.ts"],"names":[],"mappings":";;;AAQA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAmG;AAmBtF,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAC,EAAC,EAAE,EAAE;QACjD,MAAM,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ACZ,CAAC;IACH,CAAC;AACH,CAAC;AA5BD,oDA4BC;AAED,SAAgB,kBAAkB,CAAC,GAAe,EAAE,aAAwB,GAAG,CAAC,MAAM;IACpF,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACpC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;QAC9B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,UAAU,CAAC,IAAI,CAAc,CAAC;YAAE,SAAQ;QAClE,GAAG,CAAC,EAAE,CACJ,IAAA,qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EACtD,GAAG,EAAE;YACH,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;YAChE,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACxC,CAAC,EACD,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,WAAW;SACvC,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;AACH,CAAC;AAfD,gDAeC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("./dependencies");
const def = {
    keyword: "dependentSchemas",
    type: "object",
    schemaType: "object",
    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentSchemas.js.map{"version":3,"file":"dependentSchemas.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependentSchemas.ts"],"names":[],"mappings":";;AACA,iDAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,iCAAkB,EAAC,GAAG,CAAC;CACvC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === undefined && parentSchema.else === undefined) {
            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
            return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
            const ifClause = gen.let("ifClause");
            cxt.setParams({ ifClause });
            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        }
        else if (hasThen) {
            gen.if(schValid, validateClause("then"));
        }
        else {
            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
            const schCxt = cxt.subschema({
                keyword: "if",
                compositeRule: true,
                createErrors: false,
                allErrors: false,
            }, schValid);
            cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
            return () => {
                const schCxt = cxt.subschema({ keyword }, schValid);
                gen.assign(valid, schValid);
                cxt.mergeValidEvaluated(schCxt, valid);
                if (ifClause)
                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
                else
                    cxt.setParams({ ifClause: keyword });
            };
        }
    },
};
function hasSchema(it, keyword) {
    const schema = it.schema[keyword];
    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports.default = def;
//# sourceMappingURL=if.js.map{"version":3,"file":"if.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/if.ts"],"names":[],"mappings":";;AAQA,mDAAuD;AACvD,6CAAqE;AAIrE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,eAAe,MAAM,CAAC,QAAQ,UAAU;IAClE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,QAAQ,GAAG;CAC9D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACvE,IAAA,sBAAe,EAAC,EAAE,EAAE,2CAA2C,CAAC,CAAA;QAClE,CAAC;QACD,MAAM,OAAO,GAAG,SAAS,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;QACrC,MAAM,OAAO,GAAG,SAAS,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;QACrC,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO;YAAE,OAAM;QAEhC,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;QACpC,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACnC,UAAU,EAAE,CAAA;QACZ,GAAG,CAAC,KAAK,EAAE,C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I,QAAQ;oBAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,EAAE,CAAC,CAAA;;oBAC5C,GAAG,CAAC,SAAS,CAAC,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,CAAC,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAS,SAAS,CAAC,EAAgB,EAAE,OAAe;IAClD,MAAM,MAAM,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO,MAAM,KAAK,SAAS,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,CAAA;AAC/D,CAAC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const additionalItems_1 = require("./additionalItems");
const prefixItems_1 = require("./prefixItems");
const items_1 = require("./items");
const items2020_1 = require("./items2020");
const contains_1 = require("./contains");
const dependencies_1 = require("./dependencies");
const propertyNames_1 = require("./propertyNames");
const additionalProperties_1 = require("./additionalProperties");
const properties_1 = require("./properties");
const patternProperties_1 = require("./patternProperties");
const not_1 = require("./not");
const anyOf_1 = require("./anyOf");
const oneOf_1 = require("./oneOf");
const allOf_1 = require("./allOf");
const if_1 = require("./if");
const thenElse_1 = require("./thenElse");
function getApplicator(draft2020 = false) {
    const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default,
    ];
    // array
    if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
    else
        applicator.push(additionalItems_1.default, items_1.default);
    applicator.push(contains_1.default);
    return applicator;
}
exports.default = getApplicator;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/index.ts"],"names":[],"mappings":";;AACA,uDAAuE;AACvE,+CAAuC;AACvC,mCAA2B;AAC3B,2CAAiD;AACjD,yCAAkD;AAClD,iDAA8D;AAC9D,mDAAiE;AACjE,iEAAsF;AACtF,6CAAqC;AACrC,2DAAmD;AACnD,+BAAiD;AACjD,mCAAyC;AACzC,mCAAyC;AACzC,mCAA2B;AAC3B,6BAA8C;AAC9C,yCAAiC;AAEjC,SAAwB,aAAa,CAAC,SAAS,GAAG,KAAK;IACrD,MAAM,UAAU,GAAG;QACjB,MAAM;QACN,aAAU;QACV,eAAK;QACL,eAAK;QACL,eAAK;QACL,YAAS;QACT,kBAAQ;QACR,SAAS;QACT,uBAAa;QACb,8BAAoB;QACpB,sBAAY;QACZ,oBAAU;QACV,2BAAiB;KAClB,CAAA;IACD,QAAQ;IACR,IAAI,SAAS;QAAE,UAAU,CAAC,IAAI,CAAC,qBAAW,EAAE,mBAAS,CAAC,CAAA;;QACjD,UAAU,CAAC,IAAI,CAAC,yBAAe,EAAE,eAAK,CAAC,CAAA;IAC5C,UAAU,CAAC,IAAI,CAAC,kBAAQ,CAAC,CAAA;IACzB,OAAO,UAAU,CAAA;AACnB,CAAC;AArBD,gCAqBC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTuple = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
            return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        cxt.ok((0, code_1.validateArray)(cxt));
    },
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data, keyword, it } = cxt;
    checkStrictTuple(parentSchema);
    if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
            keyword,
            schemaProp: i,
            dataProp: i,
        }, valid));
        cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
    }
}
exports.validateTuple = validateTuple;
exports.default = def;
//# sourceMappingURL=items.js.map{"version":3,"file":"items.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items.ts"],"names":[],"mappings":";;;AAEA,mDAAuC;AACvC,6CAAqF;AACrF,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC;IAC1C,MAAM,EAAE,aAAa;IACrB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACxB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,OAAO,aAAa,CAAC,GAAG,EAAE,iBAAiB,EAAE,MAAM,CAAC,CAAA;QAC/E,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IAC5B,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAC3B,GAAe,EACf,UAAkB,EAClB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K,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK,CAAC,CAAA;QACzF,IAAI,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,IAAI,OAAO,QAAQ,CAAC,oCAAoC,UAAU,4CAA4C,aAAa,GAAG,CAAA;YAC1I,IAAA,sBAAe,EAAC,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QAC7C,CAAC;IACH,CAAC;AACH,CAAC;AApCD,sCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const additionalItems_1 = require("./additionalItems");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        if (prefixItems)
            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
            cxt.ok((0, code_1.validateArray)(cxt));
    },
};
exports.default = def;
//# sourceMappingURL=items2020.js.map{"version":3,"file":"items2020.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items2020.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAqC;AACrC,uDAAyD;AAIzD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtC,MAAM,EAAC,WAAW,EAAC,GAAG,YAAY,CAAA;QAClC,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,IAAI,WAAW;YAAE,IAAA,yCAAuB,EAAC,GAAG,EAAE,WAAW,CAAC,CAAA;;YACrD,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IACjC,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            cxt.fail();
            return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
            keyword: "not",
            compositeRule: true,
            createErrors: false,
            allErrors: false,
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" },
};
exports.default = def;
//# sourceMappingURL=not.js.map{"version":3,"file":"not.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/not.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAIpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YAClC,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,OAAM;QACR,CAAC;QAED,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CACX;YACE,OAAO,EAAE,KAAK;YACd,aAAa,EAAE,IAAI;YACnB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,KAAK;SACjB,EACD,KAAK,CACN,CAAA;QAED,GAAG,CAAC,UAAU,CACZ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CAAA;IACH,CAAC;IACD,KAAK,EAAE,EAAC,OAAO,EAAE,mBAAmB,EAAC;CACtC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
            return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
            schArr.forEach((sch, i) => {
                let schCxt;
                if ((0, util_1.alwaysValidSchema)(it, sch)) {
                    gen.var(schValid, true);
                }
                else {
                    schCxt = cxt.subschema({
                        keyword: "oneOf",
                        schemaProp: i,
                        compositeRule: true,
                    }, schValid);
                }
                if (i > 0) {
                    gen
                        .if((0, codegen_1._) `${schValid} && ${valid}`)
                        .assign(valid, false)
                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
                        .else();
                }
                gen.if(schValid, () => {
                    gen.assign(valid, true);
                    gen.assign(passing, i);
                    if (schCxt)
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=oneOf.js.map{"version":3,"file":"oneOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/oneOf.ts"],"names":[],"mappings":";;AAOA,mDAA6C;AAC7C,6CAAoD;AASpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,OAAO,GAAG;CAC7D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC3C,wBAAwB;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QACvE,IAAI,EAAE,CAAC,IAAI,CAAC,aAAa,IAAI,YAAY,CAAC,aAAa;YAAE,OAAM;QAC/D,MAAM,MAAM,GAAgB,MAAM,CAAA;QAClC,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO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pB,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;oBACvB,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;oBACtB,IAAI,MAAM;wBAAE,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;gBAC9C,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const util_2 = require("../../compile/util");
const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 ||
            (alwaysValidPatterns.length === patterns.length &&
                (!it.opts.unevaluated || it.props === true))) {
            return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
            for (const pat of patterns) {
                if (checkProperties)
                    checkMatchingProperties(pat);
                if (it.allErrors) {
                    validateProperties(pat);
                }
                else {
                    gen.var(valid, true); // TODO var
                    validateProperties(pat);
                    gen.if(valid);
                }
            }
        }
        function checkMatchingProperties(pat) {
            for (const prop in checkProperties) {
                if (new RegExp(pat).test(prop)) {
                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
                }
            }
        }
        function validateProperties(pat) {
            gen.forIn("key", data, (key) => {
                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
                    const alwaysValid = alwaysValidPatterns.includes(pat);
                    if (!alwaysValid) {
                        cxt.subschema({
                            keyword: "patternProperties",
                            schemaProp: pat,
                            dataProp: key,
                            dataPropType: util_2.Type.Str,
                        }, valid);
                    }
                    if (it.opts.unevaluated && props !== true) {
                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
                    }
                    else if (!alwaysValid && !it.allErrors) {
                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
                        // or if all properties were evaluated (props === true)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                    }
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=patternProperties.js.map{"version":3,"file":"patternProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/patternProperties.ts"],"names":[],"mappings":";;AAEA,kCAAuD;AACvD,mDAAkD;AAClD,6CAAqE;AACrE,6CAA6D;AAG7D,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,MAAM,EAAC,IAAI,EAAC,GAAG,EAAE,CAAA;QACjB,MAAM,QAAQ,GAAG,IAAA,0BAAmB,EAAC,MAAM,CAAC,CAAA;QAC5C,MAAM,mBAAmB,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAChD,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAc,CAAC,CAC9C,CAAA;QAED,IACE,QAAQ,CAAC,MAAM,KAAK,CAAC;YACrB,CAAC,mBAAmB,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM;gBAC7C,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,KAAK,KAAK,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AED,SAAS,kBAAkB,CAAC,GAAW;YACrC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;gBAC7B,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAA,iBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG,EAAE;oBACnD,MAAM,WAAW,GAAG,mBAAmB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;oBACrD,IAAI,CAAC,WAAW,EAAE,CAAC;wBACjB,GAAG,CAAC,SAAS,CACX;4BACE,OAAO,EAAE,mBAAmB;4BAC5B,UAAU,EAAE,GAAG;4BACf,QAAQ,EAAE,GAAG;4BACb,YAAY,EAAE,WAAI,CAAC,GAAG;yBACvB,EACD,KAAK,CACN,CAAA;oBACH,CAAC;oBAED,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;wBAC1C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,IAAI,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;oBACvC,CAAC;yBAAM,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC;wBACzC,sFAAsF;wBACtF,uDAAuD;wBACvD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;oBACvC,CAAC;gBACH,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const items_1 = require("./items");
const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports.default = def;
//# sourceMappingURL=prefixItems.js.map{"version":3,"file":"prefixItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/prefixItems.ts"],"names":[],"mappings":";;AACA,mCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,OAAO,CAAC;IACrB,MAAM,EAAE,aAAa;IACrB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,GAAG,EAAE,OAAO,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("../../compile/validate");
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const additionalProperties_1 = require("./additionalProperties");
const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
            it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
            return;
        const valid = gen.name("valid");
        for (const prop of properties) {
            if (hasDefault(prop)) {
                applyPropertySchema(prop);
            }
            else {
                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
                applyPropertySchema(prop);
                if (!it.allErrors)
                    gen.else().var(valid, true);
                gen.endIf();
            }
            cxt.it.definedProperties.add(prop);
            cxt.ok(valid);
        }
        function hasDefault(prop) {
            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
        }
        function applyPropertySchema(prop) {
            cxt.subschema({
                keyword: "properties",
                schemaProp: prop,
                dataProp: prop,
            }, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/properties.ts"],"names":[],"mappings":";;AACA,qDAAiD;AACjD,kCAA2D;AAC3D,6CAA4E;AAC5E,iEAA0C;AAE1C,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,IAAI,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,YAAY,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC1F,8BAAK,CAAC,IAAI,CAAC,IAAI,qBAAU,CAAC,EAAE,EAAE,8BAAK,EAAE,sBAAsB,CAAC,CAAC,CAAA;QAC/D,CAAC;QACD,MAAM,QAAQ,GAAG,IAAA,0BAAmB,EAAC,MAAM,CAAC,CAAA;QAC5C,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;YAC5B,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QAChC,CAAC;QACD,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,QAAQ,CAAC,MAAM,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAChE,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,IAAA,aAAM,EAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;QAClE,CAAC;QACD,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAA,wBAAiB,EAAC,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esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
            cxt.setParams({ propertyName: key });
            cxt.subschema({
                keyword: "propertyNames",
                data: key,
                dataTypes: ["string"],
                propertyName: key,
                compositeRule: true,
            }, valid);
            gen.if((0, codegen_1.not)(valid), () => {
                cxt.error(true);
                if (!it.allErrors)
                    gen.break();
            });
        });
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=propertyNames.js.map{"version":3,"file":"propertyNames.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/propertyNames.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AAIpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,6BAA6B;IACtC,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,MAAM,CAAC,YAAY,GAAG;CAChE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAE/B,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;YAC7B,GAAG,CAAC,SAAS,CAAC,EAAC,YAAY,EAAE,GAAG,EAAC,CAAC,CAAA;YAClC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,eAAe;gBACxB,IAAI,EAAE,GAAG;gBACT,SAAS,EAAE,CAAC,QAAQ,CAAC;gBACrB,YAAY,EAAE,GAAG;gBACjB,aAAa,EAAE,IAAI;aACpB,EACD,KAAK,CACN,CAAA;YACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;gBACtB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBACf,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,KAAK,EAAE,CAAA;YAChC,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword, parentSchema, it }) {
        if (parentSchema.if === undefined)
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
    },
};
exports.default = def;
//# sourceMappingURL=thenElse.js.map{"version":3,"file":"thenElse.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/thenElse.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,EAAE,KAAK,SAAS;YAAE,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,2BAA2B,CAAC,CAAA;IAChG,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/types/index.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=json-schema.js.map{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../lib/types/json-schema.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/types/jtd-schema.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_1 = require("../compile/codegen/scope");
const code_1 = require("../compile/codegen/code");
function standaloneCode(ajv, refsOrFunc) {
    if (!ajv.opts.code.source) {
        throw new Error("moduleCode: ajv instance must have code.source option");
    }
    const { _n } = ajv.scope.opts;
    return typeof refsOrFunc == "function"
        ? funcExportCode(refsOrFunc.source)
        : refsOrFunc !== undefined
            ? multiExportsCode(refsOrFunc, getValidate)
            : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
    function getValidate(id) {
        const v = ajv.getSchema(id);
        if (!v)
            throw new Error(`moduleCode: no schema with id ${id}`);
        return v;
    }
    function funcExportCode(source) {
        const usedValues = {};
        const n = source === null || source === void 0 ? void 0 : source.validateName;
        const vCode = validateCode(usedValues, source);
        if (ajv.opts.code.esm) {
            // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
            return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
        }
        return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
    }
    function multiExportsCode(schemas, getValidateFunc) {
        var _a;
        const usedValues = {};
        let code = (0, code_1._) `"use strict";`;
        for (const name in schemas) {
            const v = getValidateFunc(schemas[name]);
            if (v) {
                const vCode = validateCode(usedValues, v.source);
                const exportSyntax = ajv.opts.code.esm
                    ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
                    : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
                code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
            }
        }
        return `${code}`;
    }
    function validateCode(usedValues, s) {
        if (!s)
            throw new Error('moduleCode: function does not have "source" property');
        if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
            return code_1.nil;
        setUsedState(s.validateName, scope_1.UsedValueState.Started);
        const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
        const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
        return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
        function refValidateCode(n) {
            var _a;
            const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
            if (n.prefix === "validate" && typeof vRef == "function") {
                const v = vRef;
                return validateCode(usedValues, v.source);
            }
            else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
                const { validate, validateName } = vRef;
                if (!validateName)
                    throw new Error("ajv internal error");
                const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
                const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
                if (usedState(validateName) === scope_1.UsedValueState.Started)
                    return wrapper;
                const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
                return (0, code_1._) `${wrapper}${_n}${vCode}`;
            }
            return undefined;
        }
        function usedState(name) {
            var _a;
            return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
        }
        function setUsedState(name, state) {
            const { prefix } = name;
            const names = (usedValues[prefix] = usedValues[prefix] || new Map());
            names.set(name, state);
        }
    }
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = standaloneCode;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/standalone/index.ts"],"names":[],"mappings":";;AAGA,oDAAkG;AAClG,kDAA0F;AAE1F,SAAS,cAAc,CACrB,GAAY,EACZ,UAA2D;IAE3D,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;IACD,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAA;IAC3B,OAAO,OAAO,UAAU,IAAI,UAAU;QACpC,CAAC,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC;QACnC,CAAC,CAAC,UAAU,KAAK,SAAS;YAC1B,CAAC,CAAC,gBAAgB,CAAS,UAAU,EAAE,WAAW,CAAC;YACnD,CAAC,CAAC,gBAAgB,CAAY,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAC/C,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAC/C,CAAA;IAEL,SAAS,WAAW,CAAC,EAAU;QAC7B,MAAM,CAAC,GAAG,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QAC3B,IAAI,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,EAAE,EAAE,CAAC,CAAA;QAC9D,OAAO,CAAC,CAAA;IACV,CAAC;IAED,SAAS,cAAc,CAAC,MAAmB;QACzC,MAAM,UAAU,GAAoB,EAAE,CAAA;QACtC,MAAM,CAAC,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAA;QAC9B,MAAM,KAAK,GAAG,YAAY,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;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C,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK,CAAA;gBAC7D,MAAM,OAAO,GAAG,IAAA,QAAC,EAAA,GAAG,GAAG,IAAI,CAAC,iBAAiB,YAAY,IAAI,CAAA;gBAC7D,IAAI,SAAS,CAAC,YAAY,CAAC,KAAK,sBAAc,CAAC,OAAO;oBAAE,OAAO,OAAO,CAAA;gBACtE,MAAM,KAAK,GAAG,YAAY,CAAC,UAAU,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,CAAC,CAAA;gBACxD,OAAO,IAAA,QAAC,EAAA,GAAG,OAAO,GAAG,EAAE,GAAG,KAAK,EAAE,CAAA;YACnC,CAAC;YACD,OAAO,SAAS,CAAA;QAClB,CAAC;QAED,SAAS,SAAS,CAAC,IAAoB;;YACrC,OAAO,MAAA,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,0CAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QAC3C,CAAC;QAED,SAAS,YAAY,CAAC,IAAoB,EAAE,KAAqB;YAC/D,MAAM,EAAC,MAAM,EAAC,GAAG,IAAI,CAAA;YACrB,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACpE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,cAAc,CAAA;AACzC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,cAAc,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("../core");
const _1 = require(".");
const requireFromString = require("require-from-string");
class AjvPack {
    constructor(ajv) {
        this.ajv = ajv;
    }
    validate(schemaKeyRef, data) {
        return core_1.default.prototype.validate.call(this, schemaKeyRef, data);
    }
    compile(schema, meta) {
        return this.getStandalone(this.ajv.compile(schema, meta));
    }
    getSchema(keyRef) {
        const v = this.ajv.getSchema(keyRef);
        if (!v)
            return undefined;
        return this.getStandalone(v);
    }
    getStandalone(v) {
        return requireFromString((0, _1.default)(this.ajv, v));
    }
    addSchema(...args) {
        this.ajv.addSchema.call(this.ajv, ...args);
        return this;
    }
    addKeyword(...args) {
        this.ajv.addKeyword.call(this.ajv, ...args);
        return this;
    }
}
exports.default = AjvPack;
//# sourceMappingURL=instance.js.map{"version":3,"file":"instance.js","sourceRoot":"","sources":["../../lib/standalone/instance.ts"],"names":[],"mappings":";;AAAA,kCAAwE;AACxE,wBAA8B;AAC9B,yDAAwD;AAExD,MAAqB,OAAO;IAE1B,YAAqB,GAAQ;QAAR,QAAG,GAAH,GAAG,CAAK;IAAG,CAAC;IAEjC,QAAQ,CAAC,YAAgC,EAAE,IAAa;QACtD,OAAO,cAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CAAc,MAAiB,EAAE,IAAc;QACpD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;IAC9D,CAAC;IAED,SAAS,CAAc,MAAc;QACnC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAI,MAAM,CAAC,CAAA;QACvC,IAAI,CAAC,CAAC;YAAE,OAAO,SAAS,CAAA;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;IAC9B,CAAC;IAEO,aAAa,CAAc,CAAyB;QAC1D,OAAO,iBAAiB,CAAC,IAAA,UAAc,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAA2B,CAAA;IACjF,CAAC;IAED,SAAS,CAAC,GAAG,IAAgD;QAC3D,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC1C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,UAAU,CAAC,GAAG,IAAiD;QAC7D,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA/BD,0BA+BC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/ajv-validator/ajv/issues/889
const equal = require("fast-deep-equal");
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
//# sourceMappingURL=equal.js.map{"version":3,"file":"equal.js","sourceRoot":"","sources":["../../lib/runtime/equal.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAClD,yCAAwC;AAGtC,KAAe,CAAC,IAAI,GAAG,2CAA2C,CAAA;AAEpE,kBAAe,KAAc,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
    let endPos;
    parseJson.message = undefined;
    let matches;
    if (pos)
        s = s.slice(pos);
    try {
        parseJson.position = pos + s.length;
        return JSON.parse(s);
    }
    catch (e) {
        matches = rxParseJson.exec(e.message);
        if (!matches) {
            parseJson.message = "unexpected end";
            return undefined;
        }
        endPos = +matches[1];
        const c = s[endPos];
        s = s.slice(0, endPos);
        parseJson.position = pos + endPos;
        try {
            return JSON.parse(s);
        }
        catch (e1) {
            parseJson.message = `unexpected token ${c}`;
            return undefined;
        }
    }
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
    let numStr = "";
    let c;
    parseJsonNumber.message = undefined;
    if (s[pos] === "-") {
        numStr += "-";
        pos++;
    }
    if (s[pos] === "0") {
        numStr += "0";
        pos++;
    }
    else {
        if (!parseDigits(maxDigits)) {
            errorMessage();
            return undefined;
        }
    }
    if (maxDigits) {
        parseJsonNumber.position = pos;
        return +numStr;
    }
    if (s[pos] === ".") {
        numStr += ".";
        pos++;
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    if (((c = s[pos]), c === "e" || c === "E")) {
        numStr += "e";
        pos++;
        if (((c = s[pos]), c === "+" || c === "-")) {
            numStr += c;
            pos++;
        }
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    parseJsonNumber.position = pos;
    return +numStr;
    function parseDigits(maxLen) {
        let digit = false;
        while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
            digit = true;
            numStr += c;
            pos++;
        }
        return digit;
    }
    function errorMessage() {
        parseJsonNumber.position = pos;
        parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
    }
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    '"': '"',
    "/": "/",
    "\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
    let str = "";
    let c;
    parseJsonString.message = undefined;
    // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
    while (true) {
        c = s[pos++];
        if (c === '"')
            break;
        if (c === "\\") {
            c = s[pos];
            if (c in escapedChars) {
                str += escapedChars[c];
                pos++;
            }
            else if (c === "u") {
                pos++;
                let count = 4;
                let code = 0;
                while (count--) {
                    code <<= 4;
                    c = s[pos];
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    if (c === undefined) {
                        errorMessage("unexpected end");
                        return undefined;
                    }
                    c = c.toLowerCase();
                    if (c >= "a" && c <= "f") {
                        code += c.charCodeAt(0) - CODE_A + 10;
                    }
                    else if (c >= "0" && c <= "9") {
                        code += c.charCodeAt(0) - CODE_0;
                    }
                    else {
                        errorMessage(`unexpected token ${c}`);
                        return undefined;
                    }
                    pos++;
                }
                str += String.fromCharCode(code);
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        }
        else if (c === undefined) {
            errorMessage("unexpected end");
            return undefined;
        }
        else {
            if (c.charCodeAt(0) >= 0x20) {
                str += c;
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
        }
    }
    parseJsonString.position = pos;
    return str;
    function errorMessage(msg) {
        parseJsonString.position = pos;
        parseJsonString.message = msg;
    }
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map{"version":3,"file":"parseJson.js","sourceRoot":"","sources":["../../lib/runtime/parseJson.ts"],"names":[],"mappings":";;;AAAA,MAAM,WAAW,GAAG,+CAA+C,CAAA;AAEnE,SAAgB,SAAS,CAAC,CAAS,EAAE,GAAW;IAC9C,IAAI,MAA0B,CAAA;IAC9B,SAAS,CAAC,OAAO,GAAG,SAAS,CAAA;IAC7B,IAAI,OAA+B,CAAA;IACnC,IAAI,GAAG;QAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACzB,IAAI,CAAC;QACH,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,CAAC,CAAC,MAAM,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IAAC,OAAO,CAA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O,SAAS,CAAA;YAClB,CAAC;YACD,uEAAuE;QACzE,CAAC;aAAM,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;YAC3B,YAAY,CAAC,gBAAgB,CAAC,CAAA;YAC9B,OAAO,SAAS,CAAA;QAClB,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC;gBAC5B,GAAG,IAAI,CAAC,CAAA;YACV,CAAC;iBAAM,CAAC;gBACN,YAAY,CAAC,oBAAoB,CAAC,EAAE,CAAC,CAAA;gBACrC,OAAO,SAAS,CAAA;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IACD,eAAe,CAAC,QAAQ,GAAG,GAAG,CAAA;IAC9B,OAAO,GAAG,CAAA;IAEV,SAAS,YAAY,CAAC,GAAW;QAC/B,eAAe,CAAC,QAAQ,GAAG,GAAG,CAAA;QAC9B,eAAe,CAAC,OAAO,GAAG,GAAG,CAAA;IAC/B,CAAC;AACH,CAAC;AA7DD,0CA6DC;AAED,eAAe,CAAC,OAAO,GAAG,SAA+B,CAAA;AACzD,eAAe,CAAC,QAAQ,GAAG,CAAW,CAAA;AACtC,eAAe,CAAC,IAAI,GAAG,uDAAuD,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxEscapable = 
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
    "\b": "\\b",
    "\t": "\\t",
    "\n": "\\n",
    "\f": "\\f",
    "\r": "\\r",
    '"': '\\"',
    "\\": "\\\\",
};
function quote(s) {
    rxEscapable.lastIndex = 0;
    return ('"' +
        (rxEscapable.test(s)
            ? s.replace(rxEscapable, (a) => {
                const c = escaped[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            })
            : s) +
        '"');
}
exports.default = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map{"version":3,"file":"quote.js","sourceRoot":"","sources":["../../lib/runtime/quote.ts"],"names":[],"mappings":";;AAAA,MAAM,WAAW;AACf,2EAA2E;AAC3E,iIAAiI,CAAA;AAEnI,MAAM,OAAO,GAA6B;IACxC,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;CACb,CAAA;AAED,SAAwB,KAAK,CAAC,CAAS;IACrC,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;IACzB,OAAO,CACL,GAAG;QACH,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE;gBAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;gBACpB,OAAO,OAAO,CAAC,KAAK,QAAQ;oBAC1B,CAAC,CAAC,CAAC;oBACH,CAAC,CAAC,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC/D,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC,CAAC;QACN,GAAG,CACJ,CAAA;AACH,CAAC;AAdD,wBAcC;AAED,KAAK,CAAC,IAAI,GAAG,2CAA2C,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const re2 = require("re2");
re2.code = 'require("ajv/dist/runtime/re2").default';
exports.default = re2;
//# sourceMappingURL=re2.js.map{"version":3,"file":"re2.js","sourceRoot":"","sources":["../../lib/runtime/re2.ts"],"names":[],"mappings":";;AAAA,2BAA0B;AAGxB,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dt = str.split(DT_SEPARATOR);
    return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
        (allowDate && dt.length === 1 && validDate(dt[0])));
}
exports.default = validTimestamp;
function validDate(str) {
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const y = +matches[1];
    const m = +matches[2];
    const d = +matches[3];
    return (m >= 1 &&
        m <= 12 &&
        d >= 1 &&
        (d <= DAYS[m] ||
            // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
            (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hr = +matches[1];
    const min = +matches[2];
    const sec = +matches[3];
    const tzH = +(matches[4] || 0);
    const tzM = +(matches[5] || 0);
    return ((hr <= 23 && min <= 59 && sec <= 59) ||
        // leap second
        (hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../lib/runtime/timestamp.ts"],"names":[],"mappings":";;AAAA,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,IAAI,GAAG,4BAA4B,CAAA;AACzC,MAAM,IAAI,GAAG,gEAAgE,CAAA;AAC7E,MAAM,IAAI,GAAG,CAAC,C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AAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAC1E,CAAA;AACH,CAAC;AAED,SAAS,SAAS,CAAC,GAAW;IAC5B,MAAM,OAAO,GAAoB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC/C,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAA;IAC1B,MAAM,EAAE,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC9B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,OAAO,CACL,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;QACpC,cAAc;QACd,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,KAAK,EAAE,CAAC,CACpD,CAAA;AACH,CAAC;AAED,cAAc,CAAC,IAAI,GAAG,+CAA+C,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let value;
    while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
            // high surrogate, and there is a next character
            value = str.charCodeAt(pos);
            if ((value & 0xfc00) === 0xdc00)
                pos++; // low surrogate
        }
    }
    return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map{"version":3,"file":"ucs2length.js","sourceRoot":"","sources":["../../lib/runtime/ucs2length.ts"],"names":[],"mappings":";;AAAA,qDAAqD;AACrD,iEAAiE;AACjE,SAAwB,UAAU,CAAC,GAAW;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAA;IACtB,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,IAAI,KAAa,CAAA;IACjB,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACjB,MAAM,EAAE,CAAA;QACR,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAA;QAC7B,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;YACpD,gDAAgD;YAChD,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,MAAM;gBAAE,GAAG,EAAE,CAAA,CAAC,gBAAgB;QACzD,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAfD,6BAeC;AAED,UAAU,CAAC,IAAI,GAAG,gDAAgD,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uri = require("fast-uri");
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
//# sourceMappingURL=uri.js.map{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../lib/runtime/uri.ts"],"names":[],"mappings":";;AAAA,gCAA+B;AAG7B,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ValidationError extends Error {
    constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
    }
}
exports.default = ValidationError;
//# sourceMappingURL=validation_error.js.map{"version":3,"file":"validation_error.js","sourceRoot":"","sources":["../../lib/runtime/validation_error.ts"],"names":[],"mappings":";;AAEA,MAAqB,eAAgB,SAAQ,KAAK;IAKhD,YAAY,MAA8B;QACxC,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;IACnC,CAAC;CACF;AAVD,kCAUC"}{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared = (root) => {
    const sch = {
        nullable: { type: "boolean" },
        metadata: {
            optionalProperties: {
                union: { elements: { ref: "schema" } },
            },
            additionalProperties: true,
        },
    };
    if (root)
        sch.definitions = { values: { ref: "schema" } };
    return sch;
};
const emptyForm = (root) => ({
    optionalProperties: shared(root),
});
const refForm = (root) => ({
    properties: {
        ref: { type: "string" },
    },
    optionalProperties: shared(root),
});
const typeForm = (root) => ({
    properties: {
        type: {
            enum: [
                "boolean",
                "timestamp",
                "string",
                "float32",
                "float64",
                "int8",
                "uint8",
                "int16",
                "uint16",
                "int32",
                "uint32",
            ],
        },
    },
    optionalProperties: shared(root),
});
const enumForm = (root) => ({
    properties: {
        enum: { elements: { type: "string" } },
    },
    optionalProperties: shared(root),
});
const elementsForm = (root) => ({
    properties: {
        elements: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
    properties: {
        properties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        optionalProperties: { values: { ref: "schema" } },
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const optionalPropertiesForm = (root) => ({
    properties: {
        optionalProperties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const discriminatorForm = (root) => ({
    properties: {
        discriminator: { type: "string" },
        mapping: {
            values: {
                metadata: {
                    union: [propertiesForm(false), optionalPropertiesForm(false)],
                },
            },
        },
    },
    optionalProperties: shared(root),
});
const valuesForm = (root) => ({
    properties: {
        values: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const schema = (root) => ({
    metadata: {
        union: [
            emptyForm,
            refForm,
            typeForm,
            enumForm,
            elementsForm,
            propertiesForm,
            optionalPropertiesForm,
            discriminatorForm,
            valuesForm,
        ].map((s) => s(root)),
    },
});
const jtdMetaSchema = {
    definitions: {
        schema: schema(false),
    },
    ...schema(true),
};
exports.default = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/refs/jtd-schema.ts"],"names":[],"mappings":";;AAIA,MAAM,MAAM,GAAe,CAAC,IAAI,EAAE,EAAE;IAClC,MAAM,GAAG,GAAiB;QACxB,QAAQ,EAAE,EAAC,IAAI,EAAE,SAAS,EAAC;QAC3B,QAAQ,EAAE;YACR,kBAAkB,EAAE;gBAClB,KAAK,EAAE,EAAC,QAAQ,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC,EAAC;aACnC;YACD,oBAAoB,EAAE,IAAI;SAC3B;KACF,CAAA;IACD,IAAI,IAAI;QAAE,GAAG,CAAC,WAAW,GAAG,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC,EAAC,CAAA;IACrD,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,MAAM,SAAS,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvC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CAAC,IAAI,CAAC,CAAC;KACtB;CACF,CAAC,CAAA;AAEF,MAAM,aAAa,GAAiB;IAClC,WAAW,EAAE;QACX,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC;KACtB;IACD,GAAG,MAAM,CAAC,IAAI,CAAC;CAChB,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const unevaluated = require("./meta/unevaluated.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format-annotation.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
    ;
    [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2020;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2020-12/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,uDAAsD;AACtD,+CAA8C;AAC9C,yCAAwC;AACxC,wDAAuD;AACvD,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,WAAW;QACX,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAhBD,oCAgBC"}{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2019($data) {
    ;
    [
        metaSchema,
        applicator,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2019;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,+CAA8C;AAC9C,yCAAwC;AACxC,6CAA4C;AAC5C,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"}{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = require("./codegen");
const util_1 = require("./util");
const names_1 = require("./names");
exports.keywordError = {
    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
    message: ({ keyword, schemaType }) => schemaType
        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
        addError(gen, errObj);
    }
    else {
        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
    }
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    addError(gen, errObj);
    if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
    }
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
    gen.assign(names_1.default.errors, errsCount);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
    /* istanbul ignore if */
    if (errsCount === undefined)
        throw new Error("ajv implementation error");
    const err = gen.name("err");
    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
            gen.assign((0, codegen_1._) `${err}.data`, data);
        }
    });
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
    const err = gen.const("err", errObj);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
    const { gen, validateName, schemaEnv } = it;
    if (schemaEnv.$async) {
        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
        gen.return(false);
    }
}
const E = {
    keyword: new codegen_1.Name("keyword"),
    schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
    params: new codegen_1.Name("params"),
    propertyName: new codegen_1.Name("propertyName"),
    message: new codegen_1.Name("message"),
    schema: new codegen_1.Name("schema"),
    parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
    const { createErrors } = cxt.it;
    if (createErrors === false)
        return (0, codegen_1._) `{}`;
    return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
    const { gen, it } = cxt;
    const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths),
    ];
    extraErrorProps(cxt, error, keyValues);
    return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
    const instPath = instancePath
        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
        : errorPath;
    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
    if (schemaPath) {
        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
    }
    return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
    const { keyword, data, schemaValue, it } = cxt;
    const { opts, propertyName, topSchemaRef, schemaPath } = it;
    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
    if (opts.messages) {
        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
    }
    if (opts.verbose) {
        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
    }
    if (propertyName)
        keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/compile/errors.ts"],"names":[],"mappings":";;;AAEA,uCAAgE;AAEhE,iCAAyC;AACzC,mCAAuB;AAEV,QAAA,YAAY,GAA2B;IAClD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,cAAc,OAAO,sBAAsB;CACvE,CAAA;AAEY,QAAA,iBAAiB,GAA2B;IACvD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CACjC,UAAU;QACR,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,qBAAqB,UAAU,UAAU;QACzD,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,8BAA8B;CACnD,CAAA;AAQD,SA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AC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAA;IACpF,CAAC;IACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;QACjB,SAAS,CAAC,IAAI,CACZ,CAAC,CAAC,CAAC,MAAM,EAAE,WAAW,CAAC,EACvB,CAAC,CAAC,CAAC,YAAY,EAAE,IAAA,WAAC,EAAA,GAAG,YAAY,GAAG,UAAU,EAAE,CAAC,EACjD,CAAC,eAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CACf,CAAA;IACH,CAAC;IACD,IAAI,YAAY;QAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;AAClE,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = require("./codegen");
const validation_error_1 = require("../runtime/validation_error");
const names_1 = require("./names");
const resolve_1 = require("./resolve");
const util_1 = require("./util");
const validate_1 = require("./validate");
class SchemaEnv {
    constructor(env) {
        var _a;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
            schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
    }
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
    // TODO refactor - remove compilations
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
            ref: validation_error_1.default,
            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
        });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
            : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._) `""`,
        opts: this.opts,
        self: this,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        // gen.optimize(1)
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
        if (this.opts.code.process)
            sourceCode = this.opts.code.process(sourceCode, sch);
        // console.log("\n\n\n *** \n", sourceCode)
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
            validate.$async = true;
        if (this.opts.code.source === true) {
            validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
            const { props, items } = schemaCxt;
            validate.evaluated = {
                props: props instanceof codegen_1.Name ? undefined : props,
                items: items instanceof codegen_1.Name ? undefined : items,
                dynamicProps: props instanceof codegen_1.Name,
                dynamicItems: items instanceof codegen_1.Name,
            };
            if (validate.source)
                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
    }
    catch (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
            this.logger.error("Error compiling schema, function code:", sourceCode);
        // console.log("\n\n\n *** \n", sourceCode, this.opts)
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
    var _a;
    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
    const schOrFunc = root.refs[ref];
    if (schOrFunc)
        return schOrFunc;
    let _sch = resolve.call(this, root, ref);
    if (_sch === undefined) {
        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
        const { schemaId } = this.opts;
        if (schema)
            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === undefined)
        return;
    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
            return sch;
    }
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
    let sch;
    while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
    const p = this.opts.uriResolver.parse(ref);
    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
    }
    const id = (0, resolve_1.normalizeId)(refPath);
    const schOrRef = this.refs[id] || this.schemas[id];
    if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
            return;
        return getJsonPointer.call(this, p, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
    if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
    if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a;
    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
        return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
            return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === undefined)
            return;
        schema = partSchema;
        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
    }
    // even though resolution failed we need to return SchemaEnv to throw exception
    // so that compileAsync loads missing schema.
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
        return env;
    return undefined;
}
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/compile/index.ts"],"names":[],"mappings":";;;AAUA,uCAAgF;AAChF,kEAAyD;AACzD,mCAAuB;AACvB,uCAAkG;AAClG,iCAA6D;AAC7D,yCAA+C;AA0D/C,MAAa,SAAS;IAkBpB,YAAY,GAAkB;;QATrB,SAAI,GAAe,EAAE,CAAA;QACrB,mBAAc,GAA6B,EAAE,CAAA;QASpD,IAAI,MAAmC,CAAA;QACvC,IAAI,OAAO,GAAG,CAAC,MAAM,IAAI,QAAQ;YAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAA;QACtD,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,IAAI,CAAA;QAC5B,IAAI,CAAC,MAAM,GAAG,MAAA,GAAG,CAAC,MAAM,mCAAI,IAAA,qBAAW,EAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAG,GAAG,CAAC,QAAQ,IAAI,KAAK,CAAC,CA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IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC5C,CAAC;IACD,+EAA+E;IAC/E,6CAA6C;IAC7C,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,GAAG,GAAG,GAAG,IAAI,IAAI,SAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IAC5D,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,CAAA;IAC9C,OAAO,SAAS,CAAA;AAClB,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("./codegen");
const names = {
    // validation function arguments
    data: new codegen_1.Name("data"), // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
    errors: new codegen_1.Name("errors"), // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart"),
};
exports.default = names;
//# sourceMappingURL=names.js.map{"version":3,"file":"names.js","sourceRoot":"","sources":["../../lib/compile/names.ts"],"names":[],"mappings":";;AAAA,uCAA8B;AAE9B,MAAM,KAAK,GAAG;IACZ,gCAAgC;IAChC,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC,EAAE,qCAAqC;IAC7D,sCAAsC;IACtC,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+FAA+F;IAC3H,YAAY,EAAE,IAAI,cAAI,CAAC,cAAc,CAAC;IACtC,UAAU,EAAE,IAAI,cAAI,CAAC,YAAY,CAAC;IAClC,kBAAkB,EAAE,IAAI,cAAI,CAAC,oBAAoB,CAAC;IAClD,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC,EAAE,2EAA2E;IAC3G,cAAc,EAAE,IAAI,cAAI,CAAC,gBAAgB,CAAC,EAAE,8CAA8C;IAC1F,4BAA4B;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC,EAAE,qCAAqC;IACnE,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+BAA+B;IAC3D,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,YAAY;IACZ,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,KAAK,EAAE,IAAI,cAAI,CAAC,OAAO,CAAC;IACxB,wDAAwD;IACxD,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;CAC/B,CAAA;AAED,kBAAe,KAAK,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const resolve_1 = require("./resolve");
class MissingRefError extends Error {
    constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
    }
}
exports.default = MissingRefError;
//# sourceMappingURL=ref_error.js.map{"version":3,"file":"ref_error.js","sourceRoot":"","sources":["../../lib/compile/ref_error.ts"],"names":[],"mappings":";;AAAA,uCAA8D;AAG9D,MAAqB,eAAgB,SAAQ,KAAK;IAIhD,YAAY,QAAqB,EAAE,MAAc,EAAE,GAAW,EAAE,GAAY;QAC1E,KAAK,CAAC,GAAG,IAAI,2BAA2B,GAAG,YAAY,MAAM,EAAE,CAAC,CAAA;QAChE,IAAI,CAAC,UAAU,GAAG,IAAA,oBAAU,EAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;QACnD,IAAI,CAAC,aAAa,GAAG,IAAA,qBAAW,EAAC,IAAA,qBAAW,EAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AATD,kCASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = require("./util");
const equal = require("fast-deep-equal");
const traverse = require("json-schema-traverse");
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const",
]);
function inlineRef(schema, limit = true) {
    if (typeof schema == "boolean")
        return true;
    if (limit === true)
        return !hasRef(schema);
    if (!limit)
        return false;
    return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor",
]);
function hasRef(schema) {
    for (const key in schema) {
        if (REF_KEYWORDS.has(key))
            return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
            return true;
        if (typeof sch == "object" && hasRef(sch))
            return true;
    }
    return false;
}
function countKeys(schema) {
    let count = 0;
    for (const key in schema) {
        if (key === "$ref")
            return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
            continue;
        if (typeof schema[key] == "object") {
            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
        }
        if (count === Infinity)
            return Infinity;
    }
    return count;
}
function getFullPath(resolver, id = "", normalize) {
    if (normalize !== false)
        id = normalizeId(id);
    const p = resolver.parse(id);
    return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
    const serialized = resolver.serialize(p);
    return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
    id = normalizeId(id);
    return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
        return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === undefined)
            return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
            innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
            // eslint-disable-next-line @typescript-eslint/unbound-method
            const _resolve = this.opts.uriResolver.resolve;
            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
            if (schemaRefs.has(ref))
                throw ambiguos(ref);
            schemaRefs.add(ref);
            let schOrRef = this.refs[ref];
            if (typeof schOrRef == "string")
                schOrRef = this.refs[schOrRef];
            if (typeof schOrRef == "object") {
                checkAmbiguosRef(sch, schOrRef.schema, ref);
            }
            else if (ref !== normalizeId(fullPath)) {
                if (ref[0] === "#") {
                    checkAmbiguosRef(sch, localRefs[ref], ref);
                    localRefs[ref] = sch;
                }
                else {
                    this.refs[ref] = fullPath;
                }
            }
            return ref;
        }
        function addAnchor(anchor) {
            if (typeof anchor == "string") {
                if (!ANCHOR.test(anchor))
                    throw new Error(`invalid anchor "${anchor}"`);
                addRef.call(this, `#${anchor}`);
            }
        }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== undefined && !equal(sch1, sch2))
            throw ambiguos(ref);
    }
    function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
    }
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../lib/compile/resolve.ts"],"names":[],"mappings":";;;AAGA,iCAA+B;AAC/B,yCAAwC;AACxC,iDAAgD;AAKhD,2CAA2C;AAC3C,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,MAAM;IACN,QAAQ;IACR,SAAS;IACT,WAAW;IACX,WAAW;IACX,eAAe;IACf,eAAe;IACf,UAAU;IACV,UAAU;IACV,SAAS;IACT,SAAS;IACT,aAAa;IACb,YAAY;IACZ,UAAU;IACV,MAAM;IACN,OAAO;CACR,CAAC,CAAA;AAEF,SAAgB,SAAS,CAAC,MAAiB,EAAE,QAA0B,IAAI;IACzE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,IAAI,CAAA;IAC3C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IAC1C,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAA;IACxB,OAAO,SAAS,CAAC,MAAM,CAAC,IAAI,KAAK,CAAA;AACnC,CAAC;AALD,8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,KAAK,CAAC,cAAc,GAAG,oCAAoC,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AAxDD,sCAwDC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
    return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
    const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] },
    };
    return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {},
    };
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../lib/compile/rules.ts"],"names":[],"mappings":";;;AAEA,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAA;AAIjG,MAAM,SAAS,GAAgB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;AAElD,SAAgB,UAAU,CAAC,CAAU;IACnC,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAFD,gCAEC;AAyBD,SAAgB,QAAQ;IACtB,MAAM,MAAM,GAAgE;QAC1E,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,KAAK,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAC;QACjC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;KACpC,CAAA;IACD,OAAO;QACL,KAAK,EAAE,EAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAC;QAC5D,KAAK,EAAE,CAAC,EAAC,KAAK,EAAE,EAAE,EAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/E,IAAI,EAAE,EAAC,KAAK,EAAE,EAAE,EAAC;QACjB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;KACb,CAAA;AACH,CAAC;AAdD,4BAcC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = require("./codegen");
const code_1 = require("./codegen/code");
// TODO refactor to use Set
function toHash(arr) {
    const hash = {};
    for (const item of arr)
        hash[item] = true;
    return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
    if (typeof schema == "boolean")
        return schema;
    if (Object.keys(schema).length === 0)
        return true;
    checkUnknownRules(it, schema);
    return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
    const { opts, self } = it;
    if (!opts.strictSchema)
        return;
    if (typeof schema === "boolean")
        return;
    const rules = self.RULES.keywords;
    for (const key in schema) {
        if (!rules[key])
            checkStrictMode(it, `unknown keyword: "${key}"`);
    }
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (rules[key])
            return true;
    return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
            return true;
    return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
    if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
            return schema;
        if (typeof schema == "string")
            return (0, codegen_1._) `${schema}`;
    }
    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
    if (typeof str == "number")
        return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
    if (Array.isArray(xs)) {
        for (const x of xs)
            f(x);
    }
    else {
        f(xs);
    }
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
    return (gen, from, to, toName) => {
        const res = to === undefined
            ? from
            : to instanceof codegen_1.Name
                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
                : from instanceof codegen_1.Name
                    ? (mergeToName(gen, to, from), from)
                    : mergeValues(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
}
exports.mergeEvaluated = {
    props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
            if (from === true) {
                gen.assign(to, true);
            }
            else {
                gen.assign(to, (0, codegen_1._) `${to} || {}`);
                setEvaluated(gen, to, from);
            }
        }),
        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
        resultToName: evaluatedPropsToName,
    }),
    items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
        resultToName: (gen, items) => gen.var("items", items),
    }),
};
function evaluatedPropsToName(gen, ps) {
    if (ps === true)
        return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._) `{}`);
    if (ps !== undefined)
        setEvaluated(gen, props, ps);
    return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
    return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
    });
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
    Type[Type["Num"] = 0] = "Num";
    Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    // let path
    if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax
            ? isNumber
                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
            : isNumber
                ? (0, codegen_1._) `"/" + ${dataProp}`
                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
    if (!mode)
        return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
        throw new Error(msg);
    it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map{"version":3,"file":"util.js","sourceRoot":"","sources":["../../lib/compile/util.ts"],"names":[],"mappings":";;;AAEA,uCAA6D;AAC7D,yCAAoC;AAGpC,2BAA2B;AAC3B,SAAgB,MAAM,CAA4B,GAAQ;IACxD,MAAM,IAAI,GAAsB,EAAE,CAAA;IAClC,KAAK,MAAM,IAAI,IAAI,GAAG;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACzC,OAAO,IAAI,CAAA;AACb,CAAC;AAJD,wBAIC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,MAAiB;IAChE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,MAAM,CAAA;IAC7C,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IACjD,iBAAiB,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;IAC7B,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACnD,CAAC;AALD,8CAKC;AAED,SAAgB,iBAAiB,CAAC,EAA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,OAAM;IACjB,GAAG,GAAG,gBAAgB,GAAG,EAAE,CAAA;IAC3B,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AATD,0CASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
    const group = self.RULES.types[type];
    return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
    var _a;
    return (schema[rule.keyword] !== undefined ||
        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map{"version":3,"file":"applicability.js","sourceRoot":"","sources":["../../../lib/compile/validate/applicability.ts"],"names":[],"mappings":";;;AAIA,SAAgB,qBAAqB,CACnC,EAAC,MAAM,EAAE,IAAI,EAAe,EAC5B,IAAc;IAEd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACpC,OAAO,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AACjE,CAAC;AAND,sDAMC;AAED,SAAgB,cAAc,CAAC,MAAuB,EAAE,KAAgB;IACtE,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAuB,EAAE,IAAU;;IAC/D,OAAO,CACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,SAAS;SAClC,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC,CAAA,CACrE,CAAA;AACH,CAAC;AALD,sCAKC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const boolError = {
    message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
    const { gen, schema, validateName } = it;
    if (schema === false) {
        falseSchemaError(it, false);
    }
    else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
        gen.return(true);
    }
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
    const { gen, schema } = it;
    if (schema === false) {
        gen.var(valid, false); // TODO var
        falseSchemaError(it);
    }
    else {
        gen.var(valid, true); // TODO var
    }
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
    const { gen, data } = it;
    // TODO maybe some other interface should be used for non-keyword validation errors...
    const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it,
    };
    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map{"version":3,"file":"boolSchema.js","sourceRoot":"","sources":["../../../lib/compile/validate/boolSchema.ts"],"names":[],"mappings":";;;AAEA,sCAAqC;AACrC,wCAAkC;AAClC,oCAAwB;AAExB,MAAM,SAAS,GAA2B;IACxC,OAAO,EAAE,yBAAyB;CACnC,CAAA;AAED,SAAgB,oBAAoB,CAAC,EAA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AA,oBAAW,EAAC,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;AAC3D,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = require("../rules");
const applicability_1 = require("./applicability");
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const util_1 = require("../util");
var DataType;
(function (DataType) {
    DataType[DataType["Correct"] = 0] = "Correct";
    DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
    const types = getJSONTypes(schema.type);
    const hasNull = types.includes("null");
    if (hasNull) {
        if (schema.nullable === false)
            throw new Error("type: null contradicts nullable: false");
    }
    else {
        if (!types.length && schema.nullable !== undefined) {
            throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
            types.push("null");
    }
    return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
    if (types.every(rules_1.isJSONType))
        return types;
    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
    const { gen, data, opts } = it;
    const coerceTo = coerceToTypes(types, opts.coerceTypes);
    const checkTypes = types.length > 0 &&
        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
    if (checkTypes) {
        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
            if (coerceTo.length)
                coerceData(it, types, coerceTo);
            else
                reportTypeError(it);
        });
    }
    return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
    return coerceTypes
        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
        : [];
}
function coerceData(it, types, coerceTo) {
    const { gen, data, opts } = it;
    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
    if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
            .assign(data, (0, codegen_1._) `${data}[0]`)
            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
    }
    gen.if((0, codegen_1._) `${coerced} !== undefined`);
    for (const t of coerceTo) {
        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
            coerceSpecificType(t);
        }
    }
    gen.else();
    reportTypeError(it);
    gen.endIf();
    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
    });
    function coerceSpecificType(t) {
        switch (t) {
            case "string":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
                    .elseIf((0, codegen_1._) `${data} === null`)
                    .assign(coerced, (0, codegen_1._) `""`);
                return;
            case "number":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "integer":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "boolean":
                gen
                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
                    .assign(coerced, false)
                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
                    .assign(coerced, true);
                return;
            case "null":
                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
                gen.assign(coerced, null);
                return;
            case "array":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
                    .assign(coerced, (0, codegen_1._) `[${data}]`);
        }
    }
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    // TODO use gen.property
    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType) {
        case "null":
            return (0, codegen_1._) `${data} ${EQ} null`;
        case "array":
            cond = (0, codegen_1._) `Array.isArray(${data})`;
            break;
        case "object":
            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
            break;
        case "integer":
            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
            break;
        case "number":
            cond = numCond();
            break;
        default:
            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
    }
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
    if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
    }
    let cond;
    const types = (0, util_1.toHash)(dataTypes);
    if (types.array && types.object) {
        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
        delete types.null;
        delete types.array;
        delete types.object;
    }
    else {
        cond = codegen_1.nil;
    }
    if (types.number)
        delete types.integer;
    for (const t in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
    return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
    const cxt = getTypeErrorContext(it);
    (0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
    const { gen, data, schema } = it;
    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
    return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it,
    };
}
//# sourceMappingURL=dataType.js.map{"version":3,"file":"dataType.js","sourceRoot":"","sources":["../../../lib/compile/validate/dataType.ts"],"names":[],"mappings":";;;AAOA,oCAA6C;AAC7C,mDAAqD;AACrD,sCAAqC;AACrC,wCAAkE;AAClE,kCAA8C;AAE9C,IAAY,QAGX;AAHD,WAAY,QAAQ;IAClB,6CAAO,CAAA;IACP,yCAAK,CAAA;AACP,CAAC,EAHW,QAAQ,wBAAR,QAAQ,QAGnB;AAED,SAAgB,cAAc,CAAC,MAAuB;IACpD,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;IACtC,IAAI,OAAO,EAAE,CAAC;QACZ,IAAI,MAAM,CAAC,QAAQ,KAAK,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IAC1F,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACnD,MAAM,IAAI,KAAK,CAAC,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,GAAG,IAAA,aAAG,EAAC,IAAI,EAAE,aAAa,CAAC,CAAa,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAA;IAChG,OAAO,IAAI,CAAA;AACb,CAAC;AAvBD,wCAuBC;AAID,MAAM,SAAS,GAA2B;IACxC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,WAAW,MAAM,EAAE;IAC1C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,WAAW,EAAC,EAAE,EAAE,CAChC,OAAO,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,MAAM,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,WAAW,GAAG;CAC/E,CAAA;AAED,SAAgB,eAAe,CAAC,EAAgB;IAC9C,MAAM,GAAG,GAAG,mBAAmB,CAAC,EAAE,CAAC,CAAA;IACnC,IAAA,oBAAW,EAAC,GAAG,EAAE,SAAS,CAAC,CAAA;AAC7B,CAAC;AAHD,0CAGC;AAED,SAAS,mBAAmB,CAAC,EAAgB;IAC3C,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IAC9B,MAAM,UAAU,GAAG,IAAA,qBAAc,EAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACrD,OAAO;QACL,GAAG;QACH,OAAO,EAAE,MAAM;QACf,IAAI;QACJ,MAAM,EAAE,MAAM,CAAC,IAAI;QACnB,UAAU;QACV,WAAW,EAAE,UAAU;QACvB,YAAY,EAAE,MAAM;QACpB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;AACH,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignDefaults = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function assignDefaults(it, ty) {
    const { properties, items } = it.schema;
    if (ty === "object" && properties) {
        for (const key in properties) {
            assignDefault(it, key, properties[key].default);
        }
    }
    else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
    }
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
    const { gen, compositeRule, data, opts } = it;
    if (defaultValue === undefined)
        return;
    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
    }
    let condition = (0, codegen_1._) `${childData} === undefined`;
    if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
    }
    // `${childData} === undefined` +
    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../../lib/compile/validate/defaults.ts"],"names":[],"mappings":";;;AACA,wCAAoD;AACpD,kCAAuC;AAEvC,SAAgB,cAAc,CAAC,EAAgB,EAAE,EAAW;IAC1D,MAAM,EAAC,UAAU,EAAE,KAAK,EAAC,GAAG,EAAE,CAAC,MAAM,CAAA;IACrC,IAAI,EAAE,KAAK,QAAQ,IAAI,UAAU,EAAE,CAAC;QAClC,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;YAC7B,aAAa,CAAC,EAAE,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAA;QACjD,CAAC;IACH,CAAC;SAAM,IAAI,EAAE,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAClD,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAS,EAAE,EAAE,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAA;IACtE,CAAC;AACH,CAAC;AATD,wCASC;AAED,SAAS,aAAa,CAAC,EAAgB,EAAE,IAAqB,EAAE,YAAqB;IACnF,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IAC3C,IAAI,YAAY,KAAK,SAAS;QAAE,OAAM;IACtC,MAAM,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,EAAE,CAAA;IAChD,IAAI,aAAa,EAAE,CAAC;QAClB,IAAA,sBAAe,EAAC,EAAE,EAAE,2BAA2B,SAAS,EAAE,CAAC,CAAA;QAC3D,OAAM;IACR,CAAC;IAED,IAAI,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,gBAAgB,CAAA;IAC7C,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,EAAE,CAAC;QACjC,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,OAAO,SAAS,gBAAgB,SAAS,SAAS,CAAA;IAC7E,CAAC;IACD,iCAAiC;IACjC,2FAA2F;IAC3F,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,MAAM,IAAA,mBAAS,EAAC,YAAY,CAAC,EAAE,CAAC,CAAA;AACjE,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = require("./boolSchema");
const dataType_1 = require("./dataType");
const applicability_1 = require("./applicability");
const dataType_2 = require("./dataType");
const defaults_1 = require("./defaults");
const keyword_1 = require("./keyword");
const subschema_1 = require("./subschema");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const resolve_1 = require("../resolve");
const util_1 = require("../util");
const errors_1 = require("../errors");
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            topSchemaObjCode(it);
            return;
        }
    }
    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
            destructureValCxtES5(gen, opts);
            gen.code(body);
        });
    }
    else {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
}
function destructureValCxt(opts) {
    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
    });
}
function topSchemaObjCode(it) {
    const { schema, opts, gen } = it;
    validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
            commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
            resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
    });
    return;
}
function resetEvaluated(it) {
    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
    const { gen, validateName } = it;
    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            subSchemaObjCode(it, valid);
            return;
        }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (self.RULES.all[key])
            return true;
    return false;
}
function isSchemaObj(it) {
    return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
    const { schema, gen, opts } = it;
    if (opts.$comment && schema.$comment)
        commentKeyword(it);
    updateContext(it);
    checkAsyncSchema(it);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it, errsCount);
    // TODO var
    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
    (0, util_1.checkUnknownRules)(it);
    checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
    if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
    const types = (0, dataType_1.getSchemaTypes)(it.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
    schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
    const { schema, errSchemaPath, opts, self } = it;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
}
function checkNoDefault(it) {
    const { schema, opts } = it;
    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
    }
}
function updateContext(it) {
    const schId = it.schema[it.opts.schemaId];
    if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
    if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
    }
    else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
}
function returnResults(it) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
    if (schemaEnv.$async) {
        // TODO assign unevaluated
        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
            assignEvaluated(it);
        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
    }
}
function assignEvaluated({ gen, evaluated, props, items }) {
    if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
    if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
    const { gen, schema, data, allErrors, opts, self } = it;
    const { RULES } = self;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
        return;
    }
    if (!opts.jtd)
        checkStrictTypes(it, types);
    gen.block(() => {
        for (const group of RULES.rules)
            groupKeywords(group);
        groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
            return;
        if (group.type) {
            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
            iterateKeywords(it, group);
            if (types.length === 1 && types[0] === group.type && typeErrors) {
                gen.else();
                (0, dataType_2.reportTypeError)(it);
            }
            gen.endIf();
        }
        else {
            iterateKeywords(it, group);
        }
        // TODO make it "ok" call?
        if (!allErrors)
            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
    }
}
function iterateKeywords(it, group) {
    const { gen, schema, opts: { useDefaults }, } = it;
    if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
    gen.block(() => {
        for (const rule of group.rules) {
            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
                keywordCode(it, rule.keyword, rule.definition, group.type);
            }
        }
    });
}
function checkStrictTypes(it, types) {
    if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
    checkContextTypes(it, types);
    if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types);
    checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
    if (!types.length)
        return;
    if (!it.dataTypes.length) {
        it.dataTypes = types;
        return;
    }
    types.forEach((t) => {
        if (!includesType(it.dataTypes, t)) {
            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
    });
    narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
    }
}
function checkKeywordTypes(it, ts) {
    const rules = it.self.RULES.all;
    for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
            const { type } = rule.definition;
            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
            }
        }
    }
}
function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
    return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
    const ts = [];
    for (const t of it.dataTypes) {
        if (includesType(withTypes, t))
            ts.push(t);
        else if (withTypes.includes("integer") && t === "number")
            ts.push("integer");
    }
    it.dataTypes = ts;
}
function strictTypesError(it, msg) {
    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
    constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        }
        else {
            this.schemaCode = this.schemaValue;
            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
            }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
            this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
    }
    result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
            failAction();
        else
            this.error();
        if (successAction) {
            this.gen.else();
            successAction();
            if (this.allErrors)
                this.gen.endIf();
        }
        else {
            if (this.allErrors)
                this.gen.endIf();
            else
                this.gen.else();
        }
    }
    pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
    }
    fail(condition) {
        if (condition === undefined) {
            this.error();
            if (!this.allErrors)
                this.gen.if(false); // this branch will be removed by gen.optimize
            return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
            this.gen.endIf();
        else
            this.gen.else();
    }
    fail$data(condition) {
        if (!this.$data)
            return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
        if (errorParams) {
            this.setParams(errorParams);
            this._error(append, errorPaths);
            this.setParams({});
            return;
        }
        this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
        if (this.errsCount === undefined)
            throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
        if (!this.allErrors)
            this.gen.if(cond);
    }
    setParams(obj, assign) {
        if (assign)
            Object.assign(this.params, obj);
        else
            this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
            this.check$data(valid, $dataValid);
            codeBlock();
        });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
            return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
            gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
            gen.elseIf(this.invalid$data());
            this.$dataError();
            if (valid !== codegen_1.nil)
                gen.assign(valid, false);
        }
        gen.else();
    }
    invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
            if (schemaType.length) {
                /* istanbul ignore if */
                if (!(schemaCode instanceof codegen_1.Name))
                    throw new Error("ajv implementation error");
                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
            }
            return codegen_1.nil;
        }
        function invalid$DataSchema() {
            if (def.validateSchema) {
                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
            }
            return codegen_1.nil;
        }
    }
    subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
        subschemaCode(nextContext, valid);
        return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
            return;
        if (it.props !== true && schemaCxt.props !== undefined) {
            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== undefined) {
            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
    }
    mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
            return true;
        }
    }
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
    const cxt = new KeywordCxt(it, def, keyword);
    if ("code" in def) {
        def.code(cxt, ruleType);
    }
    else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
    else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
    }
    else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data;
    if ($data === "")
        return names_1.default.rootData;
    if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
    }
    else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
            if (up >= dataLevel)
                throw new Error(errorMsg("property/index", up));
            return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
            throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
            return data;
    }
    let expr = data;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
        if (segment) {
            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
            expr = (0, codegen_1._) `${expr} && ${data}`;
        }
    }
    return expr;
    function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
    }
}
exports.getData = getData;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/validate/index.ts"],"names":[],"mappings":";;;AASA,6CAAoE;AACpE,yCAAiE;AACjE,mDAA6D;AAC7D,yCAAmF;AACnF,yCAAyC;AACzC,uCAAkG;AAClG,2CAAiG;AACjG,wCAAwF;AACxF,oCAAwB;AACxB,wCAAqC;AACrC,kCAOgB;AAEhB,sCAMkB;AAElB,mGAAmG;AACnG,SAAgB,oBAAoB,CAAC,EAAa;IAChD,IAAI,WAAW,CAAC,EAAE,CAAC,EAAE,CAAC;QACpB,aAAa,CAAC,EAAE,CAAC,CAAA;QACjB,IAAI,iBAAiB,CAAC,EAAE,CAAC,EAAE,CAAC;YAC1B,gBAAgB,CAAC,EAAE,CAAC,CAAA;YACpB,OAAM;QACR,CAAC;IACH,CAAC;IACD,gBAAgB,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,IAAA,iCAAoB,EAAC,EAAE,CAAC,CAAC,CAAA;AACtD,CAAC;AATD,oDASC;AAED,SAAS,gBAAgB,CACvB,EAAC,GAAG,EAAE,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAY,EACvD,IAAW;IAEX,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAClB,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,KAAK,eAAC,CAAC,MAAM,EAAE,EAAE,SAAS,CAAC,MAAM,EAAE,GAAG,EAAE;YACvE,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,iBAAiB,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,CAAA;YACzD,oBAAoB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;YAC/B,GAAG,CAAC,IAAI,CAAC,IAAI,C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CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAA;QACzD,IAAI,GAAG,SAAS,CAAC,SAAS,GAAG,EAAE,CAAC,CAAA;QAChC,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAA;IAC/B,CAAC;IAED,IAAI,IAAI,GAAG,IAAI,CAAA;IACf,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAA,0BAAmB,EAAC,OAAO,CAAC,CAAC,EAAE,CAAA;YAC7D,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,EAAE,CAAA;QAC9B,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;IAEX,SAAS,QAAQ,CAAC,WAAmB,EAAE,EAAU;QAC/C,OAAO,iBAAiB,WAAW,IAAI,EAAE,gCAAgC,SAAS,EAAE,CAAA;IACtF,CAAC;AACH,CAAC;AAtCD,0BAsCC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const errors_1 = require("../errors");
function macroKeywordCode(cxt, def) {
    const { gen, keyword, schema, parentSchema, it } = cxt;
    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
    const schemaRef = useKeyword(gen, keyword, macroSchema);
    if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true,
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
    var _a;
    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
    checkAsyncKeyword(it, def);
    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
    const validateRef = useKeyword(gen, keyword, validate);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
    function validateKeyword() {
        if (def.errors === false) {
            assignValid();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => cxt.error());
        }
        else {
            const ruleErrs = def.async ? validateAsync() : validateSync();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => addErrs(cxt, ruleErrs));
        }
    }
    function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
        return ruleErrs;
    }
    function validateSync() {
        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !(("compile" in def && !$data) || def.schema === false);
        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors) {
        var _a;
        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
    }
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
    const { gen, data, it } = cxt;
    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
        gen
            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
    if (result === undefined)
        throw new Error(`keyword "${keyword}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
    // TODO add tests
    return (!schemaType.length ||
        schemaType.some((st) => st === "array"
            ? Array.isArray(schema)
            : st === "object"
                ? schema && typeof schema == "object" && !Array.isArray(schema)
                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
    /* istanbul ignore if */
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
                self.errorsText(def.validateSchema.errors);
            if (opts.validateSchema === "log")
                self.logger.error(msg);
            else
                throw new Error(msg);
        }
    }
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map{"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../lib/compile/validate/keyword.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,GAAG,GAAG,CAAC,YAAY,CAAA;IAC7B,IAAI,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,2CAA2C,OAAO,KAAK,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC1F,CAAC;IAED,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC;QACvB,MAAM,KAAK,GAAG,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAA;QACjD,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,GAAG,GACP,YAAY,OAAO,+BAA+B,aAAa,KAAK;gBACpE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;YAC5C,IAAI,IAAI,CAAC,cAAc,KAAK,KAAK;gBAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;;gBACpD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;QAC3B,CAAC;IACH,CAAC;AACH,CAAC;AAzBD,oDAyBC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword !== undefined && schema !== undefined) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword !== undefined) {
        const sch = it.schema[keyword];
        return schemaProp === undefined
            ? {
                schema: sch,
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
            }
            : {
                schema: sch[schemaProp],
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
            };
    }
    if (schema !== undefined) {
        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
            schema,
            schemaPath,
            topSchemaRef,
            errSchemaPath,
        };
    }
    throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
    if (data !== undefined && dataProp !== undefined) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it;
    if (dataProp !== undefined) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
    }
    if (data !== undefined) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
        dataContextProps(nextData);
        if (propertyName !== undefined)
            subschema.propertyName = propertyName;
        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
    }
    if (dataTypes)
        subschema.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
    }
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== undefined)
        subschema.compositeRule = compositeRule;
    if (createErrors !== undefined)
        subschema.createErrors = createErrors;
    if (allErrors !== undefined)
        subschema.allErrors = allErrors;
    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
    subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map{"version":3,"file":"subschema.js","sourceRoot":"","sources":["../../../lib/compile/validate/subschema.ts"],"names":[],"mappings":";;;AAEA,wCAA0D;AAC1D,kCAA0D;AA6C1D,SAAgB,YAAY,CAC1B,EAAgB,EAChB,EAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAgB;IAErF,IAAI,OAAO,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QAC9B,OAAO,UAAU,KAAK,SAAS;YAC7B,CAAC,CAAC;gBACE,MAAM,EAAE,GAAG;gBACX,UAAU,EAAE,IAAA,WAAC,EAAA,GAAG,EAAE,CAAC,UAAU,GAAG,IAAA,qBAAW,EAAC,OAAO,CAAC,EAAE;gBACtD,aAAa,EAAE,GAAG,EAAE,CAAC,aAAa,IAAI,OAAO,EAAE;aAChD;YACH,CAAC,CAAC;gBACE,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC;gBACvB,UAAU,EAAE,IAAA,WAAC,EAAA,GAAG,EAAE,CAAC,UAAU,GAAG,IAAA,qBAAW,EAAC,OAAO,CAAC,GAAG,IAAA,qBAAW,EAAC,UAAU,CAAC,EAAE;gBAChF,aAAa,EAAE,GAAG,EAAE,CAAC,aA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,GAAG,YAAY,CAAA;IACrE,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5D,SAAS,CAAC,gBAAgB,GAAG,gBAAgB,CAAA,CAAC,gBAAgB;IAC9D,SAAS,CAAC,WAAW,GAAG,WAAW,CAAA,CAAC,gBAAgB;AACtD,CAAC;AATD,kDASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const type_1 = require("../../vocabularies/jtd/type");
const parseJson_1 = require("../../runtime/parseJson");
const util_1 = require("../util");
const timestamp_1 = require("../../runtime/timestamp");
const genParse = {
    elements: parseElements,
    values: parseValues,
    discriminator: parseDiscriminator,
    properties: parseProperties,
    optionalProperties: parseProperties,
    enum: parseEnum,
    type: parseType,
    ref: parseRef,
};
function compileParser(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const parseName = gen.scopeName("parse");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
        parseName,
        char: gen.name("c"),
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.parseName = parseName;
        parserFunction(cxt);
        gen.optimize(this.opts.code.optimize);
        const parseFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
        const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
        const parse = makeParse(this.scope.get());
        this.scope.value(parseName, { ref: parse });
        sch.parse = parse;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling parser, function code:", sourceCode);
        delete sch.parse;
        delete sch.parseName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileParser;
const undef = (0, codegen_1._) `undefined`;
function parserFunction(cxt) {
    const { gen, parseName, char } = cxt;
    gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
        gen.let(names_1.default.data);
        gen.let(char);
        gen.assign((0, codegen_1._) `${parseName}.message`, undef);
        gen.assign((0, codegen_1._) `${parseName}.position`, undef);
        gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`);
        gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`);
        parseCode(cxt);
        skipWhitespace(cxt);
        gen.if(names_1.default.jsonPart, () => {
            gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
            gen.return(names_1.default.data);
        });
        gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
        jsonSyntaxError(cxt);
    });
}
function parseCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    if (form)
        parseNullable(cxt, genParse[form]);
    else
        parseEmpty(cxt);
}
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
function parseNullable(cxt, parseForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return parseForm(cxt);
    tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
}
function parseElements(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "[");
    const ix = gen.let("i", 0);
    gen.assign(data, (0, codegen_1._) `[]`);
    parseItems(cxt, "]", () => {
        const el = gen.let("el");
        parseCode({ ...cxt, schema: schema.elements, data: el });
        gen.assign((0, codegen_1._) `${data}[${ix}++]`, el);
    });
}
function parseValues(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
}
function parseItems(cxt, endToken, block) {
    tryParseItems(cxt, endToken, block);
    parseToken(cxt, endToken);
}
function tryParseItems(cxt, endToken, block) {
    const { gen } = cxt;
    gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
        block();
        tryParseToken(cxt, ",", () => gen.break(), hasItem);
    });
    function hasItem() {
        tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
    }
}
function parseKeyValue(cxt, schema) {
    const { gen } = cxt;
    const key = gen.let("key");
    parseString({ ...cxt, data: key });
    parseToken(cxt, ":");
    parsePropertyValue(cxt, key, schema);
}
function parseDiscriminator(cxt) {
    const { gen, data, schema } = cxt;
    const { discriminator, mapping } = schema;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    const startPos = gen.const("pos", names_1.default.jsonPos);
    const value = gen.let("value");
    const tag = gen.let("tag");
    tryParseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => {
            parseString({ ...cxt, data: tag });
            gen.assign((0, codegen_1._) `${data}[${key}]`, tag);
            gen.break();
        }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
        );
    });
    gen.assign(names_1.default.jsonPos, startPos);
    gen.if((0, codegen_1._) `${tag} === undefined`);
    parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`);
    for (const tagValue in mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
    }
    gen.else();
    parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`);
    gen.endIf();
}
function parseProperties(cxt) {
    const { gen, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseSchemaProperties(cxt);
}
function parseSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties, additionalProperties } = schema;
    parseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if(false);
        parseDefinedProperty(cxt, key, properties);
        parseDefinedProperty(cxt, key, optionalProperties);
        if (discriminator) {
            gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`);
            const tag = gen.let("tag");
            parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
        }
        gen.else();
        if (additionalProperties) {
            parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` });
        }
        else {
            parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`);
        }
        gen.endIf();
    });
    if (properties) {
        const hasProp = (0, code_1.hasPropFunc)(gen);
        const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`));
        gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`));
    }
}
function parseDefinedProperty(cxt, key, schemas = {}) {
    const { gen } = cxt;
    for (const prop in schemas) {
        gen.elseIf((0, codegen_1._) `${key} === ${prop}`);
        parsePropertyValue(cxt, key, schemas[prop]);
    }
}
function parsePropertyValue(cxt, key, schema) {
    parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` });
}
function parseType(cxt) {
    const { gen, schema, data, self } = cxt;
    switch (schema.type) {
        case "boolean":
            parseBoolean(cxt);
            break;
        case "string":
            parseString(cxt);
            break;
        case "timestamp": {
            parseString(cxt);
            const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
            const { allowDate, parseDate } = self.opts;
            const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`;
            const fail = parseDate
                ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`)
                : notValid;
            gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`));
            break;
        }
        case "float32":
        case "float64":
            parseNumber(cxt);
            break;
        default: {
            const t = schema.type;
            if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
                parseNumber(cxt, 16); // 2 ** 53 - max safe integer
                if (t === "uint32") {
                    gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
                }
            }
            else {
                const [min, max, maxDigits] = type_1.intRange[t];
                parseNumber(cxt, maxDigits);
                gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
            }
        }
    }
}
function parseString(cxt) {
    parseToken(cxt, '"');
    parseWith(cxt, parseJson_1.parseJsonString);
}
function parseEnum(cxt) {
    const { gen, data, schema } = cxt;
    const enumSch = schema.enum;
    parseToken(cxt, '"');
    // TODO loopEnum
    gen.if(false);
    for (const value of enumSch) {
        const valueStr = JSON.stringify(value).slice(1); // remove starting quote
        gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`);
        gen.assign(data, (0, codegen_1.str) `${value}`);
        gen.add(names_1.default.jsonPos, valueStr.length);
    }
    gen.else();
    jsonSyntaxError(cxt);
    gen.endIf();
}
function parseNumber(cxt, maxDigits) {
    const { gen } = cxt;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
}
function parseBooleanToken(bool, fail) {
    return (cxt) => {
        const { gen, data } = cxt;
        tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
    };
}
function parseRef(cxt) {
    const { gen, self, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return parseCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    partialParse(cxt, getParser(gen, sch), true);
}
function getParser(gen, sch) {
    return sch.parse
        ? gen.scopeValue("parse", { ref: sch.parse })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
}
function parseEmpty(cxt) {
    parseWith(cxt, parseJson_1.parseJson);
}
function parseWith(cxt, parseFunc, args) {
    partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args);
}
function partialParse(cxt, parseFunc, args) {
    const { gen, data } = cxt;
    gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`);
    gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`);
    gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`));
}
function parseToken(cxt, tok) {
    tryParseToken(cxt, tok, jsonSyntaxError);
}
function tryParseToken(cxt, tok, fail, success) {
    const { gen } = cxt;
    const n = tok.length;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => {
        gen.add(names_1.default.jsonPos, n);
        success === null || success === void 0 ? void 0 : success(cxt);
    }, () => fail(cxt));
}
function skipWhitespace({ gen, char: c }) {
    gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
}
function jsonSlice(len) {
    return len === 1
        ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]`
        : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
}
function jsonSyntaxError(cxt) {
    parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
}
function parsingError({ gen, parseName }, msg) {
    gen.assign((0, codegen_1._) `${parseName}.message`, msg);
    gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
    gen.return(undef);
}
//# sourceMappingURL=parse.js.map{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../../lib/compile/jtd/parse.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAmF;AACnF,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAmD;AACnD,oDAAiD;AACjD,sDAA6D;AAC7D,uDAAmF;AACnF,kCAA+B;AAC/B,uDAAoD;AAIpD,MAAM,QAAQ,GAA+B;IAC3C,QAAQ,EAAE,aAAa;IACvB,MAAM,EAAE,WAAW;IACnB,aAAa,EAAE,kBAAkB;IACjC,UAAU,EAAE,eAAe;IAC3B,kBAAkB,EAAE,eAAe;IACnC,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,QAAQ;CACd,CAAA;AAaD,SAAwB,aAAa,CAEnC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC/C,IAAI,IAAI;QAAE,OAAO,IAAI,CAAA;IACrB,MAAM,EAAC,GAAG,EAAE,KAAK,EAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;IACnC,MAAM,EAAC,aAAa,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IACjC,MAAM,GAAG,GAAG,IAAI,iBAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,aAAa,EAAC,CAAC,CAAA;IAChE,MAAM,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;IACxC,MAAM,GAAG,GAAa;QACpB,IAAI,EAAE,IAAI;QACV,GAAG;QACH,MAAM,EAAE,GAAG,CAAC,MAAs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EAAW,EAAE,GAAS;IACzD,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,UAAU,EAAE,GAAG,CAAC,CAAA;IACxC,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;IAC/C,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACnB,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const util_1 = require("../util");
const quote_1 = require("../../runtime/quote");
const genSerialize = {
    elements: serializeElements,
    values: serializeValues,
    discriminator: serializeDiscriminator,
    properties: serializeProperties,
    optionalProperties: serializeProperties,
    enum: serializeString,
    type: serializeType,
    ref: serializeRef,
};
function compileSerializer(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const serializeName = gen.scopeName("serialize");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.serializeName = serializeName;
        gen.func(serializeName, names_1.default.data, false, () => {
            gen.let(names_1.default.json, (0, codegen_1.str) ``);
            serializeCode(cxt);
            gen.return(names_1.default.json);
        });
        gen.optimize(this.opts.code.optimize);
        const serializeFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
        const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
        const serialize = makeSerialize(this.scope.get());
        this.scope.value(serializeName, { ref: serialize });
        sch.serialize = serialize;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling serializer, function code:", sourceCode);
        delete sch.serialize;
        delete sch.serializeName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileSerializer;
function serializeCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return serializeForm(cxt);
    gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `[`);
    const first = gen.let("first", true);
    gen.forOf("el", data, (el) => {
        addComma(cxt, first);
        serializeCode({ ...cxt, schema: schema.elements, data: el });
    });
    gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    const first = gen.let("first", true);
    gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
    const { gen, data } = cxt;
    addComma(cxt, first);
    serializeString({ ...cxt, data: key });
    gen.add(names_1.default.json, (0, codegen_1.str) `:`);
    const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
    const { gen, schema, data } = cxt;
    const { discriminator } = schema;
    gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
    const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
    serializeString({ ...cxt, data: tag });
    gen.if(false);
    for (const tagValue in schema.mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        const sch = schema.mapping[tagValue];
        serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
    }
    gen.endIf();
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
    const { gen } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    serializeSchemaProperties(cxt);
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties } = schema;
    const props = keys(properties);
    const optProps = keys(optionalProperties);
    const allProps = allProperties(props.concat(optProps));
    let first = !discriminator;
    let firstProp;
    for (const key of props) {
        if (first)
            first = false;
        else
            gen.add(names_1.default.json, (0, codegen_1.str) `,`);
        serializeProperty(key, properties[key], keyValue(key));
    }
    if (first)
        firstProp = gen.let("first", true);
    for (const key of optProps) {
        const value = keyValue(key);
        gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => {
            addComma(cxt, firstProp);
            serializeProperty(key, optionalProperties[key], value);
        });
    }
    if (schema.additionalProperties) {
        gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)));
    }
    function keys(ps) {
        return ps ? Object.keys(ps) : [];
    }
    function allProperties(ps) {
        if (discriminator)
            ps.push(discriminator);
        if (new Set(ps).size !== ps.length) {
            throw new Error("JTD: properties/optionalProperties/disciminator overlap");
        }
        return ps;
    }
    function keyValue(key) {
        return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    }
    function serializeProperty(key, propSchema, value) {
        gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
        serializeCode({ ...cxt, schema: propSchema, data: value });
    }
    function isAdditional(key, ps) {
        return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
    }
}
function serializeType(cxt) {
    const { gen, schema, data } = cxt;
    switch (schema.type) {
        case "boolean":
            gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
            break;
        case "string":
            serializeString(cxt);
            break;
        case "timestamp":
            gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
            break;
        default:
            serializeNumber(cxt);
    }
}
function serializeString({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data, self }) {
    const condition = (0, codegen_1._) `${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`;
    if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
        gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
    }
    else {
        // specialNumbers === "null"
        gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._) `null`), () => gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`));
    }
}
function serializeRef(cxt) {
    const { gen, self, data, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return serializeCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
    return sch.serialize
        ? gen.scopeValue("serialize", { ref: sch.serialize })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
    if (first) {
        gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
    }
    else {
        gen.add(names_1.default.json, (0, codegen_1.str) `,`);
    }
}
//# sourceMappingURL=serialize.js.map{"version":3,"file":"serialize.js","sourceRoot":"","sources":["../../../lib/compile/jtd/serialize.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAwE;AACxE,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAqD;AACrD,oDAAiD;AACjD,kCAA+B;AAC/B,+CAAuC;AAEvC,MAAM,YAAY,GAAkD;IAClE,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,eAAe;IACvB,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,mBAAmB;IAC/B,kBAAkB,EAAE,mBAAmB;IACvC,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,aAAa;IACnB,GAAG,EAAE,YAAY;CAClB,CAAA;AAWD,SAAwB,iBAAiB,CAEvC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC/C,IAAI,IAAI;QAAE,OAAO,IAAI,CAAA;IACrB,MAAM,EAAC,GAAG,EAAE,KAAK,EAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;IACnC,MAAM,EAAC,aAAa,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IACjC,MAAM,GAAG,GAAG,IAAI,iBAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,aAAa,EAAC,CAAC,CAAA;IAChE,MAAM,aAAa,GAAG,GAAG,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;IAChD,MAAM,GAAG,GAAiB;QACxB,IAAI,EAAE,IAAI;QACV,GAAG;QACH,MAAM,EAAE,GAAG,CAAC,MAAsB;QAClC,SAAS,EAAE,GAAG;QACd,WAAW;QACX,IAAI,EAAE,eAAC,CAAC,IAAI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AC,CAAA;AAC7C,CAAC;AAED,SAAS,QAAQ,CAAC,EAAC,GAAG,EAAe,EAAE,KAAY;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,EAAE,CACJ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC9B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAC9B,CAAA;IACH,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACzB,CAAC;AACH,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jtdForms = void 0;
exports.jtdForms = [
    "elements",
    "values",
    "discriminator",
    "properties",
    "optionalProperties",
    "enum",
    "type",
    "ref",
];
//# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
    constructor(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        return false;
    }
    get names() {
        return { [this.str]: 1 };
    }
}
exports.Name = Name;
class _Code extends _CodeOrName {
    constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        if (this._items.length > 1)
            return false;
        const item = this._items[0];
        return item === "" || item === '""';
    }
    get str() {
        var _a;
        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
    }
    get names() {
        var _a;
        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
            if (c instanceof Name)
                names[c.str] = (names[c.str] || 0) + 1;
            return names;
        }, {})));
    }
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
    const code = [strs[0]];
    let i = 0;
    while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
    }
    return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
    if (arg instanceof _Code)
        code.push(...arg._items);
    else if (arg instanceof Name)
        code.push(arg);
    else
        code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
        if (expr[i] === plus) {
            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
            if (res !== undefined) {
                expr.splice(i - 1, 3, res);
                continue;
            }
            expr[i++] = "+";
        }
        i++;
    }
}
function mergeExprItems(a, b) {
    if (b === '""')
        return a;
    if (a === '""')
        return b;
    if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
            return;
        if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
        return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.slice(1)}`;
    return;
}
function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null
        ? x
        : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
    return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
    return JSON.stringify(x)
        .replace(/\u2028/g, "\\u2028")
        .replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
    return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,kEAAkE;AAClE,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,YAAY,CAAS;QACnB,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAU,CAAC,IAAI,CAAC,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QACpF,IAAI,CAAC,GAAG,GAAG,CAAC,CAAA;IACd,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,OAAO,KAAK,CAAA;IACd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AAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAClC,CAAC;AAJD,sCAIC;AAED,SAAgB,WAAW,CAAC,GAA2B;IACrD,OAAO,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,IAAI,GAAG,GAAG,CAAA;AAC5F,CAAC;AAFD,kCAEC;AAED,8CAA8C;AAC9C,SAAgB,gBAAgB,CAAC,GAA2B;IAC1D,IAAI,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACnD,OAAO,IAAI,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC,CAAA;IAC5B,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,iCAAiC,GAAG,iCAAiC,CAAC,CAAA;AACxF,CAAC;AALD,4CAKC;AAED,SAAgB,UAAU,CAAC,EAAU;IACnC,OAAO,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;AACjC,CAAC;AAFD,gCAEC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = require("./code");
const scope_1 = require("./scope");
var code_2 = require("./code");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
var scope_2 = require("./scope");
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
exports.operators = {
    GT: new code_1._Code(">"),
    GTE: new code_1._Code(">="),
    LT: new code_1._Code("<"),
    LTE: new code_1._Code("<="),
    EQ: new code_1._Code("==="),
    NEQ: new code_1._Code("!=="),
    NOT: new code_1._Code("!"),
    OR: new code_1._Code("||"),
    AND: new code_1._Code("&&"),
    ADD: new code_1._Code("+"),
};
class Node {
    optimizeNodes() {
        return this;
    }
    optimizeNames(_names, _constants) {
        return this;
    }
}
class Def extends Node {
    constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
    }
    render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (!names[this.name.str])
            return;
        if (this.rhs)
            this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
    }
}
class Assign extends Node {
    constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
    }
    render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
            return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
    }
}
class AssignOp extends Assign {
    constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
    }
    render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
    }
}
class Label extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        return `${this.label}:` + _n;
    }
}
class Break extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
    }
}
class Throw extends Node {
    constructor(error) {
        super();
        this.error = error;
    }
    render({ _n }) {
        return `throw ${this.error};` + _n;
    }
    get names() {
        return this.error.names;
    }
}
class AnyCode extends Node {
    constructor(code) {
        super();
        this.code = code;
    }
    render({ _n }) {
        return `${this.code};` + _n;
    }
    optimizeNodes() {
        return `${this.code}` ? this : undefined;
    }
    optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
    }
    get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
    }
}
class ParentNode extends Node {
    constructor(nodes = []) {
        super();
        this.nodes = nodes;
    }
    render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
    }
    optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            const n = nodes[i].optimizeNodes();
            if (Array.isArray(n))
                nodes.splice(i, 1, ...n);
            else if (n)
                nodes[i] = n;
            else
                nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    optimizeNames(names, constants) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            // iterating backwards improves 1-pass optimization
            const n = nodes[i];
            if (n.optimizeNames(names, constants))
                continue;
            subtractNames(names, n.names);
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
    }
}
class BlockNode extends ParentNode {
    render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
    }
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
    constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
    }
    render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
            code += "else " + this.else.render(opts);
        return code;
    }
    optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
            return this.nodes; // else is ignored here
        let e = this.else;
        if (e) {
            const ns = e.optimizeNodes();
            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e) {
            if (cond === false)
                return e instanceof If ? e : e.nodes;
            if (this.nodes.length)
                return this;
            return new If(not(cond), e instanceof If ? [e] : e.nodes);
        }
        if (cond === false || !this.nodes.length)
            return undefined;
        return this;
    }
    optimizeNames(names, constants) {
        var _a;
        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
            return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
            addNames(names, this.else.names);
        return names;
    }
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
    constructor(iteration) {
        super();
        this.iteration = iteration;
    }
    render(opts) {
        return `for(${this.iteration})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iteration.names);
    }
}
class ForRange extends For {
    constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
    }
    render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
    }
    get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
    }
}
class ForIter extends For {
    constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
    }
    render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iterable.names);
    }
}
class Func extends BlockNode {
    constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
    }
    render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
    }
}
Func.kind = "func";
class Return extends ParentNode {
    render(opts) {
        return "return " + super.render(opts);
    }
}
Return.kind = "return";
class Try extends BlockNode {
    render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
            code += this.catch.render(opts);
        if (this.finally)
            code += this.finally.render(opts);
        return code;
    }
    optimizeNodes() {
        var _a, _b;
        super.optimizeNodes();
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
    }
    optimizeNames(names, constants) {
        var _a, _b;
        super.optimizeNames(names, constants);
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        if (this.catch)
            addNames(names, this.catch.names);
        if (this.finally)
            addNames(names, this.finally.names);
        return names;
    }
}
class Catch extends BlockNode {
    constructor(error) {
        super();
        this.error = error;
    }
    render(opts) {
        return `catch(${this.error})` + super.render(opts);
    }
}
Catch.kind = "catch";
class Finally extends BlockNode {
    render(opts) {
        return "finally" + super.render(opts);
    }
}
Finally.kind = "finally";
class CodeGen {
    constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
    }
    toString() {
        return this._root.render(this.opts);
    }
    // returns unique name in the internal scope
    name(prefix) {
        return this._scope.name(prefix);
    }
    // reserves unique name in the external scope
    scopeName(prefix) {
        return this._extScope.name(prefix);
    }
    // reserves unique name in the external scope and assigns value to it
    scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
        vs.add(name);
        return name;
    }
    getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
    }
    // return code that assigns values in the external scope to the names that are used internally
    // (same names that were returned by gen.scopeName or gen.scopeValue)
    scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
    }
    scopeCode() {
        return this._extScope.scopeCode(this._values);
    }
    _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== undefined && constant)
            this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
    }
    // `const` declaration (`var` in es5 mode)
    const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
    }
    // `let` declaration with optional assignment (`var` in es5 mode)
    let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
    }
    // `var` declaration with optional assignment
    var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
    }
    // assignment code
    assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
    }
    // `+=` code
    add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
    }
    // appends passed SafeExpr to code or executes Block
    code(c) {
        if (typeof c == "function")
            c();
        else if (c !== code_1.nil)
            this._leafNode(new AnyCode(c));
        return this;
    }
    // returns code for object literal for the passed argument list of key-value pairs
    object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
            if (code.length > 1)
                code.push(",");
            code.push(key);
            if (key !== value || this.opts.es5) {
                code.push(":");
                (0, code_1.addCodeArg)(code, value);
            }
        }
        code.push("}");
        return new code_1._Code(code);
    }
    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
    if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
            this.code(thenBody).else().code(elseBody).endIf();
        }
        else if (thenBody) {
            this.code(thenBody).endIf();
        }
        else if (elseBody) {
            throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
    }
    // `else if` clause - invalid without `if` or after `else` clauses
    elseIf(condition) {
        return this._elseNode(new If(condition));
    }
    // `else` clause - only valid after `if` or `else if` clauses
    else() {
        return this._elseNode(new Else());
    }
    // end `if` statement (needed if gen.if was used only with condition)
    endIf() {
        return this._endBlockNode(If, Else);
    }
    _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
            this.code(forBody).endFor();
        return this;
    }
    // a generic `for` clause (or statement if `forBody` is passed)
    for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
    }
    // `for` statement for a range of values
    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
    }
    // `for-of` statement (in es5 mode replace with a normal for loop)
    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
                this.var(name, (0, code_1._) `${arr}[${i}]`);
                forBody(name);
            });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
    }
    // `for-in` statement.
    // With option `ownProperties` replaced with a `for-of` loop for object keys
    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
    }
    // end `for` loop
    endFor() {
        return this._endBlockNode(For);
    }
    // `label` statement
    label(label) {
        return this._leafNode(new Label(label));
    }
    // `break` statement
    break(label) {
        return this._leafNode(new Break(label));
    }
    // `return` statement
    return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
            throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
    }
    // `try` statement
    try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
            throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
            const error = this.name("e");
            this._currNode = node.catch = new Catch(error);
            catchCode(error);
        }
        if (finallyCode) {
            this._currNode = node.finally = new Finally();
            this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
    }
    // `throw` statement
    throw(error) {
        return this._leafNode(new Throw(error));
    }
    // start self-balancing block
    block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
            this.code(body).endBlock(nodeCount);
        return this;
    }
    // end the current self-balancing block
    endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === undefined)
            throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
    }
    // `function` heading (or definition if funcBody is passed)
    func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
            this.code(funcBody).endFunc();
        return this;
    }
    // end function definition
    endFunc() {
        return this._endBlockNode(Func);
    }
    optimize(n = 1) {
        while (n-- > 0) {
            this._root.optimizeNodes();
            this._root.optimizeNames(this._root.names, this._constants);
        }
    }
    _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
    }
    _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
    }
    _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || (N2 && n instanceof N2)) {
            this._nodes.pop();
            return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
    }
    _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
            throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
    }
    get _root() {
        return this._nodes[0];
    }
    get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
    }
    set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
    }
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
    return names;
}
function addExprNames(names, from) {
    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
    if (expr instanceof code_1.Name)
        return replaceName(expr);
    if (!canOptimize(expr))
        return expr;
    return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
            c = replaceName(c);
        if (c instanceof code_1._Code)
            items.push(...c._items);
        else
            items.push(c);
        return items;
    }, []));
    function replaceName(n) {
        const c = constants[n.str];
        if (c === undefined || names[n.str] !== 1)
            return n;
        delete names[n.str];
        return c;
    }
    function canOptimize(e) {
        return (e instanceof code_1._Code &&
            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
    }
}
function subtractNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
    return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
    return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/codegen/index.ts"],"names":[],"mappings":";;;AACA,iCAA8F;AAC9F,mCAAuC;AAEvC,+BAA6F;AAArF,yFAAA,CAAC,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,mGAAA,WAAW,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,kGAAA,UAAU,OAAA;AAAE,4FAAA,IAAI,OAAA;AACxE,iCAA+F;AAAvF,8FAAA,KAAK,OAAA;AAAc,mGAAA,UAAU,OAAA;AAAE,uGAAA,cAAc,OAAA;AAAkB,iGAAA,QAAQ,OAAA;AAQlE,QAAA,SAAS,GAAG;IACvB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,YAAK,CAAC,KA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,QAAC,EAAA,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AACjF,CAAC;AAED,SAAS,GAAG,CAAC,CAAO;IAClB,OAAO,CAAC,YAAY,WAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,CAAC,GAAG,CAAA;AAC1C,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = require("./code");
class ValueError extends Error {
    constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
    }
}
var UsedValueState;
(function (UsedValueState) {
    UsedValueState[UsedValueState["Started"] = 0] = "Started";
    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
    const: new code_1.Name("const"),
    let: new code_1.Name("let"),
    var: new code_1.Name("var"),
};
class Scope {
    constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
    }
    toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
    }
    name(prefix) {
        return new code_1.Name(this._newName(prefix));
    }
    _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
    }
    _nameGroup(prefix) {
        var _a, _b;
        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return (this._names[prefix] = { prefix, index: 0 });
    }
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
    constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
    }
    setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
    }
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
    constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
    }
    get() {
        return this._scope;
    }
    name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
    }
    value(nameOrPrefix, value) {
        var _a;
        if (value.ref === undefined)
            throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
        let vs = this._values[prefix];
        if (vs) {
            const _name = vs.get(valueKey);
            if (_name)
                return _name;
        }
        else {
            vs = this._values[prefix] = new Map();
        }
        vs.set(valueKey, name);
        const s = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s.length;
        s[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
    }
    getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
            return;
        return vs.get(keyOrRef);
    }
    scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
            if (name.scopePath === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return (0, code_1._) `${scopeName}${name.scopePath}`;
        });
    }
    scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
            if (name.value === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return name.value.code;
        }, usedValues, getCode);
    }
    _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
            const vs = values[prefix];
            if (!vs)
                continue;
            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
            vs.forEach((name) => {
                if (nameSet.has(name))
                    return;
                nameSet.set(name, UsedValueState.Started);
                let c = valueCode(name);
                if (c) {
                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
                }
                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
                }
                else {
                    throw new ValueError(name);
                }
                nameSet.set(name, UsedValueState.Completed);
            });
        }
        return code;
    }
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../lib/compile/codegen/scope.ts"],"names":[],"mappings":";;;AAAA,iCAAyC;AAezC,MAAM,UAAW,SAAQ,KAAK;IAE5B,YAAY,IAAoB;QAC9B,KAAK,CAAC,uBAAuB,IAAI,cAAc,CAAC,CAAA;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAuBD,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,6DAAS,CAAA;AACX,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAMY,QAAA,QAAQ,GAAG;IACtB,KAAK,EAAE,IAAI,WAAI,CAAC,OAAO,CAAC;IACxB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;CACrB,CAAA;AAED,MAAa,KAAK;IAKhB,YAAY,EAAC,QAAQ,EAAE,MAAM,KAAkB,EAAE;QAJ9B,WAAM,GAAqC,EAAE,CAAA;QAK9D,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,MAAM,CAAC,YAA2B;QAChC,OAAO,YAAY,YAAY,WAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;IAC9E,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,WA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5B,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;YAC7C,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAjGD,gCAiGC"}extends: eslint:recommended
env:
  node: true
  browser: true
rules:
  block-scoped-var: 2
  complexity: [2, 15]
  curly: [2, multi-or-nest, consistent]
  dot-location: [2, property]
  dot-notation: 2
  indent: [2, 2, SwitchCase: 1]
  linebreak-style: [2, unix]
  new-cap: 2
  no-console: [2, allow: [warn, error]]
  no-else-return: 2
  no-eq-null: 2
  no-fallthrough: 2
  no-invalid-this: 2
  no-return-assign: 2
  no-shadow: 1
  no-trailing-spaces: 2
  no-use-before-define: [2, nofunc]
  quotes: [2, single, avoid-escape]
  semi: [2, always]
  strict: [2, global]
  valid-jsdoc: [2, requireReturn: false]
  no-control-regex: 0
MIT License

Copyright (c) 2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
{
  "name": "json-schema-traverse",
  "version": "1.0.0",
  "description": "Traverse JSON Schema passing each schema object to callback",
  "main": "index.js",
  "types": "index.d.ts",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/epoberezkin/json-schema-traverse.git"
  },
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://github.com/epoberezkin/json-schema-traverse#readme",
  "devDependencies": {
    "eslint": "^7.3.1",
    "mocha": "^8.0.1",
    "nyc": "^15.0.0",
    "pre-commit": "^1.2.2"
  }
}parserOptions:
  ecmaVersion: 6
globals:
  beforeEach: false
  describe: false
  it: false
'use strict';

var traverse = require('../index');
var assert = require('assert');

describe('json-schema-traverse', function() {
  var calls;

  beforeEach(function() {
    calls = [];
  });

  it('should traverse all keywords containing schemas recursively', function() {
    var schema = require('./fixtures/schema').schema;
    var expectedCalls = require('./fixtures/schema').expectedCalls;

    traverse(schema, {cb: callback});
    assert.deepStrictEqual(calls, expectedCalls);
  });

  describe('Legacy v0.3.1 API', function() {
    it('should traverse all keywords containing schemas recursively', function() {
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should work when an options object is provided', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, {}, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });


  describe('allKeys option', function() {
    var schema = {
      someObject: {
        minimum: 1,
        maximum: 2
      }
    };

    it('should traverse objects with allKeys: true option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined],
        [schema.someObject, '/someObject', schema, '', 'someObject', schema, undefined]
      ];

      traverse(schema, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects with allKeys: false option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {allKeys: false, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects without allKeys option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT travers objects in standard keywords which value is not a schema', function() {
      var schema2 = {
        const: {foo: 'bar'},
        enum: ['a', 'b'],
        required: ['foo'],
        another: {

        },
        patternProperties: {}, // will not traverse - no properties
        dependencies: true, // will not traverse - invalid
        properties: {
          smaller: {
            type: 'number'
          },
          larger: {
            type: 'number',
            minimum: {$data: '1/smaller'}
          }
        }
      };

      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema2, '', schema2, undefined, undefined, undefined, undefined],
        [schema2.another, '/another', schema2, '', 'another', schema2, undefined],
        [schema2.properties.smaller, '/properties/smaller', schema2, '', 'properties', schema2, 'smaller'],
        [schema2.properties.larger, '/properties/larger', schema2, '', 'properties', schema2, 'larger'],
      ];

      traverse(schema2, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  describe('pre and post', function() {
    var schema = {
      type: 'object',
      properties: {
        name: {type: 'string'},
        age: {type: 'number'}
      }
    };

    it('should traverse schema in pre-order', function() {
      traverse(schema, {cb: {pre}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in post-order', function() {
      traverse(schema, {cb: {post}});
      var expectedCalls = [
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in pre- and post-order at the same time', function() {
      traverse(schema, {cb: {pre, post}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  function callback() {
    calls.push(Array.prototype.slice.call(arguments));
  }

  function pre() {
    calls.push(['pre'].concat(Array.prototype.slice.call(arguments)));
  }

  function post() {
    calls.push(['post'].concat(Array.prototype.slice.call(arguments)));
  }
});
'use strict';

var schema = {
  additionalItems: subschema('additionalItems'),
  items: subschema('items'),
  contains: subschema('contains'),
  additionalProperties: subschema('additionalProperties'),
  propertyNames: subschema('propertyNames'),
  not: subschema('not'),
  allOf: [
    subschema('allOf_0'),
    subschema('allOf_1'),
    {
      items: [
        subschema('items_0'),
        subschema('items_1'),
      ]
    }
  ],
  anyOf: [
    subschema('anyOf_0'),
    subschema('anyOf_1'),
  ],
  oneOf: [
    subschema('oneOf_0'),
    subschema('oneOf_1'),
  ],
  definitions: {
    foo: subschema('definitions_foo'),
    bar: subschema('definitions_bar'),
  },
  properties: {
    foo: subschema('properties_foo'),
    bar: subschema('properties_bar'),
  },
  patternProperties: {
    foo: subschema('patternProperties_foo'),
    bar: subschema('patternProperties_bar'),
  },
  dependencies: {
    foo: subschema('dependencies_foo'),
    bar: subschema('dependencies_bar'),
  },
  required: ['foo', 'bar']
};


function subschema(keyword) {
  var sch = {
    properties: {},
    additionalProperties: false,
    additionalItems: false,
    anyOf: [
      {format: 'email'},
      {format: 'hostname'}
    ]
  };
  sch.properties['foo_' + keyword] = {title: 'foo'};
  sch.properties['bar_' + keyword] = {title: 'bar'};
  return sch;
}


module.exports = {
  schema: schema,

  // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
  expectedCalls: [[schema, '', schema, undefined, undefined, undefined, undefined]]
    .concat(expectedCalls('additionalItems'))
    .concat(expectedCalls('items'))
    .concat(expectedCalls('contains'))
    .concat(expectedCalls('additionalProperties'))
    .concat(expectedCalls('propertyNames'))
    .concat(expectedCalls('not'))
    .concat(expectedCallsChild('allOf', 0))
    .concat(expectedCallsChild('allOf', 1))
    .concat([
      [schema.allOf[2], '/allOf/2', schema, '', 'allOf', schema, 2],
      [schema.allOf[2].items[0], '/allOf/2/items/0', schema, '/allOf/2', 'items', schema.allOf[2], 0],
      [schema.allOf[2].items[0].properties.foo_items_0, '/allOf/2/items/0/properties/foo_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'foo_items_0'],
      [schema.allOf[2].items[0].properties.bar_items_0, '/allOf/2/items/0/properties/bar_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'bar_items_0'],
      [schema.allOf[2].items[0].anyOf[0], '/allOf/2/items/0/anyOf/0', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 0],
      [schema.allOf[2].items[0].anyOf[1], '/allOf/2/items/0/anyOf/1', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 1],

      [schema.allOf[2].items[1], '/allOf/2/items/1', schema, '/allOf/2', 'items', schema.allOf[2], 1],
      [schema.allOf[2].items[1].properties.foo_items_1, '/allOf/2/items/1/properties/foo_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'foo_items_1'],
      [schema.allOf[2].items[1].properties.bar_items_1, '/allOf/2/items/1/properties/bar_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'bar_items_1'],
      [schema.allOf[2].items[1].anyOf[0], '/allOf/2/items/1/anyOf/0', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 0],
      [schema.allOf[2].items[1].anyOf[1], '/allOf/2/items/1/anyOf/1', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 1]
    ])
    .concat(expectedCallsChild('anyOf', 0))
    .concat(expectedCallsChild('anyOf', 1))
    .concat(expectedCallsChild('oneOf', 0))
    .concat(expectedCallsChild('oneOf', 1))
    .concat(expectedCallsChild('definitions', 'foo'))
    .concat(expectedCallsChild('definitions', 'bar'))
    .concat(expectedCallsChild('properties', 'foo'))
    .concat(expectedCallsChild('properties', 'bar'))
    .concat(expectedCallsChild('patternProperties', 'foo'))
    .concat(expectedCallsChild('patternProperties', 'bar'))
    .concat(expectedCallsChild('dependencies', 'foo'))
    .concat(expectedCallsChild('dependencies', 'bar'))
};


function expectedCalls(keyword) {
  return [
    [schema[keyword], `/${keyword}`, schema, '', keyword, schema, undefined],
    [schema[keyword].properties[`foo_${keyword}`], `/${keyword}/properties/foo_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `foo_${keyword}`],
    [schema[keyword].properties[`bar_${keyword}`], `/${keyword}/properties/bar_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `bar_${keyword}`],
    [schema[keyword].anyOf[0], `/${keyword}/anyOf/0`, schema, `/${keyword}`, 'anyOf', schema[keyword], 0],
    [schema[keyword].anyOf[1], `/${keyword}/anyOf/1`, schema, `/${keyword}`, 'anyOf', schema[keyword], 1]
  ];
}


function expectedCallsChild(keyword, i) {
  return [
    [schema[keyword][i], `/${keyword}/${i}`, schema, '', keyword, schema, i],
    [schema[keyword][i].properties[`foo_${keyword}_${i}`], `/${keyword}/${i}/properties/foo_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `foo_${keyword}_${i}`],
    [schema[keyword][i].properties[`bar_${keyword}_${i}`], `/${keyword}/${i}/properties/bar_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `bar_${keyword}_${i}`],
    [schema[keyword][i].anyOf[0], `/${keyword}/${i}/anyOf/0`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 0],
    [schema[keyword][i].anyOf[1], `/${keyword}/${i}/anyOf/1`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 1]
  ];
}
const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  required: ["foo", "bar"],
  additionalProperties: false,
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}
The MIT License (MIT)

Copyright (c) 2015-2021 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

{
  "name": "ajv",
  "version": "8.20.0",
  "description": "Another JSON Schema Validator",
  "main": "dist/ajv.js",
  "types": "dist/ajv.d.ts",
  "files": [
    "lib/",
    "dist/",
    ".runkit_example.js"
  ],
  "sideEffects": false,
  "repository": "ajv-validator/ajv",
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://ajv.js.org",
  "runkitExampleFilename": ".runkit_example.js",
  "dependencies": {
    "fast-deep-equal": "^3.1.3",
    "fast-uri": "^3.0.1",
    "json-schema-traverse": "^1.0.0",
    "require-from-string": "^2.0.2"
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.5.0",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-typescript": "^11.1.6",
    "@types/chai": "^4.3.11",
    "@types/mocha": "^10.0.6",
    "@types/node": "^20.11.30",
    "@types/require-from-string": "^1.2.3",
    "@typescript-eslint/eslint-plugin": "^7.3.1",
    "@typescript-eslint/parser": "^7.3.1",
    "ajv-formats": "^3.0.1",
    "browserify": "^17.0.0",
    "chai": "^4.4.1",
    "cross-env": "^7.0.3",
    "dayjs": "^1.11.10",
    "dayjs-plugin-utc": "^0.1.2",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "glob": "^10.3.10",
    "husky": "^9.0.11",
    "jimp": "^0.22.10",
    "js-beautify": "^1.15.1",
    "json-schema-test": "^2.0.0",
    "karma": "^6.4.2",
    "karma-chrome-launcher": "^3.2.0",
    "karma-mocha": "^2.0.1",
    "lint-staged": "^15.2.2",
    "mocha": "^10.3.0",
    "module-from-string": "^3.3.0",
    "node-fetch": "^3.3.2",
    "nyc": "^15.1.0",
    "prettier": "3.0.3",
    "re2": "^1.20.9",
    "rollup": "^2.79.1",
    "rollup-plugin-terser": "^7.0.2",
    "ts-node": "^10.9.2",
    "tsify": "^5.0.4",
    "typescript": "5.3.3",
    "uri-js": "^4.4.1"
  },
  "collective": {
    "type": "opencollective",
    "url": "https://opencollective.com/ajv"
  },
  "funding": {
    "type": "github",
    "url": "https://github.com/sponsors/epoberezkin"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{json,yaml,js,ts}": "prettier --write"
  }
}import type {AnySchemaObject} from "./types"
import AjvCore, {Options} from "./core"

import draft7Vocabularies from "./vocabularies/draft7"
import dynamicVocabulary from "./vocabularies/dynamic"
import nextVocabulary from "./vocabularies/next"
import unevaluatedVocabulary from "./vocabularies/unevaluated"
import discriminator from "./vocabularies/discriminator"
import addMetaSchema2019 from "./refs/json-schema-2019-09"

const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"

export class Ajv2019 extends AjvCore {
  constructor(opts: Options = {}) {
    super({
      ...opts,
      dynamicRef: true,
      next: true,
      unevaluated: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    this.addVocabulary(dynamicVocabulary)
    draft7Vocabularies.forEach((v) => this.addVocabulary(v))
    this.addVocabulary(nextVocabulary)
    this.addVocabulary(unevaluatedVocabulary)
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    const {$data, meta} = this.opts
    if (!meta) return
    addMetaSchema2019.call(this, $data)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv2019
module.exports.Ajv2019 = Ajv2019
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv2019

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchemaObject} from "./types"
import AjvCore, {Options} from "./core"

import draft2020Vocabularies from "./vocabularies/draft2020"
import discriminator from "./vocabularies/discriminator"
import addMetaSchema2020 from "./refs/json-schema-2020-12"

const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"

export class Ajv2020 extends AjvCore {
  constructor(opts: Options = {}) {
    super({
      ...opts,
      dynamicRef: true,
      next: true,
      unevaluated: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    draft2020Vocabularies.forEach((v) => this.addVocabulary(v))
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    const {$data, meta} = this.opts
    if (!meta) return
    addMetaSchema2020.call(this, $data)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv2020
module.exports.Ajv2020 = Ajv2020
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv2020

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchemaObject} from "./types"
import AjvCore from "./core"
import draft7Vocabularies from "./vocabularies/draft7"
import discriminator from "./vocabularies/discriminator"
import * as draft7MetaSchema from "./refs/json-schema-draft-07.json"

const META_SUPPORT_DATA = ["/properties"]

const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"

export class Ajv extends AjvCore {
  _addVocabularies(): void {
    super._addVocabularies()
    draft7Vocabularies.forEach((v) => this.addVocabulary(v))
    if (this.opts.discriminator) this.addKeyword(discriminator)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    if (!this.opts.meta) return
    const metaSchema = this.opts.$data
      ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
      : draft7MetaSchema
    this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
    this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }
}

module.exports = exports = Ajv
module.exports.Ajv = Ajv
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  SchemaValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  AnyValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {SchemaCxt, SchemaObjCxt} from "./compile"
export interface Plugin<Opts> {
  (ajv: Ajv, options?: Opts): Ajv
  [prop: string]: any
}

export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

import type {
  Schema,
  AnySchema,
  AnySchemaObject,
  SchemaObject,
  AsyncSchema,
  Vocabulary,
  KeywordDefinition,
  AddedKeywordDefinition,
  AnyValidateFunction,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  Format,
  AddedFormat,
  RegExpEngine,
  UriResolver,
} from "./types"
import type {JSONSchemaType} from "./types/json-schema"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import ValidationError from "./runtime/validation_error"
import MissingRefError from "./compile/ref_error"
import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
import {Code, ValueScope} from "./compile/codegen"
import {normalizeId, getSchemaRefs} from "./compile/resolve"
import {getJSONTypes} from "./compile/validate/dataType"
import {eachItem} from "./compile/util"
import * as $dataRefSchema from "./refs/data.json"

import DefaultUriResolver from "./runtime/uri"

const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
defaultRegExp.code = "new RegExp"

const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
const EXT_SCOPE_NAMES = new Set([
  "validate",
  "serialize",
  "parse",
  "wrapper",
  "root",
  "schema",
  "keyword",
  "pattern",
  "formats",
  "validate$data",
  "func",
  "obj",
  "Error",
])

export type Options = CurrentOptions & DeprecatedOptions

export interface CurrentOptions {
  // strict mode options (NEW)
  strict?: boolean | "log"
  strictSchema?: boolean | "log"
  strictNumbers?: boolean | "log"
  strictTypes?: boolean | "log"
  strictTuples?: boolean | "log"
  strictRequired?: boolean | "log"
  allowMatchingProperties?: boolean // disables a strict mode restriction
  allowUnionTypes?: boolean
  validateFormats?: boolean
  // validation and reporting options:
  $data?: boolean
  allErrors?: boolean
  verbose?: boolean
  discriminator?: boolean
  unicodeRegExp?: boolean
  timestamp?: "string" | "date" // JTD only
  parseDate?: boolean // JTD only
  allowDate?: boolean // JTD only
  specialNumbers?: "fast" | "null" // JTD only
  $comment?:
    | true
    | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
  formats?: {[Name in string]?: Format}
  keywords?: Vocabulary
  schemas?: AnySchema[] | {[Key in string]?: AnySchema}
  logger?: Logger | false
  loadSchema?: (uri: string) => Promise<AnySchemaObject>
  // options to modify validated data:
  removeAdditional?: boolean | "all" | "failing"
  useDefaults?: boolean | "empty"
  coerceTypes?: boolean | "array"
  // advanced options:
  next?: boolean // NEW
  unevaluated?: boolean // NEW
  dynamicRef?: boolean // NEW
  schemaId?: "id" | "$id"
  jtd?: boolean // NEW
  meta?: SchemaObject | boolean
  defaultMeta?: string | AnySchemaObject
  validateSchema?: boolean | "log"
  addUsedSchema?: boolean
  inlineRefs?: boolean | number
  passContext?: boolean
  loopRequired?: number
  loopEnum?: number // NEW
  ownProperties?: boolean
  multipleOfPrecision?: number
  int32range?: boolean // JTD only
  messages?: boolean
  code?: CodeOptions // NEW
  uriResolver?: UriResolver
}

export interface CodeOptions {
  es5?: boolean
  esm?: boolean
  lines?: boolean
  optimize?: boolean | number
  formats?: Code // code to require (or construct) map of available formats - for standalone code
  source?: boolean
  process?: (code: string, schema?: SchemaEnv) => string
  regExp?: RegExpEngine
}

interface InstanceCodeOptions extends CodeOptions {
  regExp: RegExpEngine
  optimize: number
}

interface DeprecatedOptions {
  /** @deprecated */
  ignoreKeywordsWithRef?: boolean
  /** @deprecated */
  jsPropertySyntax?: boolean // added instead of jsonPointers
  /** @deprecated */
  unicode?: boolean
}

interface RemovedOptions {
  format?: boolean
  errorDataPath?: "object" | "property"
  nullable?: boolean // "nullable" keyword is supported by default
  jsonPointers?: boolean
  extendRefs?: true | "ignore" | "fail"
  missingRefs?: true | "ignore" | "fail"
  processCode?: (code: string, schema?: SchemaEnv) => string
  sourceCode?: boolean
  strictDefaults?: boolean
  strictKeywords?: boolean
  uniqueItems?: boolean
  unknownFormats?: true | string[] | "ignore"
  cache?: any
  serialize?: (schema: AnySchema) => unknown
  ajvErrors?: boolean
}

type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
  [K in keyof T]-?: string | undefined
}

const removedOptions: OptionsInfo<RemovedOptions> = {
  errorDataPath: "",
  format: "`validateFormats: false` can be used instead.",
  nullable: '"nullable" keyword is supported by default.',
  jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
  extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
  missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
  processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
  sourceCode: "Use option `code: {source: true}`",
  strictDefaults: "It is default now, see option `strict`.",
  strictKeywords: "It is default now, see option `strict`.",
  uniqueItems: '"uniqueItems" keyword is always validated.',
  unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
  cache: "Map is used as cache, schema object as key.",
  serialize: "Map is used as cache, schema object as key.",
  ajvErrors: "It is default now.",
}

const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
  ignoreKeywordsWithRef: "",
  jsPropertySyntax: "",
  unicode: '"minLength"/"maxLength" account for unicode characters by default.',
}

type RequiredInstanceOptions = {
  [K in
    | "strictSchema"
    | "strictNumbers"
    | "strictTypes"
    | "strictTuples"
    | "strictRequired"
    | "inlineRefs"
    | "loopRequired"
    | "loopEnum"
    | "meta"
    | "messages"
    | "schemaId"
    | "addUsedSchema"
    | "validateSchema"
    | "validateFormats"
    | "int32range"
    | "unicodeRegExp"
    | "uriResolver"]: NonNullable<Options[K]>
} & {code: InstanceCodeOptions}

export type InstanceOptions = Options & RequiredInstanceOptions

const MAX_EXPRESSION = 200

// eslint-disable-next-line complexity
function requiredOptions(o: Options): RequiredInstanceOptions {
  const s = o.strict
  const _optz = o.code?.optimize
  const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
  const regExp = o.code?.regExp ?? defaultRegExp
  const uriResolver = o.uriResolver ?? DefaultUriResolver
  return {
    strictSchema: o.strictSchema ?? s ?? true,
    strictNumbers: o.strictNumbers ?? s ?? true,
    strictTypes: o.strictTypes ?? s ?? "log",
    strictTuples: o.strictTuples ?? s ?? "log",
    strictRequired: o.strictRequired ?? s ?? false,
    code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
    loopRequired: o.loopRequired ?? MAX_EXPRESSION,
    loopEnum: o.loopEnum ?? MAX_EXPRESSION,
    meta: o.meta ?? true,
    messages: o.messages ?? true,
    inlineRefs: o.inlineRefs ?? true,
    schemaId: o.schemaId ?? "$id",
    addUsedSchema: o.addUsedSchema ?? true,
    validateSchema: o.validateSchema ?? true,
    validateFormats: o.validateFormats ?? true,
    unicodeRegExp: o.unicodeRegExp ?? true,
    int32range: o.int32range ?? true,
    uriResolver: uriResolver,
  }
}

export interface Logger {
  log(...args: unknown[]): unknown
  warn(...args: unknown[]): unknown
  error(...args: unknown[]): unknown
}

export default class Ajv {
  opts: InstanceOptions
  errors?: ErrorObject[] | null // errors from the last validation
  logger: Logger
  // shared external scope values for compiled functions
  readonly scope: ValueScope
  readonly schemas: {[Key in string]?: SchemaEnv} = {}
  readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
  readonly formats: {[Name in string]?: AddedFormat} = Object.create(null)
  readonly RULES: ValidationRules
  readonly _compilations: Set<SchemaEnv> = new Set()
  private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
  private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
  private readonly _metaOpts: InstanceOptions

  static ValidationError = ValidationError
  static MissingRefError = MissingRefError

  constructor(opts: Options = {}) {
    opts = this.opts = {...opts, ...requiredOptions(opts)}
    const {es5, lines} = this.opts.code

    this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
    this.logger = getLogger(opts.logger)
    const formatOpt = opts.validateFormats
    opts.validateFormats = false

    this.RULES = getRules()
    checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
    checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
    this._metaOpts = getMetaSchemaOptions.call(this)

    if (opts.formats) addInitialFormats.call(this)
    this._addVocabularies()
    this._addDefaultMetaSchema()
    if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
    if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
    addInitialSchemas.call(this)
    opts.validateFormats = formatOpt
  }

  _addVocabularies(): void {
    this.addKeyword("$async")
  }

  _addDefaultMetaSchema(): void {
    const {$data, meta, schemaId} = this.opts
    let _dataRefSchema: SchemaObject = $dataRefSchema
    if (schemaId === "id") {
      _dataRefSchema = {...$dataRefSchema}
      _dataRefSchema.id = _dataRefSchema.$id
      delete _dataRefSchema.$id
    }
    if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    const {meta, schemaId} = this.opts
    return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
  }

  // Validate data using schema
  // AnySchema will be compiled and cached using schema itself as a key for Map
  validate(schema: Schema | string, data: unknown): boolean
  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
  validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  validate<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    data: unknown
  ): data is JTDDataType<T>
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
  validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
  validate<T>(
    schemaKeyRef: AnySchema | string, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data: unknown | T // to be validated
  ): boolean | Promise<T> {
    let v: AnyValidateFunction | undefined
    if (typeof schemaKeyRef == "string") {
      v = this.getSchema<T>(schemaKeyRef)
      if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
    } else {
      v = this.compile<T>(schemaKeyRef)
    }

    const valid = v(data)
    if (!("$async" in v)) this.errors = v.errors
    return valid
  }

  // Create validation function for passed schema
  // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
  compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  compile<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    _meta?: boolean
  ): ValidateFunction<JTDDataType<T>>
  compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
    const sch = this._addSchema(schema, _meta)
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
  }

  // Creates validating function for passed schema with asynchronous loading of missing schemas.
  // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  // TODO allow passing schema URI
  // meta - optional true to compile meta-schema
  compileAsync<T = unknown>(
    schema: SchemaObject | JSONSchemaType<T>,
    _meta?: boolean
  ): Promise<ValidateFunction<T>>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
  compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>>
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>> {
    if (typeof this.opts.loadSchema != "function") {
      throw new Error("options.loadSchema should be a function")
    }
    const {loadSchema} = this.opts
    return runCompileAsync.call(this, schema, meta)

    async function runCompileAsync(
      this: Ajv,
      _schema: AnySchemaObject,
      _meta?: boolean
    ): Promise<AnyValidateFunction> {
      await loadMetaSchema.call(this, _schema.$schema)
      const sch = this._addSchema(_schema, _meta)
      return sch.validate || _compileAsync.call(this, sch)
    }

    async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
      if ($ref && !this.getSchema($ref)) {
        await runCompileAsync.call(this, {$ref}, true)
      }
    }

    async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
      try {
        return this._compileSchemaEnv(sch)
      } catch (e) {
        if (!(e instanceof MissingRefError)) throw e
        checkLoaded.call(this, e)
        await loadMissingSchema.call(this, e.missingSchema)
        return _compileAsync.call(this, sch)
      }
    }

    function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
      if (this.refs[ref]) {
        throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
      }
    }

    async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
      const _schema = await _loadSchema.call(this, ref)
      if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
      if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
    }

    async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
      const p = this._loading[ref]
      if (p) return p
      try {
        return await (this._loading[ref] = loadSchema(ref))
      } finally {
        delete this._loading[ref]
      }
    }
  }

  // Adds schema to the instance
  addSchema(
    schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
    key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
  ): Ajv {
    if (Array.isArray(schema)) {
      for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
      return this
    }
    let id: string | undefined
    if (typeof schema === "object") {
      const {schemaId} = this.opts
      id = schema[schemaId]
      if (id !== undefined && typeof id != "string") {
        throw new Error(`schema ${schemaId} must be string`)
      }
    }
    key = normalizeId(key || id)
    this._checkUnique(key)
    this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
    return this
  }

  // Add schema that will be used to validate other schemas
  // options in META_IGNORE_OPTIONS are alway set to false
  addMetaSchema(
    schema: AnySchemaObject,
    key?: string, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
  ): Ajv {
    this.addSchema(schema, key, true, _validateSchema)
    return this
  }

  //  Validate schema against its meta-schema
  validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
    if (typeof schema == "boolean") return true
    let $schema: string | AnySchemaObject | undefined
    $schema = schema.$schema
    if ($schema !== undefined && typeof $schema != "string") {
      throw new Error("$schema must be a string")
    }
    $schema = $schema || this.opts.defaultMeta || this.defaultMeta()
    if (!$schema) {
      this.logger.warn("meta-schema not available")
      this.errors = null
      return true
    }
    const valid = this.validate($schema, schema)
    if (!valid && throwOrLogError) {
      const message = "schema is invalid: " + this.errorsText()
      if (this.opts.validateSchema === "log") this.logger.error(message)
      else throw new Error(message)
    }
    return valid
  }

  // Get compiled schema by `key` or `ref`.
  // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    let sch
    while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
    if (sch === undefined) {
      const {schemaId} = this.opts
      const root = new SchemaEnv({schema: {}, schemaId})
      sch = resolveSchema.call(this, root, keyRef)
      if (!sch) return
      this.refs[keyRef] = sch
    }
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
  }

  // Remove cached schema(s).
  // If no parameter is passed all schemas but meta-schemas are removed.
  // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
    if (schemaKeyRef instanceof RegExp) {
      this._removeAllSchemas(this.schemas, schemaKeyRef)
      this._removeAllSchemas(this.refs, schemaKeyRef)
      return this
    }
    switch (typeof schemaKeyRef) {
      case "undefined":
        this._removeAllSchemas(this.schemas)
        this._removeAllSchemas(this.refs)
        this._cache.clear()
        return this
      case "string": {
        const sch = getSchEnv.call(this, schemaKeyRef)
        if (typeof sch == "object") this._cache.delete(sch.schema)
        delete this.schemas[schemaKeyRef]
        delete this.refs[schemaKeyRef]
        return this
      }
      case "object": {
        const cacheKey = schemaKeyRef
        this._cache.delete(cacheKey)
        let id = schemaKeyRef[this.opts.schemaId]
        if (id) {
          id = normalizeId(id)
          delete this.schemas[id]
          delete this.refs[id]
        }
        return this
      }
      default:
        throw new Error("ajv.removeSchema: invalid parameter")
    }
  }

  // add "vocabulary" - a collection of keywords
  addVocabulary(definitions: Vocabulary): Ajv {
    for (const def of definitions) this.addKeyword(def)
    return this
  }

  addKeyword(
    kwdOrDef: string | KeywordDefinition,
    def?: KeywordDefinition // deprecated
  ): Ajv {
    let keyword: string | string[]
    if (typeof kwdOrDef == "string") {
      keyword = kwdOrDef
      if (typeof def == "object") {
        this.logger.warn("these parameters are deprecated, see docs for addKeyword")
        def.keyword = keyword
      }
    } else if (typeof kwdOrDef == "object" && def === undefined) {
      def = kwdOrDef
      keyword = def.keyword
      if (Array.isArray(keyword) && !keyword.length) {
        throw new Error("addKeywords: keyword must be string or non-empty array")
      }
    } else {
      throw new Error("invalid addKeywords parameters")
    }

    checkKeyword.call(this, keyword, def)
    if (!def) {
      eachItem(keyword, (kwd) => addRule.call(this, kwd))
      return this
    }
    keywordMetaschema.call(this, def)
    const definition: AddedKeywordDefinition = {
      ...def,
      type: getJSONTypes(def.type),
      schemaType: getJSONTypes(def.schemaType),
    }
    eachItem(
      keyword,
      definition.type.length === 0
        ? (k) => addRule.call(this, k, definition)
        : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
    )
    return this
  }

  getKeyword(keyword: string): AddedKeywordDefinition | boolean {
    const rule = this.RULES.all[keyword]
    return typeof rule == "object" ? rule.definition : !!rule
  }

  // Remove keyword
  removeKeyword(keyword: string): Ajv {
    // TODO return type should be Ajv
    const {RULES} = this
    delete RULES.keywords[keyword]
    delete RULES.all[keyword]
    for (const group of RULES.rules) {
      const i = group.rules.findIndex((rule) => rule.keyword === keyword)
      if (i >= 0) group.rules.splice(i, 1)
    }
    return this
  }

  // Add format
  addFormat(name: string, format: Format): Ajv {
    if (typeof format == "string") format = new RegExp(format)
    this.formats[name] = format
    return this
  }

  errorsText(
    errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
    {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
  ): string {
    if (!errors || errors.length === 0) return "No errors"
    return errors
      .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
      .reduce((text, msg) => text + separator + msg)
  }

  $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
    const rules = this.RULES.all
    metaSchema = JSON.parse(JSON.stringify(metaSchema))
    for (const jsonPointer of keywordsJsonPointers) {
      const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
      let keywords = metaSchema
      for (const seg of segments) keywords = keywords[seg] as AnySchemaObject

      for (const key in rules) {
        const rule = rules[key]
        if (typeof rule != "object") continue
        const {$data} = rule.definition
        const schema = keywords[key] as AnySchemaObject | undefined
        if ($data && schema) keywords[key] = schemaOrData(schema)
      }
    }

    return metaSchema
  }

  private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
    for (const keyRef in schemas) {
      const sch = schemas[keyRef]
      if (!regex || regex.test(keyRef)) {
        if (typeof sch == "string") {
          delete schemas[keyRef]
        } else if (sch && !sch.meta) {
          this._cache.delete(sch.schema)
          delete schemas[keyRef]
        }
      }
    }
  }

  _addSchema(
    schema: AnySchema,
    meta?: boolean,
    baseId?: string,
    validateSchema = this.opts.validateSchema,
    addSchema = this.opts.addUsedSchema
  ): SchemaEnv {
    let id: string | undefined
    const {schemaId} = this.opts
    if (typeof schema == "object") {
      id = schema[schemaId]
    } else {
      if (this.opts.jtd) throw new Error("schema must be object")
      else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
    }
    let sch = this._cache.get(schema)
    if (sch !== undefined) return sch

    baseId = normalizeId(id || baseId)
    const localRefs = getSchemaRefs.call(this, schema, baseId)
    sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
    this._cache.set(sch.schema, sch)
    if (addSchema && !baseId.startsWith("#")) {
      // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
      if (baseId) this._checkUnique(baseId)
      this.refs[baseId] = sch
    }
    if (validateSchema) this.validateSchema(schema, true)
    return sch
  }

  private _checkUnique(id: string): void {
    if (this.schemas[id] || this.refs[id]) {
      throw new Error(`schema with key or id "${id}" already exists`)
    }
  }

  private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
    if (sch.meta) this._compileMetaSchema(sch)
    else compileSchema.call(this, sch)

    /* istanbul ignore if */
    if (!sch.validate) throw new Error("ajv implementation error")
    return sch.validate
  }

  private _compileMetaSchema(sch: SchemaEnv): void {
    const currentOpts = this.opts
    this.opts = this._metaOpts
    try {
      compileSchema.call(this, sch)
    } finally {
      this.opts = currentOpts
    }
  }
}

export interface ErrorsTextOptions {
  separator?: string
  dataVar?: string
}

function checkOptions(
  this: Ajv,
  checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
  options: Options & RemovedOptions,
  msg: string,
  log: "warn" | "error" = "error"
): void {
  for (const key in checkOpts) {
    const opt = key as keyof typeof checkOpts
    if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
  }
}

function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
  keyRef = normalizeId(keyRef) // TODO tests fail without this line
  return this.schemas[keyRef] || this.refs[keyRef]
}

function addInitialSchemas(this: Ajv): void {
  const optsSchemas = this.opts.schemas
  if (!optsSchemas) return
  if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
  else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
}

function addInitialFormats(this: Ajv): void {
  for (const name in this.opts.formats) {
    const format = this.opts.formats[name]
    if (format) this.addFormat(name, format)
  }
}

function addInitialKeywords(
  this: Ajv,
  defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
  if (Array.isArray(defs)) {
    this.addVocabulary(defs)
    return
  }
  this.logger.warn("keywords option as map is deprecated, pass array")
  for (const keyword in defs) {
    const def = defs[keyword] as KeywordDefinition
    if (!def.keyword) def.keyword = keyword
    this.addKeyword(def)
  }
}

function getMetaSchemaOptions(this: Ajv): InstanceOptions {
  const metaOpts = {...this.opts}
  for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
  return metaOpts
}

const noLogs = {log() {}, warn() {}, error() {}}

function getLogger(logger?: Partial<Logger> | false): Logger {
  if (logger === false) return noLogs
  if (logger === undefined) return console
  if (logger.log && logger.warn && logger.error) return logger as Logger
  throw new Error("logger must implement log, warn and error methods")
}

const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i

function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
  const {RULES} = this
  eachItem(keyword, (kwd) => {
    if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
    if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
  })
  if (!def) return
  if (def.$data && !("code" in def || "validate" in def)) {
    throw new Error('$data keyword must have "code" or "validate" function')
  }
}

function addRule(
  this: Ajv,
  keyword: string,
  definition?: AddedKeywordDefinition,
  dataType?: JSONType
): void {
  const post = definition?.post
  if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
  const {RULES} = this
  let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
  if (!ruleGroup) {
    ruleGroup = {type: dataType, rules: []}
    RULES.rules.push(ruleGroup)
  }
  RULES.keywords[keyword] = true
  if (!definition) return

  const rule: Rule = {
    keyword,
    definition: {
      ...definition,
      type: getJSONTypes(definition.type),
      schemaType: getJSONTypes(definition.schemaType),
    },
  }
  if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
  else ruleGroup.rules.push(rule)
  RULES.all[keyword] = rule
  definition.implements?.forEach((kwd) => this.addKeyword(kwd))
}

function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
  const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
  if (i >= 0) {
    ruleGroup.rules.splice(i, 0, rule)
  } else {
    ruleGroup.rules.push(rule)
    this.logger.warn(`rule ${before} is not defined`)
  }
}

function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
  let {metaSchema} = def
  if (metaSchema === undefined) return
  if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
  def.validateSchema = this.compile(metaSchema, true)
}

const $dataRef = {
  $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
}

function schemaOrData(schema: AnySchema): AnySchemaObject {
  return {anyOf: [schema, $dataRef]}
}
import type {AnySchemaObject, SchemaObject, JTDParser} from "./types"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import AjvCore, {CurrentOptions} from "./core"
import jtdVocabulary from "./vocabularies/jtd"
import jtdMetaSchema from "./refs/jtd-schema"
import compileSerializer from "./compile/jtd/serialize"
import compileParser from "./compile/jtd/parse"
import {SchemaEnv} from "./compile"

const META_SCHEMA_ID = "JTD-meta-schema"

type JTDOptions = CurrentOptions & {
  // strict mode options not supported with JTD:
  strict?: never
  allowMatchingProperties?: never
  allowUnionTypes?: never
  validateFormats?: never
  // validation and reporting options not supported with JTD:
  $data?: never
  verbose?: boolean
  $comment?: never
  formats?: never
  loadSchema?: never
  // options to modify validated data:
  useDefaults?: never
  coerceTypes?: never
  // advanced options:
  next?: never
  unevaluated?: never
  dynamicRef?: never
  meta?: boolean
  defaultMeta?: never
  inlineRefs?: boolean
  loopRequired?: never
  multipleOfPrecision?: never
}

export class Ajv extends AjvCore {
  constructor(opts: JTDOptions = {}) {
    super({
      ...opts,
      jtd: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    this.addVocabulary(jtdVocabulary)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    if (!this.opts.meta) return
    this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }

  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string
  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string {
    const sch = this._addSchema(schema)
    return sch.serialize || this._compileSerializer(sch)
  }

  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>
  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> {
    const sch = this._addSchema(schema)
    return (sch.parse || this._compileParser(sch)) as JTDParser<T>
  }

  private _compileSerializer<T>(sch: SchemaEnv): (data: T) => string {
    compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.serialize) throw new Error("ajv implementation error")
    return sch.serialize
  }

  private _compileParser(sch: SchemaEnv): JTDParser {
    compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.parse) throw new Error("ajv implementation error")
    return sch.parse
  }
}

module.exports = exports = Ajv
module.exports.Ajv = Ajv
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
  JTDParser,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {JTDErrorObject} from "./vocabularies/jtd"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

export {JTDSchemaType, SomeJTDSchemaType, JTDDataType}
export {JTDOptions}
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"
import type {AnySchema, SchemaMap} from "../types"
import type {SchemaCxt} from "../compile"
import type {KeywordCxt} from "../compile/validate"
import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen"
import {alwaysValidSchema, Type} from "../compile/util"
import N from "../compile/names"
import {useFunc} from "../compile/util"
export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {
  const {gen, data, it} = cxt
  gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
    cxt.setParams({missingProperty: _`${prop}`}, true)
    cxt.error()
  })
}

export function checkMissingProp(
  {gen, data, it: {opts}}: KeywordCxt,
  properties: string[],
  missing: Name
): Code {
  return or(
    ...properties.map((prop) =>
      and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)
    )
  )
}

export function reportMissingProp(cxt: KeywordCxt, missing: Name): void {
  cxt.setParams({missingProperty: missing}, true)
  cxt.error()
}

export function hasPropFunc(gen: CodeGen): Name {
  return gen.scopeValue("func", {
    // eslint-disable-next-line @typescript-eslint/unbound-method
    ref: Object.prototype.hasOwnProperty,
    code: _`Object.prototype.hasOwnProperty`,
  })
}

export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {
  return _`${hasPropFunc(gen)}.call(${data}, ${property})`
}

export function propertyInData(
  gen: CodeGen,
  data: Name,
  property: Name | string,
  ownProperties?: boolean
): Code {
  const cond = _`${data}${getProperty(property)} !== undefined`
  return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond
}

export function noPropertyInData(
  gen: CodeGen,
  data: Name,
  property: Name | string,
  ownProperties?: boolean
): Code {
  const cond = _`${data}${getProperty(property)} === undefined`
  return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond
}

export function allSchemaProperties(schemaMap?: SchemaMap): string[] {
  return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []
}

export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {
  return allSchemaProperties(schemaMap).filter(
    (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)
  )
}

export function callValidateCode(
  {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,
  func: Code,
  context: Code,
  passSchema?: boolean
): Code {
  const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data
  const valCxt: [Name, Code | number][] = [
    [N.instancePath, strConcat(N.instancePath, errorPath)],
    [N.parentData, it.parentData],
    [N.parentDataProperty, it.parentDataProperty],
    [N.rootData, N.rootData],
  ]
  if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])
  const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`
  return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`
}

const newRegExp = _`new RegExp`

export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {
  const u = opts.unicodeRegExp ? "u" : ""
  const {regExp} = opts.code
  const rx = regExp(pattern, u)

  return gen.scopeValue("pattern", {
    key: rx.toString(),
    ref: rx,
    code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,
  })
}

export function validateArray(cxt: KeywordCxt): Name {
  const {gen, data, keyword, it} = cxt
  const valid = gen.name("valid")
  if (it.allErrors) {
    const validArr = gen.let("valid", true)
    validateItems(() => gen.assign(validArr, false))
    return validArr
  }
  gen.var(valid, true)
  validateItems(() => gen.break())
  return valid

  function validateItems(notValid: () => void): void {
    const len = gen.const("len", _`${data}.length`)
    gen.forRange("i", 0, len, (i) => {
      cxt.subschema(
        {
          keyword,
          dataProp: i,
          dataPropType: Type.Num,
        },
        valid
      )
      gen.if(not(valid), notValid)
    })
  }
}

export function validateUnion(cxt: KeywordCxt): void {
  const {gen, schema, keyword, it} = cxt
  /* istanbul ignore if */
  if (!Array.isArray(schema)) throw new Error("ajv implementation error")
  const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))
  if (alwaysValid && !it.opts.unevaluated) return

  const valid = gen.let("valid", false)
  const schValid = gen.name("_valid")

  gen.block(() =>
    schema.forEach((_sch: AnySchema, i: number) => {
      const schCxt = cxt.subschema(
        {
          keyword,
          schemaProp: i,
          compositeRule: true,
        },
        schValid
      )
      gen.assign(valid, _`${valid} || ${schValid}`)
      const merged = cxt.mergeValidEvaluated(schCxt, schValid)
      // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
      // or if all properties and items were evaluated (it.props === true && it.items === true)
      if (!merged) gen.if(not(valid))
    })
  )

  cxt.result(
    valid,
    () => cxt.reset(),
    () => cxt.error(true)
  )
}
import type {Vocabulary} from "../types"
import coreVocabulary from "./core"
import validationVocabulary from "./validation"
import getApplicatorVocabulary from "./applicator"
import dynamicVocabulary from "./dynamic"
import nextVocabulary from "./next"
import unevaluatedVocabulary from "./unevaluated"
import formatVocabulary from "./format"
import {metadataVocabulary, contentVocabulary} from "./metadata"

const draft2020Vocabularies: Vocabulary[] = [
  dynamicVocabulary,
  coreVocabulary,
  validationVocabulary,
  getApplicatorVocabulary(true),
  formatVocabulary,
  metadataVocabulary,
  contentVocabulary,
  nextVocabulary,
  unevaluatedVocabulary,
]

export default draft2020Vocabularies
import type {Vocabulary} from "../types"
import coreVocabulary from "./core"
import validationVocabulary from "./validation"
import getApplicatorVocabulary from "./applicator"
import formatVocabulary from "./format"
import {metadataVocabulary, contentVocabulary} from "./metadata"

const draft7Vocabularies: Vocabulary[] = [
  coreVocabulary,
  validationVocabulary,
  getApplicatorVocabulary(),
  formatVocabulary,
  metadataVocabulary,
  contentVocabulary,
]

export default draft7Vocabularies
import type {TypeError} from "../compile/validate/dataType"
import type {ApplicatorKeywordError} from "./applicator"
import type {ValidationKeywordError} from "./validation"
import type {FormatError} from "./format/format"
import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties"
import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems"
import type {DependentRequiredError} from "./validation/dependentRequired"
import type {DiscriminatorError} from "./discriminator"

export type DefinedError =
  | TypeError
  | ApplicatorKeywordError
  | ValidationKeywordError
  | FormatError
  | UnevaluatedPropertiesError
  | UnevaluatedItemsError
  | DependentRequiredError
  | DiscriminatorError
import type {Vocabulary} from "../types"

export const metadataVocabulary: Vocabulary = [
  "title",
  "description",
  "default",
  "deprecated",
  "readOnly",
  "writeOnly",
  "examples",
]

export const contentVocabulary: Vocabulary = [
  "contentMediaType",
  "contentEncoding",
  "contentSchema",
]
import type {Vocabulary} from "../types"
import dependentRequired from "./validation/dependentRequired"
import dependentSchemas from "./applicator/dependentSchemas"
import limitContains from "./validation/limitContains"

const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains]

export default next
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type ConstError = ErrorObject<"const", {allowedValue: any}>

const error: KeywordErrorDefinition = {
  message: "must be equal to constant",
  params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "const",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schemaCode, schema} = cxt
    if ($data || (schema && typeof schema == "object")) {
      cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)
    } else {
      cxt.fail(_`${schema} !== ${data}`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject} from "../../types"
import {
  validatePropertyDeps,
  error,
  DependenciesErrorParams,
  PropertyDependencies,
} from "../applicator/dependencies"

export type DependentRequiredError = ErrorObject<
  "dependentRequired",
  DependenciesErrorParams,
  PropertyDependencies
>

const def: CodeKeywordDefinition = {
  keyword: "dependentRequired",
  type: "object",
  schemaType: "object",
  error,
  code: (cxt) => validatePropertyDeps(cxt),
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, or, Name, Code} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}>

const error: KeywordErrorDefinition = {
  message: "must be equal to one of the allowed values",
  params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "enum",
  schemaType: "array",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    if (!$data && schema.length === 0) throw new Error("enum must have non-empty array")
    const useLoop = schema.length >= it.opts.loopEnum
    let eql: Name | undefined
    const getEql = (): Name => (eql ??= useFunc(gen, equal))

    let valid: Code
    if (useLoop || $data) {
      valid = gen.let("valid")
      cxt.block$data(valid, loopEnum)
    } else {
      /* istanbul ignore if */
      if (!Array.isArray(schema)) throw new Error("ajv implementation error")
      const vSchema = gen.const("vSchema", schemaCode)
      valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))
    }
    cxt.pass(valid)

    function loopEnum(): void {
      gen.assign(valid, false)
      gen.forOf("v", schemaCode as Code, (v) =>
        gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())
      )
    }

    function equalCode(vSchema: Name, i: number): Code {
      const sch = schema[i]
      return typeof sch === "object" && sch !== null
        ? _`${getEql()}(${data}, ${vSchema}[${i}])`
        : _`${data} === ${sch}`
    }
  },
}

export default def
import type {ErrorObject, Vocabulary} from "../../types"
import limitNumber, {LimitNumberError} from "./limitNumber"
import multipleOf, {MultipleOfError} from "./multipleOf"
import limitLength from "./limitLength"
import pattern, {PatternError} from "./pattern"
import limitProperties from "./limitProperties"
import required, {RequiredError} from "./required"
import limitItems from "./limitItems"
import uniqueItems, {UniqueItemsError} from "./uniqueItems"
import constKeyword, {ConstError} from "./const"
import enumKeyword, {EnumError} from "./enum"

const validation: Vocabulary = [
  // number
  limitNumber,
  multipleOf,
  // string
  limitLength,
  pattern,
  // object
  limitProperties,
  required,
  // array
  limitItems,
  uniqueItems,
  // any
  {keyword: "type", schemaType: ["string", "array"]},
  {keyword: "nullable", schemaType: "boolean"},
  constKeyword,
  enumKeyword,
]

export default validation

type LimitError = ErrorObject<
  "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength",
  {limit: number},
  number | {$data: string}
>

export type ValidationKeywordError =
  | LimitError
  | LimitNumberError
  | MultipleOfError
  | PatternError
  | RequiredError
  | UniqueItemsError
  | ConstError
  | EnumError
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: ["maxContains", "minContains"],
  type: "array",
  schemaType: "number",
  code({keyword, parentSchema, it}: KeywordCxt) {
    if (parentSchema.contains === undefined) {
      checkStrictMode(it, `"${keyword}" without "contains" is ignored`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxItems" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} items`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxItems", "minItems"],
  type: "array",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    const op = keyword === "maxItems" ? operators.GT : operators.LT
    cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import ucs2length from "../../runtime/ucs2length"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxLength" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} characters`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxLength", "minLength"],
  type: "string",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode, it} = cxt
    const op = keyword === "maxLength" ? operators.GT : operators.LT
    const len =
      it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`
    cxt.fail$data(_`${len} ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators, Code} from "../../compile/codegen"

const ops = operators

type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum"

type Comparison = "<=" | ">=" | "<" | ">"

const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {
  maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT},
  minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT},
  exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE},
  exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE},
}

export type LimitNumberError = ErrorObject<
  Kwd,
  {limit: number; comparison: Comparison},
  number | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,
  params: ({keyword, schemaCode}) =>
    _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: Object.keys(KWDs),
  type: "number",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, operators} from "../../compile/codegen"

const error: KeywordErrorDefinition = {
  message({keyword, schemaCode}) {
    const comp = keyword === "maxProperties" ? "more" : "fewer"
    return str`must NOT have ${comp} than ${schemaCode} properties`
  },
  params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: ["maxProperties", "minProperties"],
  type: "object",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {keyword, data, schemaCode} = cxt
    const op = keyword === "maxProperties" ? operators.GT : operators.LT
    cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"

export type MultipleOfError = ErrorObject<
  "multipleOf",
  {multipleOf: number},
  number | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,
  params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "multipleOf",
  type: "number",
  schemaType: "number",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, schemaCode, it} = cxt
    // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
    const prec = it.opts.multipleOfPrecision
    const res = gen.let("res")
    const invalid = prec
      ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
      : _`${res} !== parseInt(${res})`
    cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {usePattern} from "../code"
import {useFunc} from "../../compile/util"
import {_, str} from "../../compile/codegen"

export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must match pattern "${schemaCode}"`,
  params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "pattern",
  type: "string",
  schemaType: "string",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    const u = it.opts.unicodeRegExp ? "u" : ""
    if ($data) {
      const {regExp} = it.opts.code
      const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp)
      const valid = gen.let("valid")
      gen.try(
        () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),
        () => gen.assign(valid, false)
      )
      cxt.fail$data(_`!${valid}`)
    } else {
      const regExp = usePattern(cxt, schema)
      cxt.fail$data(_`!${regExp}.test(${data})`)
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {
  checkReportMissingProp,
  checkMissingProp,
  reportMissingProp,
  propertyInData,
  noPropertyInData,
} from "../code"
import {_, str, nil, not, Name, Code} from "../../compile/codegen"
import {checkStrictMode} from "../../compile/util"

export type RequiredError = ErrorObject<
  "required",
  {missingProperty: string},
  string[] | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,
  params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "required",
  type: "object",
  schemaType: "array",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, schemaCode, data, $data, it} = cxt
    const {opts} = it
    if (!$data && schema.length === 0) return
    const useLoop = schema.length >= opts.loopRequired
    if (it.allErrors) allErrorsMode()
    else exitOnErrorMode()

    if (opts.strictRequired) {
      const props = cxt.parentSchema.properties
      const {definedProperties} = cxt.it
      for (const requiredKey of schema) {
        if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {
          const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
          const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`
          checkStrictMode(it, msg, it.opts.strictRequired)
        }
      }
    }

    function allErrorsMode(): void {
      if (useLoop || $data) {
        cxt.block$data(nil, loopAllRequired)
      } else {
        for (const prop of schema) {
          checkReportMissingProp(cxt, prop)
        }
      }
    }

    function exitOnErrorMode(): void {
      const missing = gen.let("missing")
      if (useLoop || $data) {
        const valid = gen.let("valid", true)
        cxt.block$data(valid, () => loopUntilMissing(missing, valid))
        cxt.ok(valid)
      } else {
        gen.if(checkMissingProp(cxt, schema, missing))
        reportMissingProp(cxt, missing)
        gen.else()
      }
    }

    function loopAllRequired(): void {
      gen.forOf("prop", schemaCode as Code, (prop) => {
        cxt.setParams({missingProperty: prop})
        gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())
      })
    }

    function loopUntilMissing(missing: Name, valid: Name): void {
      cxt.setParams({missingProperty: missing})
      gen.forOf(
        missing,
        schemaCode as Code,
        () => {
          gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))
          gen.if(not(valid), () => {
            cxt.error()
            gen.break()
          })
        },
        nil
      )
    }
  },
}

export default def
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType"
import {_, str, Name} from "../../compile/codegen"
import {useFunc} from "../../compile/util"
import equal from "../../runtime/equal"

export type UniqueItemsError = ErrorObject<
  "uniqueItems",
  {i: number; j: number},
  boolean | {$data: string}
>

const error: KeywordErrorDefinition = {
  message: ({params: {i, j}}) =>
    str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
  params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "uniqueItems",
  type: "array",
  schemaType: "boolean",
  $data: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt
    if (!$data && !schema) return
    const valid = gen.let("valid")
    const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []
    cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)
    cxt.ok(valid)

    function validateUniqueItems(): void {
      const i = gen.let("i", _`${data}.length`)
      const j = gen.let("j")
      cxt.setParams({i, j})
      gen.assign(valid, true)
      gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))
    }

    function canOptimize(): boolean {
      return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array")
    }

    function loopN(i: Name, j: Name): void {
      const item = gen.name("item")
      const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)
      const indices = gen.const("indices", _`{}`)
      gen.for(_`;${i}--;`, () => {
        gen.let(item, _`${data}[${i}]`)
        gen.if(wrongType, _`continue`)
        if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`)
        gen
          .if(_`typeof ${indices}[${item}] == "number"`, () => {
            gen.assign(j, _`${indices}[${item}]`)
            cxt.error()
            gen.assign(valid, false).break()
          })
          .code(_`${indices}[${item}] = ${i}`)
      })
    }

    function loopN2(i: Name, j: Name): void {
      const eql = useFunc(gen, equal)
      const outer = gen.name("outer")
      gen.label(outer).for(_`;${i}--;`, () =>
        gen.for(_`${j} = ${i}; ${j}--;`, () =>
          gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {
            cxt.error()
            gen.assign(valid, false).break(outer)
          })
        )
      )
    }
  },
}

export default def
import type {Vocabulary} from "../../types"
import unevaluatedProperties from "./unevaluatedProperties"
import unevaluatedItems from "./unevaluatedItems"

const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems]

export default unevaluated
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, Type} from "../../compile/util"

export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "unevaluatedItems",
  type: "array",
  schemaType: ["boolean", "object"],
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, data, it} = cxt
    const items = it.items || 0
    if (items === true) return
    const len = gen.const("len", _`${data}.length`)
    if (schema === false) {
      cxt.setParams({len: items})
      cxt.fail(_`${len} > ${items}`)
    } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
      const valid = gen.var("valid", _`${len} <= ${items}`)
      gen.if(not(valid), () => validateItems(valid, items))
      cxt.ok(valid)
    }
    it.items = true

    function validateItems(valid: Name, from: Name | number): void {
      gen.forRange("i", from, len, (i) => {
        cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid)
        if (!it.allErrors) gen.if(not(valid), () => gen.break())
      })
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import {_, not, and, Name, Code} from "../../compile/codegen"
import {alwaysValidSchema, Type} from "../../compile/util"
import N from "../../compile/names"

export type UnevaluatedPropertiesError = ErrorObject<
  "unevaluatedProperties",
  {unevaluatedProperty: string},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: "must NOT have unevaluated properties",
  params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "unevaluatedProperties",
  type: "object",
  schemaType: ["boolean", "object"],
  trackErrors: true,
  error,
  code(cxt) {
    const {gen, schema, data, errsCount, it} = cxt
    /* istanbul ignore if */
    if (!errsCount) throw new Error("ajv implementation error")
    const {allErrors, props} = it
    if (props instanceof Name) {
      gen.if(_`${props} !== true`, () =>
        gen.forIn("key", data, (key: Name) =>
          gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))
        )
      )
    } else if (props !== true) {
      gen.forIn("key", data, (key: Name) =>
        props === undefined
          ? unevaluatedPropCode(key)
          : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))
      )
    }
    it.props = true
    cxt.ok(_`${errsCount} === ${N.errors}`)

    function unevaluatedPropCode(key: Name): void {
      if (schema === false) {
        cxt.setParams({unevaluatedProperty: key})
        cxt.error()
        if (!allErrors) gen.break()
        return
      }

      if (!alwaysValidSchema(it, schema)) {
        const valid = gen.name("valid")
        cxt.subschema(
          {
            keyword: "unevaluatedProperties",
            dataProp: key,
            dataPropType: Type.Str,
          },
          valid
        )
        if (!allErrors) gen.if(not(valid), () => gen.break())
      }
    }

    function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code {
      return _`!${evaluatedProps} || !${evaluatedProps}[${key}]`
    }

    function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code {
      const ps: Code[] = []
      for (const p in evaluatedProps) {
        if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`)
      }
      return and(...ps)
    }
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, not, getProperty, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
import {DiscrError, DiscrErrorObj} from "../discriminator/types"

export type JTDDiscriminatorError =
  | _JTDTypeError<"discriminator", "object", string>
  | DiscrErrorObj<DiscrError.Tag>
  | DiscrErrorObj<DiscrError.Mapping>

const error: KeywordErrorDefinition = {
  message: (cxt) => {
    const {schema, params} = cxt
    return params.discrError
      ? params.discrError === DiscrError.Tag
        ? `tag "${schema}" must be string`
        : `value of tag "${schema}" must be in mapping`
      : typeErrorMessage(cxt, "object")
  },
  params: (cxt) => {
    const {schema, params} = cxt
    return params.discrError
      ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
      : typeErrorParams(cxt, "object")
  },
}

const def: CodeKeywordDefinition = {
  keyword: "discriminator",
  schemaType: "string",
  implements: ["mapping"],
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, parentSchema} = cxt
    const [valid, cond] = checkNullableObject(cxt, data)

    gen.if(cond)
    validateDiscriminator()
    gen.elseIf(not(valid))
    cxt.error()
    gen.endIf()
    cxt.ok(valid)

    function validateDiscriminator(): void {
      const tag = gen.const("tag", _`${data}${getProperty(schema)}`)
      gen.if(_`${tag} === undefined`)
      cxt.error(false, {discrError: DiscrError.Tag, tag})
      gen.elseIf(_`typeof ${tag} == "string"`)
      validateMapping(tag)
      gen.else()
      cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema})
      gen.endIf()
    }

    function validateMapping(tag: Name): void {
      gen.if(false)
      for (const tagValue in parentSchema.mapping) {
        gen.elseIf(_`${tag} === ${tagValue}`)
        gen.assign(valid, applyTagSchema(tagValue))
      }
      gen.else()
      cxt.error(
        false,
        {discrError: DiscrError.Mapping, tag},
        {instancePath: schema, schemaPath: "mapping", parentSchema: true}
      )
      gen.endIf()
    }

    function applyTagSchema(schemaProp: string): Name {
      const _valid = gen.name("valid")
      cxt.subschema(
        {
          keyword: "mapping",
          schemaProp,
          jtdDiscriminator: schema,
        },
        _valid
      )
      return _valid
    }
  },
}

export default def
import type {CodeKeywordDefinition, SchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"
import {validateArray} from "../code"
import {_, not} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullable} from "./nullable"
import {typeError, _JTDTypeError} from "./error"

export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject>

const def: CodeKeywordDefinition = {
  keyword: "elements",
  schemaType: "object",
  error: typeError("array"),
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const [valid] = checkNullable(cxt)
    gen.if(not(valid), () =>
      gen.if(
        _`Array.isArray(${data})`,
        () => gen.assign(valid, validateArray(cxt)),
        () => cxt.error()
      )
    )
    cxt.ok(valid)
  },
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, or, and, Code} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullable} from "./nullable"

export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]>

const error: KeywordErrorDefinition = {
  message: "must be equal to one of the allowed values",
  params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "enum",
  schemaType: "array",
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, schemaValue, parentSchema, it} = cxt
    if (schema.length === 0) throw new Error("enum must have non-empty array")
    if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique")
    let valid: Code
    const isString = _`typeof ${data} == "string"`
    if (schema.length >= it.opts.loopEnum) {
      let cond: Code
      ;[valid, cond] = checkNullable(cxt, isString)
      gen.if(cond, loopEnum)
    } else {
      /* istanbul ignore if */
      if (!Array.isArray(schema)) throw new Error("ajv implementation error")
      valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`)))
      if (parentSchema.nullable) valid = or(_`${data} === null`, valid)
    }
    cxt.pass(valid)

    function loopEnum(): void {
      gen.forOf("v", schemaValue as Code, (v) =>
        gen.if(_`${valid} = ${data} === ${v}`, () => gen.break())
      )
    }
  },
}

export default def
import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types"
import {_, Code} from "../../compile/codegen"

export type _JTDTypeError<K extends string, T extends string, S> = ErrorObject<
  K,
  {type: T; nullable: boolean},
  S
>

export function typeError(t: string): KeywordErrorDefinition {
  return {
    message: (cxt) => typeErrorMessage(cxt, t),
    params: (cxt) => typeErrorParams(cxt, t),
  }
}

export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string {
  return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}`
}

export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code {
  return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}`
}
import type {Vocabulary} from "../../types"
import refKeyword from "./ref"
import typeKeyword, {JTDTypeError} from "./type"
import enumKeyword, {JTDEnumError} from "./enum"
import elements, {JTDElementsError} from "./elements"
import properties, {JTDPropertiesError} from "./properties"
import optionalProperties from "./optionalProperties"
import discriminator, {JTDDiscriminatorError} from "./discriminator"
import values, {JTDValuesError} from "./values"
import union from "./union"
import metadata from "./metadata"

const jtdVocabulary: Vocabulary = [
  "definitions",
  refKeyword,
  typeKeyword,
  enumKeyword,
  elements,
  properties,
  optionalProperties,
  discriminator,
  values,
  union,
  metadata,
  {keyword: "additionalProperties", schemaType: "boolean"},
  {keyword: "nullable", schemaType: "boolean"},
]

export default jtdVocabulary

export type JTDErrorObject =
  | JTDTypeError
  | JTDEnumError
  | JTDElementsError
  | JTDPropertiesError
  | JTDDiscriminatorError
  | JTDValuesError
import {KeywordCxt} from "../../ajv"
import type {CodeKeywordDefinition} from "../../types"
import {alwaysValidSchema} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "metadata",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const valid = gen.name("valid")
    cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid)
    cxt.ok(valid)
  },
}

export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void {
  if (it.jtdMetadata !== metadata) {
    throw new Error(`JTD: "${keyword}" cannot be used in this schema location`)
  }
}

export default def
import type {KeywordCxt} from "../../compile/validate"
import {_, not, nil, Code, Name} from "../../compile/codegen"

export function checkNullable(
  {gen, data, parentSchema}: KeywordCxt,
  cond: Code = nil
): [Name, Code] {
  const valid = gen.name("valid")
  if (parentSchema.nullable) {
    gen.let(valid, _`${data} === null`)
    cond = not(valid)
  } else {
    gen.let(valid, false)
  }
  return [valid, cond]
}

export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] {
  const [valid, cond_] = checkNullable(cxt, cond)
  return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]
}
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {validateProperties, error} from "./properties"

const def: CodeKeywordDefinition = {
  keyword: "optionalProperties",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    if (cxt.parentSchema.properties) return
    validateProperties(cxt)
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  SchemaObject,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {propertyInData, allSchemaProperties, isOwnProperty} from "../code"
import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util"
import {_, and, not, Code, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"

enum PropError {
  Additional = "additional",
  Missing = "missing",
}

type PropKeyword = "properties" | "optionalProperties"

type PropSchema = {[P in string]?: SchemaObject}

export type JTDPropertiesError =
  | _JTDTypeError<PropKeyword, "object", PropSchema>
  | ErrorObject<PropKeyword, {error: PropError.Additional; additionalProperty: string}, PropSchema>
  | ErrorObject<PropKeyword, {error: PropError.Missing; missingProperty: string}, PropSchema>

export const error: KeywordErrorDefinition = {
  message: (cxt) => {
    const {params} = cxt
    return params.propError
      ? params.propError === PropError.Additional
        ? "must NOT have additional properties"
        : `must have property '${params.missingProperty}'`
      : typeErrorMessage(cxt, "object")
  },
  params: (cxt) => {
    const {params} = cxt
    return params.propError
      ? params.propError === PropError.Additional
        ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
        : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
      : typeErrorParams(cxt, "object")
  },
}

const def: CodeKeywordDefinition = {
  keyword: "properties",
  schemaType: "object",
  error,
  code: validateProperties,
}

// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }

export function validateProperties(cxt: KeywordCxt): void {
  checkMetadata(cxt)
  const {gen, data, parentSchema, it} = cxt
  const {additionalProperties, nullable} = parentSchema
  if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping")
  if (commonProperties()) {
    throw new Error("JTD: properties and optionalProperties have common members")
  }
  const [allProps, properties] = schemaProperties("properties")
  const [allOptProps, optProperties] = schemaProperties("optionalProperties")
  if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
    return
  }

  const [valid, cond] =
    it.jtdDiscriminator === undefined
      ? checkNullableObject(cxt, data)
      : [gen.let("valid", false), true]
  gen.if(cond, () =>
    gen.assign(valid, true).block(() => {
      validateProps(properties, "properties", true)
      validateProps(optProperties, "optionalProperties")
      if (!additionalProperties) validateAdditional()
    })
  )
  cxt.pass(valid)

  function commonProperties(): boolean {
    const props = parentSchema.properties as Record<string, any> | undefined
    const optProps = parentSchema.optionalProperties as Record<string, any> | undefined
    if (!(props && optProps)) return false
    for (const p in props) {
      if (Object.prototype.hasOwnProperty.call(optProps, p)) return true
    }
    return false
  }

  function schemaProperties(keyword: string): [string[], string[]] {
    const schema = parentSchema[keyword]
    const allPs = schema ? allSchemaProperties(schema) : []
    if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
      throw new Error(`JTD: discriminator tag used in ${keyword}`)
    }
    const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p]))
    return [allPs, ps]
  }

  function validateProps(props: string[], keyword: string, required?: boolean): void {
    const _valid = gen.var("valid")
    for (const prop of props) {
      gen.if(
        propertyInData(gen, data, prop, it.opts.ownProperties),
        () => applyPropertySchema(prop, keyword, _valid),
        () => missingProperty(prop)
      )
      cxt.ok(_valid)
    }

    function missingProperty(prop: string): void {
      if (required) {
        gen.assign(_valid, false)
        cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop})
      } else {
        gen.assign(_valid, true)
      }
    }
  }

  function applyPropertySchema(prop: string, keyword: string, _valid: Name): void {
    cxt.subschema(
      {
        keyword,
        schemaProp: prop,
        dataProp: prop,
      },
      _valid
    )
  }

  function validateAdditional(): void {
    gen.forIn("key", data, (key: Name) => {
      const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator)
      const addOptProp = isAdditional(key, allOptProps, "optionalProperties")
      const extra =
        addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp)
      gen.if(extra, () => {
        if (it.opts.removeAdditional) {
          gen.code(_`delete ${data}[${key}]`)
        } else {
          cxt.error(
            false,
            {propError: PropError.Additional, additionalProperty: key},
            {instancePath: key, parentSchema: true}
          )
          if (!it.opts.allErrors) gen.break()
        }
      })
    })
  }

  function isAdditional(
    key: Name,
    props: string[],
    keyword: string,
    jtdDiscriminator?: string
  ): Code | true {
    let additional: Code | boolean
    if (props.length > 8) {
      // TODO maybe an option instead of hard-coded 8?
      const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword)
      additional = not(isOwnProperty(gen, propsSchema as Code, key))
      if (jtdDiscriminator !== undefined) {
        additional = and(additional, _`${key} !== ${jtdDiscriminator}`)
      }
    } else if (props.length || jtdDiscriminator !== undefined) {
      const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props)
      additional = and(...ps.map((p) => _`${key} !== ${p}`))
    } else {
      additional = true
    }
    return additional
  }
}

export default def
import type {CodeKeywordDefinition, AnySchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {compileSchema, SchemaEnv} from "../../compile"
import {_, not, nil, stringify} from "../../compile/codegen"
import MissingRefError from "../../compile/ref_error"
import N from "../../compile/names"
import {getValidate, callRef} from "../core/ref"
import {checkMetadata} from "./metadata"

const def: CodeKeywordDefinition = {
  keyword: "ref",
  schemaType: "string",
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema: ref, parentSchema, it} = cxt
    const {
      schemaEnv: {root},
    } = it
    const valid = gen.name("valid")
    if (parentSchema.nullable) {
      gen.var(valid, _`${data} === null`)
      gen.if(not(valid), validateJtdRef)
    } else {
      gen.var(valid, false)
      validateJtdRef()
    }
    cxt.ok(valid)

    function validateJtdRef(): void {
      const refSchema = (root.schema as AnySchemaObject).definitions?.[ref]
      if (!refSchema) {
        throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`)
      }
      if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema)
      else inlineRefSchema(refSchema)
    }

    function callValidate(schema: AnySchemaObject): void {
      const sch = compileSchema.call(
        it.self,
        new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
      )
      const v = getValidate(cxt, sch)
      const errsCount = gen.const("_errs", N.errors)
      callRef(cxt, v, sch, sch.$async)
      gen.assign(valid, _`${errsCount} === ${N.errors}`)
    }

    function inlineRefSchema(schema: AnySchemaObject): void {
      const schName = gen.scopeValue(
        "schema",
        it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
      )
      cxt.subschema(
        {
          schema,
          dataTypes: [],
          schemaPath: nil,
          topSchemaRef: schName,
          errSchemaPath: `/definitions/${ref}`,
        },
        valid
      )
    }
  },
}

export function hasRef(schema: AnySchemaObject): boolean {
  for (const key in schema) {
    let sch: AnySchemaObject
    if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true
  }
  return false
}

export default def
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, nil, or, Code} from "../../compile/codegen"
import validTimestamp from "../../runtime/timestamp"
import {useFunc} from "../../compile/util"
import {checkMetadata} from "./metadata"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"

export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>

export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"

export const intRange: {[T in IntType]: [number, number, number]} = {
  int8: [-128, 127, 3],
  uint8: [0, 255, 3],
  int16: [-32768, 32767, 5],
  uint16: [0, 65535, 5],
  int32: [-2147483648, 2147483647, 10],
  uint32: [0, 4294967295, 10],
}

export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType

const error: KeywordErrorDefinition = {
  message: (cxt) => typeErrorMessage(cxt, cxt.schema),
  params: (cxt) => typeErrorParams(cxt, cxt.schema),
}

function timestampCode(cxt: KeywordCxt): Code {
  const {gen, data, it} = cxt
  const {timestamp, allowDate} = it.opts
  if (timestamp === "date") return _`${data} instanceof Date `
  const vts = useFunc(gen, validTimestamp)
  const allowDateArg = allowDate ? _`, true` : nil
  const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`
  return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString)
}

const def: CodeKeywordDefinition = {
  keyword: "type",
  schemaType: "string",
  error,
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {data, schema, parentSchema, it} = cxt
    let cond: Code
    switch (schema) {
      case "boolean":
      case "string":
        cond = _`typeof ${data} == ${schema}`
        break
      case "timestamp": {
        cond = timestampCode(cxt)
        break
      }
      case "float32":
      case "float64":
        cond = _`typeof ${data} == "number"`
        break
      default: {
        const sch = schema as IntType
        cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`
        if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
          if (sch === "uint32") cond = _`${cond} && ${data} >= 0`
        } else {
          const [min, max] = intRange[sch]
          cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}`
        }
      }
    }
    cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateUnion} from "../code"

const def: CodeKeywordDefinition = {
  keyword: "union",
  schemaType: "array",
  trackErrors: true,
  code: validateUnion,
  error: {message: "must match a schema in union"},
}

export default def
import type {CodeKeywordDefinition, SchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema, Type} from "../../compile/util"
import {not, or, Name} from "../../compile/codegen"
import {checkMetadata} from "./metadata"
import {checkNullableObject} from "./nullable"
import {typeError, _JTDTypeError} from "./error"

export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject>

const def: CodeKeywordDefinition = {
  keyword: "values",
  schemaType: "object",
  error: typeError("object"),
  code(cxt: KeywordCxt) {
    checkMetadata(cxt)
    const {gen, data, schema, it} = cxt
    const [valid, cond] = checkNullableObject(cxt, data)
    if (alwaysValidSchema(it, schema)) {
      gen.if(not(or(cond, valid)), () => cxt.error())
    } else {
      gen.if(cond)
      gen.assign(valid, validateMap())
      gen.elseIf(not(valid))
      cxt.error()
      gen.endIf()
    }
    cxt.ok(valid)

    function validateMap(): Name | boolean {
      const _valid = gen.name("valid")
      if (it.allErrors) {
        const validMap = gen.let("valid", true)
        validateValues(() => gen.assign(validMap, false))
        return validMap
      }
      gen.var(_valid, true)
      validateValues(() => gen.break())
      return _valid

      function validateValues(notValid: () => void): void {
        gen.forIn("key", data, (key) => {
          cxt.subschema(
            {
              keyword: "values",
              dataProp: key,
              dataPropType: Type.Str,
            },
            _valid
          )
          gen.if(not(_valid), notValid)
        })
      }
    }
  },
}

export default def
import type {
  AddedFormat,
  FormatValidator,
  AsyncFormatValidator,
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen"

type FormatValidate =
  | FormatValidator<string>
  | FormatValidator<number>
  | AsyncFormatValidator<string>
  | AsyncFormatValidator<number>
  | RegExp
  | string
  | true

export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}>

const error: KeywordErrorDefinition = {
  message: ({schemaCode}) => str`must match format "${schemaCode}"`,
  params: ({schemaCode}) => _`{format: ${schemaCode}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "format",
  type: ["number", "string"],
  schemaType: "string",
  $data: true,
  error,
  code(cxt: KeywordCxt, ruleType?: string) {
    const {gen, data, $data, schema, schemaCode, it} = cxt
    const {opts, errSchemaPath, schemaEnv, self} = it
    if (!opts.validateFormats) return

    if ($data) validate$DataFormat()
    else validateFormat()

    function validate$DataFormat(): void {
      const fmts = gen.scopeValue("formats", {
        ref: self.formats,
        code: opts.code.formats,
      })
      const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`)
      const fType = gen.let("fType")
      const format = gen.let("format")
      // TODO simplify
      gen.if(
        _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,
        () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`),
        () => gen.assign(fType, _`"string"`).assign(format, fDef)
      )
      cxt.fail$data(or(unknownFmt(), invalidFmt()))

      function unknownFmt(): Code {
        if (opts.strictSchema === false) return nil
        return _`${schemaCode} && !${format}`
      }

      function invalidFmt(): Code {
        const callFormat = schemaEnv.$async
          ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
          : _`${format}(${data})`
        const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`
        return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`
      }
    }

    function validateFormat(): void {
      const formatDef: AddedFormat | undefined = self.formats[schema]
      if (!formatDef) {
        unknownFormat()
        return
      }
      if (formatDef === true) return
      const [fmtType, format, fmtRef] = getFormat(formatDef)
      if (fmtType === ruleType) cxt.pass(validCondition())

      function unknownFormat(): void {
        if (opts.strictSchema === false) {
          self.logger.warn(unknownMsg())
          return
        }
        throw new Error(unknownMsg())

        function unknownMsg(): string {
          return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"`
        }
      }

      function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {
        const code =
          fmtDef instanceof RegExp
            ? regexpCode(fmtDef)
            : opts.code.formats
            ? _`${opts.code.formats}${getProperty(schema)}`
            : undefined
        const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code})
        if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
          return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`]
        }

        return ["string", fmtDef, fmt]
      }

      function validCondition(): Code {
        if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
          if (!schemaEnv.$async) throw new Error("async format in sync schema")
          return _`await ${fmtRef}(${data})`
        }
        return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`
      }
    }
  },
}

export default def
import type {Vocabulary} from "../../types"
import formatKeyword from "./format"

const format: Vocabulary = [formatKeyword]

export default format
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Code} from "../../compile/codegen"
import N from "../../compile/names"
import {SchemaEnv, compileSchema} from "../../compile"
import {getValidate} from "../core/ref"

const def: CodeKeywordDefinition = {
  keyword: "$dynamicAnchor",
  schemaType: "string",
  code: (cxt) => dynamicAnchor(cxt, cxt.schema),
}

export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void {
  const {gen, it} = cxt
  it.schemaEnv.root.dynamicAnchors[anchor] = true
  const v = _`${N.dynamicAnchors}${getProperty(anchor)}`
  const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt)
  gen.if(_`!${v}`, () => gen.assign(v, validate))
}

function _getValidate(cxt: KeywordCxt): Code {
  const {schemaEnv, schema, self} = cxt.it
  const {root, baseId, localRefs, meta} = schemaEnv.root
  const {schemaId} = self.opts
  const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})
  compileSchema.call(self, sch)
  return getValidate(cxt, sch)
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import {callRef} from "../core/ref"

const def: CodeKeywordDefinition = {
  keyword: "$dynamicRef",
  schemaType: "string",
  code: (cxt) => dynamicRef(cxt, cxt.schema),
}

export function dynamicRef(cxt: KeywordCxt, ref: string): void {
  const {gen, keyword, it} = cxt
  if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`)
  const anchor = ref.slice(1)
  if (it.allErrors) {
    _dynamicRef()
  } else {
    const valid = gen.let("valid", false)
    _dynamicRef(valid)
    cxt.ok(valid)
  }

  function _dynamicRef(valid?: Name): void {
    // TODO the assumption here is that `recursiveRef: #` always points to the root
    // of the schema object, which is not correct, because there may be $id that
    // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
    // Because of that 2 tests in recursiveRef.json fail.
    // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
    // (This problem is not tested in JSON-Schema-Test-Suite)
    if (it.schemaEnv.root.dynamicAnchors[anchor]) {
      const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`)
      gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid))
    } else {
      _callRef(it.validateName, valid)()
    }
  }

  function _callRef(validate: Code, valid?: Name): () => void {
    return valid
      ? () =>
          gen.block(() => {
            callRef(cxt, validate)
            gen.let(valid, true)
          })
      : () => callRef(cxt, validate)
  }
}

export default def
import type {Vocabulary} from "../../types"
import dynamicAnchor from "./dynamicAnchor"
import dynamicRef from "./dynamicRef"
import recursiveAnchor from "./recursiveAnchor"
import recursiveRef from "./recursiveRef"

const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef]

export default dynamic
import type {CodeKeywordDefinition} from "../../types"
import {dynamicAnchor} from "./dynamicAnchor"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "$recursiveAnchor",
  schemaType: "boolean",
  code(cxt) {
    if (cxt.schema) dynamicAnchor(cxt, "")
    else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored")
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {dynamicRef} from "./dynamicRef"

const def: CodeKeywordDefinition = {
  keyword: "$recursiveRef",
  schemaType: "string",
  code: (cxt) => dynamicRef(cxt, cxt.schema),
}

export default def
import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, getProperty, Name} from "../../compile/codegen"
import {DiscrError, DiscrErrorObj} from "../discriminator/types"
import {resolveRef, SchemaEnv} from "../../compile"
import MissingRefError from "../../compile/ref_error"
import {schemaHasRulesButRef} from "../../compile/util"

export type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>

const error: KeywordErrorDefinition = {
  message: ({params: {discrError, tagName}}) =>
    discrError === DiscrError.Tag
      ? `tag "${tagName}" must be string`
      : `value of tag "${tagName}" must be in oneOf`,
  params: ({params: {discrError, tag, tagName}}) =>
    _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "discriminator",
  type: "object",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    const {gen, data, schema, parentSchema, it} = cxt
    const {oneOf} = parentSchema
    if (!it.opts.discriminator) {
      throw new Error("discriminator: requires discriminator option")
    }
    const tagName = schema.propertyName
    if (typeof tagName != "string") throw new Error("discriminator: requires propertyName")
    if (schema.mapping) throw new Error("discriminator: mapping is not supported")
    if (!oneOf) throw new Error("discriminator: requires oneOf keyword")
    const valid = gen.let("valid", false)
    const tag = gen.const("tag", _`${data}${getProperty(tagName)}`)
    gen.if(
      _`typeof ${tag} == "string"`,
      () => validateMapping(),
      () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})
    )
    cxt.ok(valid)

    function validateMapping(): void {
      const mapping = getMapping()
      gen.if(false)
      for (const tagValue in mapping) {
        gen.elseIf(_`${tag} === ${tagValue}`)
        gen.assign(valid, applyTagSchema(mapping[tagValue]))
      }
      gen.else()
      cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})
      gen.endIf()
    }

    function applyTagSchema(schemaProp?: number): Name {
      const _valid = gen.name("valid")
      const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid)
      cxt.mergeEvaluated(schCxt, Name)
      return _valid
    }

    function getMapping(): {[T in string]?: number} {
      const oneOfMapping: {[T in string]?: number} = {}
      const topRequired = hasRequired(parentSchema)
      let tagRequired = true
      for (let i = 0; i < oneOf.length; i++) {
        let sch = oneOf[i]
        if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {
          const ref = sch.$ref
          sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)
          if (sch instanceof SchemaEnv) sch = sch.schema
          if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)
        }
        const propSch = sch?.properties?.[tagName]
        if (typeof propSch != "object") {
          throw new Error(
            `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`
          )
        }
        tagRequired = tagRequired && (topRequired || hasRequired(sch))
        addMappings(propSch, i)
      }
      if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`)
      return oneOfMapping

      function hasRequired({required}: AnySchemaObject): boolean {
        return Array.isArray(required) && required.includes(tagName)
      }

      function addMappings(sch: AnySchemaObject, i: number): void {
        if (sch.const) {
          addMapping(sch.const, i)
        } else if (sch.enum) {
          for (const tagValue of sch.enum) {
            addMapping(tagValue, i)
          }
        } else {
          throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)
        }
      }

      function addMapping(tagValue: unknown, i: number): void {
        if (typeof tagValue != "string" || tagValue in oneOfMapping) {
          throw new Error(`discriminator: "${tagName}" values must be unique strings`)
        }
        oneOfMapping[tagValue] = i
      }
    }
  },
}

export default def
import type {ErrorObject} from "../../types"

export enum DiscrError {
  Tag = "tag",
  Mapping = "mapping",
}

export type DiscrErrorObj<E extends DiscrError> = ErrorObject<
  "discriminator",
  {error: E; tag: string; tagValue: unknown},
  string
>
import type {CodeKeywordDefinition} from "../../types"

const def: CodeKeywordDefinition = {
  keyword: "id",
  code() {
    throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')
  },
}

export default def
import type {Vocabulary} from "../../types"
import idKeyword from "./id"
import refKeyword from "./ref"

const core: Vocabulary = [
  "$schema",
  "$id",
  "$defs",
  "$vocabulary",
  {keyword: "$comment"},
  "definitions",
  idKeyword,
  refKeyword,
]

export default core
import type {CodeKeywordDefinition, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import MissingRefError from "../../compile/ref_error"
import {callValidateCode} from "../code"
import {_, nil, stringify, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import {SchemaEnv, resolveRef} from "../../compile"
import {mergeEvaluated} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "$ref",
  schemaType: "string",
  code(cxt: KeywordCxt): void {
    const {gen, schema: $ref, it} = cxt
    const {baseId, schemaEnv: env, validateName, opts, self} = it
    const {root} = env
    if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef()
    const schOrEnv = resolveRef.call(self, root, baseId, $ref)
    if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)
    if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)
    return inlineRefSchema(schOrEnv)

    function callRootRef(): void {
      if (env === root) return callRef(cxt, validateName, env, env.$async)
      const rootName = gen.scopeValue("root", {ref: root})
      return callRef(cxt, _`${rootName}.validate`, root, root.$async)
    }

    function callValidate(sch: SchemaEnv): void {
      const v = getValidate(cxt, sch)
      callRef(cxt, v, sch, sch.$async)
    }

    function inlineRefSchema(sch: AnySchema): void {
      const schName = gen.scopeValue(
        "schema",
        opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}
      )
      const valid = gen.name("valid")
      const schCxt = cxt.subschema(
        {
          schema: sch,
          dataTypes: [],
          schemaPath: nil,
          topSchemaRef: schName,
          errSchemaPath: $ref,
        },
        valid
      )
      cxt.mergeEvaluated(schCxt)
      cxt.ok(valid)
    }
  },
}

export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {
  const {gen} = cxt
  return sch.validate
    ? gen.scopeValue("validate", {ref: sch.validate})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.validate`
}

export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {
  const {gen, it} = cxt
  const {allErrors, schemaEnv: env, opts} = it
  const passCxt = opts.passContext ? N.this : nil
  if ($async) callAsyncRef()
  else callSyncRef()

  function callAsyncRef(): void {
    if (!env.$async) throw new Error("async schema referenced by sync schema")
    const valid = gen.let("valid")
    gen.try(
      () => {
        gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)
        addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result
        if (!allErrors) gen.assign(valid, true)
      },
      (e) => {
        gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))
        addErrorsFrom(e)
        if (!allErrors) gen.assign(valid, false)
      }
    )
    cxt.ok(valid)
  }

  function callSyncRef(): void {
    cxt.result(
      callValidateCode(cxt, v, passCxt),
      () => addEvaluatedFrom(v),
      () => addErrorsFrom(v)
    )
  }

  function addErrorsFrom(source: Code): void {
    const errs = _`${source}.errors`
    gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged
    gen.assign(N.errors, _`${N.vErrors}.length`)
  }

  function addEvaluatedFrom(source: Code): void {
    if (!it.opts.unevaluated) return
    const schEvaluated = sch?.validate?.evaluated
    // TODO refactor
    if (it.props !== true) {
      if (schEvaluated && !schEvaluated.dynamicProps) {
        if (schEvaluated.props !== undefined) {
          it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)
        }
      } else {
        const props = gen.var("props", _`${source}.evaluated.props`)
        it.props = mergeEvaluated.props(gen, props, it.props, Name)
      }
    }
    if (it.items !== true) {
      if (schEvaluated && !schEvaluated.dynamicItems) {
        if (schEvaluated.items !== undefined) {
          it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)
        }
      } else {
        const items = gen.var("items", _`${source}.evaluated.items`)
        it.items = mergeEvaluated.items(gen, items, it.items, Name)
      }
    }
  }
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util"

export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "additionalItems" as const,
  type: "array",
  schemaType: ["boolean", "object"],
  before: "uniqueItems",
  error,
  code(cxt: KeywordCxt) {
    const {parentSchema, it} = cxt
    const {items} = parentSchema
    if (!Array.isArray(items)) {
      checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas')
      return
    }
    validateAdditionalItems(cxt, items)
  },
}

export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {
  const {gen, schema, data, keyword, it} = cxt
  it.items = true
  const len = gen.const("len", _`${data}.length`)
  if (schema === false) {
    cxt.setParams({len: items.length})
    cxt.pass(_`${len} <= ${items.length}`)
  } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
    const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var
    gen.if(not(valid), () => validateItems(valid))
    cxt.ok(valid)
  }

  function validateItems(valid: Name): void {
    gen.forRange("i", items.length, len, (i) => {
      cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)
      if (!it.allErrors) gen.if(not(valid), () => gen.break())
    })
  }
}

export default def
import type {
  CodeKeywordDefinition,
  AddedKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import {allSchemaProperties, usePattern, isOwnProperty} from "../code"
import {_, nil, or, not, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"
import type {SubschemaArgs} from "../../compile/validate/subschema"
import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util"

export type AdditionalPropertiesError = ErrorObject<
  "additionalProperties",
  {additionalProperty: string},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: "must NOT have additional properties",
  params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
}

const def: CodeKeywordDefinition & AddedKeywordDefinition = {
  keyword: "additionalProperties",
  type: ["object"],
  schemaType: ["boolean", "object"],
  allowUndefined: true,
  trackErrors: true,
  error,
  code(cxt) {
    const {gen, schema, parentSchema, data, errsCount, it} = cxt
    /* istanbul ignore if */
    if (!errsCount) throw new Error("ajv implementation error")
    const {allErrors, opts} = it
    it.props = true
    if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return
    const props = allSchemaProperties(parentSchema.properties)
    const patProps = allSchemaProperties(parentSchema.patternProperties)
    checkAdditionalProperties()
    cxt.ok(_`${errsCount} === ${N.errors}`)

    function checkAdditionalProperties(): void {
      gen.forIn("key", data, (key: Name) => {
        if (!props.length && !patProps.length) additionalPropertyCode(key)
        else gen.if(isAdditional(key), () => additionalPropertyCode(key))
      })
    }

    function isAdditional(key: Name): Code {
      let definedProp: Code
      if (props.length > 8) {
        // TODO maybe an option instead of hard-coded 8?
        const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties")
        definedProp = isOwnProperty(gen, propsSchema as Code, key)
      } else if (props.length) {
        definedProp = or(...props.map((p) => _`${key} === ${p}`))
      } else {
        definedProp = nil
      }
      if (patProps.length) {
        definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))
      }
      return not(definedProp)
    }

    function deleteAdditional(key: Name): void {
      gen.code(_`delete ${data}[${key}]`)
    }

    function additionalPropertyCode(key: Name): void {
      if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
        deleteAdditional(key)
        return
      }

      if (schema === false) {
        cxt.setParams({additionalProperty: key})
        cxt.error()
        if (!allErrors) gen.break()
        return
      }

      if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
        const valid = gen.name("valid")
        if (opts.removeAdditional === "failing") {
          applyAdditionalSchema(key, valid, false)
          gen.if(not(valid), () => {
            cxt.reset()
            deleteAdditional(key)
          })
        } else {
          applyAdditionalSchema(key, valid)
          if (!allErrors) gen.if(not(valid), () => gen.break())
        }
      }
    }

    function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {
      const subschema: SubschemaArgs = {
        keyword: "additionalProperties",
        dataProp: key,
        dataPropType: Type.Str,
      }
      if (errors === false) {
        Object.assign(subschema, {
          compositeRule: true,
          createErrors: false,
          allErrors: false,
        })
      }
      cxt.subschema(subschema, valid)
    }
  },
}

export default def
import type {CodeKeywordDefinition, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: "allOf",
  schemaType: "array",
  code(cxt: KeywordCxt) {
    const {gen, schema, it} = cxt
    /* istanbul ignore if */
    if (!Array.isArray(schema)) throw new Error("ajv implementation error")
    const valid = gen.name("valid")
    schema.forEach((sch: AnySchema, i: number) => {
      if (alwaysValidSchema(it, sch)) return
      const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid)
      cxt.ok(valid)
      cxt.mergeEvaluated(schCxt)
    })
  },
}

export default def
import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types"
import {validateUnion} from "../code"

export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]>

const def: CodeKeywordDefinition = {
  keyword: "anyOf",
  schemaType: "array",
  trackErrors: true,
  code: validateUnion,
  error: {message: "must match a schema in anyOf"},
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util"

export type ContainsError = ErrorObject<
  "contains",
  {minContains: number; maxContains?: number},
  AnySchema
>

const error: KeywordErrorDefinition = {
  message: ({params: {min, max}}) =>
    max === undefined
      ? str`must contain at least ${min} valid item(s)`
      : str`must contain at least ${min} and no more than ${max} valid item(s)`,
  params: ({params: {min, max}}) =>
    max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "contains",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, data, it} = cxt
    let min: number
    let max: number | undefined
    const {minContains, maxContains} = parentSchema
    if (it.opts.next) {
      min = minContains === undefined ? 1 : minContains
      max = maxContains
    } else {
      min = 1
    }
    const len = gen.const("len", _`${data}.length`)
    cxt.setParams({min, max})
    if (max === undefined && min === 0) {
      checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`)
      return
    }
    if (max !== undefined && min > max) {
      checkStrictMode(it, `"minContains" > "maxContains" is always invalid`)
      cxt.fail()
      return
    }
    if (alwaysValidSchema(it, schema)) {
      let cond = _`${len} >= ${min}`
      if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`
      cxt.pass(cond)
      return
    }

    it.items = true
    const valid = gen.name("valid")
    if (max === undefined && min === 1) {
      validateItems(valid, () => gen.if(valid, () => gen.break()))
    } else if (min === 0) {
      gen.let(valid, true)
      if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)
    } else {
      gen.let(valid, false)
      validateItemsWithCount()
    }
    cxt.result(valid, () => cxt.reset())

    function validateItemsWithCount(): void {
      const schValid = gen.name("_valid")
      const count = gen.let("count", 0)
      validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))
    }

    function validateItems(_valid: Name, block: () => void): void {
      gen.forRange("i", 0, len, (i) => {
        cxt.subschema(
          {
            keyword: "contains",
            dataProp: i,
            dataPropType: Type.Num,
            compositeRule: true,
          },
          _valid
        )
        block()
      })
    }

    function checkLimits(count: Name): void {
      gen.code(_`${count}++`)
      if (max === undefined) {
        gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())
      } else {
        gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())
        if (min === 1) gen.assign(valid, true)
        else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))
      }
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  SchemaMap,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code"

export type PropertyDependencies = {[K in string]?: string[]}

export interface DependenciesErrorParams {
  property: string
  missingProperty: string
  depsCount: number
  deps: string // TODO change to string[]
}

type SchemaDependencies = SchemaMap

export type DependenciesError = ErrorObject<
  "dependencies",
  DependenciesErrorParams,
  {[K in string]?: string[] | AnySchema}
>

export const error: KeywordErrorDefinition = {
  message: ({params: {property, depsCount, deps}}) => {
    const property_ies = depsCount === 1 ? "property" : "properties"
    return str`must have ${property_ies} ${deps} when property ${property} is present`
  },
  params: ({params: {property, depsCount, deps, missingProperty}}) =>
    _`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
}

const def: CodeKeywordDefinition = {
  keyword: "dependencies",
  type: "object",
  schemaType: "object",
  error,
  code(cxt: KeywordCxt) {
    const [propDeps, schDeps] = splitDependencies(cxt)
    validatePropertyDeps(cxt, propDeps)
    validateSchemaDeps(cxt, schDeps)
  },
}

function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {
  const propertyDeps: PropertyDependencies = {}
  const schemaDeps: SchemaDependencies = {}
  for (const key in schema) {
    if (key === "__proto__") continue
    const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps
    deps[key] = schema[key]
  }
  return [propertyDeps, schemaDeps]
}

export function validatePropertyDeps(
  cxt: KeywordCxt,
  propertyDeps: {[K in string]?: string[]} = cxt.schema
): void {
  const {gen, data, it} = cxt
  if (Object.keys(propertyDeps).length === 0) return
  const missing = gen.let("missing")
  for (const prop in propertyDeps) {
    const deps = propertyDeps[prop] as string[]
    if (deps.length === 0) continue
    const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)
    cxt.setParams({
      property: prop,
      depsCount: deps.length,
      deps: deps.join(", "),
    })
    if (it.allErrors) {
      gen.if(hasProperty, () => {
        for (const depProp of deps) {
          checkReportMissingProp(cxt, depProp)
        }
      })
    } else {
      gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)
      reportMissingProp(cxt, missing)
      gen.else()
    }
  }
}

export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {
  const {gen, data, keyword, it} = cxt
  const valid = gen.name("valid")
  for (const prop in schemaDeps) {
    if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue
    gen.if(
      propertyInData(gen, data, prop, it.opts.ownProperties),
      () => {
        const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)
        cxt.mergeValidEvaluated(schCxt, valid)
      },
      () => gen.var(valid, true) // TODO var
    )
    cxt.ok(valid)
  }
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateSchemaDeps} from "./dependencies"

const def: CodeKeywordDefinition = {
  keyword: "dependentSchemas",
  type: "object",
  schemaType: "object",
  code: (cxt) => validateSchemaDeps(cxt),
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {SchemaObjCxt} from "../../compile"
import type {KeywordCxt} from "../../compile/validate"
import {_, str, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode} from "../../compile/util"

export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params}) => str`must match "${params.ifClause}" schema`,
  params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "if",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, parentSchema, it} = cxt
    if (parentSchema.then === undefined && parentSchema.else === undefined) {
      checkStrictMode(it, '"if" without "then" and "else" is ignored')
    }
    const hasThen = hasSchema(it, "then")
    const hasElse = hasSchema(it, "else")
    if (!hasThen && !hasElse) return

    const valid = gen.let("valid", true)
    const schValid = gen.name("_valid")
    validateIf()
    cxt.reset()

    if (hasThen && hasElse) {
      const ifClause = gen.let("ifClause")
      cxt.setParams({ifClause})
      gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause))
    } else if (hasThen) {
      gen.if(schValid, validateClause("then"))
    } else {
      gen.if(not(schValid), validateClause("else"))
    }

    cxt.pass(valid, () => cxt.error(true))

    function validateIf(): void {
      const schCxt = cxt.subschema(
        {
          keyword: "if",
          compositeRule: true,
          createErrors: false,
          allErrors: false,
        },
        schValid
      )
      cxt.mergeEvaluated(schCxt)
    }

    function validateClause(keyword: string, ifClause?: Name): () => void {
      return () => {
        const schCxt = cxt.subschema({keyword}, schValid)
        gen.assign(valid, schValid)
        cxt.mergeValidEvaluated(schCxt, valid)
        if (ifClause) gen.assign(ifClause, _`${keyword}`)
        else cxt.setParams({ifClause: keyword})
      }
    }
  },
}

function hasSchema(it: SchemaObjCxt, keyword: string): boolean {
  const schema = it.schema[keyword]
  return schema !== undefined && !alwaysValidSchema(it, schema)
}

export default def
import type {ErrorNoParams, Vocabulary} from "../../types"
import additionalItems, {AdditionalItemsError} from "./additionalItems"
import prefixItems from "./prefixItems"
import items from "./items"
import items2020, {ItemsError} from "./items2020"
import contains, {ContainsError} from "./contains"
import dependencies, {DependenciesError} from "./dependencies"
import propertyNames, {PropertyNamesError} from "./propertyNames"
import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties"
import properties from "./properties"
import patternProperties from "./patternProperties"
import notKeyword, {NotKeywordError} from "./not"
import anyOf, {AnyOfError} from "./anyOf"
import oneOf, {OneOfError} from "./oneOf"
import allOf from "./allOf"
import ifKeyword, {IfKeywordError} from "./if"
import thenElse from "./thenElse"

export default function getApplicator(draft2020 = false): Vocabulary {
  const applicator = [
    // any
    notKeyword,
    anyOf,
    oneOf,
    allOf,
    ifKeyword,
    thenElse,
    // object
    propertyNames,
    additionalProperties,
    dependencies,
    properties,
    patternProperties,
  ]
  // array
  if (draft2020) applicator.push(prefixItems, items2020)
  else applicator.push(additionalItems, items)
  applicator.push(contains)
  return applicator
}

export type ApplicatorKeywordError =
  | ErrorNoParams<"false schema">
  | AdditionalItemsError
  | ItemsError
  | ContainsError
  | AdditionalPropertiesError
  | DependenciesError
  | IfKeywordError
  | AnyOfError
  | OneOfError
  | NotKeywordError
  | PropertyNamesError
import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_} from "../../compile/codegen"
import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util"
import {validateArray} from "../code"

const def: CodeKeywordDefinition = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "array", "boolean"],
  before: "uniqueItems",
  code(cxt: KeywordCxt) {
    const {schema, it} = cxt
    if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema)
    it.items = true
    if (alwaysValidSchema(it, schema)) return
    cxt.ok(validateArray(cxt))
  },
}

export function validateTuple(
  cxt: KeywordCxt,
  extraItems: string,
  schArr: AnySchema[] = cxt.schema
): void {
  const {gen, parentSchema, data, keyword, it} = cxt
  checkStrictTuple(parentSchema)
  if (it.opts.unevaluated && schArr.length && it.items !== true) {
    it.items = mergeEvaluated.items(gen, schArr.length, it.items)
  }
  const valid = gen.name("valid")
  const len = gen.const("len", _`${data}.length`)
  schArr.forEach((sch: AnySchema, i: number) => {
    if (alwaysValidSchema(it, sch)) return
    gen.if(_`${len} > ${i}`, () =>
      cxt.subschema(
        {
          keyword,
          schemaProp: i,
          dataProp: i,
        },
        valid
      )
    )
    cxt.ok(valid)
  })

  function checkStrictTuple(sch: AnySchemaObject): void {
    const {opts, errSchemaPath} = it
    const l = schArr.length
    const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)
    if (opts.strictTuples && !fullTuple) {
      const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`
      checkStrictMode(it, msg, opts.strictTuples)
    }
  }
}

export default def
import type {
  CodeKeywordDefinition,
  KeywordErrorDefinition,
  ErrorObject,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {validateArray} from "../code"
import {validateAdditionalItems} from "./additionalItems"

export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema>

const error: KeywordErrorDefinition = {
  message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  error,
  code(cxt: KeywordCxt) {
    const {schema, parentSchema, it} = cxt
    const {prefixItems} = parentSchema
    it.items = true
    if (alwaysValidSchema(it, schema)) return
    if (prefixItems) validateAdditionalItems(cxt, prefixItems)
    else cxt.ok(validateArray(cxt))
  },
}

export default def
import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {alwaysValidSchema} from "../../compile/util"

export type NotKeywordError = ErrorNoParams<"not", AnySchema>

const def: CodeKeywordDefinition = {
  keyword: "not",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  code(cxt: KeywordCxt) {
    const {gen, schema, it} = cxt
    if (alwaysValidSchema(it, schema)) {
      cxt.fail()
      return
    }

    const valid = gen.name("valid")
    cxt.subschema(
      {
        keyword: "not",
        compositeRule: true,
        createErrors: false,
        allErrors: false,
      },
      valid
    )

    cxt.failResult(
      valid,
      () => cxt.reset(),
      () => cxt.error()
    )
  },
  error: {message: "must NOT be valid"},
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, Name} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {SchemaCxt} from "../../compile"

export type OneOfError = ErrorObject<
  "oneOf",
  {passingSchemas: [number, number] | null},
  AnySchema[]
>

const error: KeywordErrorDefinition = {
  message: "must match exactly one schema in oneOf",
  params: ({params}) => _`{passingSchemas: ${params.passing}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "oneOf",
  schemaType: "array",
  trackErrors: true,
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, it} = cxt
    /* istanbul ignore if */
    if (!Array.isArray(schema)) throw new Error("ajv implementation error")
    if (it.opts.discriminator && parentSchema.discriminator) return
    const schArr: AnySchema[] = schema
    const valid = gen.let("valid", false)
    const passing = gen.let("passing", null)
    const schValid = gen.name("_valid")
    cxt.setParams({passing})
    // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas

    gen.block(validateOneOf)

    cxt.result(
      valid,
      () => cxt.reset(),
      () => cxt.error(true)
    )

    function validateOneOf(): void {
      schArr.forEach((sch: AnySchema, i: number) => {
        let schCxt: SchemaCxt | undefined
        if (alwaysValidSchema(it, sch)) {
          gen.var(schValid, true)
        } else {
          schCxt = cxt.subschema(
            {
              keyword: "oneOf",
              schemaProp: i,
              compositeRule: true,
            },
            schValid
          )
        }

        if (i > 0) {
          gen
            .if(_`${schValid} && ${valid}`)
            .assign(valid, false)
            .assign(passing, _`[${passing}, ${i}]`)
            .else()
        }

        gen.if(schValid, () => {
          gen.assign(valid, true)
          gen.assign(passing, i)
          if (schCxt) cxt.mergeEvaluated(schCxt, Name)
        })
      })
    }
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {allSchemaProperties, usePattern} from "../code"
import {_, not, Name} from "../../compile/codegen"
import {alwaysValidSchema, checkStrictMode} from "../../compile/util"
import {evaluatedPropsToName, Type} from "../../compile/util"
import {AnySchema} from "../../types"

const def: CodeKeywordDefinition = {
  keyword: "patternProperties",
  type: "object",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    const {gen, schema, data, parentSchema, it} = cxt
    const {opts} = it
    const patterns = allSchemaProperties(schema)
    const alwaysValidPatterns = patterns.filter((p) =>
      alwaysValidSchema(it, schema[p] as AnySchema)
    )

    if (
      patterns.length === 0 ||
      (alwaysValidPatterns.length === patterns.length &&
        (!it.opts.unevaluated || it.props === true))
    ) {
      return
    }

    const checkProperties =
      opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties
    const valid = gen.name("valid")
    if (it.props !== true && !(it.props instanceof Name)) {
      it.props = evaluatedPropsToName(gen, it.props)
    }
    const {props} = it
    validatePatternProperties()

    function validatePatternProperties(): void {
      for (const pat of patterns) {
        if (checkProperties) checkMatchingProperties(pat)
        if (it.allErrors) {
          validateProperties(pat)
        } else {
          gen.var(valid, true) // TODO var
          validateProperties(pat)
          gen.if(valid)
        }
      }
    }

    function checkMatchingProperties(pat: string): void {
      for (const prop in checkProperties) {
        if (new RegExp(pat).test(prop)) {
          checkStrictMode(
            it,
            `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`
          )
        }
      }
    }

    function validateProperties(pat: string): void {
      gen.forIn("key", data, (key) => {
        gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {
          const alwaysValid = alwaysValidPatterns.includes(pat)
          if (!alwaysValid) {
            cxt.subschema(
              {
                keyword: "patternProperties",
                schemaProp: pat,
                dataProp: key,
                dataPropType: Type.Str,
              },
              valid
            )
          }

          if (it.opts.unevaluated && props !== true) {
            gen.assign(_`${props}[${key}]`, true)
          } else if (!alwaysValid && !it.allErrors) {
            // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
            // or if all properties were evaluated (props === true)
            gen.if(not(valid), () => gen.break())
          }
        })
      })
    }
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {validateTuple} from "./items"

const def: CodeKeywordDefinition = {
  keyword: "prefixItems",
  type: "array",
  schemaType: ["array"],
  before: "uniqueItems",
  code: (cxt) => validateTuple(cxt, "items"),
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import {KeywordCxt} from "../../compile/validate"
import {propertyInData, allSchemaProperties} from "../code"
import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util"
import apDef from "./additionalProperties"

const def: CodeKeywordDefinition = {
  keyword: "properties",
  type: "object",
  schemaType: "object",
  code(cxt: KeywordCxt) {
    const {gen, schema, parentSchema, data, it} = cxt
    if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
      apDef.code(new KeywordCxt(it, apDef, "additionalProperties"))
    }
    const allProps = allSchemaProperties(schema)
    for (const prop of allProps) {
      it.definedProperties.add(prop)
    }
    if (it.opts.unevaluated && allProps.length && it.props !== true) {
      it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)
    }
    const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))
    if (properties.length === 0) return
    const valid = gen.name("valid")

    for (const prop of properties) {
      if (hasDefault(prop)) {
        applyPropertySchema(prop)
      } else {
        gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))
        applyPropertySchema(prop)
        if (!it.allErrors) gen.else().var(valid, true)
        gen.endIf()
      }
      cxt.it.definedProperties.add(prop)
      cxt.ok(valid)
    }

    function hasDefault(prop: string): boolean | undefined {
      return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined
    }

    function applyPropertySchema(prop: string): void {
      cxt.subschema(
        {
          keyword: "properties",
          schemaProp: prop,
          dataProp: prop,
        },
        valid
      )
    }
  },
}

export default def
import type {
  CodeKeywordDefinition,
  ErrorObject,
  KeywordErrorDefinition,
  AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, not} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"

export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema>

const error: KeywordErrorDefinition = {
  message: "property name must be valid",
  params: ({params}) => _`{propertyName: ${params.propertyName}}`,
}

const def: CodeKeywordDefinition = {
  keyword: "propertyNames",
  type: "object",
  schemaType: ["object", "boolean"],
  error,
  code(cxt: KeywordCxt) {
    const {gen, schema, data, it} = cxt
    if (alwaysValidSchema(it, schema)) return
    const valid = gen.name("valid")

    gen.forIn("key", data, (key) => {
      cxt.setParams({propertyName: key})
      cxt.subschema(
        {
          keyword: "propertyNames",
          data: key,
          dataTypes: ["string"],
          propertyName: key,
          compositeRule: true,
        },
        valid
      )
      gen.if(not(valid), () => {
        cxt.error(true)
        if (!it.allErrors) gen.break()
      })
    })

    cxt.ok(valid)
  },
}

export default def
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {checkStrictMode} from "../../compile/util"

const def: CodeKeywordDefinition = {
  keyword: ["then", "else"],
  schemaType: ["object", "boolean"],
  code({keyword, parentSchema, it}: KeywordCxt) {
    if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`)
  },
}

export default def
import {URIComponent} from "fast-uri"
import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen"
import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile"
import type {JSONType} from "../compile/rules"
import type {KeywordCxt} from "../compile/validate"
import type Ajv from "../core"

interface _SchemaObject {
  id?: string
  $id?: string
  $schema?: string
  [x: string]: any // TODO
}

export interface SchemaObject extends _SchemaObject {
  id?: string
  $id?: string
  $schema?: string
  $async?: false
  [x: string]: any // TODO
}

export interface AsyncSchema extends _SchemaObject {
  $async: true
}

export type AnySchemaObject = SchemaObject | AsyncSchema

export type Schema = SchemaObject | boolean

export type AnySchema = Schema | AsyncSchema

export type SchemaMap = {[Key in string]?: AnySchema}

export interface SourceCode {
  validateName: ValueScopeName
  validateCode: string
  scopeValues: ScopeValueSets
  evaluated?: Code
}

export interface DataValidationCxt<T extends string | number = string | number> {
  instancePath: string
  parentData: {[K in T]: any} // object or array
  parentDataProperty: T // string or number
  rootData: Record<string, any> | any[]
  dynamicAnchors: {[Ref in string]?: ValidateFunction}
}

export interface ValidateFunction<T = unknown> {
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T
  errors?: null | ErrorObject[]
  evaluated?: Evaluated
  schema: AnySchema
  schemaEnv: SchemaEnv
  source?: SourceCode
}

export interface JTDParser<T = unknown> {
  (json: string): T | undefined
  message?: string
  position?: number
}

export type EvaluatedProperties = {[K in string]?: true} | true

export type EvaluatedItems = number | true

export interface Evaluated {
  // determined at compile time if staticProps/Items is true
  props?: EvaluatedProperties
  items?: EvaluatedItems
  // whether props/items determined at compile time
  dynamicProps: boolean
  dynamicItems: boolean
}

export interface AsyncValidateFunction<T = unknown> extends ValidateFunction<T> {
  (...args: Parameters<ValidateFunction<T>>): Promise<T>
  $async: true
}

export type AnyValidateFunction<T = any> = ValidateFunction<T> | AsyncValidateFunction<T>

export interface ErrorObject<K extends string = string, P = Record<string, any>, S = unknown> {
  keyword: K
  instancePath: string
  schemaPath: string
  params: P
  // Added to validation errors of "propertyNames" keyword schema
  propertyName?: string
  // Excluded if option `messages` set to false.
  message?: string
  // These are added with the `verbose` option.
  schema?: S
  parentSchema?: AnySchemaObject
  data?: unknown
}

export type ErrorNoParams<K extends string, S = unknown> = ErrorObject<K, Record<string, never>, S>

interface _KeywordDef {
  keyword: string | string[]
  type?: JSONType | JSONType[] // data types that keyword applies to
  schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema
  allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema
  $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference)
  implements?: string[] // other schema keywords that this keyword implements
  before?: string // keyword should be executed before this keyword (should be applicable to the same type)
  post?: boolean // keyword should be executed after other keywords without post flag
  metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable
  validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed
  dependencies?: string[] // keywords that must be present in the same schema
  error?: KeywordErrorDefinition
  $dataError?: KeywordErrorDefinition
}

export interface CodeKeywordDefinition extends _KeywordDef {
  code: (cxt: KeywordCxt, ruleType?: string) => void
  trackErrors?: boolean
}

export type MacroKeywordFunc = (
  schema: any,
  parentSchema: AnySchemaObject,
  it: SchemaCxt
) => AnySchema

export type CompileKeywordFunc = (
  schema: any,
  parentSchema: AnySchemaObject,
  it: SchemaObjCxt
) => DataValidateFunction

export interface DataValidateFunction {
  (...args: Parameters<ValidateFunction>): boolean | Promise<any>
  errors?: Partial<ErrorObject>[]
}

export interface SchemaValidateFunction {
  (
    schema: any,
    data: any,
    parentSchema?: AnySchemaObject,
    dataCxt?: DataValidationCxt
  ): boolean | Promise<any>
  errors?: Partial<ErrorObject>[]
}

export interface FuncKeywordDefinition extends _KeywordDef {
  validate?: SchemaValidateFunction | DataValidateFunction
  compile?: CompileKeywordFunc
  // schema: false makes validate not to expect schema (DataValidateFunction)
  schema?: boolean // requires "validate"
  modifying?: boolean
  async?: boolean
  valid?: boolean
  errors?: boolean | "full"
}

export interface MacroKeywordDefinition extends FuncKeywordDefinition {
  macro: MacroKeywordFunc
}

export type KeywordDefinition =
  | CodeKeywordDefinition
  | FuncKeywordDefinition
  | MacroKeywordDefinition

export type AddedKeywordDefinition = KeywordDefinition & {
  type: JSONType[]
  schemaType: JSONType[]
}

export interface KeywordErrorDefinition {
  message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
  params?: Code | ((cxt: KeywordErrorCxt) => Code)
}

export type Vocabulary = (KeywordDefinition | string)[]

export interface KeywordErrorCxt {
  gen: CodeGen
  keyword: string
  data: Name
  $data?: string | false
  schema: any // TODO
  parentSchema?: AnySchemaObject
  schemaCode: Code | number | boolean
  schemaValue: Code | number | boolean
  schemaType?: JSONType[]
  errsCount?: Name
  params: KeywordCxtParams
  it: SchemaCxt
}

export type KeywordCxtParams = {[P in string]?: Code | string | number}

export type FormatValidator<T extends string | number> = (data: T) => boolean

export type FormatCompare<T extends string | number> = (data1: T, data2: T) => number | undefined

export type AsyncFormatValidator<T extends string | number> = (data: T) => Promise<boolean>

export interface FormatDefinition<T extends string | number> {
  type?: T extends string ? "string" | undefined : "number"
  validate: FormatValidator<T> | (T extends string ? string | RegExp : never)
  async?: false | undefined
  compare?: FormatCompare<T>
}

export interface AsyncFormatDefinition<T extends string | number> {
  type?: T extends string ? "string" | undefined : "number"
  validate: AsyncFormatValidator<T>
  async: true
  compare?: FormatCompare<T>
}

export type AddedFormat =
  | true
  | RegExp
  | FormatValidator<string>
  | FormatDefinition<string>
  | FormatDefinition<number>
  | AsyncFormatDefinition<string>
  | AsyncFormatDefinition<number>

export type Format = AddedFormat | string

export interface RegExpEngine {
  (pattern: string, u: string): RegExpLike
  code: string
}

export interface RegExpLike {
  test: (s: string) => boolean
}

export interface UriResolver {
  parse(uri: string): URIComponent
  resolve(base: string, path: string): string
  serialize(component: URIComponent): string
}
/* eslint-disable @typescript-eslint/no-empty-interface */
type StrictNullChecksWrapper<Name extends string, Type> = undefined extends null
  ? `strictNullChecks must be true in tsconfig to use ${Name}`
  : Type

type UnionToIntersection<U> = (U extends any ? (_: U) => void : never) extends (_: infer I) => void
  ? I
  : never

export type SomeJSONSchema = UncheckedJSONSchemaType<Known, true>

type UncheckedPartialSchema<T> = Partial<UncheckedJSONSchemaType<T, true>>

export type PartialSchema<T> = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema<T>>

type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
  ? T | undefined
  : T

interface NumberKeywords {
  minimum?: number
  maximum?: number
  exclusiveMinimum?: number
  exclusiveMaximum?: number
  multipleOf?: number
  format?: string
}

interface StringKeywords {
  minLength?: number
  maxLength?: number
  pattern?: string
  format?: string
}

type UncheckedJSONSchemaType<T, IsPartial extends boolean> = (
  | // these two unions allow arbitrary unions of types
  {
      anyOf: readonly UncheckedJSONSchemaType<T, IsPartial>[]
    }
  | {
      oneOf: readonly UncheckedJSONSchemaType<T, IsPartial>[]
    }
  // this union allows for { type: (primitive)[] } style schemas
  | ({
      type: readonly (T extends number
        ? JSONType<"number" | "integer", IsPartial>
        : T extends string
        ? JSONType<"string", IsPartial>
        : T extends boolean
        ? JSONType<"boolean", IsPartial>
        : never)[]
    } & UnionToIntersection<
      T extends number
        ? NumberKeywords
        : T extends string
        ? StringKeywords
        : T extends boolean
        ? // eslint-disable-next-line @typescript-eslint/ban-types
          {}
        : never
    >)
  // this covers "normal" types; it's last so typescript looks to it first for errors
  | ((T extends number
      ? {
          type: JSONType<"number" | "integer", IsPartial>
        } & NumberKeywords
      : T extends string
      ? {
          type: JSONType<"string", IsPartial>
        } & StringKeywords
      : T extends boolean
      ? {
          type: JSONType<"boolean", IsPartial>
        }
      : T extends readonly [any, ...any[]]
      ? {
          // JSON AnySchema for tuple
          type: JSONType<"array", IsPartial>
          items: {
            readonly [K in keyof T]-?: UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>
          } & {length: T["length"]}
          minItems: T["length"]
        } & ({maxItems: T["length"]} | {additionalItems: false})
      : T extends readonly any[]
      ? {
          type: JSONType<"array", IsPartial>
          items: UncheckedJSONSchemaType<T[0], false>
          contains?: UncheckedPartialSchema<T[0]>
          minItems?: number
          maxItems?: number
          minContains?: number
          maxContains?: number
          uniqueItems?: true
          additionalItems?: never
        }
      : T extends Record<string, any>
      ? {
          // JSON AnySchema for records and dictionaries
          // "required" is not optional because it is often forgotten
          // "properties" are optional for more concise dictionary schemas
          // "patternProperties" and can be only used with interfaces that have string index
          type: JSONType<"object", IsPartial>
          additionalProperties?: boolean | UncheckedJSONSchemaType<T[string], false>
          unevaluatedProperties?: boolean | UncheckedJSONSchemaType<T[string], false>
          properties?: IsPartial extends true
            ? Partial<UncheckedPropertiesSchema<T>>
            : UncheckedPropertiesSchema<T>
          patternProperties?: Record<string, UncheckedJSONSchemaType<T[string], false>>
          propertyNames?: Omit<UncheckedJSONSchemaType<string, false>, "type"> & {type?: "string"}
          dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema<T>}
          dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]}
          dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema<T>}
          minProperties?: number
          maxProperties?: number
        } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties
          ? {required: readonly (keyof T)[]}
          : [UncheckedRequiredMembers<T>] extends [never]
          ? {required?: readonly UncheckedRequiredMembers<T>[]}
          : {required: readonly UncheckedRequiredMembers<T>[]})
      : T extends null
      ? {
          type: JSONType<"null", IsPartial>
          nullable: true
        }
      : never) & {
      allOf?: readonly UncheckedPartialSchema<T>[]
      anyOf?: readonly UncheckedPartialSchema<T>[]
      oneOf?: readonly UncheckedPartialSchema<T>[]
      if?: UncheckedPartialSchema<T>
      then?: UncheckedPartialSchema<T>
      else?: UncheckedPartialSchema<T>
      not?: UncheckedPartialSchema<T>
    })
) & {
  [keyword: string]: any
  $id?: string
  $ref?: string
  $defs?: Record<string, UncheckedJSONSchemaType<Known, true>>
  definitions?: Record<string, UncheckedJSONSchemaType<Known, true>>
}

export type JSONSchemaType<T> = StrictNullChecksWrapper<
  "JSONSchemaType",
  UncheckedJSONSchemaType<T, false>
>

type Known =
  | {[key: string]: Known}
  | [Known, ...Known[]]
  | Known[]
  | number
  | string
  | boolean
  | null

type UncheckedPropertiesSchema<T> = {
  [K in keyof T]-?: (UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>) | {$ref: string}
}

export type PropertiesSchema<T> = StrictNullChecksWrapper<
  "PropertiesSchema",
  UncheckedPropertiesSchema<T>
>

type UncheckedRequiredMembers<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T]

export type RequiredMembers<T> = StrictNullChecksWrapper<
  "RequiredMembers",
  UncheckedRequiredMembers<T>
>

type Nullable<T> = undefined extends T
  ? {
      nullable: true
      const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const
      enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass
      default?: T | null
    }
  : {
      nullable?: false
      const?: T
      enum?: readonly T[]
      default?: T
    }
/** numeric strings */
type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"

/** string strings */
type StringType = "string" | "timestamp"

/** Generic JTD Schema without inference of the represented type */
export type SomeJTDSchemaType = (
  | // ref
  {ref: string}
  // primitives
  | {type: NumberType | StringType | "boolean"}
  // enum
  | {enum: string[]}
  // elements
  | {elements: SomeJTDSchemaType}
  // values
  | {values: SomeJTDSchemaType}
  // properties
  | {
      properties: Record<string, SomeJTDSchemaType>
      optionalProperties?: Record<string, SomeJTDSchemaType>
      additionalProperties?: boolean
    }
  | {
      properties?: Record<string, SomeJTDSchemaType>
      optionalProperties: Record<string, SomeJTDSchemaType>
      additionalProperties?: boolean
    }
  // discriminator
  | {discriminator: string; mapping: Record<string, SomeJTDSchemaType>}
  // empty
  // NOTE see the end of
  // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492
  // eslint-disable-next-line @typescript-eslint/ban-types
  | {}
) & {
  nullable?: boolean
  metadata?: Record<string, unknown>
  definitions?: Record<string, SomeJTDSchemaType>
}

/** required keys of an object, not undefined */
type RequiredKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T]

/** optional or undifined-able keys of an object */
type OptionalKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? K : never
}[keyof T]

/** type is true if T is a union type */
type IsUnion_<T, U extends T = T> = false extends (
  T extends unknown ? ([U] extends [T] ? false : true) : never
)
  ? false
  : true
type IsUnion<T> = IsUnion_<T>

/** type is true if T is identically E */
type TypeEquality<T, E> = [T] extends [E] ? ([E] extends [T] ? true : false) : false

/** type is true if T or null is identically E or null*/
type NullTypeEquality<T, E> = TypeEquality<T | null, E | null>

/** gets only the string literals of a type or null if a type isn't a string literal */
type EnumString<T> = [T] extends [never]
  ? null
  : T extends string
  ? string extends T
    ? null
    : T
  : null

/** true if type is a union of string literals */
type IsEnum<T> = null extends EnumString<T> ? false : true

/** true only if all types are array types (not tuples) */
// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays
// have an index at every number
type IsElements<T> = false extends IsUnion<T>
  ? [T] extends [readonly unknown[]]
    ? undefined extends T[0.5]
      ? false
      : true
    : false
  : false

/** true if the the type is a values type */
type IsValues<T> = false extends IsUnion<T> ? TypeEquality<keyof T, string> : false

/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */
type IsRecord<T, Union extends boolean> = Union extends IsUnion<T>
  ? null extends EnumString<keyof T>
    ? false
    : true
  : false

/** true if type represents an empty record */
type IsEmptyRecord<T> = [T] extends [Record<string, never>]
  ? [T] extends [never]
    ? false
    : true
  : false

/** actual schema */
export type JTDSchemaType<T, D extends Record<string, unknown> = Record<string, never>> = (
  | // refs - where null wasn't specified, must match exactly
  (null extends EnumString<keyof D>
      ? never
      :
          | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false})
          // nulled refs - if ref is nullable and nullable is specified, then it can
          // match either null or non-null definitions
          | (null extends T
              ? {
                  [K in keyof D]: [Exclude<T, null>] extends [Exclude<D[K], null>]
                    ? {ref: K}
                    : never
                }[keyof D] & {nullable: true}
              : never))
  // empty - empty schemas also treat nullable differently in that it's now fully ignored
  | (unknown extends T ? {nullable?: boolean} : never)
  // all other types // numbers - only accepts the type number
  | ((true extends NullTypeEquality<T, number>
      ? {type: NumberType}
      : // booleans - accepts the type boolean
      true extends NullTypeEquality<T, boolean>
      ? {type: "boolean"}
      : // strings - only accepts the type string
      true extends NullTypeEquality<T, string>
      ? {type: StringType}
      : // strings - only accepts the type Date
      true extends NullTypeEquality<T, Date>
      ? {type: "timestamp"}
      : // enums - only accepts union of string literals
      // TODO we can't actually check that everything in the union was specified
      true extends IsEnum<Exclude<T, null>>
      ? {enum: EnumString<Exclude<T, null>>[]}
      : // arrays - only accepts arrays, could be array of unions to be resolved later
      true extends IsElements<Exclude<T, null>>
      ? T extends readonly (infer E)[]
        ? {
            elements: JTDSchemaType<E, D>
          }
        : never
      : // empty properties
      true extends IsEmptyRecord<Exclude<T, null>>
      ?
          | {properties: Record<string, never>; optionalProperties?: Record<string, never>}
          | {optionalProperties: Record<string, never>}
      : // values
      true extends IsValues<Exclude<T, null>>
      ? T extends Record<string, infer V>
        ? {
            values: JTDSchemaType<V, D>
          }
        : never
      : // properties
      true extends IsRecord<Exclude<T, null>, false>
      ? ([RequiredKeys<Exclude<T, null>>] extends [never]
          ? {
              properties?: Record<string, never>
            }
          : {
              properties: {[K in RequiredKeys<T>]: JTDSchemaType<T[K], D>}
            }) &
          ([OptionalKeys<Exclude<T, null>>] extends [never]
            ? {
                optionalProperties?: Record<string, never>
              }
            : {
                optionalProperties: {
                  [K in OptionalKeys<T>]: JTDSchemaType<Exclude<T[K], undefined>, D>
                }
              }) & {
            additionalProperties?: boolean
          }
      : // discriminator
      true extends IsRecord<Exclude<T, null>, true>
      ? {
          [K in keyof Exclude<T, null>]-?: Exclude<T, null>[K] extends string
            ? {
                discriminator: K
                mapping: {
                  // TODO currently allows descriminator to be present in schema
                  [M in Exclude<T, null>[K]]: JTDSchemaType<
                    Omit<T extends Record<K, M> ? T : never, K>,
                    D
                  >
                }
              }
            : never
        }[keyof Exclude<T, null>]
      : never) &
      (null extends T
        ? {
            nullable: true
          }
        : {nullable?: false}))
) & {
  // extra properties
  metadata?: Record<string, unknown>
  // TODO these should only be allowed at the top level
  definitions?: {[K in keyof D]: JTDSchemaType<D[K], D>}
}

type JTDDataDef<S, D extends Record<string, unknown>> =
  | // ref
  (S extends {ref: string}
      ? D extends {[K in S["ref"]]: infer V}
        ? JTDDataDef<V, D>
        : never
      : // type
      S extends {type: NumberType}
      ? number
      : S extends {type: "boolean"}
      ? boolean
      : S extends {type: "string"}
      ? string
      : S extends {type: "timestamp"}
      ? string | Date
      : // enum
      S extends {enum: readonly (infer E)[]}
      ? string extends E
        ? never
        : [E] extends [string]
        ? E
        : never
      : // elements
      S extends {elements: infer E}
      ? JTDDataDef<E, D>[]
      : // properties
      S extends {
          properties: Record<string, unknown>
          optionalProperties?: Record<string, unknown>
          additionalProperties?: boolean
        }
      ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>} & {
          -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<
            S["optionalProperties"][K],
            D
          >
        } & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown)
      : S extends {
          properties?: Record<string, unknown>
          optionalProperties: Record<string, unknown>
          additionalProperties?: boolean
        }
      ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>} & {
          -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<
            S["optionalProperties"][K],
            D
          >
        } & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown)
      : // values
      S extends {values: infer V}
      ? Record<string, JTDDataDef<V, D>>
      : // discriminator
      S extends {discriminator: infer M; mapping: Record<string, unknown>}
      ? [M] extends [string]
        ? {
            [K in keyof S["mapping"]]: JTDDataDef<S["mapping"][K], D> & {[KM in M]: K}
          }[keyof S["mapping"]]
        : never
      : // empty
        unknown)
  | (S extends {nullable: true} ? null : never)

export type JTDDataType<S> = S extends {definitions: Record<string, unknown>}
  ? JTDDataDef<S, S["definitions"]>
  : JTDDataDef<S, Record<string, never>>
import type AjvCore from "../core"
import type {AnyValidateFunction, SourceCode} from "../types"
import type {SchemaEnv} from "../compile"
import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope"
import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code"

function standaloneCode(
  ajv: AjvCore,
  refsOrFunc?: {[K in string]?: string} | AnyValidateFunction
): string {
  if (!ajv.opts.code.source) {
    throw new Error("moduleCode: ajv instance must have code.source option")
  }
  const {_n} = ajv.scope.opts
  return typeof refsOrFunc == "function"
    ? funcExportCode(refsOrFunc.source)
    : refsOrFunc !== undefined
    ? multiExportsCode<string>(refsOrFunc, getValidate)
    : multiExportsCode<SchemaEnv>(ajv.schemas, (sch) =>
        sch.meta ? undefined : ajv.compile(sch.schema)
      )

  function getValidate(id: string): AnyValidateFunction {
    const v = ajv.getSchema(id)
    if (!v) throw new Error(`moduleCode: no schema with id ${id}`)
    return v
  }

  function funcExportCode(source?: SourceCode): string {
    const usedValues: UsedScopeValues = {}
    const n = source?.validateName
    const vCode = validateCode(usedValues, source)
    if (ajv.opts.code.esm) {
      // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
      return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`
    }
    return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`
  }

  function multiExportsCode<T extends SchemaEnv | string>(
    schemas: {[K in string]?: T},
    getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined
  ): string {
    const usedValues: UsedScopeValues = {}
    let code = _`"use strict";`
    for (const name in schemas) {
      const v = getValidateFunc(schemas[name] as T)
      if (v) {
        const vCode = validateCode(usedValues, v.source)
        const exportSyntax = ajv.opts.code.esm
          ? _`export const ${getEsmExportName(name)}`
          : _`exports${getProperty(name)}`
        code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}`
      }
    }
    return `${code}`
  }

  function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code {
    if (!s) throw new Error('moduleCode: function does not have "source" property')
    if (usedState(s.validateName) === UsedValueState.Completed) return nil
    setUsedState(s.validateName, UsedValueState.Started)

    const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode)
    const code = new _Code(`${scopeCode}${_n}${s.validateCode}`)
    return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code

    function refValidateCode(n: ValueScopeName): Code | undefined {
      const vRef = n.value?.ref
      if (n.prefix === "validate" && typeof vRef == "function") {
        const v = vRef as AnyValidateFunction
        return validateCode(usedValues, v.source)
      } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
        const {validate, validateName} = vRef as SchemaEnv
        if (!validateName) throw new Error("ajv internal error")
        const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
        const wrapper = _`${def} ${n} = {validate: ${validateName}};`
        if (usedState(validateName) === UsedValueState.Started) return wrapper
        const vCode = validateCode(usedValues, validate?.source)
        return _`${wrapper}${_n}${vCode}`
      }
      return undefined
    }

    function usedState(name: ValueScopeName): UsedValueState | undefined {
      return usedValues[name.prefix]?.get(name)
    }

    function setUsedState(name: ValueScopeName, state: UsedValueState): void {
      const {prefix} = name
      const names = (usedValues[prefix] = usedValues[prefix] || new Map())
      names.set(name, state)
    }
  }
}

module.exports = exports = standaloneCode
Object.defineProperty(exports, "__esModule", {value: true})

export default standaloneCode
import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core"
import standaloneCode from "."
import * as requireFromString from "require-from-string"

export default class AjvPack {
  errors?: ErrorObject[] | null // errors from the last validation
  constructor(readonly ajv: Ajv) {}

  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown> {
    return Ajv.prototype.validate.call(this, schemaKeyRef, data)
  }

  compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T> {
    return this.getStandalone(this.ajv.compile<T>(schema, meta))
  }

  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    const v = this.ajv.getSchema<T>(keyRef)
    if (!v) return undefined
    return this.getStandalone(v)
  }

  private getStandalone<T = unknown>(v: AnyValidateFunction<T>): AnyValidateFunction<T> {
    return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction<T>
  }

  addSchema(...args: Parameters<typeof Ajv.prototype.addSchema>): AjvPack {
    this.ajv.addSchema.call(this.ajv, ...args)
    return this
  }

  addKeyword(...args: Parameters<typeof Ajv.prototype.addKeyword>): AjvPack {
    this.ajv.addKeyword.call(this.ajv, ...args)
    return this
  }
}
// https://github.com/ajv-validator/ajv/issues/889
import * as equal from "fast-deep-equal"

type Equal = typeof equal & {code: string}
;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default'

export default equal as Equal
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/

export function parseJson(s: string, pos: number): unknown {
  let endPos: number | undefined
  parseJson.message = undefined
  let matches: RegExpExecArray | null
  if (pos) s = s.slice(pos)
  try {
    parseJson.position = pos + s.length
    return JSON.parse(s)
  } catch (e) {
    matches = rxParseJson.exec((e as Error).message)
    if (!matches) {
      parseJson.message = "unexpected end"
      return undefined
    }
    endPos = +matches[1]
    const c = s[endPos]
    s = s.slice(0, endPos)
    parseJson.position = pos + endPos
    try {
      return JSON.parse(s)
    } catch (e1) {
      parseJson.message = `unexpected token ${c}`
      return undefined
    }
  }
}

parseJson.message = undefined as string | undefined
parseJson.position = 0 as number
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'

export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined {
  let numStr = ""
  let c: string
  parseJsonNumber.message = undefined
  if (s[pos] === "-") {
    numStr += "-"
    pos++
  }
  if (s[pos] === "0") {
    numStr += "0"
    pos++
  } else {
    if (!parseDigits(maxDigits)) {
      errorMessage()
      return undefined
    }
  }
  if (maxDigits) {
    parseJsonNumber.position = pos
    return +numStr
  }
  if (s[pos] === ".") {
    numStr += "."
    pos++
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  if (((c = s[pos]), c === "e" || c === "E")) {
    numStr += "e"
    pos++
    if (((c = s[pos]), c === "+" || c === "-")) {
      numStr += c
      pos++
    }
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  parseJsonNumber.position = pos
  return +numStr

  function parseDigits(maxLen?: number): boolean {
    let digit = false
    while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
      digit = true
      numStr += c
      pos++
    }
    return digit
  }

  function errorMessage(): void {
    parseJsonNumber.position = pos
    parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"
  }
}

parseJsonNumber.message = undefined as string | undefined
parseJsonNumber.position = 0 as number
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'

const escapedChars: {[X in string]?: string} = {
  b: "\b",
  f: "\f",
  n: "\n",
  r: "\r",
  t: "\t",
  '"': '"',
  "/": "/",
  "\\": "\\",
}

const CODE_A: number = "a".charCodeAt(0)
const CODE_0: number = "0".charCodeAt(0)

export function parseJsonString(s: string, pos: number): string | undefined {
  let str = ""
  let c: string | undefined
  parseJsonString.message = undefined
  // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
  while (true) {
    c = s[pos++]
    if (c === '"') break
    if (c === "\\") {
      c = s[pos]
      if (c in escapedChars) {
        str += escapedChars[c]
        pos++
      } else if (c === "u") {
        pos++
        let count = 4
        let code = 0
        while (count--) {
          code <<= 4
          c = s[pos]
          // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
          if (c === undefined) {
            errorMessage("unexpected end")
            return undefined
          }
          c = c.toLowerCase()
          if (c >= "a" && c <= "f") {
            code += c.charCodeAt(0) - CODE_A + 10
          } else if (c >= "0" && c <= "9") {
            code += c.charCodeAt(0) - CODE_0
          } else {
            errorMessage(`unexpected token ${c}`)
            return undefined
          }
          pos++
        }
        str += String.fromCharCode(code)
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    } else if (c === undefined) {
      errorMessage("unexpected end")
      return undefined
    } else {
      if (c.charCodeAt(0) >= 0x20) {
        str += c
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
    }
  }
  parseJsonString.position = pos
  return str

  function errorMessage(msg: string): void {
    parseJsonString.position = pos
    parseJsonString.message = msg
  }
}

parseJsonString.message = undefined as string | undefined
parseJsonString.position = 0 as number
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'
const rxEscapable =
  // eslint-disable-next-line no-control-regex, no-misleading-character-class
  /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g

const escaped: {[K in string]?: string} = {
  "\b": "\\b",
  "\t": "\\t",
  "\n": "\\n",
  "\f": "\\f",
  "\r": "\\r",
  '"': '\\"',
  "\\": "\\\\",
}

export default function quote(s: string): string {
  rxEscapable.lastIndex = 0
  return (
    '"' +
    (rxEscapable.test(s)
      ? s.replace(rxEscapable, (a) => {
          const c = escaped[a]
          return typeof c === "string"
            ? c
            : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
        })
      : s) +
    '"'
  )
}

quote.code = 'require("ajv/dist/runtime/quote").default'
import * as re2 from "re2"

type Re2 = typeof re2 & {code: string}
;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default'

export default re2 as Re2
const DT_SEPARATOR = /t|\s/i
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

export default function validTimestamp(str: string, allowDate: boolean): boolean {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  const dt: string[] = str.split(DT_SEPARATOR)
  return (
    (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
    (allowDate && dt.length === 1 && validDate(dt[0]))
  )
}

function validDate(str: string): boolean {
  const matches: string[] | null = DATE.exec(str)
  if (!matches) return false
  const y: number = +matches[1]
  const m: number = +matches[2]
  const d: number = +matches[3]
  return (
    m >= 1 &&
    m <= 12 &&
    d >= 1 &&
    (d <= DAYS[m] ||
      // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
      (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))
  )
}

function validTime(str: string): boolean {
  const matches: string[] | null = TIME.exec(str)
  if (!matches) return false
  const hr: number = +matches[1]
  const min: number = +matches[2]
  const sec: number = +matches[3]
  const tzH: number = +(matches[4] || 0)
  const tzM: number = +(matches[5] || 0)
  return (
    (hr <= 23 && min <= 59 && sec <= 59) ||
    // leap second
    (hr - tzH === 23 && min - tzM === 59 && sec === 60)
  )
}

validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
export default function ucs2length(str: string): number {
  const len = str.length
  let length = 0
  let pos = 0
  let value: number
  while (pos < len) {
    length++
    value = str.charCodeAt(pos++)
    if (value >= 0xd800 && value <= 0xdbff && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos)
      if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate
    }
  }
  return length
}

ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'
import * as uri from "fast-uri"

type URI = typeof uri & {code: string}
;(uri as URI).code = 'require("ajv/dist/runtime/uri").default'

export default uri as URI
import type {ErrorObject} from "../types"

export default class ValidationError extends Error {
  readonly errors: Partial<ErrorObject>[]
  readonly ajv: true
  readonly validation: true

  constructor(errors: Partial<ErrorObject>[]) {
    super("validation failed")
    this.errors = errors
    this.ajv = this.validation = true
  }
}
{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
import {SchemaObject} from "../types"

type MetaSchema = (root: boolean) => SchemaObject

const shared: MetaSchema = (root) => {
  const sch: SchemaObject = {
    nullable: {type: "boolean"},
    metadata: {
      optionalProperties: {
        union: {elements: {ref: "schema"}},
      },
      additionalProperties: true,
    },
  }
  if (root) sch.definitions = {values: {ref: "schema"}}
  return sch
}

const emptyForm: MetaSchema = (root) => ({
  optionalProperties: shared(root),
})

const refForm: MetaSchema = (root) => ({
  properties: {
    ref: {type: "string"},
  },
  optionalProperties: shared(root),
})

const typeForm: MetaSchema = (root) => ({
  properties: {
    type: {
      enum: [
        "boolean",
        "timestamp",
        "string",
        "float32",
        "float64",
        "int8",
        "uint8",
        "int16",
        "uint16",
        "int32",
        "uint32",
      ],
    },
  },
  optionalProperties: shared(root),
})

const enumForm: MetaSchema = (root) => ({
  properties: {
    enum: {elements: {type: "string"}},
  },
  optionalProperties: shared(root),
})

const elementsForm: MetaSchema = (root) => ({
  properties: {
    elements: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const propertiesForm: MetaSchema = (root) => ({
  properties: {
    properties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    optionalProperties: {values: {ref: "schema"}},
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const optionalPropertiesForm: MetaSchema = (root) => ({
  properties: {
    optionalProperties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const discriminatorForm: MetaSchema = (root) => ({
  properties: {
    discriminator: {type: "string"},
    mapping: {
      values: {
        metadata: {
          union: [propertiesForm(false), optionalPropertiesForm(false)],
        },
      },
    },
  },
  optionalProperties: shared(root),
})

const valuesForm: MetaSchema = (root) => ({
  properties: {
    values: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const schema: MetaSchema = (root) => ({
  metadata: {
    union: [
      emptyForm,
      refForm,
      typeForm,
      enumForm,
      elementsForm,
      propertiesForm,
      optionalPropertiesForm,
      discriminatorForm,
      valuesForm,
    ].map((s) => s(root)),
  },
})

const jtdMetaSchema: SchemaObject = {
  definitions: {
    schema: schema(false),
  },
  ...schema(true),
}

export default jtdMetaSchema
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as unevaluated from "./meta/unevaluated.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format-annotation.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    unevaluated,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types"
import type {SchemaCxt} from "./index"
import {CodeGen, _, str, strConcat, Code, Name} from "./codegen"
import {SafeExpr} from "./codegen/code"
import {getErrorPath, Type} from "./util"
import N from "./names"

export const keywordError: KeywordErrorDefinition = {
  message: ({keyword}) => str`must pass "${keyword}" keyword validation`,
}

export const keyword$DataError: KeywordErrorDefinition = {
  message: ({keyword, schemaType}) =>
    schemaType
      ? str`"${keyword}" keyword must be ${schemaType} ($data)`
      : str`"${keyword}" keyword is invalid ($data)`,
}

export interface ErrorPaths {
  instancePath?: Code
  schemaPath?: string
  parentSchema?: boolean
}

export function reportError(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition = keywordError,
  errorPaths?: ErrorPaths,
  overrideAllErrors?: boolean
): void {
  const {it} = cxt
  const {gen, compositeRule, allErrors} = it
  const errObj = errorObjectCode(cxt, error, errorPaths)
  if (overrideAllErrors ?? (compositeRule || allErrors)) {
    addError(gen, errObj)
  } else {
    returnErrors(it, _`[${errObj}]`)
  }
}

export function reportExtraError(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition = keywordError,
  errorPaths?: ErrorPaths
): void {
  const {it} = cxt
  const {gen, compositeRule, allErrors} = it
  const errObj = errorObjectCode(cxt, error, errorPaths)
  addError(gen, errObj)
  if (!(compositeRule || allErrors)) {
    returnErrors(it, N.vErrors)
  }
}

export function resetErrorsCount(gen: CodeGen, errsCount: Name): void {
  gen.assign(N.errors, errsCount)
  gen.if(_`${N.vErrors} !== null`, () =>
    gen.if(
      errsCount,
      () => gen.assign(_`${N.vErrors}.length`, errsCount),
      () => gen.assign(N.vErrors, null)
    )
  )
}

export function extendErrors({
  gen,
  keyword,
  schemaValue,
  data,
  errsCount,
  it,
}: KeywordErrorCxt): void {
  /* istanbul ignore if */
  if (errsCount === undefined) throw new Error("ajv implementation error")
  const err = gen.name("err")
  gen.forRange("i", errsCount, N.errors, (i) => {
    gen.const(err, _`${N.vErrors}[${i}]`)
    gen.if(_`${err}.instancePath === undefined`, () =>
      gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))
    )
    gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)
    if (it.opts.verbose) {
      gen.assign(_`${err}.schema`, schemaValue)
      gen.assign(_`${err}.data`, data)
    }
  })
}

function addError(gen: CodeGen, errObj: Code): void {
  const err = gen.const("err", errObj)
  gen.if(
    _`${N.vErrors} === null`,
    () => gen.assign(N.vErrors, _`[${err}]`),
    _`${N.vErrors}.push(${err})`
  )
  gen.code(_`${N.errors}++`)
}

function returnErrors(it: SchemaCxt, errs: Code): void {
  const {gen, validateName, schemaEnv} = it
  if (schemaEnv.$async) {
    gen.throw(_`new ${it.ValidationError as Name}(${errs})`)
  } else {
    gen.assign(_`${validateName}.errors`, errs)
    gen.return(false)
  }
}

const E = {
  keyword: new Name("keyword"),
  schemaPath: new Name("schemaPath"), // also used in JTD errors
  params: new Name("params"),
  propertyName: new Name("propertyName"),
  message: new Name("message"),
  schema: new Name("schema"),
  parentSchema: new Name("parentSchema"),
}

function errorObjectCode(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition,
  errorPaths?: ErrorPaths
): Code {
  const {createErrors} = cxt.it
  if (createErrors === false) return _`{}`
  return errorObject(cxt, error, errorPaths)
}

function errorObject(
  cxt: KeywordErrorCxt,
  error: KeywordErrorDefinition,
  errorPaths: ErrorPaths = {}
): Code {
  const {gen, it} = cxt
  const keyValues: [Name, SafeExpr | string][] = [
    errorInstancePath(it, errorPaths),
    errorSchemaPath(cxt, errorPaths),
  ]
  extraErrorProps(cxt, error, keyValues)
  return gen.object(...keyValues)
}

function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {
  const instPath = instancePath
    ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`
    : errorPath
  return [N.instancePath, strConcat(N.instancePath, instPath)]
}

function errorSchemaPath(
  {keyword, it: {errSchemaPath}}: KeywordErrorCxt,
  {schemaPath, parentSchema}: ErrorPaths
): [Name, string | Code] {
  let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`
  if (schemaPath) {
    schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`
  }
  return [E.schemaPath, schPath]
}

function extraErrorProps(
  cxt: KeywordErrorCxt,
  {params, message}: KeywordErrorDefinition,
  keyValues: [Name, SafeExpr | string][]
): void {
  const {keyword, data, schemaValue, it} = cxt
  const {opts, propertyName, topSchemaRef, schemaPath} = it
  keyValues.push(
    [E.keyword, keyword],
    [E.params, typeof params == "function" ? params(cxt) : params || _`{}`]
  )
  if (opts.messages) {
    keyValues.push([E.message, typeof message == "function" ? message(cxt) : message])
  }
  if (opts.verbose) {
    keyValues.push(
      [E.schema, schemaValue],
      [E.parentSchema, _`${topSchemaRef}${schemaPath}`],
      [N.data, data]
    )
  }
  if (propertyName) keyValues.push([E.propertyName, propertyName])
}
import type {
  AnySchema,
  AnySchemaObject,
  AnyValidateFunction,
  AsyncValidateFunction,
  EvaluatedProperties,
  EvaluatedItems,
} from "../types"
import type Ajv from "../core"
import type {InstanceOptions} from "../core"
import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
import ValidationError from "../runtime/validation_error"
import N from "./names"
import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
import {schemaHasRulesButRef, unescapeFragment} from "./util"
import {validateFunctionCode} from "./validate"
import {URIComponent} from "fast-uri"
import {JSONType} from "./rules"

export type SchemaRefs = {
  [Ref in string]?: SchemaEnv | AnySchema
}

export interface SchemaCxt {
  readonly gen: CodeGen
  readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
  readonly data: Name // Name with reference to the current part of data instance
  readonly parentData: Name // should be used in keywords modifying data
  readonly parentDataProperty: Code | number // should be used in keywords modifying data
  readonly dataNames: Name[]
  readonly dataPathArr: (Code | number)[]
  readonly dataLevel: number // the level of the currently validated data,
  // it can be used to access both the property names and the data on all levels from the top.
  dataTypes: JSONType[] // data types applied to the current part of data instance
  definedProperties: Set<string> // set of properties to keep track of for required checks
  readonly topSchemaRef: Code
  readonly validateName: Name
  evaluated?: Name
  readonly ValidationError?: Name
  readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
  readonly schemaEnv: SchemaEnv
  readonly rootId: string
  baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
  readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
  readonly errSchemaPath: string // this is actual string, should not be changed to Code
  readonly errorPath: Code
  readonly propertyName?: Name
  readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
  // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
  // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
  // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
  props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
  items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
  jtdDiscriminator?: string
  jtdMetadata?: boolean
  readonly createErrors?: boolean
  readonly opts: InstanceOptions // Ajv instance option.
  readonly self: Ajv // current Ajv instance
}

export interface SchemaObjCxt extends SchemaCxt {
  readonly schema: AnySchemaObject
}
interface SchemaEnvArgs {
  readonly schema: AnySchema
  readonly schemaId?: "$id" | "id"
  readonly root?: SchemaEnv
  readonly baseId?: string
  readonly schemaPath?: string
  readonly localRefs?: LocalRefs
  readonly meta?: boolean
}

export class SchemaEnv implements SchemaEnvArgs {
  readonly schema: AnySchema
  readonly schemaId?: "$id" | "id"
  readonly root: SchemaEnv
  baseId: string // TODO possibly, it should be readonly
  schemaPath?: string
  localRefs?: LocalRefs
  readonly meta?: boolean
  readonly $async?: boolean // true if the current schema is asynchronous.
  readonly refs: SchemaRefs = {}
  readonly dynamicAnchors: {[Ref in string]?: true} = {}
  validate?: AnyValidateFunction
  validateName?: ValueScopeName
  serialize?: (data: unknown) => string
  serializeName?: ValueScopeName
  parse?: (data: string) => unknown
  parseName?: ValueScopeName

  constructor(env: SchemaEnvArgs) {
    let schema: AnySchemaObject | undefined
    if (typeof env.schema == "object") schema = env.schema
    this.schema = env.schema
    this.schemaId = env.schemaId
    this.root = env.root || this
    this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
    this.schemaPath = env.schemaPath
    this.localRefs = env.localRefs
    this.meta = env.meta
    this.$async = schema?.$async
    this.refs = {}
  }
}

// let codeSize = 0
// let nodeCount = 0

// Compiles schema in SchemaEnv
export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
  // TODO refactor - remove compilations
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  let _ValidationError
  if (sch.$async) {
    _ValidationError = gen.scopeValue("Error", {
      ref: ValidationError,
      code: _`require("ajv/dist/runtime/validation_error").default`,
    })
  }

  const validateName = gen.scopeName("validate")
  sch.validateName = validateName

  const schemaCxt: SchemaCxt = {
    gen,
    allErrors: this.opts.allErrors,
    data: N.data,
    parentData: N.parentData,
    parentDataProperty: N.parentDataProperty,
    dataNames: [N.data],
    dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
    dataLevel: 0,
    dataTypes: [],
    definedProperties: new Set<string>(),
    topSchemaRef: gen.scopeValue(
      "schema",
      this.opts.code.source === true
        ? {ref: sch.schema, code: stringify(sch.schema)}
        : {ref: sch.schema}
    ),
    validateName,
    ValidationError: _ValidationError,
    schema: sch.schema,
    schemaEnv: sch,
    rootId,
    baseId: sch.baseId || rootId,
    schemaPath: nil,
    errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
    errorPath: _`""`,
    opts: this.opts,
    self: this,
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    validateFunctionCode(schemaCxt)
    gen.optimize(this.opts.code.optimize)
    // gen.optimize(1)
    const validateCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
    // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
    if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
    // console.log("\n\n\n *** \n", sourceCode)
    const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
    const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
    this.scope.value(validateName, {ref: validate})

    validate.errors = null
    validate.schema = sch.schema
    validate.schemaEnv = sch
    if (sch.$async) (validate as AsyncValidateFunction).$async = true
    if (this.opts.code.source === true) {
      validate.source = {validateName, validateCode, scopeValues: gen._values}
    }
    if (this.opts.unevaluated) {
      const {props, items} = schemaCxt
      validate.evaluated = {
        props: props instanceof Name ? undefined : props,
        items: items instanceof Name ? undefined : items,
        dynamicProps: props instanceof Name,
        dynamicItems: items instanceof Name,
      }
      if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
    }
    sch.validate = validate
    return sch
  } catch (e) {
    delete sch.validate
    delete sch.validateName
    if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
    // console.log("\n\n\n *** \n", sourceCode, this.opts)
    throw e
  } finally {
    this._compilations.delete(sch)
  }
}

export function resolveRef(
  this: Ajv,
  root: SchemaEnv,
  baseId: string,
  ref: string
): AnySchema | SchemaEnv | undefined {
  ref = resolveUrl(this.opts.uriResolver, baseId, ref)
  const schOrFunc = root.refs[ref]
  if (schOrFunc) return schOrFunc

  let _sch = resolve.call(this, root, ref)
  if (_sch === undefined) {
    const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
    const {schemaId} = this.opts
    if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})
  }

  if (_sch === undefined) return
  return (root.refs[ref] = inlineOrCompile.call(this, _sch))
}

function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
  if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
  return sch.validate ? sch : compileSchema.call(this, sch)
}

// Index of schema compilation in the currently compiled list
export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
  for (const sch of this._compilations) {
    if (sameSchemaEnv(sch, schEnv)) return sch
  }
}

function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
}

// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(
  this: Ajv,
  root: SchemaEnv, // information about the root schema for the current schema
  ref: string // reference to resolve
): SchemaEnv | undefined {
  let sch
  while (typeof (sch = this.refs[ref]) == "string") ref = sch
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
}

// Resolve schema, its root and baseId
export function resolveSchema(
  this: Ajv,
  root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
  ref: string // reference to resolve
): SchemaEnv | undefined {
  const p = this.opts.uriResolver.parse(ref)
  const refPath = _getFullPath(this.opts.uriResolver, p)
  let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
  // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
  if (Object.keys(root.schema).length > 0 && refPath === baseId) {
    return getJsonPointer.call(this, p, root)
  }

  const id = normalizeId(refPath)
  const schOrRef = this.refs[id] || this.schemas[id]
  if (typeof schOrRef == "string") {
    const sch = resolveSchema.call(this, root, schOrRef)
    if (typeof sch?.schema !== "object") return
    return getJsonPointer.call(this, p, sch)
  }

  if (typeof schOrRef?.schema !== "object") return
  if (!schOrRef.validate) compileSchema.call(this, schOrRef)
  if (id === normalizeId(ref)) {
    const {schema} = schOrRef
    const {schemaId} = this.opts
    const schId = schema[schemaId]
    if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
    return new SchemaEnv({schema, schemaId, root, baseId})
  }
  return getJsonPointer.call(this, p, schOrRef)
}

const PREVENT_SCOPE_CHANGE = new Set([
  "properties",
  "patternProperties",
  "enum",
  "dependencies",
  "definitions",
])

function getJsonPointer(
  this: Ajv,
  parsedRef: URIComponent,
  {baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
  if (parsedRef.fragment?.[0] !== "/") return
  for (const part of parsedRef.fragment.slice(1).split("/")) {
    if (typeof schema === "boolean") return
    const partSchema = schema[unescapeFragment(part)]
    if (partSchema === undefined) return
    schema = partSchema
    // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
    const schId = typeof schema === "object" && schema[this.opts.schemaId]
    if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
      baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
    }
  }
  let env: SchemaEnv | undefined
  if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
    const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
    env = resolveSchema.call(this, root, $ref)
  }
  // even though resolution failed we need to return SchemaEnv to throw exception
  // so that compileAsync loads missing schema.
  const {schemaId} = this.opts
  env = env || new SchemaEnv({schema, schemaId, root, baseId})
  if (env.schema !== env.root.schema) return env
  return undefined
}
import {Name} from "./codegen"

const names = {
  // validation function arguments
  data: new Name("data"), // data passed to validation function
  // args passed from referencing schema
  valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
  instancePath: new Name("instancePath"),
  parentData: new Name("parentData"),
  parentDataProperty: new Name("parentDataProperty"),
  rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function
  dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
  // function scoped variables
  vErrors: new Name("vErrors"), // null or array of validation errors
  errors: new Name("errors"), // counter of validation errors
  this: new Name("this"),
  // "globals"
  self: new Name("self"),
  scope: new Name("scope"),
  // JTD serialize/parse name for JSON string and position
  json: new Name("json"),
  jsonPos: new Name("jsonPos"),
  jsonLen: new Name("jsonLen"),
  jsonPart: new Name("jsonPart"),
}

export default names
import {resolveUrl, normalizeId, getFullPath} from "./resolve"
import type {UriResolver} from "../types"

export default class MissingRefError extends Error {
  readonly missingRef: string
  readonly missingSchema: string

  constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {
    super(msg || `can't resolve reference ${ref} from id ${baseId}`)
    this.missingRef = resolveUrl(resolver, baseId, ref)
    this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))
  }
}
import type {AnySchema, AnySchemaObject, UriResolver} from "../types"
import type Ajv from "../ajv"
import type {URIComponent} from "fast-uri"
import {eachItem} from "./util"
import * as equal from "fast-deep-equal"
import * as traverse from "json-schema-traverse"

// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution
export type LocalRefs = {[Ref in string]?: AnySchemaObject}

// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
  "type",
  "format",
  "pattern",
  "maxLength",
  "minLength",
  "maxProperties",
  "minProperties",
  "maxItems",
  "minItems",
  "maximum",
  "minimum",
  "uniqueItems",
  "multipleOf",
  "required",
  "enum",
  "const",
])

export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {
  if (typeof schema == "boolean") return true
  if (limit === true) return !hasRef(schema)
  if (!limit) return false
  return countKeys(schema) <= limit
}

const REF_KEYWORDS = new Set([
  "$ref",
  "$recursiveRef",
  "$recursiveAnchor",
  "$dynamicRef",
  "$dynamicAnchor",
])

function hasRef(schema: AnySchemaObject): boolean {
  for (const key in schema) {
    if (REF_KEYWORDS.has(key)) return true
    const sch = schema[key]
    if (Array.isArray(sch) && sch.some(hasRef)) return true
    if (typeof sch == "object" && hasRef(sch)) return true
  }
  return false
}

function countKeys(schema: AnySchemaObject): number {
  let count = 0
  for (const key in schema) {
    if (key === "$ref") return Infinity
    count++
    if (SIMPLE_INLINED.has(key)) continue
    if (typeof schema[key] == "object") {
      eachItem(schema[key], (sch) => (count += countKeys(sch)))
    }
    if (count === Infinity) return Infinity
  }
  return count
}

export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string {
  if (normalize !== false) id = normalizeId(id)
  const p = resolver.parse(id)
  return _getFullPath(resolver, p)
}

export function _getFullPath(resolver: UriResolver, p: URIComponent): string {
  const serialized = resolver.serialize(p)
  return serialized.split("#")[0] + "#"
}

const TRAILING_SLASH_HASH = /#\/?$/
export function normalizeId(id: string | undefined): string {
  return id ? id.replace(TRAILING_SLASH_HASH, "") : ""
}

export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {
  id = normalizeId(id)
  return resolver.resolve(baseId, id)
}

const ANCHOR = /^[a-z_][-a-z0-9._]*$/i

export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
  if (typeof schema == "boolean") return {}
  const {schemaId, uriResolver} = this.opts
  const schId = normalizeId(schema[schemaId] || baseId)
  const baseIds: {[JsonPtr in string]?: string} = {"": schId}
  const pathPrefix = getFullPath(uriResolver, schId, false)
  const localRefs: LocalRefs = {}
  const schemaRefs: Set<string> = new Set()

  traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
    if (parentJsonPtr === undefined) return
    const fullPath = pathPrefix + jsonPtr
    let innerBaseId = baseIds[parentJsonPtr]
    if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId])
    addAnchor.call(this, sch.$anchor)
    addAnchor.call(this, sch.$dynamicAnchor)
    baseIds[jsonPtr] = innerBaseId

    function addRef(this: Ajv, ref: string): string {
      // eslint-disable-next-line @typescript-eslint/unbound-method
      const _resolve = this.opts.uriResolver.resolve
      ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)
      if (schemaRefs.has(ref)) throw ambiguos(ref)
      schemaRefs.add(ref)
      let schOrRef = this.refs[ref]
      if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
      if (typeof schOrRef == "object") {
        checkAmbiguosRef(sch, schOrRef.schema, ref)
      } else if (ref !== normalizeId(fullPath)) {
        if (ref[0] === "#") {
          checkAmbiguosRef(sch, localRefs[ref], ref)
          localRefs[ref] = sch
        } else {
          this.refs[ref] = fullPath
        }
      }
      return ref
    }

    function addAnchor(this: Ajv, anchor: unknown): void {
      if (typeof anchor == "string") {
        if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
        addRef.call(this, `#${anchor}`)
      }
    }
  })

  return localRefs

  function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
    if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
  }

  function ambiguos(ref: string): Error {
    return new Error(`reference "${ref}" resolves to more than one schema`)
  }
}
import type {AddedKeywordDefinition} from "../types"

const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const

export type JSONType = (typeof _jsonTypes)[number]

const jsonTypes: Set<string> = new Set(_jsonTypes)

export function isJSONType(x: unknown): x is JSONType {
  return typeof x == "string" && jsonTypes.has(x)
}

type ValidationTypes = {
  [K in JSONType]: boolean | RuleGroup | undefined
}

export interface ValidationRules {
  rules: RuleGroup[]
  post: RuleGroup
  all: {[Key in string]?: boolean | Rule} // rules that have to be validated
  keywords: {[Key in string]?: boolean} // all known keywords (superset of "all")
  types: ValidationTypes
}

export interface RuleGroup {
  type?: JSONType
  rules: Rule[]
}

// This interface wraps KeywordDefinition because definition can have multiple keywords
export interface Rule {
  keyword: string
  definition: AddedKeywordDefinition
}

export function getRules(): ValidationRules {
  const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = {
    number: {type: "number", rules: []},
    string: {type: "string", rules: []},
    array: {type: "array", rules: []},
    object: {type: "object", rules: []},
  }
  return {
    types: {...groups, integer: true, boolean: true, null: true},
    rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],
    post: {rules: []},
    all: {},
    keywords: {},
  }
}
import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"

// TODO refactor to use Set
export function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {
  const hash: {[K in T]?: true} = {}
  for (const item of arr) hash[item] = true
  return hash
}

export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {
  if (typeof schema == "boolean") return schema
  if (Object.keys(schema).length === 0) return true
  checkUnknownRules(it, schema)
  return !schemaHasRules(schema, it.self.RULES.all)
}

export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
  const {opts, self} = it
  if (!opts.strictSchema) return
  if (typeof schema === "boolean") return
  const rules = self.RULES.keywords
  for (const key in schema) {
    if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
  }
}

export function schemaHasRules(
  schema: AnySchema,
  rules: {[Key in string]?: boolean | Rule}
): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (rules[key]) return true
  return false
}

export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true
  return false
}

export function schemaRefOrVal(
  {topSchemaRef, schemaPath}: SchemaObjCxt,
  schema: unknown,
  keyword: string,
  $data?: string | false
): Code | number | boolean {
  if (!$data) {
    if (typeof schema == "number" || typeof schema == "boolean") return schema
    if (typeof schema == "string") return _`${schema}`
  }
  return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`
}

export function unescapeFragment(str: string): string {
  return unescapeJsonPointer(decodeURIComponent(str))
}

export function escapeFragment(str: string | number): string {
  return encodeURIComponent(escapeJsonPointer(str))
}

export function escapeJsonPointer(str: string | number): string {
  if (typeof str == "number") return `${str}`
  return str.replace(/~/g, "~0").replace(/\//g, "~1")
}

export function unescapeJsonPointer(str: string): string {
  return str.replace(/~1/g, "/").replace(/~0/g, "~")
}

export function eachItem<T>(xs: T | T[], f: (x: T) => void): void {
  if (Array.isArray(xs)) {
    for (const x of xs) f(x)
  } else {
    f(xs)
  }
}

type SomeEvaluated = EvaluatedProperties | EvaluatedItems

type MergeEvaluatedFunc<T extends SomeEvaluated> = (
  gen: CodeGen,
  from: Name | T,
  to: Name | Exclude<T, true> | undefined,
  toName?: typeof Name
) => Name | T

interface MakeMergeFuncArgs<T extends SomeEvaluated> {
  mergeNames: (gen: CodeGen, from: Name, to: Name) => void
  mergeToName: (gen: CodeGen, from: T, to: Name) => void
  mergeValues: (from: T, to: Exclude<T, true>) => T
  resultToName: (gen: CodeGen, res?: T) => Name
}

function makeMergeEvaluated<T extends SomeEvaluated>({
  mergeNames,
  mergeToName,
  mergeValues,
  resultToName,
}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {
  return (gen, from, to, toName) => {
    const res =
      to === undefined
        ? from
        : to instanceof Name
        ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
        : from instanceof Name
        ? (mergeToName(gen, to, from), from)
        : mergeValues(from, to)
    return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res
  }
}

interface MergeEvaluated {
  props: MergeEvaluatedFunc<EvaluatedProperties>
  items: MergeEvaluatedFunc<EvaluatedItems>
}

export const mergeEvaluated: MergeEvaluated = {
  props: makeMergeEvaluated({
    mergeNames: (gen, from, to) =>
      gen.if(_`${to} !== true && ${from} !== undefined`, () => {
        gen.if(
          _`${from} === true`,
          () => gen.assign(to, true),
          () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)
        )
      }),
    mergeToName: (gen, from, to) =>
      gen.if(_`${to} !== true`, () => {
        if (from === true) {
          gen.assign(to, true)
        } else {
          gen.assign(to, _`${to} || {}`)
          setEvaluated(gen, to, from)
        }
      }),
    mergeValues: (from, to) => (from === true ? true : {...from, ...to}),
    resultToName: evaluatedPropsToName,
  }),
  items: makeMergeEvaluated({
    mergeNames: (gen, from, to) =>
      gen.if(_`${to} !== true && ${from} !== undefined`, () =>
        gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)
      ),
    mergeToName: (gen, from, to) =>
      gen.if(_`${to} !== true`, () =>
        gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)
      ),
    mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
    resultToName: (gen, items) => gen.var("items", items),
  }),
}

export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {
  if (ps === true) return gen.var("props", true)
  const props = gen.var("props", _`{}`)
  if (ps !== undefined) setEvaluated(gen, props, ps)
  return props
}

export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
  Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
}

const snippets: {[S in string]?: _Code} = {}

export function useFunc(gen: CodeGen, f: {code: string}): Name {
  return gen.scopeValue("func", {
    ref: f,
    code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),
  })
}

export enum Type {
  Num,
  Str,
}

export function getErrorPath(
  dataProp: Name | string | number,
  dataPropType?: Type,
  jsPropertySyntax?: boolean
): Code | string {
  // let path
  if (dataProp instanceof Name) {
    const isNumber = dataPropType === Type.Num
    return jsPropertySyntax
      ? isNumber
        ? _`"[" + ${dataProp} + "]"`
        : _`"['" + ${dataProp} + "']"`
      : isNumber
      ? _`"/" + ${dataProp}`
      : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer
  }
  return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp)
}

export function checkStrictMode(
  it: SchemaCxt,
  msg: string,
  mode: boolean | "log" = it.opts.strictSchema
): void {
  if (!mode) return
  msg = `strict mode: ${msg}`
  if (mode === true) throw new Error(msg)
  it.self.logger.warn(msg)
}
import type {AnySchemaObject} from "../../types"
import type {SchemaObjCxt} from ".."
import type {JSONType, RuleGroup, Rule} from "../rules"

export function schemaHasRulesForType(
  {schema, self}: SchemaObjCxt,
  type: JSONType
): boolean | undefined {
  const group = self.RULES.types[type]
  return group && group !== true && shouldUseGroup(schema, group)
}

export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
  return group.rules.some((rule) => shouldUseRule(schema, rule))
}

export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
  return (
    schema[rule.keyword] !== undefined ||
    rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
  )
}
import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types"
import type {SchemaCxt} from ".."
import {reportError} from "../errors"
import {_, Name} from "../codegen"
import N from "../names"

const boolError: KeywordErrorDefinition = {
  message: "boolean schema is false",
}

export function topBoolOrEmptySchema(it: SchemaCxt): void {
  const {gen, schema, validateName} = it
  if (schema === false) {
    falseSchemaError(it, false)
  } else if (typeof schema == "object" && schema.$async === true) {
    gen.return(N.data)
  } else {
    gen.assign(_`${validateName}.errors`, null)
    gen.return(true)
  }
}

export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {
  const {gen, schema} = it
  if (schema === false) {
    gen.var(valid, false) // TODO var
    falseSchemaError(it)
  } else {
    gen.var(valid, true) // TODO var
  }
}

function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {
  const {gen, data} = it
  // TODO maybe some other interface should be used for non-keyword validation errors...
  const cxt: KeywordErrorCxt = {
    gen,
    keyword: "false schema",
    data,
    schema: false,
    schemaCode: false,
    schemaValue: false,
    params: {},
    it,
  }
  reportError(cxt, boolError, undefined, overrideAllErrors)
}
import type {
  KeywordErrorDefinition,
  KeywordErrorCxt,
  ErrorObject,
  AnySchemaObject,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {isJSONType, JSONType} from "../rules"
import {schemaHasRulesForType} from "./applicability"
import {reportError} from "../errors"
import {_, nil, and, not, operators, Code, Name} from "../codegen"
import {toHash, schemaRefOrVal} from "../util"

export enum DataType {
  Correct,
  Wrong,
}

export function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
  const types = getJSONTypes(schema.type)
  const hasNull = types.includes("null")
  if (hasNull) {
    if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
  } else {
    if (!types.length && schema.nullable !== undefined) {
      throw new Error('"nullable" cannot be used without "type"')
    }
    if (schema.nullable === true) types.push("null")
  }
  return types
}

// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
export function getJSONTypes(ts: unknown | unknown[]): JSONType[] {
  const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []
  if (types.every(isJSONType)) return types
  throw new Error("type must be JSONType or JSONType[]: " + types.join(","))
}

export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
  const {gen, data, opts} = it
  const coerceTo = coerceToTypes(types, opts.coerceTypes)
  const checkTypes =
    types.length > 0 &&
    !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
  if (checkTypes) {
    const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
    gen.if(wrongType, () => {
      if (coerceTo.length) coerceData(it, types, coerceTo)
      else reportTypeError(it)
    })
  }
  return checkTypes
}

const COERCIBLE: Set<JSONType> = new Set(["string", "number", "integer", "boolean", "null"])
function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] {
  return coerceTypes
    ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
    : []
}

function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
  const {gen, data, opts} = it
  const dataType = gen.let("dataType", _`typeof ${data}`)
  const coerced = gen.let("coerced", _`undefined`)
  if (opts.coerceTypes === "array") {
    gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
      gen
        .assign(data, _`${data}[0]`)
        .assign(dataType, _`typeof ${data}`)
        .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
    )
  }
  gen.if(_`${coerced} !== undefined`)
  for (const t of coerceTo) {
    if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
      coerceSpecificType(t)
    }
  }
  gen.else()
  reportTypeError(it)
  gen.endIf()

  gen.if(_`${coerced} !== undefined`, () => {
    gen.assign(data, coerced)
    assignParentData(it, coerced)
  })

  function coerceSpecificType(t: string): void {
    switch (t) {
      case "string":
        gen
          .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
          .assign(coerced, _`"" + ${data}`)
          .elseIf(_`${data} === null`)
          .assign(coerced, _`""`)
        return
      case "number":
        gen
          .elseIf(
            _`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`
          )
          .assign(coerced, _`+${data}`)
        return
      case "integer":
        gen
          .elseIf(
            _`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
          )
          .assign(coerced, _`+${data}`)
        return
      case "boolean":
        gen
          .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
          .assign(coerced, false)
          .elseIf(_`${data} === "true" || ${data} === 1`)
          .assign(coerced, true)
        return
      case "null":
        gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
        gen.assign(coerced, null)
        return

      case "array":
        gen
          .elseIf(
            _`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`
          )
          .assign(coerced, _`[${data}]`)
    }
  }
}

function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
  // TODO use gen.property
  gen.if(_`${parentData} !== undefined`, () =>
    gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
  )
}

export function checkDataType(
  dataType: JSONType,
  data: Name,
  strictNums?: boolean | "log",
  correct = DataType.Correct
): Code {
  const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
  let cond: Code
  switch (dataType) {
    case "null":
      return _`${data} ${EQ} null`
    case "array":
      cond = _`Array.isArray(${data})`
      break
    case "object":
      cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
      break
    case "integer":
      cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
      break
    case "number":
      cond = numCond()
      break
    default:
      return _`typeof ${data} ${EQ} ${dataType}`
  }
  return correct === DataType.Correct ? cond : not(cond)

  function numCond(_cond: Code = nil): Code {
    return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
  }
}

export function checkDataTypes(
  dataTypes: JSONType[],
  data: Name,
  strictNums?: boolean | "log",
  correct?: DataType
): Code {
  if (dataTypes.length === 1) {
    return checkDataType(dataTypes[0], data, strictNums, correct)
  }
  let cond: Code
  const types = toHash(dataTypes)
  if (types.array && types.object) {
    const notObj = _`typeof ${data} != "object"`
    cond = types.null ? notObj : _`!${data} || ${notObj}`
    delete types.null
    delete types.array
    delete types.object
  } else {
    cond = nil
  }
  if (types.number) delete types.integer
  for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))
  return cond
}

export type TypeError = ErrorObject<"type", {type: string}>

const typeError: KeywordErrorDefinition = {
  message: ({schema}) => `must be ${schema}`,
  params: ({schema, schemaValue}) =>
    typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,
}

export function reportTypeError(it: SchemaObjCxt): void {
  const cxt = getTypeErrorContext(it)
  reportError(cxt, typeError)
}

function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
  const {gen, data, schema} = it
  const schemaCode = schemaRefOrVal(it, schema, "type")
  return {
    gen,
    keyword: "type",
    data,
    schema: schema.type,
    schemaCode,
    schemaValue: schemaCode,
    parentSchema: schema,
    params: {},
    it,
  }
}
import type {SchemaObjCxt} from ".."
import {_, getProperty, stringify} from "../codegen"
import {checkStrictMode} from "../util"

export function assignDefaults(it: SchemaObjCxt, ty?: string): void {
  const {properties, items} = it.schema
  if (ty === "object" && properties) {
    for (const key in properties) {
      assignDefault(it, key, properties[key].default)
    }
  } else if (ty === "array" && Array.isArray(items)) {
    items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
  }
}

function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
  const {gen, compositeRule, data, opts} = it
  if (defaultValue === undefined) return
  const childData = _`${data}${getProperty(prop)}`
  if (compositeRule) {
    checkStrictMode(it, `default is ignored for: ${childData}`)
    return
  }

  let condition = _`${childData} === undefined`
  if (opts.useDefaults === "empty") {
    condition = _`${condition} || ${childData} === null || ${childData} === ""`
  }
  // `${childData} === undefined` +
  // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
  gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
}
import type {
  AddedKeywordDefinition,
  AnySchema,
  AnySchemaObject,
  KeywordErrorCxt,
  KeywordCxtParams,
} from "../../types"
import type {SchemaCxt, SchemaObjCxt} from ".."
import type {InstanceOptions} from "../../core"
import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
import {shouldUseGroup, shouldUseRule} from "./applicability"
import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
import {assignDefaults} from "./defaults"
import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import {resolveUrl} from "../resolve"
import {
  schemaRefOrVal,
  schemaHasRulesButRef,
  checkUnknownRules,
  checkStrictMode,
  unescapeJsonPointer,
  mergeEvaluated,
} from "../util"
import type {JSONType, Rule, RuleGroup} from "../rules"
import {
  ErrorPaths,
  reportError,
  reportExtraError,
  resetErrorsCount,
  keyword$DataError,
} from "../errors"

// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
export function validateFunctionCode(it: SchemaCxt): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      topSchemaObjCode(it)
      return
    }
  }
  validateFunction(it, () => topBoolOrEmptySchema(it))
}

function validateFunction(
  {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
  body: Block
): void {
  if (opts.code.es5) {
    gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
      gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
      destructureValCxtES5(gen, opts)
      gen.code(body)
    })
  } else {
    gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
      gen.code(funcSourceUrl(schema, opts)).code(body)
    )
  }
}

function destructureValCxt(opts: InstanceOptions): Code {
  return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
    N.data
  }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
}

function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
  gen.if(
    N.valCxt,
    () => {
      gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
      gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
      gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
      gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
    },
    () => {
      gen.var(N.instancePath, _`""`)
      gen.var(N.parentData, _`undefined`)
      gen.var(N.parentDataProperty, _`undefined`)
      gen.var(N.rootData, N.data)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
    }
  )
}

function topSchemaObjCode(it: SchemaObjCxt): void {
  const {schema, opts, gen} = it
  validateFunction(it, () => {
    if (opts.$comment && schema.$comment) commentKeyword(it)
    checkNoDefault(it)
    gen.let(N.vErrors, null)
    gen.let(N.errors, 0)
    if (opts.unevaluated) resetEvaluated(it)
    typeAndKeywords(it)
    returnResults(it)
  })
  return
}

function resetEvaluated(it: SchemaObjCxt): void {
  // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
  const {gen, validateName} = it
  it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
  gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
  gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
}

function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
  const schId = typeof schema == "object" && schema[opts.schemaId]
  return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
}

// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it: SchemaCxt, valid: Name): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      subSchemaObjCode(it, valid)
      return
    }
  }
  boolOrEmptySchema(it, valid)
}

function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (self.RULES.all[key]) return true
  return false
}

function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
  return typeof it.schema != "boolean"
}

function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
  const {schema, gen, opts} = it
  if (opts.$comment && schema.$comment) commentKeyword(it)
  updateContext(it)
  checkAsyncSchema(it)
  const errsCount = gen.const("_errs", N.errors)
  typeAndKeywords(it, errsCount)
  // TODO var
  gen.var(valid, _`${errsCount} === ${N.errors}`)
}

function checkKeywords(it: SchemaObjCxt): void {
  checkUnknownRules(it)
  checkRefsAndKeywords(it)
}

function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
  if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
  const types = getSchemaTypes(it.schema)
  const checkedTypes = coerceAndCheckDataType(it, types)
  schemaKeywords(it, types, !checkedTypes, errsCount)
}

function checkRefsAndKeywords(it: SchemaObjCxt): void {
  const {schema, errSchemaPath, opts, self} = it
  if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
    self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
  }
}

function checkNoDefault(it: SchemaObjCxt): void {
  const {schema, opts} = it
  if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
    checkStrictMode(it, "default is ignored in the schema root")
  }
}

function updateContext(it: SchemaObjCxt): void {
  const schId = it.schema[it.opts.schemaId]
  if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
}

function checkAsyncSchema(it: SchemaObjCxt): void {
  if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
}

function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
  const msg = schema.$comment
  if (opts.$comment === true) {
    gen.code(_`${N.self}.logger.log(${msg})`)
  } else if (typeof opts.$comment == "function") {
    const schemaPath = str`${errSchemaPath}/$comment`
    const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
    gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
  }
}

function returnResults(it: SchemaCxt): void {
  const {gen, schemaEnv, validateName, ValidationError, opts} = it
  if (schemaEnv.$async) {
    // TODO assign unevaluated
    gen.if(
      _`${N.errors} === 0`,
      () => gen.return(N.data),
      () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
    )
  } else {
    gen.assign(_`${validateName}.errors`, N.vErrors)
    if (opts.unevaluated) assignEvaluated(it)
    gen.return(_`${N.errors} === 0`)
  }
}

function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
  if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
  if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
}

function schemaKeywords(
  it: SchemaObjCxt,
  types: JSONType[],
  typeErrors: boolean,
  errsCount?: Name
): void {
  const {gen, schema, data, allErrors, opts, self} = it
  const {RULES} = self
  if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
    gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
    return
  }
  if (!opts.jtd) checkStrictTypes(it, types)
  gen.block(() => {
    for (const group of RULES.rules) groupKeywords(group)
    groupKeywords(RULES.post)
  })

  function groupKeywords(group: RuleGroup): void {
    if (!shouldUseGroup(schema, group)) return
    if (group.type) {
      gen.if(checkDataType(group.type, data, opts.strictNumbers))
      iterateKeywords(it, group)
      if (types.length === 1 && types[0] === group.type && typeErrors) {
        gen.else()
        reportTypeError(it)
      }
      gen.endIf()
    } else {
      iterateKeywords(it, group)
    }
    // TODO make it "ok" call?
    if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
  }
}

function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
  const {
    gen,
    schema,
    opts: {useDefaults},
  } = it
  if (useDefaults) assignDefaults(it, group.type)
  gen.block(() => {
    for (const rule of group.rules) {
      if (shouldUseRule(schema, rule)) {
        keywordCode(it, rule.keyword, rule.definition, group.type)
      }
    }
  })
}

function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (it.schemaEnv.meta || !it.opts.strictTypes) return
  checkContextTypes(it, types)
  if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
  checkKeywordTypes(it, it.dataTypes)
}

function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (!types.length) return
  if (!it.dataTypes.length) {
    it.dataTypes = types
    return
  }
  types.forEach((t) => {
    if (!includesType(it.dataTypes, t)) {
      strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
    }
  })
  narrowSchemaTypes(it, types)
}

function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
    strictTypesError(it, "use allowUnionTypes to allow union type keyword")
  }
}

function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  const rules = it.self.RULES.all
  for (const keyword in rules) {
    const rule = rules[keyword]
    if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
      const {type} = rule.definition
      if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
        strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
      }
    }
  }
}

function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
  return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
}

function includesType(ts: JSONType[], t: JSONType): boolean {
  return ts.includes(t) || (t === "integer" && ts.includes("number"))
}

function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
  const ts: JSONType[] = []
  for (const t of it.dataTypes) {
    if (includesType(withTypes, t)) ts.push(t)
    else if (withTypes.includes("integer") && t === "number") ts.push("integer")
  }
  it.dataTypes = ts
}

function strictTypesError(it: SchemaObjCxt, msg: string): void {
  const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
  msg += ` at "${schemaPath}" (strictTypes)`
  checkStrictMode(it, msg, it.opts.strictTypes)
}

export class KeywordCxt implements KeywordErrorCxt {
  readonly gen: CodeGen
  readonly allErrors?: boolean
  readonly keyword: string
  readonly data: Name // Name referencing the current level of the data instance
  readonly $data?: string | false
  schema: any // keyword value in the schema
  readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
  readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
  readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
  readonly parentSchema: AnySchemaObject
  readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
  // requires option trackErrors in keyword definition
  params: KeywordCxtParams // object to pass parameters to error messages from keyword code
  readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
  readonly def: AddedKeywordDefinition

  constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
    validateKeywordUsage(it, def, keyword)
    this.gen = it.gen
    this.allErrors = it.allErrors
    this.keyword = keyword
    this.data = it.data
    this.schema = it.schema[keyword]
    this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
    this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
    this.schemaType = def.schemaType
    this.parentSchema = it.schema
    this.params = {}
    this.it = it
    this.def = def

    if (this.$data) {
      this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
    } else {
      this.schemaCode = this.schemaValue
      if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
        throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
      }
    }

    if ("code" in def ? def.trackErrors : def.errors !== false) {
      this.errsCount = it.gen.const("_errs", N.errors)
    }
  }

  result(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.failResult(not(condition), successAction, failAction)
  }

  failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.gen.if(condition)
    if (failAction) failAction()
    else this.error()
    if (successAction) {
      this.gen.else()
      successAction()
      if (this.allErrors) this.gen.endIf()
    } else {
      if (this.allErrors) this.gen.endIf()
      else this.gen.else()
    }
  }

  pass(condition: Code, failAction?: () => void): void {
    this.failResult(not(condition), undefined, failAction)
  }

  fail(condition?: Code): void {
    if (condition === undefined) {
      this.error()
      if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
      return
    }
    this.gen.if(condition)
    this.error()
    if (this.allErrors) this.gen.endIf()
    else this.gen.else()
  }

  fail$data(condition: Code): void {
    if (!this.$data) return this.fail(condition)
    const {schemaCode} = this
    this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
  }

  error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
    if (errorParams) {
      this.setParams(errorParams)
      this._error(append, errorPaths)
      this.setParams({})
      return
    }
    this._error(append, errorPaths)
  }

  private _error(append?: boolean, errorPaths?: ErrorPaths): void {
    ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
  }

  $dataError(): void {
    reportError(this, this.def.$dataError || keyword$DataError)
  }

  reset(): void {
    if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
    resetErrorsCount(this.gen, this.errsCount)
  }

  ok(cond: Code | boolean): void {
    if (!this.allErrors) this.gen.if(cond)
  }

  setParams(obj: KeywordCxtParams, assign?: true): void {
    if (assign) Object.assign(this.params, obj)
    else this.params = obj
  }

  block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
    this.gen.block(() => {
      this.check$data(valid, $dataValid)
      codeBlock()
    })
  }

  check$data(valid: Name = nil, $dataValid: Code = nil): void {
    if (!this.$data) return
    const {gen, schemaCode, schemaType, def} = this
    gen.if(or(_`${schemaCode} === undefined`, $dataValid))
    if (valid !== nil) gen.assign(valid, true)
    if (schemaType.length || def.validateSchema) {
      gen.elseIf(this.invalid$data())
      this.$dataError()
      if (valid !== nil) gen.assign(valid, false)
    }
    gen.else()
  }

  invalid$data(): Code {
    const {gen, schemaCode, schemaType, def, it} = this
    return or(wrong$DataType(), invalid$DataSchema())

    function wrong$DataType(): Code {
      if (schemaType.length) {
        /* istanbul ignore if */
        if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
        const st = Array.isArray(schemaType) ? schemaType : [schemaType]
        return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
      }
      return nil
    }

    function invalid$DataSchema(): Code {
      if (def.validateSchema) {
        const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
        return _`!${validateSchemaRef}(${schemaCode})`
      }
      return nil
    }
  }

  subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
    const subschema = getSubschema(this.it, appl)
    extendSubschemaData(subschema, this.it, appl)
    extendSubschemaMode(subschema, appl)
    const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
    subschemaCode(nextContext, valid)
    return nextContext
  }

  mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
    const {it, gen} = this
    if (!it.opts.unevaluated) return
    if (it.props !== true && schemaCxt.props !== undefined) {
      it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
    }
    if (it.items !== true && schemaCxt.items !== undefined) {
      it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
    }
  }

  mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
    const {it, gen} = this
    if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
      gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
      return true
    }
  }
}

function keywordCode(
  it: SchemaObjCxt,
  keyword: string,
  def: AddedKeywordDefinition,
  ruleType?: JSONType
): void {
  const cxt = new KeywordCxt(it, def, keyword)
  if ("code" in def) {
    def.code(cxt, ruleType)
  } else if (cxt.$data && def.validate) {
    funcKeywordCode(cxt, def)
  } else if ("macro" in def) {
    macroKeywordCode(cxt, def)
  } else if (def.compile || def.validate) {
    funcKeywordCode(cxt, def)
  }
}

const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
export function getData(
  $data: string,
  {dataLevel, dataNames, dataPathArr}: SchemaCxt
): Code | number {
  let jsonPointer
  let data: Code
  if ($data === "") return N.rootData
  if ($data[0] === "/") {
    if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
    jsonPointer = $data
    data = N.rootData
  } else {
    const matches = RELATIVE_JSON_POINTER.exec($data)
    if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
    const up: number = +matches[1]
    jsonPointer = matches[2]
    if (jsonPointer === "#") {
      if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
      return dataPathArr[dataLevel - up]
    }
    if (up > dataLevel) throw new Error(errorMsg("data", up))
    data = dataNames[dataLevel - up]
    if (!jsonPointer) return data
  }

  let expr = data
  const segments = jsonPointer.split("/")
  for (const segment of segments) {
    if (segment) {
      data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
      expr = _`${expr} && ${data}`
    }
  }
  return expr

  function errorMsg(pointerType: string, up: number): string {
    return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
  }
}
import type {KeywordCxt} from "."
import type {
  AnySchema,
  SchemaValidateFunction,
  AnyValidateFunction,
  AddedKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import type {JSONType} from "../rules"
import {callValidateCode} from "../../vocabularies/code"
import {extendErrors} from "../errors"

type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction

export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, it} = cxt
  const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
  const schemaRef = useKeyword(gen, keyword, macroSchema)
  if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)

  const valid = gen.name("valid")
  cxt.subschema(
    {
      schema: macroSchema,
      schemaPath: nil,
      errSchemaPath: `${it.errSchemaPath}/${keyword}`,
      topSchemaRef: schemaRef,
      compositeRule: true,
    },
    valid
  )
  cxt.pass(valid, () => cxt.error(true))
}

export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, $data, it} = cxt
  checkAsyncKeyword(it, def)
  const validate =
    !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
  const validateRef = useKeyword(gen, keyword, validate)
  const valid = gen.let("valid")
  cxt.block$data(valid, validateKeyword)
  cxt.ok(def.valid ?? valid)

  function validateKeyword(): void {
    if (def.errors === false) {
      assignValid()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => cxt.error())
    } else {
      const ruleErrs = def.async ? validateAsync() : validateSync()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => addErrs(cxt, ruleErrs))
    }
  }

  function validateAsync(): Name {
    const ruleErrs = gen.let("ruleErrs", null)
    gen.try(
      () => assignValid(_`await `),
      (e) =>
        gen.assign(valid, false).if(
          _`${e} instanceof ${it.ValidationError as Name}`,
          () => gen.assign(ruleErrs, _`${e}.errors`),
          () => gen.throw(e)
        )
    )
    return ruleErrs
  }

  function validateSync(): Code {
    const validateErrs = _`${validateRef}.errors`
    gen.assign(validateErrs, null)
    assignValid(nil)
    return validateErrs
  }

  function assignValid(_await: Code = def.async ? _`await ` : nil): void {
    const passCxt = it.opts.passContext ? N.this : N.self
    const passSchema = !(("compile" in def && !$data) || def.schema === false)
    gen.assign(
      valid,
      _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
      def.modifying
    )
  }

  function reportErrs(errors: () => void): void {
    gen.if(not(def.valid ?? valid), errors)
  }
}

function modifyData(cxt: KeywordCxt): void {
  const {gen, data, it} = cxt
  gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))
}

function addErrs(cxt: KeywordCxt, errs: Code): void {
  const {gen} = cxt
  gen.if(
    _`Array.isArray(${errs})`,
    () => {
      gen
        .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
        .assign(N.errors, _`${N.vErrors}.length`)
      extendErrors(cxt)
    },
    () => cxt.error()
  )
}

function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
  if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
}

function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
  if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
  return gen.scopeValue(
    "keyword",
    typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
  )
}

export function validSchemaType(
  schema: unknown,
  schemaType: JSONType[],
  allowUndefined = false
): boolean {
  // TODO add tests
  return (
    !schemaType.length ||
    schemaType.some((st) =>
      st === "array"
        ? Array.isArray(schema)
        : st === "object"
        ? schema && typeof schema == "object" && !Array.isArray(schema)
        : typeof schema == st || (allowUndefined && typeof schema == "undefined")
    )
  )
}

export function validateKeywordUsage(
  {schema, opts, self, errSchemaPath}: SchemaObjCxt,
  def: AddedKeywordDefinition,
  keyword: string
): void {
  /* istanbul ignore if */
  if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
    throw new Error("ajv implementation error")
  }

  const deps = def.dependencies
  if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
    throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
  }

  if (def.validateSchema) {
    const valid = def.validateSchema(schema[keyword])
    if (!valid) {
      const msg =
        `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
        self.errorsText(def.validateSchema.errors)
      if (opts.validateSchema === "log") self.logger.error(msg)
      else throw new Error(msg)
    }
  }
}
import type {AnySchema} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, str, getProperty, Code, Name} from "../codegen"
import {escapeFragment, getErrorPath, Type} from "../util"
import type {JSONType} from "../rules"

export interface SubschemaContext {
  // TODO use Optional? align with SchemCxt property types
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef?: Code
  errorPath?: Code
  dataLevel?: number
  dataTypes?: JSONType[]
  data?: Name
  parentData?: Name
  parentDataProperty?: Code | number
  dataNames?: Name[]
  dataPathArr?: (Code | number)[]
  propertyName?: Name
  jtdDiscriminator?: string
  jtdMetadata?: boolean
  compositeRule?: true
  createErrors?: boolean
  allErrors?: boolean
}

export type SubschemaArgs = Partial<{
  keyword: string
  schemaProp: string | number
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef: Code
  data: Name | Code
  dataProp: Code | string | number
  dataTypes: JSONType[]
  definedProperties: Set<string>
  propertyName: Name
  dataPropType: Type
  jtdDiscriminator: string
  jtdMetadata: boolean
  compositeRule: true
  createErrors: boolean
  allErrors: boolean
}>

export function getSubschema(
  it: SchemaObjCxt,
  {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
): SubschemaContext {
  if (keyword !== undefined && schema !== undefined) {
    throw new Error('both "keyword" and "schema" passed, only one allowed')
  }

  if (keyword !== undefined) {
    const sch = it.schema[keyword]
    return schemaProp === undefined
      ? {
          schema: sch,
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        }
      : {
          schema: sch[schemaProp],
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
        }
  }

  if (schema !== undefined) {
    if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
      throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
    }
    return {
      schema,
      schemaPath,
      topSchemaRef,
      errSchemaPath,
    }
  }

  throw new Error('either "keyword" or "schema" must be passed')
}

export function extendSubschemaData(
  subschema: SubschemaContext,
  it: SchemaObjCxt,
  {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
  if (data !== undefined && dataProp !== undefined) {
    throw new Error('both "data" and "dataProp" passed, only one allowed')
  }

  const {gen} = it

  if (dataProp !== undefined) {
    const {errorPath, dataPathArr, opts} = it
    const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
    dataContextProps(nextData)
    subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
    subschema.parentDataProperty = _`${dataProp}`
    subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
  }

  if (data !== undefined) {
    const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
    dataContextProps(nextData)
    if (propertyName !== undefined) subschema.propertyName = propertyName
    // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
  }

  if (dataTypes) subschema.dataTypes = dataTypes

  function dataContextProps(_nextData: Name): void {
    subschema.data = _nextData
    subschema.dataLevel = it.dataLevel + 1
    subschema.dataTypes = []
    it.definedProperties = new Set<string>()
    subschema.parentData = it.data
    subschema.dataNames = [...it.dataNames, _nextData]
  }
}

export function extendSubschemaMode(
  subschema: SubschemaContext,
  {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
): void {
  if (compositeRule !== undefined) subschema.compositeRule = compositeRule
  if (createErrors !== undefined) subschema.createErrors = createErrors
  if (allErrors !== undefined) subschema.allErrors = allErrors
  subschema.jtdDiscriminator = jtdDiscriminator // not inherited
  subschema.jtdMetadata = jtdMetadata // not inherited
}
import type Ajv from "../../core"
import type {SchemaObject} from "../../types"
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
import {SchemaEnv, getCompilingSchema} from ".."
import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen"
import MissingRefError from "../ref_error"
import N from "../names"
import {hasPropFunc} from "../../vocabularies/code"
import {hasRef} from "../../vocabularies/jtd/ref"
import {intRange, IntType} from "../../vocabularies/jtd/type"
import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson"
import {useFunc} from "../util"
import validTimestamp from "../../runtime/timestamp"

type GenParse = (cxt: ParseCxt) => void

const genParse: {[F in JTDForm]: GenParse} = {
  elements: parseElements,
  values: parseValues,
  discriminator: parseDiscriminator,
  properties: parseProperties,
  optionalProperties: parseProperties,
  enum: parseEnum,
  type: parseType,
  ref: parseRef,
}

interface ParseCxt {
  readonly gen: CodeGen
  readonly self: Ajv // current Ajv instance
  readonly schemaEnv: SchemaEnv
  readonly definitions: SchemaObjectMap
  schema: SchemaObject
  data: Code
  parseName: Name
  char: Name
}

export default function compileParser(
  this: Ajv,
  sch: SchemaEnv,
  definitions: SchemaObjectMap
): SchemaEnv {
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  const parseName = gen.scopeName("parse")
  const cxt: ParseCxt = {
    self: this,
    gen,
    schema: sch.schema as SchemaObject,
    schemaEnv: sch,
    definitions,
    data: N.data,
    parseName,
    char: gen.name("c"),
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    sch.parseName = parseName
    parserFunction(cxt)
    gen.optimize(this.opts.code.optimize)
    const parseFuncCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
    const makeParse = new Function(`${N.scope}`, sourceCode)
    const parse: (json: string) => unknown = makeParse(this.scope.get())
    this.scope.value(parseName, {ref: parse})
    sch.parse = parse
  } catch (e) {
    if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
    delete sch.parse
    delete sch.parseName
    throw e
  } finally {
    this._compilations.delete(sch)
  }
  return sch
}

const undef = _`undefined`

function parserFunction(cxt: ParseCxt): void {
  const {gen, parseName, char} = cxt
  gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => {
    gen.let(N.data)
    gen.let(char)
    gen.assign(_`${parseName}.message`, undef)
    gen.assign(_`${parseName}.position`, undef)
    gen.assign(N.jsonPos, _`${N.jsonPos} || 0`)
    gen.const(N.jsonLen, _`${N.json}.length`)
    parseCode(cxt)
    skipWhitespace(cxt)
    gen.if(N.jsonPart, () => {
      gen.assign(_`${parseName}.position`, N.jsonPos)
      gen.return(N.data)
    })
    gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data))
    jsonSyntaxError(cxt)
  })
}

function parseCode(cxt: ParseCxt): void {
  let form: JTDForm | undefined
  for (const key of jtdForms) {
    if (key in cxt.schema) {
      form = key
      break
    }
  }
  if (form) parseNullable(cxt, genParse[form])
  else parseEmpty(cxt)
}

const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError))

function parseNullable(cxt: ParseCxt, parseForm: GenParse): void {
  const {gen, schema, data} = cxt
  if (!schema.nullable) return parseForm(cxt)
  tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null))
}

function parseElements(cxt: ParseCxt): void {
  const {gen, schema, data} = cxt
  parseToken(cxt, "[")
  const ix = gen.let("i", 0)
  gen.assign(data, _`[]`)
  parseItems(cxt, "]", () => {
    const el = gen.let("el")
    parseCode({...cxt, schema: schema.elements, data: el})
    gen.assign(_`${data}[${ix}++]`, el)
  })
}

function parseValues(cxt: ParseCxt): void {
  const {gen, schema, data} = cxt
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values))
}

function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
  tryParseItems(cxt, endToken, block)
  parseToken(cxt, endToken)
}

function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
  const {gen} = cxt
  gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
    block()
    tryParseToken(cxt, ",", () => gen.break(), hasItem)
  })

  function hasItem(): void {
    tryParseToken(cxt, endToken, () => {}, jsonSyntaxError)
  }
}

function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void {
  const {gen} = cxt
  const key = gen.let("key")
  parseString({...cxt, data: key})
  parseToken(cxt, ":")
  parsePropertyValue(cxt, key, schema)
}

function parseDiscriminator(cxt: ParseCxt): void {
  const {gen, data, schema} = cxt
  const {discriminator, mapping} = schema
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  const startPos = gen.const("pos", N.jsonPos)
  const value = gen.let("value")
  const tag = gen.let("tag")
  tryParseItems(cxt, "}", () => {
    const key = gen.let("key")
    parseString({...cxt, data: key})
    parseToken(cxt, ":")
    gen.if(
      _`${key} === ${discriminator}`,
      () => {
        parseString({...cxt, data: tag})
        gen.assign(_`${data}[${key}]`, tag)
        gen.break()
      },
      () => parseEmpty({...cxt, data: value}) // can be discarded/skipped
    )
  })
  gen.assign(N.jsonPos, startPos)
  gen.if(_`${tag} === undefined`)
  parsingError(cxt, str`discriminator tag not found`)
  for (const tagValue in mapping) {
    gen.elseIf(_`${tag} === ${tagValue}`)
    parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator)
  }
  gen.else()
  parsingError(cxt, str`discriminator value not in schema`)
  gen.endIf()
}

function parseProperties(cxt: ParseCxt): void {
  const {gen, data} = cxt
  parseToken(cxt, "{")
  gen.assign(data, _`{}`)
  parseSchemaProperties(cxt)
}

function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void {
  const {gen, schema, data} = cxt
  const {properties, optionalProperties, additionalProperties} = schema
  parseItems(cxt, "}", () => {
    const key = gen.let("key")
    parseString({...cxt, data: key})
    parseToken(cxt, ":")
    gen.if(false)
    parseDefinedProperty(cxt, key, properties)
    parseDefinedProperty(cxt, key, optionalProperties)
    if (discriminator) {
      gen.elseIf(_`${key} === ${discriminator}`)
      const tag = gen.let("tag")
      parseString({...cxt, data: tag}) // can be discarded, it is already assigned
    }
    gen.else()
    if (additionalProperties) {
      parseEmpty({...cxt, data: _`${data}[${key}]`})
    } else {
      parsingError(cxt, str`property ${key} not allowed`)
    }
    gen.endIf()
  })
  if (properties) {
    const hasProp = hasPropFunc(gen)
    const allProps: Code = and(
      ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`)
    )
    gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`))
  }
}

function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
  const {gen} = cxt
  for (const prop in schemas) {
    gen.elseIf(_`${key} === ${prop}`)
    parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
  }
}

function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void {
  parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`})
}

function parseType(cxt: ParseCxt): void {
  const {gen, schema, data, self} = cxt
  switch (schema.type) {
    case "boolean":
      parseBoolean(cxt)
      break
    case "string":
      parseString(cxt)
      break
    case "timestamp": {
      parseString(cxt)
      const vts = useFunc(gen, validTimestamp)
      const {allowDate, parseDate} = self.opts
      const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})`
      const fail: Code = parseDate
        ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`)
        : notValid
      gen.if(fail, () => parsingError(cxt, str`invalid timestamp`))
      break
    }
    case "float32":
    case "float64":
      parseNumber(cxt)
      break
    default: {
      const t = schema.type as IntType
      if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
        parseNumber(cxt, 16) // 2 ** 53 - max safe integer
        if (t === "uint32") {
          gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`))
        }
      } else {
        const [min, max, maxDigits] = intRange[t]
        parseNumber(cxt, maxDigits)
        gen.if(_`${data} < ${min} || ${data} > ${max}`, () =>
          parsingError(cxt, str`integer out of range`)
        )
      }
    }
  }
}

function parseString(cxt: ParseCxt): void {
  parseToken(cxt, '"')
  parseWith(cxt, parseJsonString)
}

function parseEnum(cxt: ParseCxt): void {
  const {gen, data, schema} = cxt
  const enumSch = schema.enum
  parseToken(cxt, '"')
  // TODO loopEnum
  gen.if(false)
  for (const value of enumSch) {
    const valueStr = JSON.stringify(value).slice(1) // remove starting quote
    gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`)
    gen.assign(data, str`${value}`)
    gen.add(N.jsonPos, valueStr.length)
  }
  gen.else()
  jsonSyntaxError(cxt)
  gen.endIf()
}

function parseNumber(cxt: ParseCxt, maxDigits?: number): void {
  const {gen} = cxt
  skipWhitespace(cxt)
  gen.if(
    _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`,
    () => jsonSyntaxError(cxt),
    () => parseWith(cxt, parseJsonNumber, maxDigits)
  )
}

function parseBooleanToken(bool: boolean, fail: GenParse): GenParse {
  return (cxt) => {
    const {gen, data} = cxt
    tryParseToken(
      cxt,
      `${bool}`,
      () => fail(cxt),
      () => gen.assign(data, bool)
    )
  }
}

function parseRef(cxt: ParseCxt): void {
  const {gen, self, definitions, schema, schemaEnv} = cxt
  const {ref} = schema
  const refSchema = definitions[ref]
  if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
  if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema})
  const {root} = schemaEnv
  const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
  partialParse(cxt, getParser(gen, sch), true)
}

function getParser(gen: CodeGen, sch: SchemaEnv): Code {
  return sch.parse
    ? gen.scopeValue("parse", {ref: sch.parse})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.parse`
}

function parseEmpty(cxt: ParseCxt): void {
  parseWith(cxt, parseJson)
}

function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void {
  partialParse(cxt, useFunc(cxt.gen, parseFunc), args)
}

function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void {
  const {gen, data} = cxt
  gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`)
  gen.assign(N.jsonPos, _`${parseFunc}.position`)
  gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`))
}

function parseToken(cxt: ParseCxt, tok: string): void {
  tryParseToken(cxt, tok, jsonSyntaxError)
}

function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void {
  const {gen} = cxt
  const n = tok.length
  skipWhitespace(cxt)
  gen.if(
    _`${jsonSlice(n)} === ${tok}`,
    () => {
      gen.add(N.jsonPos, n)
      success?.(cxt)
    },
    () => fail(cxt)
  )
}

function skipWhitespace({gen, char: c}: ParseCxt): void {
  gen.code(
    _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;`
  )
}

function jsonSlice(len: number | Name): Code {
  return len === 1
    ? _`${N.json}[${N.jsonPos}]`
    : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})`
}

function jsonSyntaxError(cxt: ParseCxt): void {
  parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`)
}

function parsingError({gen, parseName}: ParseCxt, msg: Code): void {
  gen.assign(_`${parseName}.message`, msg)
  gen.assign(_`${parseName}.position`, N.jsonPos)
  gen.return(undef)
}
import type Ajv from "../../core"
import type {SchemaObject} from "../../types"
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
import {SchemaEnv, getCompilingSchema} from ".."
import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen"
import MissingRefError from "../ref_error"
import N from "../names"
import {isOwnProperty} from "../../vocabularies/code"
import {hasRef} from "../../vocabularies/jtd/ref"
import {useFunc} from "../util"
import quote from "../../runtime/quote"

const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = {
  elements: serializeElements,
  values: serializeValues,
  discriminator: serializeDiscriminator,
  properties: serializeProperties,
  optionalProperties: serializeProperties,
  enum: serializeString,
  type: serializeType,
  ref: serializeRef,
}

interface SerializeCxt {
  readonly gen: CodeGen
  readonly self: Ajv // current Ajv instance
  readonly schemaEnv: SchemaEnv
  readonly definitions: SchemaObjectMap
  schema: SchemaObject
  data: Code
}

export default function compileSerializer(
  this: Ajv,
  sch: SchemaEnv,
  definitions: SchemaObjectMap
): SchemaEnv {
  const _sch = getCompilingSchema.call(this, sch)
  if (_sch) return _sch
  const {es5, lines} = this.opts.code
  const {ownProperties} = this.opts
  const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  const serializeName = gen.scopeName("serialize")
  const cxt: SerializeCxt = {
    self: this,
    gen,
    schema: sch.schema as SchemaObject,
    schemaEnv: sch,
    definitions,
    data: N.data,
  }

  let sourceCode: string | undefined
  try {
    this._compilations.add(sch)
    sch.serializeName = serializeName
    gen.func(serializeName, N.data, false, () => {
      gen.let(N.json, str``)
      serializeCode(cxt)
      gen.return(N.json)
    })
    gen.optimize(this.opts.code.optimize)
    const serializeFuncCode = gen.toString()
    sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}`
    const makeSerialize = new Function(`${N.scope}`, sourceCode)
    const serialize: (data: unknown) => string = makeSerialize(this.scope.get())
    this.scope.value(serializeName, {ref: serialize})
    sch.serialize = serialize
  } catch (e) {
    if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode)
    delete sch.serialize
    delete sch.serializeName
    throw e
  } finally {
    this._compilations.delete(sch)
  }
  return sch
}

function serializeCode(cxt: SerializeCxt): void {
  let form: JTDForm | undefined
  for (const key of jtdForms) {
    if (key in cxt.schema) {
      form = key
      break
    }
  }
  serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty)
}

function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void {
  const {gen, schema, data} = cxt
  if (!schema.nullable) return serializeForm(cxt)
  gen.if(
    _`${data} === undefined || ${data} === null`,
    () => gen.add(N.json, _`"null"`),
    () => serializeForm(cxt)
  )
}

function serializeElements(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  gen.add(N.json, str`[`)
  const first = gen.let("first", true)
  gen.forOf("el", data, (el) => {
    addComma(cxt, first)
    serializeCode({...cxt, schema: schema.elements, data: el})
  })
  gen.add(N.json, str`]`)
}

function serializeValues(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  gen.add(N.json, str`{`)
  const first = gen.let("first", true)
  gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first))
  gen.add(N.json, str`}`)
}

function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void {
  const {gen, data} = cxt
  addComma(cxt, first)
  serializeString({...cxt, data: key})
  gen.add(N.json, str`:`)
  const value = gen.const("value", _`${data}${getProperty(key)}`)
  serializeCode({...cxt, schema, data: value})
}

function serializeDiscriminator(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  const {discriminator} = schema
  gen.add(N.json, str`{${JSON.stringify(discriminator)}:`)
  const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`)
  serializeString({...cxt, data: tag})
  gen.if(false)
  for (const tagValue in schema.mapping) {
    gen.elseIf(_`${tag} === ${tagValue}`)
    const sch = schema.mapping[tagValue]
    serializeSchemaProperties({...cxt, schema: sch}, discriminator)
  }
  gen.endIf()
  gen.add(N.json, str`}`)
}

function serializeProperties(cxt: SerializeCxt): void {
  const {gen} = cxt
  gen.add(N.json, str`{`)
  serializeSchemaProperties(cxt)
  gen.add(N.json, str`}`)
}

function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void {
  const {gen, schema, data} = cxt
  const {properties, optionalProperties} = schema
  const props = keys(properties)
  const optProps = keys(optionalProperties)
  const allProps = allProperties(props.concat(optProps))
  let first = !discriminator
  let firstProp: Name | undefined

  for (const key of props) {
    if (first) first = false
    else gen.add(N.json, str`,`)
    serializeProperty(key, properties[key], keyValue(key))
  }
  if (first) firstProp = gen.let("first", true)
  for (const key of optProps) {
    const value = keyValue(key)
    gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => {
      addComma(cxt, firstProp)
      serializeProperty(key, optionalProperties[key], value)
    })
  }
  if (schema.additionalProperties) {
    gen.forIn("key", data, (key) =>
      gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))
    )
  }

  function keys(ps?: SchemaObjectMap): string[] {
    return ps ? Object.keys(ps) : []
  }

  function allProperties(ps: string[]): string[] {
    if (discriminator) ps.push(discriminator)
    if (new Set(ps).size !== ps.length) {
      throw new Error("JTD: properties/optionalProperties/disciminator overlap")
    }
    return ps
  }

  function keyValue(key: string): Name {
    return gen.const("value", _`${data}${getProperty(key)}`)
  }

  function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void {
    gen.add(N.json, str`${JSON.stringify(key)}:`)
    serializeCode({...cxt, schema: propSchema, data: value})
  }

  function isAdditional(key: Name, ps: string[]): Code | true {
    return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true
  }
}

function serializeType(cxt: SerializeCxt): void {
  const {gen, schema, data} = cxt
  switch (schema.type) {
    case "boolean":
      gen.add(N.json, _`${data} ? "true" : "false"`)
      break
    case "string":
      serializeString(cxt)
      break
    case "timestamp":
      gen.if(
        _`${data} instanceof Date`,
        () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
        () => serializeString(cxt)
      )
      break
    default:
      serializeNumber(cxt)
  }
}

function serializeString({gen, data}: SerializeCxt): void {
  gen.add(N.json, _`${useFunc(gen, quote)}(${data})`)
}

function serializeNumber({gen, data, self}: SerializeCxt): void {
  const condition = _`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`

  if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
    gen.add(N.json, _`"" + ${data}`)
  } else {
    // specialNumbers === "null"
    gen.if(
      condition,
      () => gen.add(N.json, _`null`),
      () => gen.add(N.json, _`"" + ${data}`)
    )
  }
}

function serializeRef(cxt: SerializeCxt): void {
  const {gen, self, data, definitions, schema, schemaEnv} = cxt
  const {ref} = schema
  const refSchema = definitions[ref]
  if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
  if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema})
  const {root} = schemaEnv
  const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
  gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`)
}

function getSerialize(gen: CodeGen, sch: SchemaEnv): Code {
  return sch.serialize
    ? gen.scopeValue("serialize", {ref: sch.serialize})
    : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize`
}

function serializeEmpty({gen, data}: SerializeCxt): void {
  gen.add(N.json, _`JSON.stringify(${data})`)
}

function addComma({gen}: SerializeCxt, first?: Name): void {
  if (first) {
    gen.if(
      first,
      () => gen.assign(first, false),
      () => gen.add(N.json, str`,`)
    )
  } else {
    gen.add(N.json, str`,`)
  }
}
import type {SchemaObject} from "../../types"

export type SchemaObjectMap = {[Ref in string]?: SchemaObject}

export const jtdForms = [
  "elements",
  "values",
  "discriminator",
  "properties",
  "optionalProperties",
  "enum",
  "type",
  "ref",
] as const

export type JTDForm = (typeof jtdForms)[number]
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export abstract class _CodeOrName {
  abstract readonly str: string
  abstract readonly names: UsedNames
  abstract toString(): string
  abstract emptyStr(): boolean
}

export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i

export class Name extends _CodeOrName {
  readonly str: string
  constructor(s: string) {
    super()
    if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
    this.str = s
  }

  toString(): string {
    return this.str
  }

  emptyStr(): boolean {
    return false
  }

  get names(): UsedNames {
    return {[this.str]: 1}
  }
}

export class _Code extends _CodeOrName {
  readonly _items: readonly CodeItem[]
  private _str?: string
  private _names?: UsedNames

  constructor(code: string | readonly CodeItem[]) {
    super()
    this._items = typeof code === "string" ? [code] : code
  }

  toString(): string {
    return this.str
  }

  emptyStr(): boolean {
    if (this._items.length > 1) return false
    const item = this._items[0]
    return item === "" || item === '""'
  }

  get str(): string {
    return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, ""))
  }

  get names(): UsedNames {
    return (this._names ??= this._items.reduce((names: UsedNames, c) => {
      if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1
      return names
    }, {}))
  }
}

export type CodeItem = Name | string | number | boolean | null

export type UsedNames = Record<string, number | undefined>

export type Code = _Code | Name

export type SafeExpr = Code | number | boolean | null

export const nil = new _Code("")

type CodeArg = SafeExpr | string | undefined

export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {
  const code: CodeItem[] = [strs[0]]
  let i = 0
  while (i < args.length) {
    addCodeArg(code, args[i])
    code.push(strs[++i])
  }
  return new _Code(code)
}

const plus = new _Code("+")

export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {
  const expr: CodeItem[] = [safeStringify(strs[0])]
  let i = 0
  while (i < args.length) {
    expr.push(plus)
    addCodeArg(expr, args[i])
    expr.push(plus, safeStringify(strs[++i]))
  }
  optimize(expr)
  return new _Code(expr)
}

export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {
  if (arg instanceof _Code) code.push(...arg._items)
  else if (arg instanceof Name) code.push(arg)
  else code.push(interpolate(arg))
}

function optimize(expr: CodeItem[]): void {
  let i = 1
  while (i < expr.length - 1) {
    if (expr[i] === plus) {
      const res = mergeExprItems(expr[i - 1], expr[i + 1])
      if (res !== undefined) {
        expr.splice(i - 1, 3, res)
        continue
      }
      expr[i++] = "+"
    }
    i++
  }
}

function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {
  if (b === '""') return a
  if (a === '""') return b
  if (typeof a == "string") {
    if (b instanceof Name || a[a.length - 1] !== '"') return
    if (typeof b != "string") return `${a.slice(0, -1)}${b}"`
    if (b[0] === '"') return a.slice(0, -1) + b.slice(1)
    return
  }
  if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`
  return
}

export function strConcat(c1: Code, c2: Code): Code {
  return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`
}

// TODO do not allow arrays here
function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {
  return typeof x == "number" || typeof x == "boolean" || x === null
    ? x
    : safeStringify(Array.isArray(x) ? x.join(",") : x)
}

export function stringify(x: unknown): Code {
  return new _Code(safeStringify(x))
}

export function safeStringify(x: unknown): string {
  return JSON.stringify(x)
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029")
}

export function getProperty(key: Code | string | number): Code {
  return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`
}

//Does best effort to format the name properly
export function getEsmExportName(key: Code | string | number): Code {
  if (typeof key == "string" && IDENTIFIER.test(key)) {
    return new _Code(`${key}`)
  }
  throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)
}

export function regexpCode(rx: RegExp): Code {
  return new _Code(rx.toString())
}
import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope"
import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code"
import {Scope, varKinds} from "./scope"

export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"

// type for expressions that can be safely inserted in code without quotes
export type SafeExpr = Code | number | boolean | null

// type that is either Code of function that adds code to CodeGen instance using its methods
export type Block = Code | (() => void)

export const operators = {
  GT: new _Code(">"),
  GTE: new _Code(">="),
  LT: new _Code("<"),
  LTE: new _Code("<="),
  EQ: new _Code("==="),
  NEQ: new _Code("!=="),
  NOT: new _Code("!"),
  OR: new _Code("||"),
  AND: new _Code("&&"),
  ADD: new _Code("+"),
}

abstract class Node {
  abstract readonly names: UsedNames

  optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
    return this
  }

  optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
    return this
  }

  // get count(): number {
  //   return 1
  // }
}

class Def extends Node {
  constructor(
    private readonly varKind: Name,
    private readonly name: Name,
    private rhs?: SafeExpr
  ) {
    super()
  }

  render({es5, _n}: CGOptions): string {
    const varKind = es5 ? varKinds.var : this.varKind
    const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`
    return `${varKind} ${this.name}${rhs};` + _n
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!names[this.name.str]) return
    if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)
    return this
  }

  get names(): UsedNames {
    return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
  }
}

class Assign extends Node {
  constructor(
    readonly lhs: Code,
    public rhs: SafeExpr,
    private readonly sideEffects?: boolean
  ) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.lhs} = ${this.rhs};` + _n
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return
    this.rhs = optimizeExpr(this.rhs, names, constants)
    return this
  }

  get names(): UsedNames {
    const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
    return addExprNames(names, this.rhs)
  }
}

class AssignOp extends Assign {
  constructor(
    lhs: Code,
    private readonly op: Code,
    rhs: SafeExpr,
    sideEffects?: boolean
  ) {
    super(lhs, rhs, sideEffects)
  }

  render({_n}: CGOptions): string {
    return `${this.lhs} ${this.op}= ${this.rhs};` + _n
  }
}

class Label extends Node {
  readonly names: UsedNames = {}
  constructor(readonly label: Name) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.label}:` + _n
  }
}

class Break extends Node {
  readonly names: UsedNames = {}
  constructor(readonly label?: Code) {
    super()
  }

  render({_n}: CGOptions): string {
    const label = this.label ? ` ${this.label}` : ""
    return `break${label};` + _n
  }
}

class Throw extends Node {
  constructor(readonly error: Code) {
    super()
  }

  render({_n}: CGOptions): string {
    return `throw ${this.error};` + _n
  }

  get names(): UsedNames {
    return this.error.names
  }
}

class AnyCode extends Node {
  constructor(private code: SafeExpr) {
    super()
  }

  render({_n}: CGOptions): string {
    return `${this.code};` + _n
  }

  optimizeNodes(): this | undefined {
    return `${this.code}` ? this : undefined
  }

  optimizeNames(names: UsedNames, constants: Constants): this {
    this.code = optimizeExpr(this.code, names, constants)
    return this
  }

  get names(): UsedNames {
    return this.code instanceof _CodeOrName ? this.code.names : {}
  }
}

abstract class ParentNode extends Node {
  constructor(readonly nodes: ChildNode[] = []) {
    super()
  }

  render(opts: CGOptions): string {
    return this.nodes.reduce((code, n) => code + n.render(opts), "")
  }

  optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
    const {nodes} = this
    let i = nodes.length
    while (i--) {
      const n = nodes[i].optimizeNodes()
      if (Array.isArray(n)) nodes.splice(i, 1, ...n)
      else if (n) nodes[i] = n
      else nodes.splice(i, 1)
    }
    return nodes.length > 0 ? this : undefined
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    const {nodes} = this
    let i = nodes.length
    while (i--) {
      // iterating backwards improves 1-pass optimization
      const n = nodes[i]
      if (n.optimizeNames(names, constants)) continue
      subtractNames(names, n.names)
      nodes.splice(i, 1)
    }
    return nodes.length > 0 ? this : undefined
  }

  get names(): UsedNames {
    return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
  }

  // get count(): number {
  //   return this.nodes.reduce((c, n) => c + n.count, 1)
  // }
}

abstract class BlockNode extends ParentNode {
  render(opts: CGOptions): string {
    return "{" + opts._n + super.render(opts) + "}" + opts._n
  }
}

class Root extends ParentNode {}

class Else extends BlockNode {
  static readonly kind = "else"
}

class If extends BlockNode {
  static readonly kind = "if"
  else?: If | Else
  constructor(
    private condition: Code | boolean,
    nodes?: ChildNode[]
  ) {
    super(nodes)
  }

  render(opts: CGOptions): string {
    let code = `if(${this.condition})` + super.render(opts)
    if (this.else) code += "else " + this.else.render(opts)
    return code
  }

  optimizeNodes(): If | ChildNode[] | undefined {
    super.optimizeNodes()
    const cond = this.condition
    if (cond === true) return this.nodes // else is ignored here
    let e = this.else
    if (e) {
      const ns = e.optimizeNodes()
      e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
    }
    if (e) {
      if (cond === false) return e instanceof If ? e : e.nodes
      if (this.nodes.length) return this
      return new If(not(cond), e instanceof If ? [e] : e.nodes)
    }
    if (cond === false || !this.nodes.length) return undefined
    return this
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    this.else = this.else?.optimizeNames(names, constants)
    if (!(super.optimizeNames(names, constants) || this.else)) return
    this.condition = optimizeExpr(this.condition, names, constants)
    return this
  }

  get names(): UsedNames {
    const names = super.names
    addExprNames(names, this.condition)
    if (this.else) addNames(names, this.else.names)
    return names
  }

  // get count(): number {
  //   return super.count + (this.else?.count || 0)
  // }
}

abstract class For extends BlockNode {
  static readonly kind = "for"
}

class ForLoop extends For {
  constructor(private iteration: Code) {
    super()
  }

  render(opts: CGOptions): string {
    return `for(${this.iteration})` + super.render(opts)
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!super.optimizeNames(names, constants)) return
    this.iteration = optimizeExpr(this.iteration, names, constants)
    return this
  }

  get names(): UsedNames {
    return addNames(super.names, this.iteration.names)
  }
}

class ForRange extends For {
  constructor(
    private readonly varKind: Name,
    private readonly name: Name,
    private readonly from: SafeExpr,
    private readonly to: SafeExpr
  ) {
    super()
  }

  render(opts: CGOptions): string {
    const varKind = opts.es5 ? varKinds.var : this.varKind
    const {name, from, to} = this
    return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)
  }

  get names(): UsedNames {
    const names = addExprNames(super.names, this.from)
    return addExprNames(names, this.to)
  }
}

class ForIter extends For {
  constructor(
    private readonly loop: "of" | "in",
    private readonly varKind: Name,
    private readonly name: Name,
    private iterable: Code
  ) {
    super()
  }

  render(opts: CGOptions): string {
    return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
  }

  optimizeNames(names: UsedNames, constants: Constants): this | undefined {
    if (!super.optimizeNames(names, constants)) return
    this.iterable = optimizeExpr(this.iterable, names, constants)
    return this
  }

  get names(): UsedNames {
    return addNames(super.names, this.iterable.names)
  }
}

class Func extends BlockNode {
  static readonly kind = "func"
  constructor(
    public name: Name,
    public args: Code,
    public async?: boolean
  ) {
    super()
  }

  render(opts: CGOptions): string {
    const _async = this.async ? "async " : ""
    return `${_async}function ${this.name}(${this.args})` + super.render(opts)
  }
}

class Return extends ParentNode {
  static readonly kind = "return"

  render(opts: CGOptions): string {
    return "return " + super.render(opts)
  }
}

class Try extends BlockNode {
  catch?: Catch
  finally?: Finally

  render(opts: CGOptions): string {
    let code = "try" + super.render(opts)
    if (this.catch) code += this.catch.render(opts)
    if (this.finally) code += this.finally.render(opts)
    return code
  }

  optimizeNodes(): this {
    super.optimizeNodes()
    this.catch?.optimizeNodes() as Catch | undefined
    this.finally?.optimizeNodes() as Finally | undefined
    return this
  }

  optimizeNames(names: UsedNames, constants: Constants): this {
    super.optimizeNames(names, constants)
    this.catch?.optimizeNames(names, constants)
    this.finally?.optimizeNames(names, constants)
    return this
  }

  get names(): UsedNames {
    const names = super.names
    if (this.catch) addNames(names, this.catch.names)
    if (this.finally) addNames(names, this.finally.names)
    return names
  }

  // get count(): number {
  //   return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
  // }
}

class Catch extends BlockNode {
  static readonly kind = "catch"
  constructor(readonly error: Name) {
    super()
  }

  render(opts: CGOptions): string {
    return `catch(${this.error})` + super.render(opts)
  }
}

class Finally extends BlockNode {
  static readonly kind = "finally"
  render(opts: CGOptions): string {
    return "finally" + super.render(opts)
  }
}

type StartBlockNode = If | For | Func | Return | Try

type LeafNode = Def | Assign | Label | Break | Throw | AnyCode

type ChildNode = StartBlockNode | LeafNode

type EndBlockNodeType =
  | typeof If
  | typeof Else
  | typeof For
  | typeof Func
  | typeof Return
  | typeof Catch
  | typeof Finally

type Constants = Record<string, SafeExpr | undefined>

export interface CodeGenOptions {
  es5?: boolean
  lines?: boolean
  ownProperties?: boolean
}

interface CGOptions extends CodeGenOptions {
  _n: "\n" | ""
}

export class CodeGen {
  readonly _scope: Scope
  readonly _extScope: ValueScope
  readonly _values: ScopeValueSets = {}
  private readonly _nodes: ParentNode[]
  private readonly _blockStarts: number[] = []
  private readonly _constants: Constants = {}
  private readonly opts: CGOptions

  constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
    this.opts = {...opts, _n: opts.lines ? "\n" : ""}
    this._extScope = extScope
    this._scope = new Scope({parent: extScope})
    this._nodes = [new Root()]
  }

  toString(): string {
    return this._root.render(this.opts)
  }

  // returns unique name in the internal scope
  name(prefix: string): Name {
    return this._scope.name(prefix)
  }

  // reserves unique name in the external scope
  scopeName(prefix: string): ValueScopeName {
    return this._extScope.name(prefix)
  }

  // reserves unique name in the external scope and assigns value to it
  scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
    const name = this._extScope.value(prefixOrName, value)
    const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
    vs.add(name)
    return name
  }

  getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
    return this._extScope.getValue(prefix, keyOrRef)
  }

  // return code that assigns values in the external scope to the names that are used internally
  // (same names that were returned by gen.scopeName or gen.scopeValue)
  scopeRefs(scopeName: Name): Code {
    return this._extScope.scopeRefs(scopeName, this._values)
  }

  scopeCode(): Code {
    return this._extScope.scopeCode(this._values)
  }

  private _def(
    varKind: Name,
    nameOrPrefix: Name | string,
    rhs?: SafeExpr,
    constant?: boolean
  ): Name {
    const name = this._scope.toName(nameOrPrefix)
    if (rhs !== undefined && constant) this._constants[name.str] = rhs
    this._leafNode(new Def(varKind, name, rhs))
    return name
  }

  // `const` declaration (`var` in es5 mode)
  const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
  }

  // `let` declaration with optional assignment (`var` in es5 mode)
  let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
  }

  // `var` declaration with optional assignment
  var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
    return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
  }

  // assignment code
  assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
    return this._leafNode(new Assign(lhs, rhs, sideEffects))
  }

  // `+=` code
  add(lhs: Code, rhs: SafeExpr): CodeGen {
    return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
  }

  // appends passed SafeExpr to code or executes Block
  code(c: Block | SafeExpr): CodeGen {
    if (typeof c == "function") c()
    else if (c !== nil) this._leafNode(new AnyCode(c))
    return this
  }

  // returns code for object literal for the passed argument list of key-value pairs
  object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
    const code: CodeItem[] = ["{"]
    for (const [key, value] of keyValues) {
      if (code.length > 1) code.push(",")
      code.push(key)
      if (key !== value || this.opts.es5) {
        code.push(":")
        addCodeArg(code, value)
      }
    }
    code.push("}")
    return new _Code(code)
  }

  // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
  if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
    this._blockNode(new If(condition))

    if (thenBody && elseBody) {
      this.code(thenBody).else().code(elseBody).endIf()
    } else if (thenBody) {
      this.code(thenBody).endIf()
    } else if (elseBody) {
      throw new Error('CodeGen: "else" body without "then" body')
    }
    return this
  }

  // `else if` clause - invalid without `if` or after `else` clauses
  elseIf(condition: Code | boolean): CodeGen {
    return this._elseNode(new If(condition))
  }

  // `else` clause - only valid after `if` or `else if` clauses
  else(): CodeGen {
    return this._elseNode(new Else())
  }

  // end `if` statement (needed if gen.if was used only with condition)
  endIf(): CodeGen {
    return this._endBlockNode(If, Else)
  }

  private _for(node: For, forBody?: Block): CodeGen {
    this._blockNode(node)
    if (forBody) this.code(forBody).endFor()
    return this
  }

  // a generic `for` clause (or statement if `forBody` is passed)
  for(iteration: Code, forBody?: Block): CodeGen {
    return this._for(new ForLoop(iteration), forBody)
  }

  // `for` statement for a range of values
  forRange(
    nameOrPrefix: Name | string,
    from: SafeExpr,
    to: SafeExpr,
    forBody: (index: Name) => void,
    varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
  ): CodeGen {
    const name = this._scope.toName(nameOrPrefix)
    return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
  }

  // `for-of` statement (in es5 mode replace with a normal for loop)
  forOf(
    nameOrPrefix: Name | string,
    iterable: Code,
    forBody: (item: Name) => void,
    varKind: Code = varKinds.const
  ): CodeGen {
    const name = this._scope.toName(nameOrPrefix)
    if (this.opts.es5) {
      const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
      return this.forRange("_i", 0, _`${arr}.length`, (i) => {
        this.var(name, _`${arr}[${i}]`)
        forBody(name)
      })
    }
    return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
  }

  // `for-in` statement.
  // With option `ownProperties` replaced with a `for-of` loop for object keys
  forIn(
    nameOrPrefix: Name | string,
    obj: Code,
    forBody: (item: Name) => void,
    varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
  ): CodeGen {
    if (this.opts.ownProperties) {
      return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
    }
    const name = this._scope.toName(nameOrPrefix)
    return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
  }

  // end `for` loop
  endFor(): CodeGen {
    return this._endBlockNode(For)
  }

  // `label` statement
  label(label: Name): CodeGen {
    return this._leafNode(new Label(label))
  }

  // `break` statement
  break(label?: Code): CodeGen {
    return this._leafNode(new Break(label))
  }

  // `return` statement
  return(value: Block | SafeExpr): CodeGen {
    const node = new Return()
    this._blockNode(node)
    this.code(value)
    if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
    return this._endBlockNode(Return)
  }

  // `try` statement
  try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
    if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
    const node = new Try()
    this._blockNode(node)
    this.code(tryBody)
    if (catchCode) {
      const error = this.name("e")
      this._currNode = node.catch = new Catch(error)
      catchCode(error)
    }
    if (finallyCode) {
      this._currNode = node.finally = new Finally()
      this.code(finallyCode)
    }
    return this._endBlockNode(Catch, Finally)
  }

  // `throw` statement
  throw(error: Code): CodeGen {
    return this._leafNode(new Throw(error))
  }

  // start self-balancing block
  block(body?: Block, nodeCount?: number): CodeGen {
    this._blockStarts.push(this._nodes.length)
    if (body) this.code(body).endBlock(nodeCount)
    return this
  }

  // end the current self-balancing block
  endBlock(nodeCount?: number): CodeGen {
    const len = this._blockStarts.pop()
    if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
    const toClose = this._nodes.length - len
    if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
      throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
    }
    this._nodes.length = len
    return this
  }

  // `function` heading (or definition if funcBody is passed)
  func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
    this._blockNode(new Func(name, args, async))
    if (funcBody) this.code(funcBody).endFunc()
    return this
  }

  // end function definition
  endFunc(): CodeGen {
    return this._endBlockNode(Func)
  }

  optimize(n = 1): void {
    while (n-- > 0) {
      this._root.optimizeNodes()
      this._root.optimizeNames(this._root.names, this._constants)
    }
  }

  private _leafNode(node: LeafNode): CodeGen {
    this._currNode.nodes.push(node)
    return this
  }

  private _blockNode(node: StartBlockNode): void {
    this._currNode.nodes.push(node)
    this._nodes.push(node)
  }

  private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
    const n = this._currNode
    if (n instanceof N1 || (N2 && n instanceof N2)) {
      this._nodes.pop()
      return this
    }
    throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
  }

  private _elseNode(node: If | Else): CodeGen {
    const n = this._currNode
    if (!(n instanceof If)) {
      throw new Error('CodeGen: "else" without "if"')
    }
    this._currNode = n.else = node
    return this
  }

  private get _root(): Root {
    return this._nodes[0] as Root
  }

  private get _currNode(): ParentNode {
    const ns = this._nodes
    return ns[ns.length - 1]
  }

  private set _currNode(node: ParentNode) {
    const ns = this._nodes
    ns[ns.length - 1] = node
  }

  // get nodeCount(): number {
  //   return this._root.count
  // }
}

function addNames(names: UsedNames, from: UsedNames): UsedNames {
  for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
  return names
}

function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
  return from instanceof _CodeOrName ? addNames(names, from.names) : names
}

function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T
function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
  if (expr instanceof Name) return replaceName(expr)
  if (!canOptimize(expr)) return expr
  return new _Code(
    expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
      if (c instanceof Name) c = replaceName(c)
      if (c instanceof _Code) items.push(...c._items)
      else items.push(c)
      return items
    }, [])
  )

  function replaceName(n: Name): SafeExpr {
    const c = constants[n.str]
    if (c === undefined || names[n.str] !== 1) return n
    delete names[n.str]
    return c
  }

  function canOptimize(e: SafeExpr): e is _Code {
    return (
      e instanceof _Code &&
      e._items.some(
        (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
      )
    )
  }
}

function subtractNames(names: UsedNames, from: UsedNames): void {
  for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
}

export function not<T extends Code | SafeExpr>(x: T): T
export function not(x: Code | SafeExpr): Code | SafeExpr {
  return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}`
}

const andCode = mappend(operators.AND)

// boolean AND (&&) expression with the passed arguments
export function and(...args: Code[]): Code {
  return args.reduce(andCode)
}

const orCode = mappend(operators.OR)

// boolean OR (||) expression with the passed arguments
export function or(...args: Code[]): Code {
  return args.reduce(orCode)
}

type MAppend = (x: Code, y: Code) => Code

function mappend(op: Code): MAppend {
  return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
}

function par(x: Code): Code {
  return x instanceof Name ? x : _`(${x})`
}
import {_, nil, Code, Name} from "./code"

interface NameGroup {
  prefix: string
  index: number
}

export interface NameValue {
  ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure
  key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used
  code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)
}

export type ValueReference = unknown // possibly make CodeGen parameterized type on this type

class ValueError extends Error {
  readonly value?: NameValue
  constructor(name: ValueScopeName) {
    super(`CodeGen: "code" for ${name} not defined`)
    this.value = name.value
  }
}

interface ScopeOptions {
  prefixes?: Set<string>
  parent?: Scope
}

interface ValueScopeOptions extends ScopeOptions {
  scope: ScopeStore
  es5?: boolean
  lines?: boolean
}

export type ScopeStore = Record<string, ValueReference[] | undefined>

type ScopeValues = {
  [Prefix in string]?: Map<unknown, ValueScopeName>
}

export type ScopeValueSets = {
  [Prefix in string]?: Set<ValueScopeName>
}

export enum UsedValueState {
  Started,
  Completed,
}

export type UsedScopeValues = {
  [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>
}

export const varKinds = {
  const: new Name("const"),
  let: new Name("let"),
  var: new Name("var"),
}

export class Scope {
  protected readonly _names: {[Prefix in string]?: NameGroup} = {}
  protected readonly _prefixes?: Set<string>
  protected readonly _parent?: Scope

  constructor({prefixes, parent}: ScopeOptions = {}) {
    this._prefixes = prefixes
    this._parent = parent
  }

  toName(nameOrPrefix: Name | string): Name {
    return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)
  }

  name(prefix: string): Name {
    return new Name(this._newName(prefix))
  }

  protected _newName(prefix: string): string {
    const ng = this._names[prefix] || this._nameGroup(prefix)
    return `${prefix}${ng.index++}`
  }

  private _nameGroup(prefix: string): NameGroup {
    if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {
      throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`)
    }
    return (this._names[prefix] = {prefix, index: 0})
  }
}

interface ScopePath {
  property: string
  itemIndex: number
}

export class ValueScopeName extends Name {
  readonly prefix: string
  value?: NameValue
  scopePath?: Code

  constructor(prefix: string, nameStr: string) {
    super(nameStr)
    this.prefix = prefix
  }

  setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
    this.value = value
    this.scopePath = _`.${new Name(property)}[${itemIndex}]`
  }
}

interface VSOptions extends ValueScopeOptions {
  _n: Code
}

const line = _`\n`

export class ValueScope extends Scope {
  protected readonly _values: ScopeValues = {}
  protected readonly _scope: ScopeStore
  readonly opts: VSOptions

  constructor(opts: ValueScopeOptions) {
    super(opts)
    this._scope = opts.scope
    this.opts = {...opts, _n: opts.lines ? line : nil}
  }

  get(): ScopeStore {
    return this._scope
  }

  name(prefix: string): ValueScopeName {
    return new ValueScopeName(prefix, this._newName(prefix))
  }

  value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {
    if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value")
    const name = this.toName(nameOrPrefix) as ValueScopeName
    const {prefix} = name
    const valueKey = value.key ?? value.ref
    let vs = this._values[prefix]
    if (vs) {
      const _name = vs.get(valueKey)
      if (_name) return _name
    } else {
      vs = this._values[prefix] = new Map()
    }
    vs.set(valueKey, name)

    const s = this._scope[prefix] || (this._scope[prefix] = [])
    const itemIndex = s.length
    s[itemIndex] = value.ref
    name.setValue(value, {property: prefix, itemIndex})
    return name
  }

  getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
    const vs = this._values[prefix]
    if (!vs) return
    return vs.get(keyOrRef)
  }

  scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {
    return this._reduceValues(values, (name: ValueScopeName) => {
      if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
      return _`${scopeName}${name.scopePath}`
    })
  }

  scopeCode(
    values: ScopeValues | ScopeValueSets = this._values,
    usedValues?: UsedScopeValues,
    getCode?: (n: ValueScopeName) => Code | undefined
  ): Code {
    return this._reduceValues(
      values,
      (name: ValueScopeName) => {
        if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
        return name.value.code
      },
      usedValues,
      getCode
    )
  }

  private _reduceValues(
    values: ScopeValues | ScopeValueSets,
    valueCode: (n: ValueScopeName) => Code | undefined,
    usedValues: UsedScopeValues = {},
    getCode?: (n: ValueScopeName) => Code | undefined
  ): Code {
    let code: Code = nil
    for (const prefix in values) {
      const vs = values[prefix]
      if (!vs) continue
      const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())
      vs.forEach((name: ValueScopeName) => {
        if (nameSet.has(name)) return
        nameSet.set(name, UsedValueState.Started)
        let c = valueCode(name)
        if (c) {
          const def = this.opts.es5 ? varKinds.var : varKinds.const
          code = _`${code}${def} ${name} = ${c};${this.opts._n}`
        } else if ((c = getCode?.(name))) {
          code = _`${code}${c}${this.opts._n}`
        } else {
          throw new ValueError(name)
        }
        nameSet.set(name, UsedValueState.Completed)
      })
    }
    return code
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const dynamic_1 = require("./vocabularies/dynamic");
const next_1 = require("./vocabularies/next");
const unevaluated_1 = require("./vocabularies/unevaluated");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
class Ajv2019 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(dynamic_1.default);
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        this.addVocabulary(next_1.default);
        this.addVocabulary(unevaluated_1.default);
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2019_09_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2019 = Ajv2019;
module.exports = exports = Ajv2019;
module.exports.Ajv2019 = Ajv2019;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2019;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2019.js.map{"version":3,"file":"2019.js","sourceRoot":"","sources":["../lib/2019.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,kDAAsD;AACtD,oDAAsD;AACtD,8CAAgD;AAChD,4DAA8D;AAC9D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,IAAI,CAAC,aAAa,CAAC,iBAAiB,CAAC,CAAA;QACrC,gBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QACxD,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,CAAA;QAClC,IAAI,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAA;QACzC,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa;YAAE,IAAI,CAAC,UAAU,CAAC,uBAAa,CAAC,CAAA;IAC7D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,MAAM,EAAC,KAAK,EAAE,IAAI,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;QAC/B,IAAI,CAAC,IAAI;YAAE,OAAM;QACjB,6BAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACnC,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AA/BD,0BA+BC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAClC,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAA;AAChC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;
const core_1 = require("./core");
const draft2020_1 = require("./vocabularies/draft2020");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2020_12_1 = require("./refs/json-schema-2020-12");
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
class Ajv2020 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2020_12_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2020 = Ajv2020;
module.exports = exports = Ajv2020;
module.exports.Ajv2020 = Ajv2020;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2020;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2020.js.map{"version":3,"file":"2020.js","sourceRoot":"","sources":["../lib/2020.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,wDAA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,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const discriminator_1 = require("./vocabularies/discriminator");
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
    _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        const metaSchema = this.opts.$data
            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
            : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=ajv.js.map{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../lib/ajv.ts"],"names":[],"mappings":";;;AACA,iCAA4B;AAC5B,kDAAsD;AACtD,gEAAwD;AACxD,qEAAoE;AAEpE,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,MAAM,cAAc,GAAG,wCAAwC,CAAA;AAE/D,MAAa,GAAI,SAAQ,cAAO;IAC9B,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,gBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QACxD,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa;YAAE,IAAI,CAAC,UAAU,CAAC,uBAAa,CAAC,CAAA;IAC7D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAM;QAC3B,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK;YAChC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC;YAC3D,CAAC,CAAC,gBAAgB,CAAA;QACpB,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,cAAc,EAAE,KAAK,CAAC,CAAA;QACrD,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AArBD,kBAqBC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,GAAG,CAAA;AAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAA;AACxB,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error",
]);
const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now.",
};
const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver: uriResolver,
    };
}
class Ajv {
    constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = Object.create(null);
        this._compilations = new Set();
        this._loading = {};
        this._cache = new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
            addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
        this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
            _dataRefSchema = { ...$dataRefSchema };
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
        }
        if (meta && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
        const { meta, schemaId } = this.opts;
        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
    }
    validate(schemaKeyRef, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data // to be validated
    ) {
        let v;
        if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        }
        else {
            v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
            this.errors = v.errors;
        return valid;
    }
    compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
            await loadMetaSchema.call(this, _schema.$schema);
            const sch = this._addSchema(_schema, _meta);
            return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
            if ($ref && !this.getSchema($ref)) {
                await runCompileAsync.call(this, { $ref }, true);
            }
        }
        async function _compileAsync(sch) {
            try {
                return this._compileSchemaEnv(sch);
            }
            catch (e) {
                if (!(e instanceof ref_error_1.default))
                    throw e;
                checkLoaded.call(this, e);
                await loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
            }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
            if (this.refs[ref]) {
                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
            }
        }
        async function loadMissingSchema(ref) {
            const _schema = await _loadSchema.call(this, ref);
            if (!this.refs[ref])
                await loadMetaSchema.call(this, _schema.$schema);
            if (!this.refs[ref])
                this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
            const p = this._loading[ref];
            if (p)
                return p;
            try {
                return await (this._loading[ref] = loadSchema(ref));
            }
            finally {
                delete this._loading[ref];
            }
        }
    }
    // Adds schema to the instance
    addSchema(schema, // If array is passed, `key` will be ignored
    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
    ) {
        if (Array.isArray(schema)) {
            for (const sch of schema)
                this.addSchema(sch, undefined, _meta, _validateSchema);
            return this;
        }
        let id;
        if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id = schema[schemaId];
            if (id !== undefined && typeof id != "string") {
                throw new Error(`schema ${schemaId} must be string`);
            }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
    ) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
            return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != "string") {
            throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
        if (sch === undefined) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
                return;
            this.refs[keyRef] = sch;
        }
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case "undefined":
                this._removeAllSchemas(this.schemas);
                this._removeAllSchemas(this.refs);
                this._cache.clear();
                return this;
            case "string": {
                const sch = getSchEnv.call(this, schemaKeyRef);
                if (typeof sch == "object")
                    this._cache.delete(sch.schema);
                delete this.schemas[schemaKeyRef];
                delete this.refs[schemaKeyRef];
                return this;
            }
            case "object": {
                const cacheKey = schemaKeyRef;
                this._cache.delete(cacheKey);
                let id = schemaKeyRef[this.opts.schemaId];
                if (id) {
                    id = (0, resolve_1.normalizeId)(id);
                    delete this.schemas[id];
                    delete this.refs[id];
                }
                return this;
            }
            default:
                throw new Error("ajv.removeSchema: invalid parameter");
        }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions) {
        for (const def of definitions)
            this.addKeyword(def);
        return this;
    }
    addKeyword(kwdOrDef, def // deprecated
    ) {
        let keyword;
        if (typeof kwdOrDef == "string") {
            keyword = kwdOrDef;
            if (typeof def == "object") {
                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
                def.keyword = keyword;
            }
        }
        else if (typeof kwdOrDef == "object" && def === undefined) {
            def = kwdOrDef;
            keyword = def.keyword;
            if (Array.isArray(keyword) && !keyword.length) {
                throw new Error("addKeywords: keyword must be string or non-empty array");
            }
        }
        else {
            throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
            return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
            ...def,
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0
            ? (k) => addRule.call(this, k, definition)
            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        return this;
    }
    getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword) {
        // TODO return type should be Ajv
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
            if (i >= 0)
                group.rules.splice(i, 1);
        }
        return this;
    }
    // Add format
    addFormat(name, format) {
        if (typeof format == "string")
            format = new RegExp(format);
        this.formats[name] = format;
        return this;
    }
    errorsText(errors = this.errors, // optional array of validation errors
    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
    ) {
        if (!errors || errors.length === 0)
            return "No errors";
        return errors
            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
            .reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
            let keywords = metaSchema;
            for (const seg of segments)
                keywords = keywords[seg];
            for (const key in rules) {
                const rule = rules[key];
                if (typeof rule != "object")
                    continue;
                const { $data } = rule.definition;
                const schema = keywords[key];
                if ($data && schema)
                    keywords[key] = schemaOrData(schema);
            }
        }
        return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
                if (typeof sch == "string") {
                    delete schemas[keyRef];
                }
                else if (sch && !sch.meta) {
                    this._cache.delete(sch.schema);
                    delete schemas[keyRef];
                }
            }
        }
    }
    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
            id = schema[schemaId];
        }
        else {
            if (this.opts.jtd)
                throw new Error("schema must be object");
            else if (typeof schema != "boolean")
                throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== undefined)
            return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
            if (baseId)
                this._checkUnique(baseId);
            this.refs[baseId] = sch;
        }
        if (validateSchema)
            this.validateSchema(schema, true);
        return sch;
    }
    _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
            throw new Error(`schema with key or id "${id}" already exists`);
        }
    }
    _compileSchemaEnv(sch) {
        if (sch.meta)
            this._compileMetaSchema(sch);
        else
            compile_1.compileSchema.call(this, sch);
        /* istanbul ignore if */
        if (!sch.validate)
            throw new Error("ajv implementation error");
        return sch.validate;
    }
    _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
            compile_1.compileSchema.call(this, sch);
        }
        finally {
            this.opts = currentOpts;
        }
    }
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
    for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
}
function getSchEnv(keyRef) {
    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
    return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
        return;
    if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
    else
        for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
    for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
            this.addFormat(name, format);
    }
}
function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
            def.keyword = keyword;
        this.addKeyword(def);
    }
}
function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
    return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
    if (logger === false)
        return noLogs;
    if (logger === undefined)
        return console;
    if (logger.log && logger.warn && logger.error)
        return logger;
    throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
    const { RULES } = this;
    (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def)
        return;
    if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
    }
}
function addRule(keyword, definition, dataType) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
    if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword] = true;
    if (!definition)
        return;
    const rule = {
        keyword,
        definition: {
            ...definition,
            type: (0, dataType_1.getJSONTypes)(definition.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
        },
    };
    if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
        ruleGroup.rules.push(rule);
    RULES.all[keyword] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
    }
    else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
    }
}
function keywordMetaschema(def) {
    let { metaSchema } = def;
    if (metaSchema === undefined)
        return;
    if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
    def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map{"version":3,"file":"core.js","sourceRoot":"","sources":["../lib/core.ts"],"names":[],"mappings":";;;AA4BA,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAKlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAsBnD,iEAAwD;AACxD,mDAAiD;AACjD,2CAAoF;AACpF,uCAAiE;AACjE,+CAAkD;AAClD,+CAA4D;AAC5D,0DAAwD;AACxD,yCAAuC;AACvC,mDAAkD;AAElD,uCAA8C;AAE9C,MAAM,aAAa,GAAiB,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;AAC1E,aAAa,CAAC,IAAI,GAAG,YAAY,CAAA;AAEjC,MAAM,mBAAmB,GAAsB,CAAC,kBAAkB,EAAE,aAAa,EAAE,aAAa,CAAC,CAAA;AACjG,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,UAAU;IACV,WAAW;IACX,OAAO;IACP,SAAS;IACT,MAAM;IACN,QAAQ;IACR,S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,GAAG;IACf,IAAI,EAAE,gFAAgF;CACvF,CAAA;AAED,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,EAAC,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAC,CAAA;AACpC,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const jtd_1 = require("./vocabularies/jtd");
const jtd_schema_1 = require("./refs/jtd-schema");
const serialize_1 = require("./compile/jtd/serialize");
const parse_1 = require("./compile/jtd/parse");
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            jtd: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(jtd_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
    compileSerializer(schema) {
        const sch = this._addSchema(schema);
        return sch.serialize || this._compileSerializer(sch);
    }
    compileParser(schema) {
        const sch = this._addSchema(schema);
        return (sch.parse || this._compileParser(sch));
    }
    _compileSerializer(sch) {
        serialize_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.serialize)
            throw new Error("ajv implementation error");
        return sch.serialize;
    }
    _compileParser(sch) {
        parse_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.parse)
            throw new Error("ajv implementation error");
        return sch.parse;
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=jtd.js.map{"version":3,"file":"jtd.js","sourceRoot":"","sources":["../lib/jtd.ts"],"names":[],"mappings":";;;AAEA,iCAA8C;AAC9C,4CAA8C;AAC9C,kDAA6C;AAC7C,uDAAuD;AACvD,+CAA+C;AAG/C,MAAM,cAAc,GAAG,iBAAiB,CAAA;AA4BxC,MAAa,GAAI,SAAQ,cAAO;IAC9B,YAAY,OAAmB,EAAE;QAC/B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,GAAG,EAAE,IAAI;SACV,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,IAAI,CAAC,aAAa,CAAC,aAAa,CAAC,CAAA;IACnC,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAM;QAC3B,IAAI,CAAC,aAAa,CAAC,oBAAa,EAAE,cAAc,EAAE,KAAK,CAAC,CAAA;IAC1D,CAAC;IAED,WAAW;Q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;AAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAA;AACxB,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAElB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAInD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = require("../compile/codegen");
const util_1 = require("../compile/util");
const names_1 = require("../compile/names");
const util_2 = require("../compile/util");
function checkReportMissingProp(cxt, prop) {
    const { gen, data, it } = cxt;
    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
        cxt.error();
    });
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
    return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
    });
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
    const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData],
    ];
    if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
    const u = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern, u);
    return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
    });
}
exports.usePattern = usePattern;
function validateArray(cxt) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
                keyword,
                dataProp: i,
                dataPropType: util_1.Type.Num,
            }, valid);
            gen.if((0, codegen_1.not)(valid), notValid);
        });
    }
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
    const { gen, schema, keyword, it } = cxt;
    /* istanbul ignore if */
    if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
    if (alwaysValid && !it.opts.unevaluated)
        return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
            keyword,
            schemaProp: i,
            compositeRule: true,
        }, schValid);
        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
        // or if all properties and items were evaluated (it.props === true && it.items === true)
        if (!merged)
            gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../lib/vocabularies/code.ts"],"names":[],"mappings":";;;AAGA,gDAAoG;AACpG,0CAAuD;AACvD,4CAAgC;AAChC,0CAAuC;AACvC,SAAgB,sBAAsB,CAAC,GAAe,EAAE,IAAY;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,GAAG,CAAC,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE;QACpE,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,EAAE,EAAC,EAAE,IAAI,CAAC,CAAA;QAClD,GAAG,CAAC,KAAK,EAAE,CAAA;IACb,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,wDAMC;AAED,SAAgB,gBAAgB,CAC9B,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAC,IAAI,EAAC,EAAa,EACnC,UAAoB,EACpB,OAAa;IAEb,OAAO,IAAA,YAAE,EACP,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACzB,IAAA,aAAG,EAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,MAAM,IAAI,EAAE,CAAC,CACpF,CACF,CAAA;AACH,CAAC;AAVD,4CAUC;AAED,SAAgB,iBAAiB,CAAC,GAAe,EAAE,OAAa;IAC9D,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,OAAO,EAAC,EAAE,IAAI,CAAC,CAAA;IAC/C,GAAG,CAAC,KAAK,EAAE,CAAA;AACb,CAAC;AAHD,8CAGC;AAED,SAAgB,WAAW,CAAC,GAAY;IAC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EAAE,CAAC,IAAI,CAAC,WAAW;QAAE,OAAM;IAE/C,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IACrC,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IAEnC,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,CACb,MAAM,CAAC,OAAO,CAAC,CAAC,IAAe,EAAE,CAAS,EAAE,EAAE;QAC5C,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAC1B;YACE,OAAO;YACP,UAAU,EAAE,CAAC;YACb,aAAa,EAAE,IAAI;SACpB,EACD,QAAQ,CACT,CAAA;QACD,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,KAAK,OAAO,QAAQ,EAAE,CAAC,CAAA;QAC7C,MAAM,MAAM,GAAG,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACxD,+FAA+F;QAC/F,yFAAyF;QACzF,IAAI,CAAC,MAAM;YAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,CAAC,CAAA;IACjC,CAAC,CAAC,CACH,CAAA;IAED,GAAG,CAAC,MAAM,CACR,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CACtB,CAAA;AACH,CAAC;AAjCD,sCAiCC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const dynamic_1 = require("./dynamic");
const next_1 = require("./next");
const unevaluated_1 = require("./unevaluated");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft2020Vocabularies = [
    dynamic_1.default,
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(true),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
    next_1.default,
    unevaluated_1.default,
];
exports.default = draft2020Vocabularies;
//# sourceMappingURL=draft2020.js.map{"version":3,"file":"draft2020.js","sourceRoot":"","sources":["../../lib/vocabularies/draft2020.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,uCAAyC;AACzC,iCAAmC;AACnC,+CAAiD;AACjD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,qBAAqB,GAAiB;IAC1C,iBAAiB;IACjB,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,EAAC,IAAI,CAAC;IAC7B,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;IACjB,cAAc;IACd,qBAAqB;CACtB,CAAA;AAED,kBAAe,qBAAqB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
];
exports.default = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map{"version":3,"file":"draft7.js","sourceRoot":"","sources":["../../lib/vocabularies/draft7.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,kBAAkB,GAAiB;IACvC,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,GAAE;IACzB,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;CAClB,CAAA;AAED,kBAAe,kBAAkB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/vocabularies/errors.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples",
];
exports.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema",
];
//# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../lib/vocabularies/metadata.ts"],"names":[],"mappings":";;;AAEa,QAAA,kBAAkB,GAAe;IAC5C,OAAO;IACP,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU;IACV,WAAW;IACX,UAAU;CACX,CAAA;AAEY,QAAA,iBAAiB,GAAe;IAC3C,kBAAkB;IAClB,iBAAiB;IACjB,eAAe;CAChB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependentRequired_1 = require("./validation/dependentRequired");
const dependentSchemas_1 = require("./applicator/dependentSchemas");
const limitContains_1 = require("./validation/limitContains");
const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
exports.default = next;
//# sourceMappingURL=next.js.map{"version":3,"file":"next.js","sourceRoot":"","sources":["../../lib/vocabularies/next.ts"],"names":[],"mappings":";;AACA,sEAA8D;AAC9D,oEAA4D;AAC5D,8DAAsD;AAEtD,MAAM,IAAI,GAAe,CAAC,2BAAiB,EAAE,0BAAgB,EAAE,uBAAa,CAAC,CAAA;AAE7E,kBAAe,IAAI,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || (schema && typeof schema == "object")) {
            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        }
        else {
            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=const.js.map{"version":3,"file":"const.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/const.ts"],"names":[],"mappings":";;AAEA,mDAAuC;AACvC,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,2BAA2B;IACpC,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,UAAU,GAAG;CAC3D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAClD,IAAI,KAAK,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,EAAE,CAAC;YACnD,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,IAAI,IAAI,KAAK,UAAU,GAAG,CAAC,CAAA;QACnE,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,QAAQ,IAAI,EAAE,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("../applicator/dependencies");
const def = {
    keyword: "dependentRequired",
    type: "object",
    schemaType: "object",
    error: dependencies_1.error,
    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentRequired.js.map{"version":3,"file":"dependentRequired.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/dependentRequired.ts"],"names":[],"mappings":";;AACA,6DAKmC;AAQnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,oBAAK;IACL,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,mCAAoB,EAAC,GAAG,CAAC;CACzC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
            throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
        let valid;
        if (useLoop || $data) {
            valid = gen.let("valid");
            cxt.block$data(valid, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            const vSchema = gen.const("vSchema", schemaCode);
            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.assign(valid, false);
            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i) {
            const sch = schema[i];
            return typeof sch === "object" && sch !== null
                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
                : (0, codegen_1._) `${data} === ${sch}`;
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources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,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;YAChD,KAAK,GAAG,IAAA,YAAE,EAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,EAAW,EAAE,CAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9E,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAEf,SAAS,QAAQ;YACf,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;YACxB,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,UAAkB,EAAE,CAAC,CAAC,EAAE,EAAE,CACvC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,EAAE,IAAI,IAAI,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC,CAC7E,CAAA;QACH,CAAC;QAED,SAAS,SAAS,CAAC,OAAa,EAAE,CAAS;YACzC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;YACrB,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI;gBAC5C,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,EAAE,IAAI,IAAI,KAAK,OAAO,IAAI,CAAC,IAAI;gBAC3C,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,QAAQ,GAAG,EAAE,CAAA;QAC3B,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const limitNumber_1 = require("./limitNumber");
const multipleOf_1 = require("./multipleOf");
const limitLength_1 = require("./limitLength");
const pattern_1 = require("./pattern");
const limitProperties_1 = require("./limitProperties");
const required_1 = require("./required");
const limitItems_1 = require("./limitItems");
const uniqueItems_1 = require("./uniqueItems");
const const_1 = require("./const");
const enum_1 = require("./enum");
const validation = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default,
];
exports.default = validation;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/index.ts"],"names":[],"mappings":";;AACA,+CAA2D;AAC3D,6CAAwD;AACxD,+CAAuC;AACvC,uCAA+C;AAC/C,uDAA+C;AAC/C,yCAAkD;AAClD,6CAAqC;AACrC,+CAA2D;AAC3D,mCAAgD;AAChD,iCAA6C;AAE7C,MAAM,UAAU,GAAe;IAC7B,SAAS;IACT,qBAAW;IACX,oBAAU;IACV,SAAS;IACT,qBAAW;IACX,iBAAO;IACP,SAAS;IACT,yBAAe;IACf,kBAAQ;IACR,QAAQ;IACR,oBAAU;IACV,qBAAW;IACX,MAAM;IACN,EAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAC;IAClD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;IAC5C,eAAY;IACZ,cAAW;CACZ,CAAA;AAED,kBAAe,UAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["maxContains", "minContains"],
    type: "array",
    schemaType: "number",
    code({ keyword, parentSchema, it }) {
        if (parentSchema.contains === undefined) {
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=limitContains.js.map{"version":3,"file":"limitContains.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitContains.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC;IACvC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACxC,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,iCAAiC,CAAC,CAAA;QACnE,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitItems.js.map{"version":3,"file":"limitItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitItems.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACtD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,QAAQ,CAAA;IAC5D,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;IACjC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAC/D,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACtD,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const ucs2length_1 = require("../../runtime/ucs2length");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitLength.js.map{"version":3,"file":"limitLength.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitLength.ts"],"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});
const codegen_1 = require("../../compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
    },
};
exports.default = def;
//# sourceMappingURL=limitNumber.js.map{"version":3,"file":"limitNumber.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitNumber.ts"],"names":[],"mappings":";;AAEA,mDAA6D;AAE7D,MAAM,GAAG,GAAG,mBAAS,CAAA;AAMrB,MAAM,IAAI,GAA4D;IACpE,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IACzD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAC1D,CAAA;AAQD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,WAAW,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,IAAI,UAAU,EAAE;IAC5F,MAAM,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAChC,IAAA,WAAC,EAAA,gBAAgB,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,YAAY,UAAU,GAAG;CACvE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;IAC1B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,IAAI,CAAC,OAAc,CAAC,CAAC,IAAI,IAAI,UAAU,aAAa,IAAI,GAAG,CAAC,CAAA;IACxF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitProperties.js.map{"version":3,"file":"limitProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitProperties.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QAC3D,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC;IAC3C,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QACpE,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,eAAe,IAAI,YAAY,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACnE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec
            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
            : (0, codegen_1._) `${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
    },
};
exports.default = def;
//# sourceMappingURL=multipleOf.js.map{"version":3,"file":"multipleOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/multipleOf.ts"],"names":[],"mappings":";;AAEA,mDAA4C;AAQ5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,EAAE;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,gBAAgB,UAAU,GAAG;CACzD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACvC,sEAAsE;QACtE,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAA;QACxC,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,MAAM,OAAO,GAAG,IAAI;YAClB,CAAC,CAAC,IAAA,WAAC,EAAA,uBAAuB,GAAG,OAAO,GAAG,UAAU,IAAI,EAAE;YACvD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,iBAAiB,GAAG,GAAG,CAAA;QAClC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,UAAU,cAAc,GAAG,MAAM,IAAI,IAAI,UAAU,KAAK,OAAO,IAAI,CAAC,CAAA;IACzF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
            const { regExp } = it.opts.code;
            const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);
            const valid = gen.let("valid");
            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
            cxt.fail$data((0, codegen_1._) `!${valid}`);
        }
        else {
            const regExp = (0, code_1.usePattern)(cxt, schema);
            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=pattern.js.map{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/pattern.ts"],"names":[],"mappings":";;AAEA,kCAAkC;AAClC,6CAA0C;AAC1C,mDAA4C;AAI5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,GAAG;IAClE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,aAAa,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AC,CAAA;QAC5C,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
            return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
            allErrorsMode();
        else
            exitOnErrorMode();
        if (opts.strictRequired) {
            const props = cxt.parentSchema.properties;
            const { definedProperties } = cxt.it;
            for (const requiredKey of schema) {
                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
                }
            }
        }
        function allErrorsMode() {
            if (useLoop || $data) {
                cxt.block$data(codegen_1.nil, loopAllRequired);
            }
            else {
                for (const prop of schema) {
                    (0, code_1.checkReportMissingProp)(cxt, prop);
                }
            }
        }
        function exitOnErrorMode() {
            const missing = gen.let("missing");
            if (useLoop || $data) {
                const valid = gen.let("valid", true);
                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
                cxt.ok(valid);
            }
            else {
                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
                (0, code_1.reportMissingProp)(cxt, missing);
                gen.else();
            }
        }
        function loopAllRequired() {
            gen.forOf("prop", schemaCode, (prop) => {
                cxt.setParams({ missingProperty: prop });
                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
            });
        }
        function loopUntilMissing(missing, valid) {
            cxt.setParams({ missingProperty: missing });
            gen.forOf(missing, schemaCode, () => {
                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
                gen.if((0, codegen_1.not)(valid), () => {
                    cxt.error();
                    gen.break();
                });
            }, codegen_1.nil);
        }
    },
};
exports.default = def;
//# sourceMappingURL=required.js.map{"version":3,"file":"required.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/required.ts"],"names":[],"mappings":";;AAEA,kCAMgB;AAChB,mDAAkE;AAClE,6CAAkD;AAQlD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,gCAAgC,eAAe,GAAG;IAC/F,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,qBAAqB,eAAe,GAAG;CAClF,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EAAC,IAAI,EAAC,GAAG,EAAE,CAAA;QACjB,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAM;QACzC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,CAAA;QAClD,IAAI,EAAE,CAAC,SAAS;YAAE,aAAa,EAAE,CAAA;;YAC5B,eAAe,EAAE,CAAA;QAEtB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM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exports, "__esModule", { value: true });
const dataType_1 = require("../../compile/validate/dataType");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
            return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
            const j = gen.let("j");
            cxt.setParams({ i, j });
            gen.assign(valid, true);
            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        function canOptimize() {
            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i, j) {
            const item = gen.name("item");
            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
            const indices = gen.const("indices", (0, codegen_1._) `{}`);
            gen.for((0, codegen_1._) `;${i}--;`, () => {
                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
                gen.if(wrongType, (0, codegen_1._) `continue`);
                if (itemTypes.length > 1)
                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
                gen
                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
                    cxt.error();
                    gen.assign(valid, false).break();
                })
                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
            });
        }
        function loopN2(i, j) {
            const eql = (0, util_1.useFunc)(gen, equal_1.default);
            const outer = gen.name("outer");
            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
                cxt.error();
                gen.assign(valid, false).break(outer);
            })));
        }
    },
};
exports.default = def;
//# sourceMappingURL=uniqueItems.js.map{"version":3,"file":"uniqueItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/uniqueItems.ts"],"names":[],"mappings":";;AAEA,8DAAwF;AACxF,mDAAkD;AAClD,6CAA0C;AAC1C,+CAAuC;AAQvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,CAAC,EAAE,CAAC,EAAC,EAAC,EAAE,EAAE,CAC5B,IAAA,aAAG,EAAA,2CAA2C,CAAC,QAAQ,CAAC,iBAAiB;IAC3E,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,CAAC,EAAE,CAAC,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,OAAO,CAAC,QAAQ,CAAC,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,SAAS;IACrB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACpE,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM;YAAE,OAAM;QAC7B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QAC9B,MAAM,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,yBAAc,EAAC,Y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AAE,GAAG,EAAE,CACrC,GAAG,CAAC,GAAG,CAAC,IAAA,WAAC,EAAA,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CACpC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,IAAI,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE;gBACnD,GAAG,CAAC,KAAK,EAAE,CAAA;gBACX,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC,CAAC,CACH,CACF,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unevaluatedProperties_1 = require("./unevaluatedProperties");
const unevaluatedItems_1 = require("./unevaluatedItems");
const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
exports.default = unevaluated;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/index.ts"],"names":[],"mappings":";;AACA,mEAA2D;AAC3D,yDAAiD;AAEjD,MAAM,WAAW,GAAe,CAAC,+BAAqB,EAAE,0BAAgB,CAAC,CAAA;AAEzE,kBAAe,WAAW,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "unevaluatedItems",
    type: "array",
    schemaType: ["boolean", "object"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        const items = it.items || 0;
        if (items === true)
            return;
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        if (schema === false) {
            cxt.setParams({ len: items });
            cxt.fail((0, codegen_1._) `${len} > ${items}`);
        }
        else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`);
            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
            cxt.ok(valid);
        }
        it.items = true;
        function validateItems(valid, from) {
            gen.forRange("i", from, len, (i) => {
                cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
                if (!it.allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedItems.js.map{"version":3,"file":"unevaluatedItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedItems.ts"],"names":[],"mappings":";;AAOA,mDAAuD;AACvD,6CAA0D;AAI1D,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC,CAAA;QAC3B,IAAI,KAAK,KAAK,IAAI;YAAE,OAAM;QAC1B,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAA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Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const names_1 = require("../../compile/names");
const error = {
    message: "must NOT have unevaluated properties",
    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,
};
const def = {
    keyword: "unevaluatedProperties",
    type: "object",
    schemaType: ["boolean", "object"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, props } = it;
        if (props instanceof codegen_1.Name) {
            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
        }
        else if (props !== true) {
            gen.forIn("key", data, (key) => props === undefined
                ? unevaluatedPropCode(key)
                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
        }
        it.props = true;
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function unevaluatedPropCode(key) {
            if (schema === false) {
                cxt.setParams({ unevaluatedProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (!(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                cxt.subschema({
                    keyword: "unevaluatedProperties",
                    dataProp: key,
                    dataPropType: util_1.Type.Str,
                }, valid);
                if (!allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
        }
        function unevaluatedDynamic(evaluatedProps, key) {
            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;
        }
        function unevaluatedStatic(evaluatedProps, key) {
            const ps = [];
            for (const p in evaluatedProps) {
                if (evaluatedProps[p] === true)
                    ps.push((0, codegen_1._) `${key} !== ${p}`);
            }
            return (0, codegen_1.and)(...ps);
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedProperties.js.map{"version":3,"file":"unevaluatedProperties.js","sourceRo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B,CAAC,cAAsC,EAAE,GAAS;YAC1E,MAAM,EAAE,GAAW,EAAE,CAAA;YACrB,KAAK,MAAM,CAAC,IAAI,cAAc,EAAE,CAAC;gBAC/B,IAAI,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI;oBAAE,EAAE,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAA;YAC7D,CAAC;YACD,OAAO,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,CAAA;QACnB,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const types_1 = require("../discriminator/types");
const error = {
    message: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? params.discrError === types_1.DiscrError.Tag
                ? `tag "${schema}" must be string`
                : `value of tag "${schema}" must be in mapping`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "discriminator",
    schemaType: "string",
    implements: ["mapping"],
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, parentSchema } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        gen.if(cond);
        validateDiscriminator();
        gen.elseIf((0, codegen_1.not)(valid));
        cxt.error();
        gen.endIf();
        cxt.ok(valid);
        function validateDiscriminator() {
            const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`);
            gen.if((0, codegen_1._) `${tag} === undefined`);
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag });
            gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`);
            validateMapping(tag);
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema });
            gen.endIf();
        }
        function validateMapping(tag) {
            gen.if(false);
            for (const tagValue in parentSchema.mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(tagValue));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            cxt.subschema({
                keyword: "mapping",
                schemaProp,
                jtdDiscriminator: schema,
            }, _valid);
            return _valid;
        }
    },
};
exports.default = def;
//# sourceMappingURL=discriminator.js.map{"version":3,"file":"discriminator.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/discriminator.ts"],"names":[],"mappings":";;AAEA,mDAA+D;AAC/D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AACxE,kDAAgE;AAOhE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,MAAM,EAAC,MAAM,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAC5B,OAAO,MAAM,CAAC,UAAU;YACtB,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,kBAAU,CAAC,GAAG;gBACpC,CAAC,CAAC,QAAQ,MAAM,kBAAkB;gBAClC,CAAC,CAAC,iBAAiB,MAAM,sBAAsB;YACjD,CAAC,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACrC,CAAC;IACD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE;QACd,MAAM,EAAC,MAAM,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAC5B,OAAO,MAAM,CAAC,UAAU;YACtB,CAAC,CAAC,IAAA,WAAC,EAAA,WAAW,MAAM,CAAC,UAAU,UAAU,MAAM,eAAe,MAAM,CA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CAAC,IAAI,EAAE,CAAA;YACV,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,EAAC,UAAU,EAAE,kBAAU,CAAC,GAAG,EAAE,GAAG,EAAC,EAAE,EAAC,YAAY,EAAE,MAAM,EAAC,CAAC,CAAA;YAC3E,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,eAAe,CAAC,GAAS;YAChC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;gBAC5C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,QAAQ,EAAE,CAAC,CAAA;gBACrC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAA;YAC7C,CAAC;YACD,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,GAAG,CAAC,KAAK,CACP,KAAK,EACL,EAAC,UAAU,EAAE,kBAAU,CAAC,OAAO,EAAE,GAAG,EAAC,EACrC,EAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAC,CAClE,CAAA;YACD,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,cAAc,CAAC,UAAkB;YACxC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAChC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,SAAS;gBAClB,UAAU;gBACV,gBAAgB,EAAE,MAAM;aACzB,EACD,MAAM,CACP,CAAA;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "elements",
    schemaType: "object",
    error: (0, error_1.typeError)("array"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const [valid] = (0, nullable_1.checkNullable)(cxt);
        gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error()));
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=elements.js.map{"version":3,"file":"elements.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/elements.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AACpD,kCAAqC;AACrC,mDAA4C;AAC5C,yCAAwC;AACxC,yCAAwC;AACxC,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,OAAO,CAAC;IACzB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CACtB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,iBAAiB,IAAI,GAAG,EACzB,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,EAC3C,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
        if (schema.length === 0)
            throw new Error("enum must have non-empty array");
        if (schema.length !== new Set(schema).size)
            throw new Error("enum items must be unique");
        let valid;
        const isString = (0, codegen_1._) `typeof ${data} == "string"`;
        if (schema.length >= it.opts.loopEnum) {
            let cond;
            [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString);
            gen.if(cond, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`)));
            if (parentSchema.nullable)
                valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid);
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break()));
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/enum.ts"],"names":[],"mappings":";;AAEA,mDAAsD;AACtD,yCAAwC;AACxC,yCAAwC;AAIxC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU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,KAAK,GAAG,IAAA,YAAE,EAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,KAAK,CAAC,CAAA;QACnE,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAEf,SAAS,QAAQ;YACf,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,WAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CACxC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,IAAI,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAC1D,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0;
const codegen_1 = require("../../compile/codegen");
function typeError(t) {
    return {
        message: (cxt) => typeErrorMessage(cxt, t),
        params: (cxt) => typeErrorParams(cxt, t),
    };
}
exports.typeError = typeError;
function typeErrorMessage({ parentSchema }, t) {
    return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`;
}
exports.typeErrorMessage = typeErrorMessage;
function typeErrorParams({ parentSchema }, t) {
    return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`;
}
exports.typeErrorParams = typeErrorParams;
//# sourceMappingURL=error.js.map{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/error.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAQ7C,SAAgB,SAAS,CAAC,CAAS;IACjC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;KACzC,CAAA;AACH,CAAC;AALD,8BAKC;AAED,SAAgB,gBAAgB,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACzE,OAAO,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAA;AACzE,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACxE,OAAO,IAAA,WAAC,EAAA,UAAU,CAAC,eAAe,CAAC,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,CAAA,GAAG,CAAA;AAC/D,CAAC;AAFD,0CAEC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ref_1 = require("./ref");
const type_1 = require("./type");
const enum_1 = require("./enum");
const elements_1 = require("./elements");
const properties_1 = require("./properties");
const optionalProperties_1 = require("./optionalProperties");
const discriminator_1 = require("./discriminator");
const values_1 = require("./values");
const union_1 = require("./union");
const metadata_1 = require("./metadata");
const jtdVocabulary = [
    "definitions",
    ref_1.default,
    type_1.default,
    enum_1.default,
    elements_1.default,
    properties_1.default,
    optionalProperties_1.default,
    discriminator_1.default,
    values_1.default,
    union_1.default,
    metadata_1.default,
    { keyword: "additionalProperties", schemaType: "boolean" },
    { keyword: "nullable", schemaType: "boolean" },
];
exports.default = jtdVocabulary;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/index.ts"],"names":[],"mappings":";;AACA,+BAA8B;AAC9B,iCAAgD;AAChD,iCAAgD;AAChD,yCAAqD;AACrD,6CAA2D;AAC3D,6DAAqD;AACrD,mDAAoE;AACpE,qCAA+C;AAC/C,mCAA2B;AAC3B,yCAAiC;AAEjC,MAAM,aAAa,GAAe;IAChC,aAAa;IACb,aAAU;IACV,cAAW;IACX,cAAW;IACX,kBAAQ;IACR,oBAAU;IACV,4BAAkB;IAClB,uBAAa;IACb,gBAAM;IACN,eAAK;IACL,kBAAQ;IACR,EAAC,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,SAAS,EAAC;IACxD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;CAC7C,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkMetadata = void 0;
const util_1 = require("../../compile/util");
const def = {
    keyword: "metadata",
    schemaType: "object",
    code(cxt) {
        checkMetadata(cxt);
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid);
        cxt.ok(valid);
    },
};
function checkMetadata({ it, keyword }, metadata) {
    if (it.jtdMetadata !== metadata) {
        throw new Error(`JTD: "${keyword}" cannot be used in this schema location`);
    }
}
exports.checkMetadata = checkMetadata;
exports.default = def;
//# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/metadata.ts"],"names":[],"mappings":";;;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,aAAa,CAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;QAC9D,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAAC,EAAC,EAAE,EAAE,OAAO,EAAa,EAAE,QAAkB;IACzE,IAAI,EAAE,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,SAAS,OAAO,0CAA0C,CAAC,CAAA;IAC7E,CAAC;AACH,CAAC;AAJD,sCAIC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkNullableObject = exports.checkNullable = void 0;
const codegen_1 = require("../../compile/codegen");
function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) {
    const valid = gen.name("valid");
    if (parentSchema.nullable) {
        gen.let(valid, (0, codegen_1._) `${data} === null`);
        cond = (0, codegen_1.not)(valid);
    }
    else {
        gen.let(valid, false);
    }
    return [valid, cond];
}
exports.checkNullable = checkNullable;
function checkNullableObject(cxt, cond) {
    const [valid, cond_] = checkNullable(cxt, cond);
    return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`];
}
exports.checkNullableObject = checkNullableObject;
//# sourceMappingURL=nullable.js.map{"version":3,"file":"nullable.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/nullable.ts"],"names":[],"mappings":";;;AACA,mDAA6D;AAE7D,SAAgB,aAAa,CAC3B,EAAC,GAAG,EAAE,IAAI,EAAE,YAAY,EAAa,EACrC,OAAa,aAAG;IAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;QACnC,IAAI,GAAG,IAAA,aAAG,EAAC,KAAK,CAAC,CAAA;IACnB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAZD,sCAYC;AAED,SAAgB,mBAAmB,CAAC,GAAe,EAAE,IAAU;IAC7D,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC/C,OAAO,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,KAAK,cAAc,GAAG,CAAC,IAAI,kCAAkC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAA;AAC9F,CAAC;AAHD,kDAGC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const properties_1 = require("./properties");
const def = {
    keyword: "optionalProperties",
    schemaType: "object",
    error: properties_1.error,
    code(cxt) {
        if (cxt.parentSchema.properties)
            return;
        (0, properties_1.validateProperties)(cxt);
    },
};
exports.default = def;
//# sourceMappingURL=optionalProperties.js.map{"version":3,"file":"optionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/optionalProperties.ts"],"names":[],"mappings":";;AAEA,6CAAsD;AAEtD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,oBAAoB;IAC7B,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,kBAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU;YAAE,OAAM;QACvC,IAAA,+BAAkB,EAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperties = exports.error = void 0;
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
var PropError;
(function (PropError) {
    PropError["Additional"] = "additional";
    PropError["Missing"] = "missing";
})(PropError || (PropError = {}));
exports.error = {
    message: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? "must NOT have additional properties"
                : `must have property '${params.missingProperty}'`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
                : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "properties",
    schemaType: "object",
    error: exports.error,
    code: validateProperties,
};
// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }
function validateProperties(cxt) {
    (0, metadata_1.checkMetadata)(cxt);
    const { gen, data, parentSchema, it } = cxt;
    const { additionalProperties, nullable } = parentSchema;
    if (it.jtdDiscriminator && nullable)
        throw new Error("JTD: nullable inside discriminator mapping");
    if (commonProperties()) {
        throw new Error("JTD: properties and optionalProperties have common members");
    }
    const [allProps, properties] = schemaProperties("properties");
    const [allOptProps, optProperties] = schemaProperties("optionalProperties");
    if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
        return;
    }
    const [valid, cond] = it.jtdDiscriminator === undefined
        ? (0, nullable_1.checkNullableObject)(cxt, data)
        : [gen.let("valid", false), true];
    gen.if(cond, () => gen.assign(valid, true).block(() => {
        validateProps(properties, "properties", true);
        validateProps(optProperties, "optionalProperties");
        if (!additionalProperties)
            validateAdditional();
    }));
    cxt.pass(valid);
    function commonProperties() {
        const props = parentSchema.properties;
        const optProps = parentSchema.optionalProperties;
        if (!(props && optProps))
            return false;
        for (const p in props) {
            if (Object.prototype.hasOwnProperty.call(optProps, p))
                return true;
        }
        return false;
    }
    function schemaProperties(keyword) {
        const schema = parentSchema[keyword];
        const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
        if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
            throw new Error(`JTD: discriminator tag used in ${keyword}`);
        }
        const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        return [allPs, ps];
    }
    function validateProps(props, keyword, required) {
        const _valid = gen.var("valid");
        for (const prop of props) {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop));
            cxt.ok(_valid);
        }
        function missingProperty(prop) {
            if (required) {
                gen.assign(_valid, false);
                cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop });
            }
            else {
                gen.assign(_valid, true);
            }
        }
    }
    function applyPropertySchema(prop, keyword, _valid) {
        cxt.subschema({
            keyword,
            schemaProp: prop,
            dataProp: prop,
        }, _valid);
    }
    function validateAdditional() {
        gen.forIn("key", data, (key) => {
            const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator);
            const addOptProp = isAdditional(key, allOptProps, "optionalProperties");
            const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp);
            gen.if(extra, () => {
                if (it.opts.removeAdditional) {
                    gen.code((0, codegen_1._) `delete ${data}[${key}]`);
                }
                else {
                    cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true });
                    if (!it.opts.allErrors)
                        gen.break();
                }
            });
        });
    }
    function isAdditional(key, props, keyword, jtdDiscriminator) {
        let additional;
        if (props.length > 8) {
            // TODO maybe an option instead of hard-coded 8?
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword);
            additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key));
            if (jtdDiscriminator !== undefined) {
                additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`);
            }
        }
        else if (props.length || jtdDiscriminator !== undefined) {
            const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props);
            additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`));
        }
        else {
            additional = true;
        }
        return additional;
    }
}
exports.validateProperties = validateProperties;
exports.default = def;
//# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/properties.ts"],"names":[],"mappings":";;;AAOA,kCAA0E;AAC1E,6CAAoE;AACpE,mDAA6D;AAC7D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AAExE,IAAK,SAGJ;AAHD,WAAK,SAAS;IACZ,sCAAyB,CAAA;IACzB,gCAAmB,CAAA;AACrB,CAAC,EAHI,SAAS,KAAT,SAAS,QAGb;AAWY,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,MAAM,EAAC,MAAM,EAAC,GAAG,GAAG,CAAA;QACpB,OAAO,MAAM,CAAC,SAAS;YACrB,CAAC,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,UAAU;gBACzC,CAAC,CAAC,qCAAqC;gBACvC,CAAC,CAAC,uBAAuB,MAAM,CAAC,eAAe,GAAG;YACpD,CAAC,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACrC,CAAC;IACD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE;QACd,MAAM,EAAC,MAAM,EAAC,GAAG,GAAG,CAAA;QACpB,OAAO,MAAM,CAAC,SAAS;YACrB,CAAC,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,UAAU;gBACzC,CAAC,CAAC,IAAA,WAAC,EAAA,WAAW,MAAM,CAAC,SAAS,yBAAyB,MAAM,CAAC,kBAAkB,GAAG;gBACnF,CAAC,CAAC,IAAA,WAAC,EAAA,WAAW,MAAM,CAAC,SAAS,sBAAsB,MAAM,CAAC,eAAe,GAAG;YAC/E,CAAC,CAAC,IAAA,uBAAe,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;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,CAAC,EAAE,OAAO,CAAC,CAAA;YACtE,UAAU,GAAG,IAAA,aAAG,EAAC,IAAA,oBAAa,EAAC,GAAG,EAAE,WAAmB,EAAE,GAAG,CAAC,CAAC,CAAA;YAC9D,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;gBACnC,UAAU,GAAG,IAAA,aAAG,EAAC,UAAU,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,gBAAgB,EAAE,CAAC,CAAA;YACjE,CAAC;QACH,CAAC;aAAM,IAAI,KAAK,CAAC,MAAM,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;YAC1D,MAAM,EAAE,GAAG,gBAAgB,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACpF,UAAU,GAAG,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,IAAI,CAAA;QACnB,CAAC;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;AACH,CAAC;AA1HD,gDA0HC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasRef = void 0;
const compile_1 = require("../../compile");
const codegen_1 = require("../../compile/codegen");
const ref_error_1 = require("../../compile/ref_error");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const metadata_1 = require("./metadata");
const def = {
    keyword: "ref",
    schemaType: "string",
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema: ref, parentSchema, it } = cxt;
        const { schemaEnv: { root }, } = it;
        const valid = gen.name("valid");
        if (parentSchema.nullable) {
            gen.var(valid, (0, codegen_1._) `${data} === null`);
            gen.if((0, codegen_1.not)(valid), validateJtdRef);
        }
        else {
            gen.var(valid, false);
            validateJtdRef();
        }
        cxt.ok(valid);
        function validateJtdRef() {
            var _a;
            const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
            if (!refSchema) {
                throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
            }
            if (hasRef(refSchema) || !it.opts.inlineRefs)
                callValidate(refSchema);
            else
                inlineRefSchema(refSchema);
        }
        function callValidate(schema) {
            const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
            const v = (0, ref_1.getValidate)(cxt, sch);
            const errsCount = gen.const("_errs", names_1.default.errors);
            (0, ref_1.callRef)(cxt, v, sch, sch.$async);
            gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        }
        function inlineRefSchema(schema) {
            const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
            cxt.subschema({
                schema,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: `/definitions/${ref}`,
            }, valid);
        }
    },
};
function hasRef(schema) {
    for (const key in schema) {
        let sch;
        if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
            return true;
    }
    return false;
}
exports.hasRef = hasRef;
exports.default = def;
//# sourceMappingURL=ref.js.map{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/ref.ts"],"names":[],"mappings":";;;AAEA,2CAAsD;AACtD,mDAA4D;AAC5D,uDAAqD;AACrD,+CAAmC;AACnC,qCAAgD;AAChD,yCAAwC;AAExC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,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AAND,wBAMC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intRange = void 0;
const codegen_1 = require("../../compile/codegen");
const timestamp_1 = require("../../runtime/timestamp");
const util_1 = require("../../compile/util");
const metadata_1 = require("./metadata");
const error_1 = require("./error");
exports.intRange = {
    int8: [-128, 127, 3],
    uint8: [0, 255, 3],
    int16: [-32768, 32767, 5],
    uint16: [0, 65535, 5],
    int32: [-2147483648, 2147483647, 10],
    uint32: [0, 4294967295, 10],
};
const error = {
    message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
    params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
};
function timestampCode(cxt) {
    const { gen, data, it } = cxt;
    const { timestamp, allowDate } = it.opts;
    if (timestamp === "date")
        return (0, codegen_1._) `${data} instanceof Date `;
    const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
    const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
    const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
    return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
}
const def = {
    keyword: "type",
    schemaType: "string",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { data, schema, parentSchema, it } = cxt;
        let cond;
        switch (schema) {
            case "boolean":
            case "string":
                cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
                break;
            case "timestamp": {
                cond = timestampCode(cxt);
                break;
            }
            case "float32":
            case "float64":
                cond = (0, codegen_1._) `typeof ${data} == "number"`;
                break;
            default: {
                const sch = schema;
                cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
                if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
                    if (sch === "uint32")
                        cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
                }
                else {
                    const [min, max] = exports.intRange[sch];
                    cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
                }
            }
        }
        cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
    },
};
exports.default = def;
//# sourceMappingURL=type.js.map{"version":3,"file":"type.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/type.ts"],"names":[],"mappings":";;;AAEA,mDAAsD;AACtD,uDAAoD;AACpD,6CAA0C;AAC1C,yCAAwC;AACxC,mCAAwE;AAM3D,QAAA,QAAQ,GAA+C;IAClE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;IACpB,KAAK,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IAClB,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;IACrB,KAAK,EAAE,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,CAAC;IACpC,MAAM,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,CAAC;CAC5B,CAAA;AAID,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;IACnD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAe,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAClD,CAAA;AAED,SAAS,aAAa,CAAC,GAAe;IACpC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,MAAM,EAAC,SAAS,EAAE,SAAS,EAAC,GAAG,EAAE,CAAC,IAAI,CAAA;IACtC,IAAI,SAAS,KAAK,MAAM;QAAE,OAAO,IAAA,WAAC,EAAA,GAAG,IAAI,mBAAmB,CAAA;IAC5D,MAAM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gBAC3E,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,GAAG,KAAK,OAAO,IAAI,GAAG,KAAK,QAAQ,CAAC,EAAE,CAAC;oBACjE,IAAI,GAAG,KAAK,QAAQ;wBAAE,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,OAAO,CAAA;gBACzD,CAAC;qBAAM,CAAC;oBACN,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,gBAAQ,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,OAAO,GAAG,OAAO,IAAI,OAAO,GAAG,EAAE,CAAA;gBAC7D,CAAC;YACH,CAAC;QACH,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAA,YAAE,EAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACxE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "union",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in union" },
};
exports.default = def;
//# sourceMappingURL=union.js.map{"version":3,"file":"union.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/union.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "values",
    schemaType: "object",
    error: (0, error_1.typeError)("object"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error());
        }
        else {
            gen.if(cond);
            gen.assign(valid, validateMap());
            gen.elseIf((0, codegen_1.not)(valid));
            cxt.error();
            gen.endIf();
        }
        cxt.ok(valid);
        function validateMap() {
            const _valid = gen.name("valid");
            if (it.allErrors) {
                const validMap = gen.let("valid", true);
                validateValues(() => gen.assign(validMap, false));
                return validMap;
            }
            gen.var(_valid, true);
            validateValues(() => gen.break());
            return _valid;
            function validateValues(notValid) {
                gen.forIn("key", data, (key) => {
                    cxt.subschema({
                        keyword: "values",
                        dataProp: key,
                        dataPropType: util_1.Type.Str,
                    }, _valid);
                    gen.if((0, codegen_1.not)(_valid), notValid);
                });
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=values.js.map{"version":3,"file":"values.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/values.ts"],"names":[],"mappings":";;AAEA,6CAA0D;AAC1D,mDAAmD;AACnD,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,QAAQ;IACjB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,QAAQ,CAAC;IAC1B,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,IAAA,8BAAmB,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AAS,CACX;wBACE,OAAO,EAAE,QAAQ;wBACjB,QAAQ,EAAE,GAAG;wBACb,YAAY,EAAE,WAAI,CAAC,GAAG;qBACvB,EACD,MAAM,CACP,CAAA;oBACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAA;gBAC/B,CAAC,CAAC,CAAA;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self } = it;
        if (!opts.validateFormats)
            return;
        if ($data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
            const fType = gen.let("fType");
            const format = gen.let("format");
            // TODO simplify
            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
            function unknownFmt() {
                if (opts.strictSchema === false)
                    return codegen_1.nil;
                return (0, codegen_1._) `${schemaCode} && !${format}`;
            }
            function invalidFmt() {
                const callFormat = schemaEnv.$async
                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
                    : (0, codegen_1._) `${format}(${data})`;
                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
            }
        }
        function validateFormat() {
            const formatDef = self.formats[schema];
            if (!formatDef) {
                unknownFormat();
                return;
            }
            if (formatDef === true)
                return;
            const [fmtType, format, fmtRef] = getFormat(formatDef);
            if (fmtType === ruleType)
                cxt.pass(validCondition());
            function unknownFormat() {
                if (opts.strictSchema === false) {
                    self.logger.warn(unknownMsg());
                    return;
                }
                throw new Error(unknownMsg());
                function unknownMsg() {
                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
                }
            }
            function getFormat(fmtDef) {
                const code = fmtDef instanceof RegExp
                    ? (0, codegen_1.regexpCode)(fmtDef)
                    : opts.code.formats
                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
                        : undefined;
                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
                }
                return ["string", fmtDef, fmt];
            }
            function validCondition() {
                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
                    if (!schemaEnv.$async)
                        throw new Error("async format in sync schema");
                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
                }
                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=format.js.map{"version":3,"file":"format.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/format.ts"],"names":[],"mappings":";;AASA,mDAAoF;AAapF,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,sBAAsB,UAAU,GAAG;I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C,CAAC;YAED,SAAS,cAAc;gBACrB,IAAI,OAAO,SAAS,IAAI,QAAQ,IAAI,CAAC,CAAC,SAAS,YAAY,MAAM,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,CAAC;oBACtF,IAAI,CAAC,SAAS,CAAC,MAAM;wBAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;oBACrE,OAAO,IAAA,WAAC,EAAA,SAAS,MAAM,IAAI,IAAI,GAAG,CAAA;gBACpC,CAAC;gBACD,OAAO,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,SAAS,IAAI,GAAG,CAAA;YACzF,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const format_1 = require("./format");
const format = [format_1.default];
exports.default = format;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/index.ts"],"names":[],"mappings":";;AACA,qCAAoC;AAEpC,MAAM,MAAM,GAAe,CAAC,gBAAa,CAAC,CAAA;AAE1C,kBAAe,MAAM,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicAnchor = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicAnchor",
    schemaType: "string",
    code: (cxt) => dynamicAnchor(cxt, cxt.schema),
};
function dynamicAnchor(cxt, anchor) {
    const { gen, it } = cxt;
    it.schemaEnv.root.dynamicAnchors[anchor] = true;
    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
    const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));
}
exports.dynamicAnchor = dynamicAnchor;
function _getValidate(cxt) {
    const { schemaEnv, schema, self } = cxt.it;
    const { root, baseId, localRefs, meta } = schemaEnv.root;
    const { schemaId } = self.opts;
    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
    compile_1.compileSchema.call(self, sch);
    return (0, ref_1.getValidate)(cxt, sch);
}
exports.default = def;
//# sourceMappingURL=dynamicAnchor.js.map{"version":3,"file":"dynamicAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicAnchor.ts"],"names":[],"mappings":";;;AAEA,mDAA0D;AAC1D,+CAAmC;AACnC,2CAAsD;AACtD,qCAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,gBAAgB;IACzB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC9C,CAAA;AAED,SAAgB,aAAa,CAAC,GAAe,EAAE,MAAc;IAC3D,MAAM,EAAC,GAAG,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACrB,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;IAC/C,MAAM,CAAC,GAAG,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,cAAc,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,EAAE,CAAA;IACtD,MAAM,QAAQ,GAAG,EAAE,CAAC,aAAa,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;IAC/E,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAA;AACjD,CAAC;AAND,sCAMC;AAED,SAAS,YAAY,CAAC,GAAe;IACnC,MAAM,EAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAC,EAAE,CAAA;IACxC,MAAM,EAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,GAAG,SAAS,CAAC,IAAI,CAAA;IACtD,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,MAAM,GAAG,GAAG,IAAI,mBAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,CAAA;IAC5E,uBAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7B,OAAO,IAAA,iBAAW,EAAC,GAAG,EAAE,GAAG,CAAC,CAAA;AAC9B,CAAC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicRef = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicRef",
    schemaType: "string",
    code: (cxt) => dynamicRef(cxt, cxt.schema),
};
function dynamicRef(cxt, ref) {
    const { gen, keyword, it } = cxt;
    if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
    const anchor = ref.slice(1);
    if (it.allErrors) {
        _dynamicRef();
    }
    else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
    }
    function _dynamicRef(valid) {
        // TODO the assumption here is that `recursiveRef: #` always points to the root
        // of the schema object, which is not correct, because there may be $id that
        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
        // Because of that 2 tests in recursiveRef.json fail.
        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
        // (This problem is not tested in JSON-Schema-Test-Suite)
        if (it.schemaEnv.root.dynamicAnchors[anchor]) {
            const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
        }
        else {
            _callRef(it.validateName, valid)();
        }
    }
    function _callRef(validate, valid) {
        return valid
            ? () => gen.block(() => {
                (0, ref_1.callRef)(cxt, validate);
                gen.let(valid, true);
            })
            : () => (0, ref_1.callRef)(cxt, validate);
    }
}
exports.dynamicRef = dynamicRef;
exports.default = def;
//# sourceMappingURL=dynamicRef.js.map{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicRef.ts"],"names":[],"mappings":";;;AAEA,mDAAgE;AAChE,+CAAmC;AACnC,qCAAmC;AAEnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,SAAgB,UAAU,CAAC,GAAe,EAAE,GAAW;IACrD,MAAM,EAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC9B,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,IAAI,OAAO,yCAAyC,CAAC,CAAA;IACzF,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC3B,IAAI,EAAE,CAAC,SAAS,EAAE,CAAC;QACjB,WAAW,EAAE,CAAA;IACf,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QACrC,WAAW,CAAC,KAAK,CAAC,CAAA;QAClB,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,SAAS,WAAW,CAAC,KAAY;QAC/B,+EAA+E;QAC/E,4EAA4E;QAC5E,sFAAsF;QACtF,qDAAqD;QACrD,kGAAkG;QAClG,yDAAyD;QACzD,IAAI,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7C,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,cAAc,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,EAAE,CAAC,CAAA;YACrE,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC,CAAA;QACjE,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,EAAE,CAAA;QACpC,CAAC;IACH,CAAC;IAED,SAAS,QAAQ,CAAC,QAAc,EAAE,KAAY;QAC5C,OAAO,KAAK;YACV,CAAC,CAAC,GAAG,EAAE,CACH,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE;gBACb,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBACtB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;YACN,CAAC,CAAC,GAAG,EAAE,CAAC,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IAClC,CAAC;AACH,CAAC;AApCD,gCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const dynamicRef_1 = require("./dynamicRef");
const recursiveAnchor_1 = require("./recursiveAnchor");
const recursiveRef_1 = require("./recursiveRef");
const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/index.ts"],"names":[],"mappings":";;AACA,mDAA2C;AAC3C,6CAAqC;AACrC,uDAA+C;AAC/C,iDAAyC;AAEzC,MAAM,OAAO,GAAe,CAAC,uBAAa,EAAE,oBAAU,EAAE,yBAAe,EAAE,sBAAY,CAAC,CAAA;AAEtF,kBAAe,OAAO,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$recursiveAnchor",
    schemaType: "boolean",
    code(cxt) {
        if (cxt.schema)
            (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
        else
            (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
    },
};
exports.default = def;
//# sourceMappingURL=recursiveAnchor.js.map{"version":3,"file":"recursiveAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveAnchor.ts"],"names":[],"mappings":";;AACA,mDAA6C;AAC7C,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,UAAU,EAAE,SAAS;IACrB,IAAI,CAAC,GAAG;QACN,IAAI,GAAG,CAAC,MAAM;YAAE,IAAA,6BAAa,EAAC,GAAG,EAAE,EAAE,CAAC,CAAA;;YACjC,IAAA,sBAAe,EAAC,GAAG,CAAC,EAAE,EAAE,oCAAoC,CAAC,CAAA;IACpE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicRef_1 = require("./dynamicRef");
const def = {
    keyword: "$recursiveRef",
    schemaType: "string",
    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),
};
exports.default = def;
//# sourceMappingURL=recursiveRef.js.map{"version":3,"file":"recursiveRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveRef.ts"],"names":[],"mappings":";;AACA,6CAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const types_1 = require("../discriminator/types");
const compile_1 = require("../../compile");
const ref_error_1 = require("../../compile/ref_error");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
        ? `tag "${tagName}" must be string`
        : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
            throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
            throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
            throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
            throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
            const mapping = getMapping();
            gen.if(false);
            for (const tagValue in mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(mapping[tagValue]));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
            cxt.mergeEvaluated(schCxt, codegen_1.Name);
            return _valid;
        }
        function getMapping() {
            var _a;
            const oneOfMapping = {};
            const topRequired = hasRequired(parentSchema);
            let tagRequired = true;
            for (let i = 0; i < oneOf.length; i++) {
                let sch = oneOf[i];
                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
                    const ref = sch.$ref;
                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
                    if (sch instanceof compile_1.SchemaEnv)
                        sch = sch.schema;
                    if (sch === undefined)
                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
                }
                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
                if (typeof propSch != "object") {
                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
                }
                tagRequired = tagRequired && (topRequired || hasRequired(sch));
                addMappings(propSch, i);
            }
            if (!tagRequired)
                throw new Error(`discriminator: "${tagName}" must be required`);
            return oneOfMapping;
            function hasRequired({ required }) {
                return Array.isArray(required) && required.includes(tagName);
            }
            function addMappings(sch, i) {
                if (sch.const) {
                    addMapping(sch.const, i);
                }
                else if (sch.enum) {
                    for (const tagValue of sch.enum) {
                        addMapping(tagValue, i);
                    }
                }
                else {
                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
                }
            }
            function addMapping(tagValue, i) {
                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
                }
                oneOfMapping[tagValue] = i;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies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(exports, "__esModule", { value: true });
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
    DiscrError["Tag"] = "tag";
    DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,yBAAW,CAAA;IACX,iCAAmB,CAAA;AACrB,CAAC,EAHW,UAAU,0BAAV,UAAU,QAGrB"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const def = {
    keyword: "id",
    code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    },
};
exports.default = def;
//# sourceMappingURL=id.js.map{"version":3,"file":"id.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/id.ts"],"names":[],"mappings":";;AAEA,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,IAAI;QACF,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const id_1 = require("./id");
const ref_1 = require("./ref");
const core = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default,
];
exports.default = core;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/index.ts"],"names":[],"mappings":";;AACA,6BAA4B;AAC5B,+BAA8B;AAE9B,MAAM,IAAI,GAAe;IACvB,SAAS;IACT,KAAK;IACL,OAAO;IACP,aAAa;IACb,EAAC,OAAO,EAAE,UAAU,EAAC;IACrB,aAAa;IACb,YAAS;IACT,aAAU;CACX,CAAA;AAED,kBAAe,IAAI,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = require("../../compile/ref_error");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
            return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
        if (schOrEnv === undefined)
            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
            return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
            if (env === root)
                return callRef(cxt, validateName, env, env.$async);
            const rootName = gen.scopeValue("root", { ref: root });
            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
            const v = getValidate(cxt, sch);
            callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
            const valid = gen.name("valid");
            const schCxt = cxt.subschema({
                schema: sch,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: $ref,
            }, valid);
            cxt.mergeEvaluated(schCxt);
            cxt.ok(valid);
        }
    },
};
function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate
        ? gen.scopeValue("validate", { ref: sch.validate })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
    const { gen, it } = cxt;
    const { allErrors, schemaEnv: env, opts } = it;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
        callAsyncRef();
    else
        callSyncRef();
    function callAsyncRef() {
        if (!env.$async)
            throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
            if (!allErrors)
                gen.assign(valid, true);
        }, (e) => {
            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
            addErrorsFrom(e);
            if (!allErrors)
                gen.assign(valid, false);
        });
        cxt.ok(valid);
    }
    function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
    }
    function addErrorsFrom(source) {
        const errs = (0, codegen_1._) `${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
        var _a;
        if (!it.opts.unevaluated)
            return;
        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
        // TODO refactor
        if (it.props !== true) {
            if (schEvaluated && !schEvaluated.dynamicProps) {
                if (schEvaluated.props !== undefined) {
                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
                }
            }
            else {
                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
            }
        }
        if (it.items !== true) {
            if (schEvaluated && !schEvaluated.dynamicItems) {
                if (schEvaluated.items !== undefined) {
                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
                }
            }
            else {
                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
            }
        }
    }
}
exports.callRef = callRef;
exports.default = def;
//# sourceMapping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,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;QACD,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACtB,IAAI,YAAY,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC;gBAC/C,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;oBACrC,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAhED,0BAgEC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
            return;
        }
        validateAdditionalItems(cxt, items);
    },
};
function validateAdditionalItems(cxt, items) {
    const { gen, schema, data, keyword, it } = cxt;
    it.items = true;
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
    }
    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
    }
    function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
            if (!it.allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
    }
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
//# sourceMappingURL=additionalItems.js.map{"version":3,"file":"additionalItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalItems.ts"],"names":[],"mappings":";;;AAOA,mDAAuD;AACvD,6CAA2E;AAI3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,iBAA0B;IACnC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AAC,WAAW;QACxE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;QAC9C,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,SAAS,aAAa,CAAC,KAAW;QAChC,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;YACzC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;YACpE,IAAI,CAAC,EAAE,CAAC,SAAS;gBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QAC1D,CAAC,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAnBD,0DAmBC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const util_1 = require("../../compile/util");
const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
            return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
            gen.forIn("key", data, (key) => {
                if (!props.length && !patProps.length)
                    additionalPropertyCode(key);
                else
                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
            });
        }
        function isAdditional(key) {
            let definedProp;
            if (props.length > 8) {
                // TODO maybe an option instead of hard-coded 8?
                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
            }
            else if (props.length) {
                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
            }
            else {
                definedProp = codegen_1.nil;
            }
            if (patProps.length) {
                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
            }
            return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
                deleteAdditional(key);
                return;
            }
            if (schema === false) {
                cxt.setParams({ additionalProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                if (opts.removeAdditional === "failing") {
                    applyAdditionalSchema(key, valid, false);
                    gen.if((0, codegen_1.not)(valid), () => {
                        cxt.reset();
                        deleteAdditional(key);
                    });
                }
                else {
                    applyAdditionalSchema(key, valid);
                    if (!allErrors)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                }
            }
        }
        function applyAdditionalSchema(key, valid, errors) {
            const subschema = {
                keyword: "additionalProperties",
                dataProp: key,
                dataPropType: util_1.Type.Str,
            };
            if (errors === false) {
                Object.assign(subschema, {
                    compositeRule: true,
                    createErrors: false,
                    allErrors: false,
                });
            }
            cxt.subschema(subschema, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=additionalProperties.js.map{"version":3,"file":"additionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalProperties.ts"],"names":[],"mappings":";;AAOA,kCAAsE;AACtE,mDAAiE;AACjE,+CAAmC;AAEnC,6CAA0E;AAQ1E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,qCAAqC;IAC9C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,wBAAwB,MAAM,CAAC,kBAAkB,GAAG;CAC5E,CAAA;AAED,MAAM,GAAG,GAAmD;IAC1D,OAAO,EAAE,sBAAsB;IAC/B,IAAI,EAAE,CAAC,QAAQ,CAAC;IAChB,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,cAAc,EAAE,IAAI;IACpB,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAG;QACN,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC5D,wBAAwB;QACxB,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC3D,MAAM,EAAC,SAAS,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;QAC5B,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QAC5E,MAAM,KAAK,GAAG,IAAA,0BAAmB,EAAC,YAAY,CAAC,UAAU,CAAC,CAAA;QAC1D,MAAM,QAAQ,GAAG,IAAA,0BAAmB,EAAC,YAAY,CAAC,iBAAiB,CAAC,CAAA;QACpE,yBAAyB,EAAE,CAAA;QAC3B,GAAG,CAAC,EAAE,C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qBAAqB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;oBACjC,IAAI,CAAC,SAAS;wBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;gBACvD,CAAC;YACH,CAAC;QACH,CAAC;QAED,SAAS,qBAAqB,CAAC,GAAS,EAAE,KAAW,EAAE,MAAc;YACnE,MAAM,SAAS,GAAkB;gBAC/B,OAAO,EAAE,sBAAsB;gBAC/B,QAAQ,EAAE,GAAG;gBACb,YAAY,EAAE,WAAI,CAAC,GAAG;aACvB,CAAA;YACD,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;gBACrB,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE;oBACvB,aAAa,EAAE,IAAI;oBACnB,YAAY,EAAE,KAAK;oBACnB,SAAS,EAAE,KAAK;iBACjB,CAAC,CAAA;YACJ,CAAC;YACD,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QACjC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
        const { gen, schema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
            if ((0, util_1.alwaysValidSchema)(it, sch))
                return;
            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
            cxt.ok(valid);
            cxt.mergeEvaluated(schCxt);
        });
    },
};
exports.default = def;
//# sourceMappingURL=allOf.js.map{"version":3,"file":"allOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/allOf.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,wBAAwB;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QACvE,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,MAAM,CAAC,OAAO,CAAC,CAAC,GAAc,EAAE,CAAS,EAAE,EAAE;YAC3C,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;gBAAE,OAAM;YACtC,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAC,EAAE,KAAK,CAAC,CAAA;YACtE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map{"version":3,"file":"anyOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/anyOf.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAIrC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { min, max } }) => max === undefined
        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
            min = minContains === undefined ? 1 : minContains;
            max = maxContains;
        }
        else {
            min = 1;
        }
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        cxt.setParams({ min, max });
        if (max === undefined && min === 0) {
            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
            return;
        }
        if (max !== undefined && min > max) {
            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
            cxt.fail();
            return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            let cond = (0, codegen_1._) `${len} >= ${min}`;
            if (max !== undefined)
                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
            cxt.pass(cond);
            return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === undefined && min === 1) {
            validateItems(valid, () => gen.if(valid, () => gen.break()));
        }
        else if (min === 0) {
            gen.let(valid, true);
            if (max !== undefined)
                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
        }
        else {
            gen.let(valid, false);
            validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
            const schValid = gen.name("_valid");
            const count = gen.let("count", 0);
            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
            gen.forRange("i", 0, len, (i) => {
                cxt.subschema({
                    keyword: "contains",
                    dataProp: i,
                    dataPropType: util_1.Type.Num,
                    compositeRule: true,
                }, _valid);
                block();
            });
        }
        function checkLimits(count) {
            gen.code((0, codegen_1._) `${count}++`);
            if (max === undefined) {
                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
            }
            else {
                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
                if (min === 1)
                    gen.assign(valid, true);
                else
                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=contains.js.map{"version":3,"file":"contains.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/contains.ts"],"names":[],"mappings":";;AAOA,mDAAkD;AAClD,6CAA2E;AAQ3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,EAAC,EAAE,EAAE,CAChC,GAAG,KAAK,SAAS;QACf,CAAC,CAAC,IAAA,aAAG,EAAA,yBAAyB,GAAG,gBAAgB;QACjD,CAAC,CAAC,IAAA,aAAG,EAAA,yBAAyB,GAAG,qBAAqB,GAAG,gBAAgB;IAC7E,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,EAAC,EAAE,EAAE,CAC/B,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,iBAAiB,GAAG,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,iBAAiB,GAAG,kBAAkB,GAAG,GAAG;CAC/F,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IA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ePropertyDeps = exports.error = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
exports.error = {
    message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
    },
    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
};
const def = {
    keyword: "dependencies",
    type: "object",
    schemaType: "object",
    error: exports.error,
    code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
    },
};
function splitDependencies({ schema }) {
    const propertyDeps = {};
    const schemaDeps = {};
    for (const key in schema) {
        if (key === "__proto__")
            continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
    }
    return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
    const { gen, data, it } = cxt;
    if (Object.keys(propertyDeps).length === 0)
        return;
    const missing = gen.let("missing");
    for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
            continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
            property: prop,
            depsCount: deps.length,
            deps: deps.join(", "),
        });
        if (it.allErrors) {
            gen.if(hasProperty, () => {
                for (const depProp of deps) {
                    (0, code_1.checkReportMissingProp)(cxt, depProp);
                }
            });
        }
        else {
            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
        }
    }
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
            continue;
        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
        }, () => gen.var(valid, true) // TODO var
        );
        cxt.ok(valid);
    }
}
exports.validateSchemaDeps = validateSchemaDeps;
exports.default = def;
//# sourceMappingURL=dependencies.js.map{"version":3,"file":"dependencies.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependencies.ts"],"names":[],"mappings":";;;AAQA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAmG;AAmBtF,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAC,EAAC,EAAE,EAAE;QACjD,MAAM,YAAY,GAAG,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY,CAAA;QAChE,OAAO,IAAA,aAAG,EAAA,aAAa,YAAY,IAAI,IAAI,kBAAkB,QAAQ,aAAa,CAAA;IACpF,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAC,EAAC,EAAE,EAAE,CACjE,IAAA,WAAC,EAAA,cAAc,QAAQ;uBACJ,eAAe;iBACrB,SAAS;YACd,IAAI,GAAG,EAAE,2BAA2B;CAC/C,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,cAAc;IACvB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,aAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAA;QAClD,oBAAoB,CAAC,GAAG,EAAE,QAAQ,C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AC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACxC,CAAC,EACD,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,WAAW;SACvC,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;AACH,CAAC;AAfD,gDAeC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("./dependencies");
const def = {
    keyword: "dependentSchemas",
    type: "object",
    schemaType: "object",
    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentSchemas.js.map{"version":3,"file":"dependentSchemas.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependentSchemas.ts"],"names":[],"mappings":";;AACA,iDAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,iCAAkB,EAAC,GAAG,CAAC;CACvC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === undefined && parentSchema.else === undefined) {
            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
            return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
            const ifClause = gen.let("ifClause");
            cxt.setParams({ ifClause });
            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        }
        else if (hasThen) {
            gen.if(schValid, validateClause("then"));
        }
        else {
            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
            const schCxt = cxt.subschema({
                keyword: "if",
                compositeRule: true,
                createErrors: false,
                allErrors: false,
            }, schValid);
            cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
            return () => {
                const schCxt = cxt.subschema({ keyword }, schValid);
                gen.assign(valid, schValid);
                cxt.mergeValidEvaluated(schCxt, valid);
                if (ifClause)
                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
                else
                    cxt.setParams({ ifClause: keyword });
            };
        }
    },
};
function hasSchema(it, keyword) {
    const schema = it.schema[keyword];
    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports.default = def;
//# sourceMappingURL=if.js.map{"version":3,"file":"if.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/if.ts"],"names":[],"mappings":";;AAQA,mDAAuD;AACvD,6CAAqE;AAIrE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,eAAe,MAAM,CAAC,QAAQ,UAAU;IAClE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,QAAQ,GAAG;CAC9D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GA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,CAAC,CAAA;QAEtC,SAAS,UAAU;YACjB,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAC1B;gBACE,OAAO,EAAE,IAAI;gBACb,aAAa,EAAE,IAAI;gBACnB,YAAY,EAAE,KAAK;gBACnB,SAAS,EAAE,KAAK;aACjB,EACD,QAAQ,CACT,CAAA;YACD,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC;QAED,SAAS,cAAc,CAAC,OAAe,EAAE,QAAe;YACtD,OAAO,GAAG,EAAE;gBACV,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAC,EAAE,QAAQ,CAAC,CAAA;gBACjD,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;gBAC3B,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;gBACtC,IAAI,QAAQ;oBAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,EAAE,CAAC,CAAA;;oBAC5C,GAAG,CAAC,SAAS,CAAC,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,CAAC,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAS,SAAS,CAAC,EAAgB,EAAE,OAAe;IAClD,MAAM,MAAM,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO,MAAM,KAAK,SAAS,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,CAAA;AAC/D,CAAC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const additionalItems_1 = require("./additionalItems");
const prefixItems_1 = require("./prefixItems");
const items_1 = require("./items");
const items2020_1 = require("./items2020");
const contains_1 = require("./contains");
const dependencies_1 = require("./dependencies");
const propertyNames_1 = require("./propertyNames");
const additionalProperties_1 = require("./additionalProperties");
const properties_1 = require("./properties");
const patternProperties_1 = require("./patternProperties");
const not_1 = require("./not");
const anyOf_1 = require("./anyOf");
const oneOf_1 = require("./oneOf");
const allOf_1 = require("./allOf");
const if_1 = require("./if");
const thenElse_1 = require("./thenElse");
function getApplicator(draft2020 = false) {
    const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default,
    ];
    // array
    if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
    else
        applicator.push(additionalItems_1.default, items_1.default);
    applicator.push(contains_1.default);
    return applicator;
}
exports.default = getApplicator;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/index.ts"],"names":[],"mappings":";;AACA,uDAAuE;AACvE,+CAAuC;AACvC,mCAA2B;AAC3B,2CAAiD;AACjD,yCAAkD;AAClD,iDAA8D;AAC9D,mDAAiE;AACjE,iEAAsF;AACtF,6CAAqC;AACrC,2DAAmD;AACnD,+BAAiD;AACjD,mCAAyC;AACzC,mCAAyC;AACzC,mCAA2B;AAC3B,6BAA8C;AAC9C,yCAAiC;AAEjC,SAAwB,aAAa,CAAC,SAAS,GAAG,KAAK;IACrD,MAAM,UAAU,GAAG;QACjB,MAAM;QACN,aAAU;QACV,eAAK;QACL,eAAK;QACL,eAAK;QACL,YAAS;QACT,kBAAQ;QACR,SAAS;QACT,uBAAa;QACb,8BAAoB;QACpB,sBAAY;QACZ,oBAAU;QACV,2BAAiB;KAClB,CAAA;IACD,QAAQ;IACR,IAAI,SAAS;QAAE,UAAU,CAAC,IAAI,CAAC,qBAAW,EAAE,mBAAS,CAAC,CAAA;;QACjD,UAAU,CAAC,IAAI,CAAC,yBAAe,EAAE,eAAK,CAAC,CAAA;IAC5C,UAAU,CAAC,IAAI,CAAC,kBAAQ,CAAC,CAAA;IACzB,OAAO,UAAU,CAAA;AACnB,CAAC;AArBD,gCAqBC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTuple = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
            return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        cxt.ok((0, code_1.validateArray)(cxt));
    },
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data, keyword, it } = cxt;
    checkStrictTuple(parentSchema);
    if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
            keyword,
            schemaProp: i,
            dataProp: i,
        }, valid));
        cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
    }
}
exports.validateTuple = validateTuple;
exports.default = def;
//# sourceMappingURL=items.js.map{"version":3,"file":"items.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items.ts"],"names":[],"mappings":";;;AAEA,mDAAuC;AACvC,6CAAqF;AACrF,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IA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,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;YAAE,OAAM;QACtC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE,CAC5B,GAAG,CAAC,SAAS,CACX;YACE,OAAO;YACP,UAAU,EAAE,CAAC;YACb,QAAQ,EAAE,CAAC;SACZ,EACD,KAAK,CACN,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC,CAAC,CAAA;IAEF,SAAS,gBAAgB,CAAC,GAAoB;QAC5C,MAAM,EAAC,IAAI,EAAE,aAAa,EAAC,GAAG,EAAE,CAAA;QAChC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAA;QACvB,MAAM,SAAS,GAAG,CAAC,KAAK,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK,CAAC,CAAA;QACzF,IAAI,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,IAAI,OAAO,QAAQ,CAAC,oCAAoC,UAAU,4CAA4C,aAAa,GAAG,CAAA;YAC1I,IAAA,sBAAe,EAAC,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QAC7C,CAAC;IACH,CAAC;AACH,CAAC;AApCD,sCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const additionalItems_1 = require("./additionalItems");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        if (prefixItems)
            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
            cxt.ok((0, code_1.validateArray)(cxt));
    },
};
exports.default = def;
//# sourceMappingURL=items2020.js.map{"version":3,"file":"items2020.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items2020.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAqC;AACrC,uDAAyD;AAIzD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtC,MAAM,EAAC,WAAW,EAAC,GAAG,YAAY,CAAA;QAClC,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,IAAI,WAAW;YAAE,IAAA,yCAAuB,EAAC,GAAG,EAAE,WAAW,CAAC,CAAA;;YACrD,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IACjC,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            cxt.fail();
            return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
            keyword: "not",
            compositeRule: true,
            createErrors: false,
            allErrors: false,
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" },
};
exports.default = def;
//# sourceMappingURL=not.js.map{"version":3,"file":"not.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/not.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAIpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YAClC,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,OAAM;QACR,CAAC;QAED,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CACX;YACE,OAAO,EAAE,KAAK;YACd,aAAa,EAAE,IAAI;YACnB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,KAAK;SACjB,EACD,KAAK,CACN,CAAA;QAED,GAAG,CAAC,UAAU,CACZ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CAAA;IACH,CAAC;IACD,KAAK,EAAE,EAAC,OAAO,EAAE,mBAAmB,EAAC;CACtC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
            return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
            schArr.forEach((sch, i) => {
                let schCxt;
                if ((0, util_1.alwaysValidSchema)(it, sch)) {
                    gen.var(schValid, true);
                }
                else {
                    schCxt = cxt.subschema({
                        keyword: "oneOf",
                        schemaProp: i,
                        compositeRule: true,
                    }, schValid);
                }
                if (i > 0) {
                    gen
                        .if((0, codegen_1._) `${schValid} && ${valid}`)
                        .assign(valid, false)
                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
                        .else();
                }
                gen.if(schValid, () => {
                    gen.assign(valid, true);
                    gen.assign(passing, i);
                    if (schCxt)
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=oneOf.js.map{"version":3,"file":"oneOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/oneOf.ts"],"names":[],"mappings":";;AAOA,mDAA6C;AAC7C,6CAAoD;AASpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA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,EAAE,IAAI,CAAC,CAAA;gBACzB,CAAC;qBAAM,CAAC;oBACN,MAAM,GAAG,GAAG,CAAC,SAAS,CACpB;wBACE,OAAO,EAAE,OAAO;wBAChB,UAAU,EAAE,CAAC;wBACb,aAAa,EAAE,IAAI;qBACpB,EACD,QAAQ,CACT,CAAA;gBACH,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;oBACV,GAAG;yBACA,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,QAAQ,OAAO,KAAK,EAAE,CAAC;yBAC9B,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC;yBACpB,MAAM,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC;yBACtC,IAAI,EAAE,CAAA;gBACX,CAAC;gBAED,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;oBACpB,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;oBACvB,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;oBACtB,IAAI,MAAM;wBAAE,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;gBAC9C,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const util_2 = require("../../compile/util");
const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 ||
            (alwaysValidPatterns.length === patterns.length &&
                (!it.opts.unevaluated || it.props === true))) {
            return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
            for (const pat of patterns) {
                if (checkProperties)
                    checkMatchingProperties(pat);
                if (it.allErrors) {
                    validateProperties(pat);
                }
                else {
                    gen.var(valid, true); // TODO var
                    validateProperties(pat);
                    gen.if(valid);
                }
            }
        }
        function checkMatchingProperties(pat) {
            for (const prop in checkProperties) {
                if (new RegExp(pat).test(prop)) {
                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
                }
            }
        }
        function validateProperties(pat) {
            gen.forIn("key", data, (key) => {
                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
                    const alwaysValid = alwaysValidPatterns.includes(pat);
                    if (!alwaysValid) {
                        cxt.subschema({
                            keyword: "patternProperties",
                            schemaProp: pat,
                            dataProp: key,
                            dataPropType: util_2.Type.Str,
                        }, valid);
                    }
                    if (it.opts.unevaluated && props !== true) {
                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
                    }
                    else if (!alwaysValid && !it.allErrors) {
                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
                        // or if all properties were evaluated (props === true)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                    }
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=patternProperties.js.map{"version":3,"file":"patternProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/patternProperties.ts"],"names":[],"mappings":";;AAEA,kCAAuD;AACvD,mDAAkD;AAClD,6CAAqE;AACrE,6CAA6D;AAG7D,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,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AAG,KAAK,IAAI,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;oBACvC,CAAC;yBAAM,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC;wBACzC,sFAAsF;wBACtF,uDAAuD;wBACvD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;oBACvC,CAAC;gBACH,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const items_1 = require("./items");
const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports.default = def;
//# sourceMappingURL=prefixItems.js.map{"version":3,"file":"prefixItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/prefixItems.ts"],"names":[],"mappings":";;AACA,mCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,OAAO,CAAC;IACrB,MAAM,EAAE,aAAa;IACrB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,GAAG,EAAE,OAAO,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("../../compile/validate");
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const additionalProperties_1 = require("./additionalProperties");
const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
            it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
            return;
        const valid = gen.name("valid");
        for (const prop of properties) {
            if (hasDefault(prop)) {
                applyPropertySchema(prop);
            }
            else {
                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
                applyPropertySchema(prop);
                if (!it.allErrors)
                    gen.else().var(valid, true);
                gen.endIf();
            }
            cxt.it.definedProperties.add(prop);
            cxt.ok(valid);
        }
        function hasDefault(prop) {
            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
        }
        function applyPropertySchema(prop) {
            cxt.subschema({
                keyword: "properties",
                schemaProp: prop,
                dataProp: prop,
            }, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/properties.ts"],"names":[],"mappings":";;AACA,qDAAiD;AACjD,kCAA2D;AAC3D,6CAA4E;AAC5E,iEAA0C;AAE1C,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,IAAI,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,YAAY,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC1F,8BAAK,CAAC,IAAI,CAAC,IAAI,qBAAU,CAAC,EAAE,EAAE,8BAAK,EAAE,sBAAsB,CAAC,CAAC,CAAA;QAC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A;YACb,CAAC;YACD,GAAG,CAAC,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;YAClC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACf,CAAC;QAED,SAAS,UAAU,CAAC,IAAY;YAC9B,OAAO,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC,aAAa,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,KAAK,SAAS,CAAA;QACvF,CAAC;QAED,SAAS,mBAAmB,CAAC,IAAY;YACvC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,YAAY;gBACrB,UAAU,EAAE,IAAI;gBAChB,QAAQ,EAAE,IAAI;aACf,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
            cxt.setParams({ propertyName: key });
            cxt.subschema({
                keyword: "propertyNames",
                data: key,
                dataTypes: ["string"],
                propertyName: key,
                compositeRule: true,
            }, valid);
            gen.if((0, codegen_1.not)(valid), () => {
                cxt.error(true);
                if (!it.allErrors)
                    gen.break();
            });
        });
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=propertyNames.js.map{"version":3,"file":"propertyNames.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/propertyNames.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AAIpD,MAAM,KAAK,GAA2B;IACpC,O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Module", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword, parentSchema, it }) {
        if (parentSchema.if === undefined)
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
    },
};
exports.default = def;
//# sourceMappingURL=thenElse.js.map{"version":3,"file":"thenElse.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/thenElse.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,EAAE,KAAK,SAAS;YAAE,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,2BAA2B,CAAC,CAAA;IAChG,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/types/index.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=json-schema.js.map{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../lib/types/json-schema.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/types/jtd-schema.ts"],"names":[],"mappings":""}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_1 = require("../compile/codegen/scope");
const code_1 = require("../compile/codegen/code");
function standaloneCode(ajv, refsOrFunc) {
    if (!ajv.opts.code.source) {
        throw new Error("moduleCode: ajv instance must have code.source option");
    }
    const { _n } = ajv.scope.opts;
    return typeof refsOrFunc == "function"
        ? funcExportCode(refsOrFunc.source)
        : refsOrFunc !== undefined
            ? multiExportsCode(refsOrFunc, getValidate)
            : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
    function getValidate(id) {
        const v = ajv.getSchema(id);
        if (!v)
            throw new Error(`moduleCode: no schema with id ${id}`);
        return v;
    }
    function funcExportCode(source) {
        const usedValues = {};
        const n = source === null || source === void 0 ? void 0 : source.validateName;
        const vCode = validateCode(usedValues, source);
        if (ajv.opts.code.esm) {
            // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
            return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
        }
        return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
    }
    function multiExportsCode(schemas, getValidateFunc) {
        var _a;
        const usedValues = {};
        let code = (0, code_1._) `"use strict";`;
        for (const name in schemas) {
            const v = getValidateFunc(schemas[name]);
            if (v) {
                const vCode = validateCode(usedValues, v.source);
                const exportSyntax = ajv.opts.code.esm
                    ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
                    : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
                code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
            }
        }
        return `${code}`;
    }
    function validateCode(usedValues, s) {
        if (!s)
            throw new Error('moduleCode: function does not have "source" property');
        if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
            return code_1.nil;
        setUsedState(s.validateName, scope_1.UsedValueState.Started);
        const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
        const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
        return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
        function refValidateCode(n) {
            var _a;
            const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
            if (n.prefix === "validate" && typeof vRef == "function") {
                const v = vRef;
                return validateCode(usedValues, v.source);
            }
            else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
                const { validate, validateName } = vRef;
                if (!validateName)
                    throw new Error("ajv internal error");
                const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
                const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
                if (usedState(validateName) === scope_1.UsedValueState.Started)
                    return wrapper;
                const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
                return (0, code_1._) `${wrapper}${_n}${vCode}`;
            }
            return undefined;
        }
        function usedState(name) {
            var _a;
            return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
        }
        function setUsedState(name, state) {
            const { prefix } = name;
            const names = (usedValues[prefix] = usedValues[prefix] || new Map());
            names.set(name, state);
        }
    }
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = standaloneCode;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/standalone/index.ts"],"names":[],"mappings":";;AAGA,oDAAkG;AAClG,kDAA0F;AAE1F,SAAS,cAAc,CACrB,GAAY,EACZ,UAA2D;IAE3D,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;IACD,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAA;IAC3B,OAAO,OAAO,UAAU,IAAI,UAAU;QACpC,CAAC,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC;QACnC,CAAC,CAAC,UAAU,KAAK,SAAS;YAC1B,CAAC,CAAC,gBAAgB,CAAS,UAAU,EAAE,WAAW,CAAC;YACnD,CAAC,CAAC,gBAAgB,CAAY,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,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,YAAY,CAAC,IAAoB,EAAE,KAAqB;YAC/D,MAAM,EAAC,MAAM,EAAC,GAAG,IAAI,CAAA;YACrB,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACpE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,cAAc,CAAA;AACzC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,cAAc,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("../core");
const _1 = require(".");
const requireFromString = require("require-from-string");
class AjvPack {
    constructor(ajv) {
        this.ajv = ajv;
    }
    validate(schemaKeyRef, data) {
        return core_1.default.prototype.validate.call(this, schemaKeyRef, data);
    }
    compile(schema, meta) {
        return this.getStandalone(this.ajv.compile(schema, meta));
    }
    getSchema(keyRef) {
        const v = this.ajv.getSchema(keyRef);
        if (!v)
            return undefined;
        return this.getStandalone(v);
    }
    getStandalone(v) {
        return requireFromString((0, _1.default)(this.ajv, v));
    }
    addSchema(...args) {
        this.ajv.addSchema.call(this.ajv, ...args);
        return this;
    }
    addKeyword(...args) {
        this.ajv.addKeyword.call(this.ajv, ...args);
        return this;
    }
}
exports.default = AjvPack;
//# sourceMappingURL=instance.js.map{"version":3,"file":"instance.js","sourceRoot":"","sources":["../../lib/standalone/instance.ts"],"names":[],"mappings":";;AAAA,kCAAwE;AACxE,wBAA8B;AAC9B,yDAAwD;AAExD,MAAqB,OAAO;IAE1B,YAAqB,GAAQ;QAAR,QAAG,GAAH,GAAG,CAAK;IAAG,CAAC;IAEjC,QAAQ,CAAC,YAAgC,EAAE,IAAa;QACtD,OAAO,cAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CAAc,MAAiB,EAAE,IAAc;QACpD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;IAC9D,CAAC;IAED,SAAS,CAAc,MAAc;QACnC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAI,MAAM,CAAC,CAAA;QACvC,IAAI,CAAC,CAAC;YAAE,OAAO,SAAS,CAAA;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;IAC9B,CAAC;IAEO,aAAa,CAAc,CAAyB;QAC1D,OAAO,iBAAiB,CAAC,IAAA,UAAc,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAA2B,CAAA;IACjF,CAAC;IAED,SAAS,CAAC,GAAG,IAAgD;QAC3D,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC1C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,UAAU,CAAC,GAAG,IAAiD;QAC7D,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA/BD,0BA+BC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/ajv-validator/ajv/issues/889
const equal = require("fast-deep-equal");
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
//# sourceMappingURL=equal.js.map{"version":3,"file":"equal.js","sourceRoot":"","sources":["../../lib/runtime/equal.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAClD,yCAAwC;AAGtC,KAAe,CAAC,IAAI,GAAG,2CAA2C,CAAA;AAEpE,kBAAe,KAAc,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
    let endPos;
    parseJson.message = undefined;
    let matches;
    if (pos)
        s = s.slice(pos);
    try {
        parseJson.position = pos + s.length;
        return JSON.parse(s);
    }
    catch (e) {
        matches = rxParseJson.exec(e.message);
        if (!matches) {
            parseJson.message = "unexpected end";
            return undefined;
        }
        endPos = +matches[1];
        const c = s[endPos];
        s = s.slice(0, endPos);
        parseJson.position = pos + endPos;
        try {
            return JSON.parse(s);
        }
        catch (e1) {
            parseJson.message = `unexpected token ${c}`;
            return undefined;
        }
    }
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
    let numStr = "";
    let c;
    parseJsonNumber.message = undefined;
    if (s[pos] === "-") {
        numStr += "-";
        pos++;
    }
    if (s[pos] === "0") {
        numStr += "0";
        pos++;
    }
    else {
        if (!parseDigits(maxDigits)) {
            errorMessage();
            return undefined;
        }
    }
    if (maxDigits) {
        parseJsonNumber.position = pos;
        return +numStr;
    }
    if (s[pos] === ".") {
        numStr += ".";
        pos++;
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    if (((c = s[pos]), c === "e" || c === "E")) {
        numStr += "e";
        pos++;
        if (((c = s[pos]), c === "+" || c === "-")) {
            numStr += c;
            pos++;
        }
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    parseJsonNumber.position = pos;
    return +numStr;
    function parseDigits(maxLen) {
        let digit = false;
        while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
            digit = true;
            numStr += c;
            pos++;
        }
        return digit;
    }
    function errorMessage() {
        parseJsonNumber.position = pos;
        parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
    }
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    '"': '"',
    "/": "/",
    "\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
    let str = "";
    let c;
    parseJsonString.message = undefined;
    // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
    while (true) {
        c = s[pos++];
        if (c === '"')
            break;
        if (c === "\\") {
            c = s[pos];
            if (c in escapedChars) {
                str += escapedChars[c];
                pos++;
            }
            else if (c === "u") {
                pos++;
                let count = 4;
                let code = 0;
                while (count--) {
                    code <<= 4;
                    c = s[pos];
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    if (c === undefined) {
                        errorMessage("unexpected end");
                        return undefined;
                    }
                    c = c.toLowerCase();
                    if (c >= "a" && c <= "f") {
                        code += c.charCodeAt(0) - CODE_A + 10;
                    }
                    else if (c >= "0" && c <= "9") {
                        code += c.charCodeAt(0) - CODE_0;
                    }
                    else {
                        errorMessage(`unexpected token ${c}`);
                        return undefined;
                    }
                    pos++;
                }
                str += String.fromCharCode(code);
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        }
        else if (c === undefined) {
            errorMessage("unexpected end");
            return undefined;
        }
        else {
            if (c.charCodeAt(0) >= 0x20) {
                str += c;
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
        }
    }
    parseJsonString.position = pos;
    return str;
    function errorMessage(msg) {
        parseJsonString.position = pos;
        parseJsonString.message = msg;
    }
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map{"version":3,"file":"parseJson.js","sourceRoot":"","sources":["../../lib/runtime/parseJson.ts"],"names":[],"mappings":";;;AAAA,MAAM,WAAW,GAAG,+CAA+C,CAAA;AAEnE,SAAgB,SAAS,CAAC,CAAS,EAAE,GAAW;IAC9C,IAAI,MAA0B,CAAA;IAC9B,SAAS,CAAC,OAAO,GAAG,SAAS,CAAA;IAC7B,IAAI,OAA+B,CAAA;IACnC,IAAI,GAAG;QAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACzB,IAAI,CAAC;QACH,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,CAAC,CAAC,MAAM,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,GAAG,WAAW,CAAC,IAAI,CAAE,CAAW,CAAC,OAAO,CAAC,CAAA;QAChD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAA;YACpC,OAAO,SAAS,CAAA;QAClB,CAAC;QACD,MAAM,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;QACpB,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAA;QACnB,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QACtB,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,MAAM,CAAA;QACjC,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QACtB,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,SAAS,CAAC,OAAO,GAAG,oBAAoB,CAAC,EAAE,CAAA;YAC3C,OAAO,SAAS,CAAA;QAClB,CAAC;IACH,CAAC;AACH,CAAC;AAz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GAAG,SAA+B,CAAA;AACzD,eAAe,CAAC,QAAQ,GAAG,CAAW,CAAA;AACtC,eAAe,CAAC,IAAI,GAAG,uDAAuD,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxEscapable = 
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
    "\b": "\\b",
    "\t": "\\t",
    "\n": "\\n",
    "\f": "\\f",
    "\r": "\\r",
    '"': '\\"',
    "\\": "\\\\",
};
function quote(s) {
    rxEscapable.lastIndex = 0;
    return ('"' +
        (rxEscapable.test(s)
            ? s.replace(rxEscapable, (a) => {
                const c = escaped[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            })
            : s) +
        '"');
}
exports.default = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map{"version":3,"file":"quote.js","sourceRoot":"","sources":["../../lib/runtime/quote.ts"],"names":[],"mappings":";;AAAA,MAAM,WAAW;AACf,2EAA2E;AAC3E,iIAAiI,CAAA;AAEnI,MAAM,OAAO,GAA6B;IACxC,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;CACb,CAAA;AAED,SAAwB,KAAK,CAAC,CAAS;IACrC,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;IACzB,OAAO,CACL,GAAG;QACH,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE;gBAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;gBACpB,OAAO,OAAO,CAAC,KAAK,QAAQ;oBAC1B,CAAC,CAAC,CAAC;oBACH,CAAC,CAAC,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC/D,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC,CAAC;QACN,GAAG,CACJ,CAAA;AACH,CAAC;AAdD,wBAcC;AAED,KAAK,CAAC,IAAI,GAAG,2CAA2C,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const re2 = require("re2");
re2.code = 'require("ajv/dist/runtime/re2").default';
exports.default = re2;
//# sourceMappingURL=re2.js.map{"version":3,"file":"re2.js","sourceRoot":"","sources":["../../lib/runtime/re2.ts"],"names":[],"mappings":";;AAAA,2BAA0B;AAGxB,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dt = str.split(DT_SEPARATOR);
    return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
        (allowDate && dt.length === 1 && validDate(dt[0])));
}
exports.default = validTimestamp;
function validDate(str) {
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const y = +matches[1];
    const m = +matches[2];
    const d = +matches[3];
    return (m >= 1 &&
        m <= 12 &&
        d >= 1 &&
        (d <= DAYS[m] ||
            // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
            (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hr = +matches[1];
    const min = +matches[2];
    const sec = +matches[3];
    const tzH = +(matches[4] || 0);
    const tzM = +(matches[5] || 0);
    return ((hr <= 23 && min <= 59 && sec <= 59) ||
        // leap second
        (hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../lib/runtime/timestamp.ts"],"names":[],"mappings":";;AAAA,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,IAAI,GAAG,4BAA4B,CAAA;AACzC,MAAM,IAAI,GAAG,gEAAgE,CAAA;AAC7E,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;AAEhE,SAAwB,cAAc,CAAC,GAAW,EAAE,SAAkB;IACpE,iDAAiD;IACjD,MAAM,EAAE,GAAa,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAA;IAC5C,OAAO,CACL,CAAC,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzD,CAAC,SAAS,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CACnD,CAAA;AACH,CAAC;AAPD,iCAOC;AAED,SAAS,SAAS,CAAC,GAAW;IAC5B,MAAM,OAAO,GAAoB,IAAI,CAAC,IAAI,CAAC,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AAc;QACd,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,KAAK,EAAE,CAAC,CACpD,CAAA;AACH,CAAC;AAED,cAAc,CAAC,IAAI,GAAG,+CAA+C,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let value;
    while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
            // high surrogate, and there is a next character
            value = str.charCodeAt(pos);
            if ((value & 0xfc00) === 0xdc00)
                pos++; // low surrogate
        }
    }
    return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map{"version":3,"file":"ucs2length.js","sourceRoot":"","sources":["../../lib/runtime/ucs2length.ts"],"names":[],"mappings":";;AAAA,qDAAqD;AACrD,iEAAiE;AACjE,SAAwB,UAAU,CAAC,GAAW;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAA;IACtB,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,IAAI,KAAa,CAAA;IACjB,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACjB,MAAM,EAAE,CAAA;QACR,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAA;QAC7B,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;YACpD,gDAAgD;YAChD,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,MAAM;gBAAE,GAAG,EAAE,CAAA,CAAC,gBAAgB;QACzD,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAfD,6BAeC;AAED,UAAU,CAAC,IAAI,GAAG,gDAAgD,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uri = require("fast-uri");
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
//# sourceMappingURL=uri.js.map{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../lib/runtime/uri.ts"],"names":[],"mappings":";;AAAA,gCAA+B;AAG7B,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ValidationError extends Error {
    constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
    }
}
exports.default = ValidationError;
//# sourceMappingURL=validation_error.js.map{"version":3,"file":"validation_error.js","sourceRoot":"","sources":["../../lib/runtime/validation_error.ts"],"names":[],"mappings":";;AAEA,MAAqB,eAAgB,SAAQ,KAAK;IAKhD,YAAY,MAA8B;QACxC,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;IACnC,CAAC;CACF;AAVD,kCAUC"}{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared = (root) => {
    const sch = {
        nullable: { type: "boolean" },
        metadata: {
            optionalProperties: {
                union: { elements: { ref: "schema" } },
            },
            additionalProperties: true,
        },
    };
    if (root)
        sch.definitions = { values: { ref: "schema" } };
    return sch;
};
const emptyForm = (root) => ({
    optionalProperties: shared(root),
});
const refForm = (root) => ({
    properties: {
        ref: { type: "string" },
    },
    optionalProperties: shared(root),
});
const typeForm = (root) => ({
    properties: {
        type: {
            enum: [
                "boolean",
                "timestamp",
                "string",
                "float32",
                "float64",
                "int8",
                "uint8",
                "int16",
                "uint16",
                "int32",
                "uint32",
            ],
        },
    },
    optionalProperties: shared(root),
});
const enumForm = (root) => ({
    properties: {
        enum: { elements: { type: "string" } },
    },
    optionalProperties: shared(root),
});
const elementsForm = (root) => ({
    properties: {
        elements: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
    properties: {
        properties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        optionalProperties: { values: { ref: "schema" } },
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const optionalPropertiesForm = (root) => ({
    properties: {
        optionalProperties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const discriminatorForm = (root) => ({
    properties: {
        discriminator: { type: "string" },
        mapping: {
            values: {
                metadata: {
                    union: [propertiesForm(false), optionalPropertiesForm(false)],
                },
            },
        },
    },
    optionalProperties: shared(root),
});
const valuesForm = (root) => ({
    properties: {
        values: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const schema = (root) => ({
    metadata: {
        union: [
            emptyForm,
            refForm,
            typeForm,
            enumForm,
            elementsForm,
            propertiesForm,
            optionalPropertiesForm,
            discriminatorForm,
            valuesForm,
        ].map((s) => s(root)),
    },
});
const jtdMetaSchema = {
    definitions: {
        schema: schema(false),
    },
    ...schema(true),
};
exports.default = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"j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AAC,KAAK,CAAC,CAAC;iBAC9D;aACF;SACF;KACF;IACD,kBAAkB,EAAE,MAAM,CAAC,IAAI,CAAC;CACjC,CAAC,CAAA;AAEF,MAAM,UAAU,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACxC,UAAU,EAAE;QACV,MAAM,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC;KACxB;IACD,kBAAkB,EAAE,MAAM,CAAC,IAAI,CAAC;CACjC,CAAC,CAAA;AAEF,MAAM,MAAM,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACpC,QAAQ,EAAE;QACR,KAAK,EAAE;YACL,SAAS;YACT,OAAO;YACP,QAAQ;YACR,QAAQ;YACR,YAAY;YACZ,cAAc;YACd,sBAAsB;YACtB,iBAAiB;YACjB,UAAU;SACX,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;KACtB;CACF,CAAC,CAAA;AAEF,MAAM,aAAa,GAAiB;IAClC,WAAW,EAAE;QACX,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC;KACtB;IACD,GAAG,MAAM,CAAC,IAAI,CAAC;CAChB,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const unevaluated = require("./meta/unevaluated.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format-annotation.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
    ;
    [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2020;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2020-12/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,uDAAsD;AACtD,+CAA8C;AAC9C,yCAAwC;AACxC,wDAAuD;AACvD,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,WAAW;QACX,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAhBD,oCAgBC"}{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2019($data) {
    ;
    [
        metaSchema,
        applicator,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2019;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,+CAA8C;AAC9C,yCAAwC;AACxC,6CAA4C;AAC5C,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"}{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = require("./codegen");
const util_1 = require("./util");
const names_1 = require("./names");
exports.keywordError = {
    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
    message: ({ keyword, schemaType }) => schemaType
        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
        addError(gen, errObj);
    }
    else {
        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
    }
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    addError(gen, errObj);
    if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
    }
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
    gen.assign(names_1.default.errors, errsCount);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
    /* istanbul ignore if */
    if (errsCount === undefined)
        throw new Error("ajv implementation error");
    const err = gen.name("err");
    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
            gen.assign((0, codegen_1._) `${err}.data`, data);
        }
    });
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
    const err = gen.const("err", errObj);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
    const { gen, validateName, schemaEnv } = it;
    if (schemaEnv.$async) {
        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
        gen.return(false);
    }
}
const E = {
    keyword: new codegen_1.Name("keyword"),
    schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
    params: new codegen_1.Name("params"),
    propertyName: new codegen_1.Name("propertyName"),
    message: new codegen_1.Name("message"),
    schema: new codegen_1.Name("schema"),
    parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
    const { createErrors } = cxt.it;
    if (createErrors === false)
        return (0, codegen_1._) `{}`;
    return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
    const { gen, it } = cxt;
    const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths),
    ];
    extraErrorProps(cxt, error, keyValues);
    return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
    const instPath = instancePath
        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
        : errorPath;
    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
    if (schemaPath) {
        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
    }
    return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
    const { keyword, data, schemaValue, it } = cxt;
    const { opts, propertyName, topSchemaRef, schemaPath } = it;
    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
    if (opts.messages) {
        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
    }
    if (opts.verbose) {
        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
    }
    if (propertyName)
        keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/compile/errors.ts"],"names":[],"mappings":";;;AAEA,uCAAgE;AAEhE,iCAAyC;AACzC,mCAAuB;AAEV,QAAA,YAAY,GAA2B;IAClD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,cAAc,OAAO,sBAAsB;CACvE,CAAA;AAEY,QAAA,iBAAiB,GAA2B;IACvD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CACjC,UAAU;QACR,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,qBAAqB,UAAU,UAAU;QACzD,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,8BAA8B;CACnD,CAAA;AAQD,SAAgB,WAAW,CACzB,GAAoB,EACpB,QAAgC,oBAAY,EAC5C,UAAuB,EACvB,iBAA2B;IAE3B,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAA;IAChB,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,SAAS,EAAC,GAAG,EAAE,CAAA;IAC1C,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,KAAK,EAAE,UAAU,CAAC,CAAA;IACtD,IAAI,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,CAAC,aAAa,IAAI,SAAS,CAAC,EAAE,CAAC;QACtD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IACvB,CAAC;SAAM,CAAC;QACN,YAAY,CAAC,EAAE,EAAE,IAAA,WAAC,EAAA,IAAI,MAAM,GAAG,CAAC,CAAA;IAClC,CAAC;AACH,CAAC;AAdD,kCAcC;AAED,SAAgB,gBAAgB,CAC9B,GAAoB,EACpB,QAAgC,oBAAY,EAC5C,UAAuB;IAEvB,MAAM,EAAC,EAAE,EAAC,GAAG,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ACzC,SAAsC;IAEtC,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC5C,MAAM,EAAC,IAAI,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAC,GAAG,EAAE,CAAA;IACzD,SAAS,CAAC,IAAI,CACZ,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,EACpB,CAAC,CAAC,CAAC,MAAM,EAAE,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAA,WAAC,EAAA,IAAI,CAAC,CACxE,CAAA;IACD,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;QAClB,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAA;IACpF,CAAC;IACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;QACjB,SAAS,CAAC,IAAI,CACZ,CAAC,CAAC,CAAC,MAAM,EAAE,WAAW,CAAC,EACvB,CAAC,CAAC,CAAC,YAAY,EAAE,IAAA,WAAC,EAAA,GAAG,YAAY,GAAG,UAAU,EAAE,CAAC,EACjD,CAAC,eAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CACf,CAAA;IACH,CAAC;IACD,IAAI,YAAY;QAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;AAClE,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = require("./codegen");
const validation_error_1 = require("../runtime/validation_error");
const names_1 = require("./names");
const resolve_1 = require("./resolve");
const util_1 = require("./util");
const validate_1 = require("./validate");
class SchemaEnv {
    constructor(env) {
        var _a;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
            schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
    }
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
    // TODO refactor - remove compilations
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
            ref: validation_error_1.default,
            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
        });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
            : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._) `""`,
        opts: this.opts,
        self: this,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        // gen.optimize(1)
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
        if (this.opts.code.process)
            sourceCode = this.opts.code.process(sourceCode, sch);
        // console.log("\n\n\n *** \n", sourceCode)
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
            validate.$async = true;
        if (this.opts.code.source === true) {
            validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
            const { props, items } = schemaCxt;
            validate.evaluated = {
                props: props instanceof codegen_1.Name ? undefined : props,
                items: items instanceof codegen_1.Name ? undefined : items,
                dynamicProps: props instanceof codegen_1.Name,
                dynamicItems: items instanceof codegen_1.Name,
            };
            if (validate.source)
                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
    }
    catch (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
            this.logger.error("Error compiling schema, function code:", sourceCode);
        // console.log("\n\n\n *** \n", sourceCode, this.opts)
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
    var _a;
    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
    const schOrFunc = root.refs[ref];
    if (schOrFunc)
        return schOrFunc;
    let _sch = resolve.call(this, root, ref);
    if (_sch === undefined) {
        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
        const { schemaId } = this.opts;
        if (schema)
            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === undefined)
        return;
    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
            return sch;
    }
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
    let sch;
    while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
    const p = this.opts.uriResolver.parse(ref);
    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
    }
    const id = (0, resolve_1.normalizeId)(refPath);
    const schOrRef = this.refs[id] || this.schemas[id];
    if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
            return;
        return getJsonPointer.call(this, p, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
    if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
    if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a;
    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
        return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
            return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === undefined)
            return;
        schema = partSchema;
        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
    }
    // even though resolution failed we need to return SchemaEnv to throw exception
    // so that compileAsync loads missing schema.
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
        return env;
    return undefined;
}
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/compile/index.ts"],"names":[],"mappings":";;;AAUA,uCAAgF;AAChF,kEAAyD;AACzD,mCAAuB;AACvB,uCAAkG;AAClG,iCAA6D;AAC7D,yCA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AAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACtE,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,EAAE,CAAC;YAC7C,MAAM,GAAG,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;QAC3D,CAAC;IACH,CAAC;IACD,IAAI,GAA0B,CAAA;IAC9B,IAAI,OAAO,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAA,2BAAoB,EAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3F,MAAM,IAAI,GAAG,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAA;QACnE,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC5C,CAAC;IACD,+EAA+E;IAC/E,6CAA6C;IAC7C,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,GAAG,GAAG,GAAG,IAAI,IAAI,SAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IAC5D,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,CAAA;IAC9C,OAAO,SAAS,CAAA;AAClB,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("./codegen");
const names = {
    // validation function arguments
    data: new codegen_1.Name("data"), // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
    errors: new codegen_1.Name("errors"), // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart"),
};
exports.default = names;
//# sourceMappingURL=names.js.map{"version":3,"file":"names.js","sourceRoot":"","sources":["../../lib/compile/names.ts"],"names":[],"mappings":";;AAAA,uCAA8B;AAE9B,MAAM,KAAK,GAAG;IACZ,gCAAgC;IAChC,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC,EAAE,qCAAqC;IAC7D,sCAAsC;IACtC,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+FAA+F;IAC3H,YAAY,EAAE,IAAI,cAAI,CAAC,cAAc,CAAC;IACtC,UAAU,EAAE,IAAI,cAAI,CAAC,YAAY,CAAC;IAClC,kBAAkB,EAAE,IAAI,cAAI,CAAC,oBAAoB,CAAC;IAClD,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC,EAAE,2EAA2E;IAC3G,cAAc,EAAE,IAAI,cAAI,CAAC,gBAAgB,CAAC,EAAE,8CAA8C;IAC1F,4BAA4B;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC,EAAE,qCAAqC;IACnE,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+BAA+B;IAC3D,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,YAAY;IACZ,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,KAAK,EAAE,IAAI,cAAI,CAAC,OAAO,CAAC;IACxB,wDAAwD;IACxD,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;CAC/B,CAAA;AAED,kBAAe,KAAK,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const resolve_1 = require("./resolve");
class MissingRefError extends Error {
    constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
    }
}
exports.default = MissingRefError;
//# sourceMappingURL=ref_error.js.map{"version":3,"file":"ref_error.js","sourceRoot":"","sources":["../../lib/compile/ref_error.ts"],"names":[],"mappings":";;AAAA,uCAA8D;AAG9D,MAAqB,eAAgB,SAAQ,KAAK;IAIhD,YAAY,QAAqB,EAAE,MAAc,EAAE,GAAW,EAAE,GAAY;QAC1E,KAAK,CAAC,GAAG,IAAI,2BAA2B,GAAG,YAAY,MAAM,EAAE,CAAC,CAAA;QAChE,IAAI,CAAC,UAAU,GAAG,IAAA,oBAAU,EAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;QACnD,IAAI,CAAC,aAAa,GAAG,IAAA,qBAAW,EAAC,IAAA,qBAAW,EAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AATD,kCASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = require("./util");
const equal = require("fast-deep-equal");
const traverse = require("json-schema-traverse");
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const",
]);
function inlineRef(schema, limit = true) {
    if (typeof schema == "boolean")
        return true;
    if (limit === true)
        return !hasRef(schema);
    if (!limit)
        return false;
    return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor",
]);
function hasRef(schema) {
    for (const key in schema) {
        if (REF_KEYWORDS.has(key))
            return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
            return true;
        if (typeof sch == "object" && hasRef(sch))
            return true;
    }
    return false;
}
function countKeys(schema) {
    let count = 0;
    for (const key in schema) {
        if (key === "$ref")
            return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
            continue;
        if (typeof schema[key] == "object") {
            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
        }
        if (count === Infinity)
            return Infinity;
    }
    return count;
}
function getFullPath(resolver, id = "", normalize) {
    if (normalize !== false)
        id = normalizeId(id);
    const p = resolver.parse(id);
    return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
    const serialized = resolver.serialize(p);
    return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
    id = normalizeId(id);
    return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
        return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === undefined)
            return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
            innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
            // eslint-disable-next-line @typescript-eslint/unbound-method
            const _resolve = this.opts.uriResolver.resolve;
            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
            if (schemaRefs.has(ref))
                throw ambiguos(ref);
            schemaRefs.add(ref);
            let schOrRef = this.refs[ref];
            if (typeof schOrRef == "string")
                schOrRef = this.refs[schOrRef];
            if (typeof schOrRef == "object") {
                checkAmbiguosRef(sch, schOrRef.schema, ref);
            }
            else if (ref !== normalizeId(fullPath)) {
                if (ref[0] === "#") {
                    checkAmbiguosRef(sch, localRefs[ref], ref);
                    localRefs[ref] = sch;
                }
                else {
                    this.refs[ref] = fullPath;
                }
            }
            return ref;
        }
        function addAnchor(anchor) {
            if (typeof anchor == "string") {
                if (!ANCHOR.test(anchor))
                    throw new Error(`invalid anchor "${anchor}"`);
                addRef.call(this, `#${anchor}`);
            }
        }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== undefined && !equal(sch1, sch2))
            throw ambiguos(ref);
    }
    function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
    }
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../lib/compile/resolve.ts"],"names":[],"mappings":";;;AAGA,iCAA+B;AAC/B,yCAAwC;AACxC,iDAAgD;AA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AY,MAAe;YAC3C,IAAI,OAAO,MAAM,IAAI,QAAQ,EAAE,CAAC;gBAC9B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,MAAM,GAAG,CAAC,CAAA;gBACvE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC,CAAA;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,SAAS,CAAA;IAEhB,SAAS,gBAAgB,CAAC,IAAe,EAAE,IAA2B,EAAE,GAAW;QACjF,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;YAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnE,CAAC;IAED,SAAS,QAAQ,CAAC,GAAW;QAC3B,OAAO,IAAI,KAAK,CAAC,cAAc,GAAG,oCAAoC,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AAxDD,sCAwDC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
    return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
    const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] },
    };
    return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {},
    };
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../lib/compile/rules.ts"],"names":[],"mappings":";;;AAEA,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAA;AAIjG,MAAM,SAAS,GAAgB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;AAElD,SAAgB,UAAU,CAAC,CAAU;IACnC,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAFD,gCAEC;AAyBD,SAAgB,QAAQ;IACtB,MAAM,MAAM,GAAgE;QAC1E,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,KAAK,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAC;QACjC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;KACpC,CAAA;IACD,OAAO;QACL,KAAK,EAAE,EAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAC;QAC5D,KAAK,EAAE,CAAC,EAAC,KAAK,EAAE,EAAE,EAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/E,IAAI,EAAE,EAAC,KAAK,EAAE,EAAE,EAAC;QACjB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;KACb,CAAA;AACH,CAAC;AAdD,4BAcC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = require("./codegen");
const code_1 = require("./codegen/code");
// TODO refactor to use Set
function toHash(arr) {
    const hash = {};
    for (const item of arr)
        hash[item] = true;
    return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
    if (typeof schema == "boolean")
        return schema;
    if (Object.keys(schema).length === 0)
        return true;
    checkUnknownRules(it, schema);
    return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
    const { opts, self } = it;
    if (!opts.strictSchema)
        return;
    if (typeof schema === "boolean")
        return;
    const rules = self.RULES.keywords;
    for (const key in schema) {
        if (!rules[key])
            checkStrictMode(it, `unknown keyword: "${key}"`);
    }
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (rules[key])
            return true;
    return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
            return true;
    return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
    if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
            return schema;
        if (typeof schema == "string")
            return (0, codegen_1._) `${schema}`;
    }
    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
    if (typeof str == "number")
        return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
    if (Array.isArray(xs)) {
        for (const x of xs)
            f(x);
    }
    else {
        f(xs);
    }
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
    return (gen, from, to, toName) => {
        const res = to === undefined
            ? from
            : to instanceof codegen_1.Name
                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
                : from instanceof codegen_1.Name
                    ? (mergeToName(gen, to, from), from)
                    : mergeValues(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
}
exports.mergeEvaluated = {
    props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
            if (from === true) {
                gen.assign(to, true);
            }
            else {
                gen.assign(to, (0, codegen_1._) `${to} || {}`);
                setEvaluated(gen, to, from);
            }
        }),
        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
        resultToName: evaluatedPropsToName,
    }),
    items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
        resultToName: (gen, items) => gen.var("items", items),
    }),
};
function evaluatedPropsToName(gen, ps) {
    if (ps === true)
        return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._) `{}`);
    if (ps !== undefined)
        setEvaluated(gen, props, ps);
    return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
    return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
    });
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
    Type[Type["Num"] = 0] = "Num";
    Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    // let path
    if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax
            ? isNumber
                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
            : isNumber
                ? (0, codegen_1._) `"/" + ${dataProp}`
                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
    if (!mode)
        return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
        throw new Error(msg);
    it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map{"version":3,"file":"util.js","sourceRoot":"","sources":["../../lib/compile/util.ts"],"names":[],"mappings":";;;AAEA,uCAA6D;AAC7D,yCAAoC;AAGpC,2BAA2B;AAC3B,SAAgB,MAAM,CAA4B,GAAQ;IACxD,MAAM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IAAA,WAAC,EAAA,SAAS,QAAQ,QAAQ;gBAC5B,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,QAAQ,SAAS;YAChC,CAAC,CAAC,QAAQ;gBACV,CAAC,CAAC,IAAA,WAAC,EAAA,SAAS,QAAQ,EAAE;gBACtB,CAAC,CAAC,IAAA,WAAC,EAAA,SAAS,QAAQ,4CAA4C,CAAA,CAAC,sCAAsC;IAC3G,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,IAAA,qBAAW,EAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAChG,CAAC;AAjBD,oCAiBC;AAED,SAAgB,eAAe,CAC7B,EAAa,EACb,GAAW,EACX,OAAwB,EAAE,CAAC,IAAI,CAAC,YAAY;IAE5C,IAAI,CAAC,IAAI;QAAE,OAAM;IACjB,GAAG,GAAG,gBAAgB,GAAG,EAAE,CAAA;IAC3B,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AATD,0CASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
    const group = self.RULES.types[type];
    return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
    var _a;
    return (schema[rule.keyword] !== undefined ||
        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map{"version":3,"file":"applicability.js","sourceRoot":"","sources":["../../../lib/compile/validate/applicability.ts"],"names":[],"mappings":";;;AAIA,SAAgB,qBAAqB,CACnC,EAAC,MAAM,EAAE,IAAI,EAAe,EAC5B,IAAc;IAEd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACpC,OAAO,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AACjE,CAAC;AAND,sDAMC;AAED,SAAgB,cAAc,CAAC,MAAuB,EAAE,KAAgB;IACtE,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAuB,EAAE,IAAU;;IAC/D,OAAO,CACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,SAAS;SAClC,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC,CAAA,CACrE,CAAA;AACH,CAAC;AALD,sCAKC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const boolError = {
    message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
    const { gen, schema, validateName } = it;
    if (schema === false) {
        falseSchemaError(it, false);
    }
    else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
        gen.return(true);
    }
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
    const { gen, schema } = it;
    if (schema === false) {
        gen.var(valid, false); // TODO var
        falseSchemaError(it);
    }
    else {
        gen.var(valid, true); // TODO var
    }
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
    const { gen, data } = it;
    // TODO maybe some other interface should be used for non-keyword validation errors...
    const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it,
    };
    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map{"version":3,"file":"boolSchema.js","sourceRoot":"","sources":["../../../lib/compile/validate/boolSchema.ts"],"names":[],"mappings":";;;AAEA,sCAAqC;AACrC,wCAAkC;AAClC,oCAAwB;AAExB,MAAM,SAAS,GAA2B;IACxC,OAAO,EAAE,yBAAyB;CACnC,CAAA;AAED,SAAgB,oBAAoB,CAAC,EAAa;IAChD,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAC,GAAG,EAAE,CAAA;IACtC,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;QACrB,gBAAgB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;IAC7B,CAAC;SAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAC/D,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;IACpB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,YAAY,SAAS,EAAE,IAAI,CAAC,CAAA;QAC3C,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAClB,CAAC;AACH,CAAC;AAVD,oDAUC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,KAAW;IAC1D,MAAM,EAAC,GAAG,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IACxB,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;QACrB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA,CAAC,WAAW;QACjC,gBAAgB,CAAC,EAAE,CAAC,CAAA;IACtB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA,CAAC,WAAW;IAClC,CAAC;AACH,CAAC;AARD,8CAQC;AAED,SAAS,gBAAgB,CAAC,EAAa,EAAE,iBAA2B;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IACtB,sFAAsF;IACtF,MAAM,GAAG,GAAoB;QAC3B,GAAG;QACH,OAAO,EAAE,cAAc;QACvB,IAAI;QACJ,MAAM,EAAE,KAAK;QACb,UAAU,EAAE,KAAK;QACjB,WAAW,EAAE,KAAK;QAClB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;IACD,IAAA,oBAAW,EAAC,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;AAC3D,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = require("../rules");
const applicability_1 = require("./applicability");
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const util_1 = require("../util");
var DataType;
(function (DataType) {
    DataType[DataType["Correct"] = 0] = "Correct";
    DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
    const types = getJSONTypes(schema.type);
    const hasNull = types.includes("null");
    if (hasNull) {
        if (schema.nullable === false)
            throw new Error("type: null contradicts nullable: false");
    }
    else {
        if (!types.length && schema.nullable !== undefined) {
            throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
            types.push("null");
    }
    return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
    if (types.every(rules_1.isJSONType))
        return types;
    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
    const { gen, data, opts } = it;
    const coerceTo = coerceToTypes(types, opts.coerceTypes);
    const checkTypes = types.length > 0 &&
        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
    if (checkTypes) {
        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
            if (coerceTo.length)
                coerceData(it, types, coerceTo);
            else
                reportTypeError(it);
        });
    }
    return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
    return coerceTypes
        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
        : [];
}
function coerceData(it, types, coerceTo) {
    const { gen, data, opts } = it;
    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
    if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
            .assign(data, (0, codegen_1._) `${data}[0]`)
            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
    }
    gen.if((0, codegen_1._) `${coerced} !== undefined`);
    for (const t of coerceTo) {
        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
            coerceSpecificType(t);
        }
    }
    gen.else();
    reportTypeError(it);
    gen.endIf();
    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
    });
    function coerceSpecificType(t) {
        switch (t) {
            case "string":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
                    .elseIf((0, codegen_1._) `${data} === null`)
                    .assign(coerced, (0, codegen_1._) `""`);
                return;
            case "number":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "integer":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "boolean":
                gen
                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
                    .assign(coerced, false)
                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
                    .assign(coerced, true);
                return;
            case "null":
                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
                gen.assign(coerced, null);
                return;
            case "array":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
                    .assign(coerced, (0, codegen_1._) `[${data}]`);
        }
    }
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    // TODO use gen.property
    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType) {
        case "null":
            return (0, codegen_1._) `${data} ${EQ} null`;
        case "array":
            cond = (0, codegen_1._) `Array.isArray(${data})`;
            break;
        case "object":
            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
            break;
        case "integer":
            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
            break;
        case "number":
            cond = numCond();
            break;
        default:
            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
    }
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
    if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
    }
    let cond;
    const types = (0, util_1.toHash)(dataTypes);
    if (types.array && types.object) {
        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
        delete types.null;
        delete types.array;
        delete types.object;
    }
    else {
        cond = codegen_1.nil;
    }
    if (types.number)
        delete types.integer;
    for (const t in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
    return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
    const cxt = getTypeErrorContext(it);
    (0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
    const { gen, data, schema } = it;
    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
    return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it,
    };
}
//# sourceMappingURL=dataType.js.map{"version":3,"file":"dataType.js","sourceRoot":"","sources":["../../../lib/compile/validate/dataType.ts"],"names":[],"mappings":";;;AAOA,oCAA6C;AAC7C,mDAAqD;AACrD,sCAAqC;AACrC,wCAAkE;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AmB,CAAC,EAAgB;IAC3C,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IAC9B,MAAM,UAAU,GAAG,IAAA,qBAAc,EAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACrD,OAAO;QACL,GAAG;QACH,OAAO,EAAE,MAAM;QACf,IAAI;QACJ,MAAM,EAAE,MAAM,CAAC,IAAI;QACnB,UAAU;QACV,WAAW,EAAE,UAAU;QACvB,YAAY,EAAE,MAAM;QACpB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;AACH,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignDefaults = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function assignDefaults(it, ty) {
    const { properties, items } = it.schema;
    if (ty === "object" && properties) {
        for (const key in properties) {
            assignDefault(it, key, properties[key].default);
        }
    }
    else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
    }
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
    const { gen, compositeRule, data, opts } = it;
    if (defaultValue === undefined)
        return;
    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
    }
    let condition = (0, codegen_1._) `${childData} === undefined`;
    if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
    }
    // `${childData} === undefined` +
    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../../lib/compile/validate/defaults.ts"],"names":[],"mappings":";;;AACA,wCAAoD;AACpD,kCAAuC;AAEvC,SAAgB,cAAc,CAA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A2F;IAC3F,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,MAAM,IAAA,mBAAS,EAAC,YAAY,CAAC,EAAE,CAAC,CAAA;AACjE,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = require("./boolSchema");
const dataType_1 = require("./dataType");
const applicability_1 = require("./applicability");
const dataType_2 = require("./dataType");
const defaults_1 = require("./defaults");
const keyword_1 = require("./keyword");
const subschema_1 = require("./subschema");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const resolve_1 = require("../resolve");
const util_1 = require("../util");
const errors_1 = require("../errors");
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            topSchemaObjCode(it);
            return;
        }
    }
    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
            destructureValCxtES5(gen, opts);
            gen.code(body);
        });
    }
    else {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
}
function destructureValCxt(opts) {
    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
    });
}
function topSchemaObjCode(it) {
    const { schema, opts, gen } = it;
    validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
            commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
            resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
    });
    return;
}
function resetEvaluated(it) {
    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
    const { gen, validateName } = it;
    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            subSchemaObjCode(it, valid);
            return;
        }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (self.RULES.all[key])
            return true;
    return false;
}
function isSchemaObj(it) {
    return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
    const { schema, gen, opts } = it;
    if (opts.$comment && schema.$comment)
        commentKeyword(it);
    updateContext(it);
    checkAsyncSchema(it);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it, errsCount);
    // TODO var
    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
    (0, util_1.checkUnknownRules)(it);
    checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
    if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
    const types = (0, dataType_1.getSchemaTypes)(it.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
    schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
    const { schema, errSchemaPath, opts, self } = it;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
}
function checkNoDefault(it) {
    const { schema, opts } = it;
    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
    }
}
function updateContext(it) {
    const schId = it.schema[it.opts.schemaId];
    if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
    if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
    }
    else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
}
function returnResults(it) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
    if (schemaEnv.$async) {
        // TODO assign unevaluated
        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
            assignEvaluated(it);
        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
    }
}
function assignEvaluated({ gen, evaluated, props, items }) {
    if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
    if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
    const { gen, schema, data, allErrors, opts, self } = it;
    const { RULES } = self;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
        return;
    }
    if (!opts.jtd)
        checkStrictTypes(it, types);
    gen.block(() => {
        for (const group of RULES.rules)
            groupKeywords(group);
        groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
            return;
        if (group.type) {
            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
            iterateKeywords(it, group);
            if (types.length === 1 && types[0] === group.type && typeErrors) {
                gen.else();
                (0, dataType_2.reportTypeError)(it);
            }
            gen.endIf();
        }
        else {
            iterateKeywords(it, group);
        }
        // TODO make it "ok" call?
        if (!allErrors)
            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
    }
}
function iterateKeywords(it, group) {
    const { gen, schema, opts: { useDefaults }, } = it;
    if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
    gen.block(() => {
        for (const rule of group.rules) {
            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
                keywordCode(it, rule.keyword, rule.definition, group.type);
            }
        }
    });
}
function checkStrictTypes(it, types) {
    if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
    checkContextTypes(it, types);
    if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types);
    checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
    if (!types.length)
        return;
    if (!it.dataTypes.length) {
        it.dataTypes = types;
        return;
    }
    types.forEach((t) => {
        if (!includesType(it.dataTypes, t)) {
            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
    });
    narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
    }
}
function checkKeywordTypes(it, ts) {
    const rules = it.self.RULES.all;
    for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
            const { type } = rule.definition;
            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
            }
        }
    }
}
function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
    return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
    const ts = [];
    for (const t of it.dataTypes) {
        if (includesType(withTypes, t))
            ts.push(t);
        else if (withTypes.includes("integer") && t === "number")
            ts.push("integer");
    }
    it.dataTypes = ts;
}
function strictTypesError(it, msg) {
    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
    constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        }
        else {
            this.schemaCode = this.schemaValue;
            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
            }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
            this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
    }
    result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
            failAction();
        else
            this.error();
        if (successAction) {
            this.gen.else();
            successAction();
            if (this.allErrors)
                this.gen.endIf();
        }
        else {
            if (this.allErrors)
                this.gen.endIf();
            else
                this.gen.else();
        }
    }
    pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
    }
    fail(condition) {
        if (condition === undefined) {
            this.error();
            if (!this.allErrors)
                this.gen.if(false); // this branch will be removed by gen.optimize
            return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
            this.gen.endIf();
        else
            this.gen.else();
    }
    fail$data(condition) {
        if (!this.$data)
            return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
        if (errorParams) {
            this.setParams(errorParams);
            this._error(append, errorPaths);
            this.setParams({});
            return;
        }
        this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
        if (this.errsCount === undefined)
            throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
        if (!this.allErrors)
            this.gen.if(cond);
    }
    setParams(obj, assign) {
        if (assign)
            Object.assign(this.params, obj);
        else
            this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
            this.check$data(valid, $dataValid);
            codeBlock();
        });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
            return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
            gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
            gen.elseIf(this.invalid$data());
            this.$dataError();
            if (valid !== codegen_1.nil)
                gen.assign(valid, false);
        }
        gen.else();
    }
    invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
            if (schemaType.length) {
                /* istanbul ignore if */
                if (!(schemaCode instanceof codegen_1.Name))
                    throw new Error("ajv implementation error");
                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
            }
            return codegen_1.nil;
        }
        function invalid$DataSchema() {
            if (def.validateSchema) {
                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
            }
            return codegen_1.nil;
        }
    }
    subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
        subschemaCode(nextContext, valid);
        return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
            return;
        if (it.props !== true && schemaCxt.props !== undefined) {
            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== undefined) {
            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
    }
    mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
            return true;
        }
    }
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
    const cxt = new KeywordCxt(it, def, keyword);
    if ("code" in def) {
        def.code(cxt, ruleType);
    }
    else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
    else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
    }
    else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data;
    if ($data === "")
        return names_1.default.rootData;
    if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
    }
    else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
            if (up >= dataLevel)
                throw new Error(errorMsg("property/index", up));
            return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
            throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
            return data;
    }
    let expr = data;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
        if (segment) {
            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
            expr = (0, codegen_1._) `${expr} && ${data}`;
        }
    }
    return expr;
    function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
    }
}
exports.getData = getData;
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/validate/index.ts"],"names":[],"mappings":";;;AASA,6CAAoE;AACpE,yCAAiE;AACjE,mDAA6D;AAC7D,yCAAmF;AACnF,yCAAyC;AACzC,uCAAkG;AAClG,2CAAiG;AACjG,wCAAwF;AACxF,oCAAwB;AACxB,wCAAqC;AACrC,kCAOgB;AAEhB,sCAMkB;AAElB,mGAAmG;AACnG,SAAgB,oBAAoB,CAAC,EAAa;IAChD,IAAI,WAAW,CAAC,EAAE,CAAC,EAAE,CAAC;QACpB,aAAa,CAAC,EAAE,CAAC,CAAA;QACjB,IAAI,iBAAiB,CAAC,EAAE,CAAC,EAAE,CAAC;YAC1B,gBAAgB,CAAC,EAAE,CAAC,CAAA;YACpB,OAAM;QACR,CAAC;IACH,CAAC;IACD,gBAAgB,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,IAAA,iCAAoB,EA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,WAAW,IAAI,EAAE,gCAAgC,SAAS,EAAE,CAAA;IACtF,CAAC;AACH,CAAC;AAtCD,0BAsCC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const errors_1 = require("../errors");
function macroKeywordCode(cxt, def) {
    const { gen, keyword, schema, parentSchema, it } = cxt;
    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
    const schemaRef = useKeyword(gen, keyword, macroSchema);
    if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true,
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
    var _a;
    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
    checkAsyncKeyword(it, def);
    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
    const validateRef = useKeyword(gen, keyword, validate);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
    function validateKeyword() {
        if (def.errors === false) {
            assignValid();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => cxt.error());
        }
        else {
            const ruleErrs = def.async ? validateAsync() : validateSync();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => addErrs(cxt, ruleErrs));
        }
    }
    function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
        return ruleErrs;
    }
    function validateSync() {
        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !(("compile" in def && !$data) || def.schema === false);
        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors) {
        var _a;
        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
    }
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
    const { gen, data, it } = cxt;
    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
        gen
            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
    if (result === undefined)
        throw new Error(`keyword "${keyword}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
    // TODO add tests
    return (!schemaType.length ||
        schemaType.some((st) => st === "array"
            ? Array.isArray(schema)
            : st === "object"
                ? schema && typeof schema == "object" && !Array.isArray(schema)
                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
    /* istanbul ignore if */
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
                self.errorsText(def.validateSchema.errors);
            if (opts.validateSchema === "log")
                self.logger.error(msg);
            else
                throw new Error(msg);
        }
    }
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map{"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../lib/compile/validate/keyword.ts"],"names":[],"mappings":";;;AAUA,wCAAsE;AACtE,oCAAwB;AAExB,kDAAwD;AACxD,sCAAsC;AAItC,SAAgB,gBAAgB,CAAC,GAAe,EAAE,GAA2B;IAC3E,MAAM,EAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACpD,MAAM,WAAW,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC,CAAA;IACrE,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,CAAC,CAAA;IACvD,IAAI,EAAE,CAAC,IAAI,CAAC,cAAc,KAAK,KAAK;QAAE,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IAE/E,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,GAAG,CAAC,SAAS,CACX;QACE,MAAM,EAAE,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KAAK;gBAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;;gBACpD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;QAC3B,CAAC;IACH,CAAC;AACH,CAAC;AAzBD,oDAyBC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword !== undefined && schema !== undefined) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword !== undefined) {
        const sch = it.schema[keyword];
        return schemaProp === undefined
            ? {
                schema: sch,
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
            }
            : {
                schema: sch[schemaProp],
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
            };
    }
    if (schema !== undefined) {
        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
            schema,
            schemaPath,
            topSchemaRef,
            errSchemaPath,
        };
    }
    throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
    if (data !== undefined && dataProp !== undefined) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it;
    if (dataProp !== undefined) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
    }
    if (data !== undefined) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
        dataContextProps(nextData);
        if (propertyName !== undefined)
            subschema.propertyName = propertyName;
        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
    }
    if (dataTypes)
        subschema.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
    }
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== undefined)
        subschema.compositeRule = compositeRule;
    if (createErrors !== undefined)
        subschema.createErrors = createErrors;
    if (allErrors !== undefined)
        subschema.allErrors = allErrors;
    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
    subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map{"version":3,"file":"subschema.js","sourceRoot":"","sources":["../../../lib/compile/validate/subschema.ts"],"names":[],"mappings":";;;AAEA,wCAA0D;AAC1D,kCAA0D;AA6C1D,SAAgB,YAAY,CAC1B,EAAgB,EAChB,EAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAgB;IAErF,IAAI,OAAO,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,E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AC,SAAS,GAAG,EAAE,CAAC,SAAS,GAAG,CAAC,CAAA;QACtC,SAAS,CAAC,SAAS,GAAG,EAAE,CAAA;QACxB,EAAE,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAU,CAAA;QACxC,SAAS,CAAC,UAAU,GAAG,EAAE,CAAC,IAAI,CAAA;QAC9B,SAAS,CAAC,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;IACpD,CAAC;AACH,CAAC;AArCD,kDAqCC;AAED,SAAgB,mBAAmB,CACjC,SAA2B,EAC3B,EAAC,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,EAAE,SAAS,EAAgB;IAEtF,IAAI,aAAa,KAAK,SAAS;QAAE,SAAS,CAAC,aAAa,GAAG,aAAa,CAAA;IACxE,IAAI,YAAY,KAAK,SAAS;QAAE,SAAS,CAAC,YAAY,GAAG,YAAY,CAAA;IACrE,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5D,SAAS,CAAC,gBAAgB,GAAG,gBAAgB,CAAA,CAAC,gBAAgB;IAC9D,SAAS,CAAC,WAAW,GAAG,WAAW,CAAA,CAAC,gBAAgB;AACtD,CAAC;AATD,kDASC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const type_1 = require("../../vocabularies/jtd/type");
const parseJson_1 = require("../../runtime/parseJson");
const util_1 = require("../util");
const timestamp_1 = require("../../runtime/timestamp");
const genParse = {
    elements: parseElements,
    values: parseValues,
    discriminator: parseDiscriminator,
    properties: parseProperties,
    optionalProperties: parseProperties,
    enum: parseEnum,
    type: parseType,
    ref: parseRef,
};
function compileParser(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const parseName = gen.scopeName("parse");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
        parseName,
        char: gen.name("c"),
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.parseName = parseName;
        parserFunction(cxt);
        gen.optimize(this.opts.code.optimize);
        const parseFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
        const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
        const parse = makeParse(this.scope.get());
        this.scope.value(parseName, { ref: parse });
        sch.parse = parse;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling parser, function code:", sourceCode);
        delete sch.parse;
        delete sch.parseName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileParser;
const undef = (0, codegen_1._) `undefined`;
function parserFunction(cxt) {
    const { gen, parseName, char } = cxt;
    gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
        gen.let(names_1.default.data);
        gen.let(char);
        gen.assign((0, codegen_1._) `${parseName}.message`, undef);
        gen.assign((0, codegen_1._) `${parseName}.position`, undef);
        gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`);
        gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`);
        parseCode(cxt);
        skipWhitespace(cxt);
        gen.if(names_1.default.jsonPart, () => {
            gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
            gen.return(names_1.default.data);
        });
        gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
        jsonSyntaxError(cxt);
    });
}
function parseCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    if (form)
        parseNullable(cxt, genParse[form]);
    else
        parseEmpty(cxt);
}
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
function parseNullable(cxt, parseForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return parseForm(cxt);
    tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
}
function parseElements(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "[");
    const ix = gen.let("i", 0);
    gen.assign(data, (0, codegen_1._) `[]`);
    parseItems(cxt, "]", () => {
        const el = gen.let("el");
        parseCode({ ...cxt, schema: schema.elements, data: el });
        gen.assign((0, codegen_1._) `${data}[${ix}++]`, el);
    });
}
function parseValues(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
}
function parseItems(cxt, endToken, block) {
    tryParseItems(cxt, endToken, block);
    parseToken(cxt, endToken);
}
function tryParseItems(cxt, endToken, block) {
    const { gen } = cxt;
    gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
        block();
        tryParseToken(cxt, ",", () => gen.break(), hasItem);
    });
    function hasItem() {
        tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
    }
}
function parseKeyValue(cxt, schema) {
    const { gen } = cxt;
    const key = gen.let("key");
    parseString({ ...cxt, data: key });
    parseToken(cxt, ":");
    parsePropertyValue(cxt, key, schema);
}
function parseDiscriminator(cxt) {
    const { gen, data, schema } = cxt;
    const { discriminator, mapping } = schema;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    const startPos = gen.const("pos", names_1.default.jsonPos);
    const value = gen.let("value");
    const tag = gen.let("tag");
    tryParseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => {
            parseString({ ...cxt, data: tag });
            gen.assign((0, codegen_1._) `${data}[${key}]`, tag);
            gen.break();
        }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
        );
    });
    gen.assign(names_1.default.jsonPos, startPos);
    gen.if((0, codegen_1._) `${tag} === undefined`);
    parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`);
    for (const tagValue in mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
    }
    gen.else();
    parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`);
    gen.endIf();
}
function parseProperties(cxt) {
    const { gen, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseSchemaProperties(cxt);
}
function parseSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties, additionalProperties } = schema;
    parseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if(false);
        parseDefinedProperty(cxt, key, properties);
        parseDefinedProperty(cxt, key, optionalProperties);
        if (discriminator) {
            gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`);
            const tag = gen.let("tag");
            parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
        }
        gen.else();
        if (additionalProperties) {
            parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` });
        }
        else {
            parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`);
        }
        gen.endIf();
    });
    if (properties) {
        const hasProp = (0, code_1.hasPropFunc)(gen);
        const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`));
        gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`));
    }
}
function parseDefinedProperty(cxt, key, schemas = {}) {
    const { gen } = cxt;
    for (const prop in schemas) {
        gen.elseIf((0, codegen_1._) `${key} === ${prop}`);
        parsePropertyValue(cxt, key, schemas[prop]);
    }
}
function parsePropertyValue(cxt, key, schema) {
    parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` });
}
function parseType(cxt) {
    const { gen, schema, data, self } = cxt;
    switch (schema.type) {
        case "boolean":
            parseBoolean(cxt);
            break;
        case "string":
            parseString(cxt);
            break;
        case "timestamp": {
            parseString(cxt);
            const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
            const { allowDate, parseDate } = self.opts;
            const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`;
            const fail = parseDate
                ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`)
                : notValid;
            gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`));
            break;
        }
        case "float32":
        case "float64":
            parseNumber(cxt);
            break;
        default: {
            const t = schema.type;
            if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
                parseNumber(cxt, 16); // 2 ** 53 - max safe integer
                if (t === "uint32") {
                    gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
                }
            }
            else {
                const [min, max, maxDigits] = type_1.intRange[t];
                parseNumber(cxt, maxDigits);
                gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
            }
        }
    }
}
function parseString(cxt) {
    parseToken(cxt, '"');
    parseWith(cxt, parseJson_1.parseJsonString);
}
function parseEnum(cxt) {
    const { gen, data, schema } = cxt;
    const enumSch = schema.enum;
    parseToken(cxt, '"');
    // TODO loopEnum
    gen.if(false);
    for (const value of enumSch) {
        const valueStr = JSON.stringify(value).slice(1); // remove starting quote
        gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`);
        gen.assign(data, (0, codegen_1.str) `${value}`);
        gen.add(names_1.default.jsonPos, valueStr.length);
    }
    gen.else();
    jsonSyntaxError(cxt);
    gen.endIf();
}
function parseNumber(cxt, maxDigits) {
    const { gen } = cxt;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
}
function parseBooleanToken(bool, fail) {
    return (cxt) => {
        const { gen, data } = cxt;
        tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
    };
}
function parseRef(cxt) {
    const { gen, self, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return parseCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    partialParse(cxt, getParser(gen, sch), true);
}
function getParser(gen, sch) {
    return sch.parse
        ? gen.scopeValue("parse", { ref: sch.parse })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
}
function parseEmpty(cxt) {
    parseWith(cxt, parseJson_1.parseJson);
}
function parseWith(cxt, parseFunc, args) {
    partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args);
}
function partialParse(cxt, parseFunc, args) {
    const { gen, data } = cxt;
    gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`);
    gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`);
    gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`));
}
function parseToken(cxt, tok) {
    tryParseToken(cxt, tok, jsonSyntaxError);
}
function tryParseToken(cxt, tok, fail, success) {
    const { gen } = cxt;
    const n = tok.length;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => {
        gen.add(names_1.default.jsonPos, n);
        success === null || success === void 0 ? void 0 : success(cxt);
    }, () => fail(cxt));
}
function skipWhitespace({ gen, char: c }) {
    gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
}
function jsonSlice(len) {
    return len === 1
        ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]`
        : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
}
function jsonSyntaxError(cxt) {
    parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
}
function parsingError({ gen, parseName }, msg) {
    gen.assign((0, codegen_1._) `${parseName}.message`, msg);
    gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
    gen.return(undef);
}
//# sourceMappingURL=parse.js.map{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../../lib/compile/jtd/parse.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAmF;AACnF,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAmD;AACnD,oDAAiD;AACjD,sDAA6D;AAC7D,uDAAmF;AACnF,kCAA+B;AAC/B,uDAAoD;AAIpD,MAAM,QAAQ,GAA+B;IAC3C,QAAQ,EAAE,aAAa;IACvB,MAAM,EAAE,WAAW;IACnB,aAAa,EAAE,kBAAkB;IACjC,UAAU,EAAE,eAAe;IAC3B,kBAAkB,EAAE,eAAe;IACnC,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,QAAQ;CACd,CAAA;AAaD,SAAwB,aAAa,CAEnC,GAA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Aa,CAAC,aAAa,eAAC,CAAC,OAAO,KAAK,CAC7G,CAAA;AACH,CAAC;AAED,SAAS,SAAS,CAAC,GAAkB;IACnC,OAAO,GAAG,KAAK,CAAC;QACd,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,IAAI,eAAC,CAAC,OAAO,GAAG;QAC5B,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,UAAU,eAAC,CAAC,OAAO,KAAK,eAAC,CAAC,OAAO,IAAI,GAAG,GAAG,CAAA;AAC3D,CAAC;AAED,SAAS,eAAe,CAAC,GAAa;IACpC,YAAY,CAAC,GAAG,EAAE,IAAA,WAAC,EAAA,yBAAyB,eAAC,CAAC,IAAI,IAAI,eAAC,CAAC,OAAO,GAAG,CAAC,CAAA;AACrE,CAAC;AAED,SAAS,YAAY,CAAC,EAAC,GAAG,EAAE,SAAS,EAAW,EAAE,GAAS;IACzD,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,UAAU,EAAE,GAAG,CAAC,CAAA;IACxC,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;IAC/C,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACnB,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const util_1 = require("../util");
const quote_1 = require("../../runtime/quote");
const genSerialize = {
    elements: serializeElements,
    values: serializeValues,
    discriminator: serializeDiscriminator,
    properties: serializeProperties,
    optionalProperties: serializeProperties,
    enum: serializeString,
    type: serializeType,
    ref: serializeRef,
};
function compileSerializer(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const serializeName = gen.scopeName("serialize");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.serializeName = serializeName;
        gen.func(serializeName, names_1.default.data, false, () => {
            gen.let(names_1.default.json, (0, codegen_1.str) ``);
            serializeCode(cxt);
            gen.return(names_1.default.json);
        });
        gen.optimize(this.opts.code.optimize);
        const serializeFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
        const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
        const serialize = makeSerialize(this.scope.get());
        this.scope.value(serializeName, { ref: serialize });
        sch.serialize = serialize;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling serializer, function code:", sourceCode);
        delete sch.serialize;
        delete sch.serializeName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileSerializer;
function serializeCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return serializeForm(cxt);
    gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `[`);
    const first = gen.let("first", true);
    gen.forOf("el", data, (el) => {
        addComma(cxt, first);
        serializeCode({ ...cxt, schema: schema.elements, data: el });
    });
    gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    const first = gen.let("first", true);
    gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
    const { gen, data } = cxt;
    addComma(cxt, first);
    serializeString({ ...cxt, data: key });
    gen.add(names_1.default.json, (0, codegen_1.str) `:`);
    const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
    const { gen, schema, data } = cxt;
    const { discriminator } = schema;
    gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
    const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
    serializeString({ ...cxt, data: tag });
    gen.if(false);
    for (const tagValue in schema.mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        const sch = schema.mapping[tagValue];
        serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
    }
    gen.endIf();
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
    const { gen } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    serializeSchemaProperties(cxt);
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties } = schema;
    const props = keys(properties);
    const optProps = keys(optionalProperties);
    const allProps = allProperties(props.concat(optProps));
    let first = !discriminator;
    let firstProp;
    for (const key of props) {
        if (first)
            first = false;
        else
            gen.add(names_1.default.json, (0, codegen_1.str) `,`);
        serializeProperty(key, properties[key], keyValue(key));
    }
    if (first)
        firstProp = gen.let("first", true);
    for (const key of optProps) {
        const value = keyValue(key);
        gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => {
            addComma(cxt, firstProp);
            serializeProperty(key, optionalProperties[key], value);
        });
    }
    if (schema.additionalProperties) {
        gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)));
    }
    function keys(ps) {
        return ps ? Object.keys(ps) : [];
    }
    function allProperties(ps) {
        if (discriminator)
            ps.push(discriminator);
        if (new Set(ps).size !== ps.length) {
            throw new Error("JTD: properties/optionalProperties/disciminator overlap");
        }
        return ps;
    }
    function keyValue(key) {
        return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    }
    function serializeProperty(key, propSchema, value) {
        gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
        serializeCode({ ...cxt, schema: propSchema, data: value });
    }
    function isAdditional(key, ps) {
        return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
    }
}
function serializeType(cxt) {
    const { gen, schema, data } = cxt;
    switch (schema.type) {
        case "boolean":
            gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
            break;
        case "string":
            serializeString(cxt);
            break;
        case "timestamp":
            gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
            break;
        default:
            serializeNumber(cxt);
    }
}
function serializeString({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data, self }) {
    const condition = (0, codegen_1._) `${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`;
    if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
        gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
    }
    else {
        // specialNumbers === "null"
        gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._) `null`), () => gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`));
    }
}
function serializeRef(cxt) {
    const { gen, self, data, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return serializeCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
    return sch.serialize
        ? gen.scopeValue("serialize", { ref: sch.serialize })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
    if (first) {
        gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
    }
    else {
        gen.add(names_1.default.json, (0, codegen_1.str) `,`);
    }
}
//# sourceMappingURL=serialize.js.map{"version":3,"file":"serialize.js","sourceRoot":"","sources":["../../../lib/compile/jtd/serialize.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAwE;AACxE,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAqD;AACrD,oDAAiD;AACjD,kCAA+B;AAC/B,+CAAuC;AAEvC,MAAM,YAAY,GAAkD;IAClE,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,eAAe;IACvB,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,mBAAmB;IAC/B,kBAAkB,EAAE,mBAAmB;IACvC,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,aAAa;IACnB,GAAG,EAAE,YAAY;CAClB,CAAA;AAWD,SAAwB,iBAAiB,CAEvC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,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IAAA,WAAC,EAAA,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;AACxD,CAAC;AAED,SAAS,YAAY,CAAC,GAAY,EAAE,GAAc;IAChD,OAAO,GAAG,CAAC,SAAS;QAClB,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,EAAC,GAAG,EAAE,GAAG,CAAC,SAAS,EAAC,CAAC;QACnD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,YAAY,CAAA;AAC3D,CAAC;AAED,SAAS,cAAc,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAC/C,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,kBAAkB,IAAI,GAAG,CAAC,CAAA;AAC7C,CAAC;AAED,SAAS,QAAQ,CAAC,EAAC,GAAG,EAAe,EAAE,KAAY;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,EAAE,CACJ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC9B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAC9B,CAAA;IACH,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACzB,CAAC;AACH,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jtdForms = void 0;
exports.jtdForms = [
    "elements",
    "values",
    "discriminator",
    "properties",
    "optionalProperties",
    "enum",
    "type",
    "ref",
];
//# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
    constructor(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        return false;
    }
    get names() {
        return { [this.str]: 1 };
    }
}
exports.Name = Name;
class _Code extends _CodeOrName {
    constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        if (this._items.length > 1)
            return false;
        const item = this._items[0];
        return item === "" || item === '""';
    }
    get str() {
        var _a;
        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
    }
    get names() {
        var _a;
        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
            if (c instanceof Name)
                names[c.str] = (names[c.str] || 0) + 1;
            return names;
        }, {})));
    }
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
    const code = [strs[0]];
    let i = 0;
    while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
    }
    return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
    if (arg instanceof _Code)
        code.push(...arg._items);
    else if (arg instanceof Name)
        code.push(arg);
    else
        code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
        if (expr[i] === plus) {
            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
            if (res !== undefined) {
                expr.splice(i - 1, 3, res);
                continue;
            }
            expr[i++] = "+";
        }
        i++;
    }
}
function mergeExprItems(a, b) {
    if (b === '""')
        return a;
    if (a === '""')
        return b;
    if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
            return;
        if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
        return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.slice(1)}`;
    return;
}
function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null
        ? x
        : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
    return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
    return JSON.stringify(x)
        .replace(/\u2028/g, "\\u2028")
        .replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
    return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,kEAAkE;AAClE,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,YAAY,CAAS;QACnB,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAU,CAAC,IAAI,CAAC,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QACpF,IAAI,CAAC,GAAG,GAAG,CAAC,CAAA;IACd,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,KAAK;QACP,OAAO,EAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAC,CAAA;IACxB,CAAC;CACF;AAnBD,oBAmBC;AAED,MAAa,KAAM,SAAQ,WAAW;IAKpC,YAAY,IAAkC;QAC5C,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,MAAM,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACxD,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,KAAK,CAAA;QACxC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QAC3B,OAAO,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,IAAI,CAAA;IACrC,CAAC;IAED,IAAI,GAAG;;QACL,OAAO,OAAC,IAAI,CAA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AED,SAAgB,UAAU,CAAC,EAAU;IACnC,OAAO,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;AACjC,CAAC;AAFD,gCAEC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = require("./code");
const scope_1 = require("./scope");
var code_2 = require("./code");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
var scope_2 = require("./scope");
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
exports.operators = {
    GT: new code_1._Code(">"),
    GTE: new code_1._Code(">="),
    LT: new code_1._Code("<"),
    LTE: new code_1._Code("<="),
    EQ: new code_1._Code("==="),
    NEQ: new code_1._Code("!=="),
    NOT: new code_1._Code("!"),
    OR: new code_1._Code("||"),
    AND: new code_1._Code("&&"),
    ADD: new code_1._Code("+"),
};
class Node {
    optimizeNodes() {
        return this;
    }
    optimizeNames(_names, _constants) {
        return this;
    }
}
class Def extends Node {
    constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
    }
    render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (!names[this.name.str])
            return;
        if (this.rhs)
            this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
    }
}
class Assign extends Node {
    constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
    }
    render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
            return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
    }
}
class AssignOp extends Assign {
    constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
    }
    render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
    }
}
class Label extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        return `${this.label}:` + _n;
    }
}
class Break extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
    }
}
class Throw extends Node {
    constructor(error) {
        super();
        this.error = error;
    }
    render({ _n }) {
        return `throw ${this.error};` + _n;
    }
    get names() {
        return this.error.names;
    }
}
class AnyCode extends Node {
    constructor(code) {
        super();
        this.code = code;
    }
    render({ _n }) {
        return `${this.code};` + _n;
    }
    optimizeNodes() {
        return `${this.code}` ? this : undefined;
    }
    optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
    }
    get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
    }
}
class ParentNode extends Node {
    constructor(nodes = []) {
        super();
        this.nodes = nodes;
    }
    render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
    }
    optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            const n = nodes[i].optimizeNodes();
            if (Array.isArray(n))
                nodes.splice(i, 1, ...n);
            else if (n)
                nodes[i] = n;
            else
                nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    optimizeNames(names, constants) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            // iterating backwards improves 1-pass optimization
            const n = nodes[i];
            if (n.optimizeNames(names, constants))
                continue;
            subtractNames(names, n.names);
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
    }
}
class BlockNode extends ParentNode {
    render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
    }
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
    constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
    }
    render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
            code += "else " + this.else.render(opts);
        return code;
    }
    optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
            return this.nodes; // else is ignored here
        let e = this.else;
        if (e) {
            const ns = e.optimizeNodes();
            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e) {
            if (cond === false)
                return e instanceof If ? e : e.nodes;
            if (this.nodes.length)
                return this;
            return new If(not(cond), e instanceof If ? [e] : e.nodes);
        }
        if (cond === false || !this.nodes.length)
            return undefined;
        return this;
    }
    optimizeNames(names, constants) {
        var _a;
        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
            return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
            addNames(names, this.else.names);
        return names;
    }
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
    constructor(iteration) {
        super();
        this.iteration = iteration;
    }
    render(opts) {
        return `for(${this.iteration})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iteration.names);
    }
}
class ForRange extends For {
    constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
    }
    render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
    }
    get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
    }
}
class ForIter extends For {
    constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
    }
    render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iterable.names);
    }
}
class Func extends BlockNode {
    constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
    }
    render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
    }
}
Func.kind = "func";
class Return extends ParentNode {
    render(opts) {
        return "return " + super.render(opts);
    }
}
Return.kind = "return";
class Try extends BlockNode {
    render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
            code += this.catch.render(opts);
        if (this.finally)
            code += this.finally.render(opts);
        return code;
    }
    optimizeNodes() {
        var _a, _b;
        super.optimizeNodes();
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
    }
    optimizeNames(names, constants) {
        var _a, _b;
        super.optimizeNames(names, constants);
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        if (this.catch)
            addNames(names, this.catch.names);
        if (this.finally)
            addNames(names, this.finally.names);
        return names;
    }
}
class Catch extends BlockNode {
    constructor(error) {
        super();
        this.error = error;
    }
    render(opts) {
        return `catch(${this.error})` + super.render(opts);
    }
}
Catch.kind = "catch";
class Finally extends BlockNode {
    render(opts) {
        return "finally" + super.render(opts);
    }
}
Finally.kind = "finally";
class CodeGen {
    constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
    }
    toString() {
        return this._root.render(this.opts);
    }
    // returns unique name in the internal scope
    name(prefix) {
        return this._scope.name(prefix);
    }
    // reserves unique name in the external scope
    scopeName(prefix) {
        return this._extScope.name(prefix);
    }
    // reserves unique name in the external scope and assigns value to it
    scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
        vs.add(name);
        return name;
    }
    getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
    }
    // return code that assigns values in the external scope to the names that are used internally
    // (same names that were returned by gen.scopeName or gen.scopeValue)
    scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
    }
    scopeCode() {
        return this._extScope.scopeCode(this._values);
    }
    _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== undefined && constant)
            this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
    }
    // `const` declaration (`var` in es5 mode)
    const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
    }
    // `let` declaration with optional assignment (`var` in es5 mode)
    let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
    }
    // `var` declaration with optional assignment
    var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
    }
    // assignment code
    assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
    }
    // `+=` code
    add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
    }
    // appends passed SafeExpr to code or executes Block
    code(c) {
        if (typeof c == "function")
            c();
        else if (c !== code_1.nil)
            this._leafNode(new AnyCode(c));
        return this;
    }
    // returns code for object literal for the passed argument list of key-value pairs
    object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
            if (code.length > 1)
                code.push(",");
            code.push(key);
            if (key !== value || this.opts.es5) {
                code.push(":");
                (0, code_1.addCodeArg)(code, value);
            }
        }
        code.push("}");
        return new code_1._Code(code);
    }
    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
    if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
            this.code(thenBody).else().code(elseBody).endIf();
        }
        else if (thenBody) {
            this.code(thenBody).endIf();
        }
        else if (elseBody) {
            throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
    }
    // `else if` clause - invalid without `if` or after `else` clauses
    elseIf(condition) {
        return this._elseNode(new If(condition));
    }
    // `else` clause - only valid after `if` or `else if` clauses
    else() {
        return this._elseNode(new Else());
    }
    // end `if` statement (needed if gen.if was used only with condition)
    endIf() {
        return this._endBlockNode(If, Else);
    }
    _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
            this.code(forBody).endFor();
        return this;
    }
    // a generic `for` clause (or statement if `forBody` is passed)
    for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
    }
    // `for` statement for a range of values
    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
    }
    // `for-of` statement (in es5 mode replace with a normal for loop)
    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
                this.var(name, (0, code_1._) `${arr}[${i}]`);
                forBody(name);
            });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
    }
    // `for-in` statement.
    // With option `ownProperties` replaced with a `for-of` loop for object keys
    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
    }
    // end `for` loop
    endFor() {
        return this._endBlockNode(For);
    }
    // `label` statement
    label(label) {
        return this._leafNode(new Label(label));
    }
    // `break` statement
    break(label) {
        return this._leafNode(new Break(label));
    }
    // `return` statement
    return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
            throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
    }
    // `try` statement
    try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
            throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
            const error = this.name("e");
            this._currNode = node.catch = new Catch(error);
            catchCode(error);
        }
        if (finallyCode) {
            this._currNode = node.finally = new Finally();
            this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
    }
    // `throw` statement
    throw(error) {
        return this._leafNode(new Throw(error));
    }
    // start self-balancing block
    block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
            this.code(body).endBlock(nodeCount);
        return this;
    }
    // end the current self-balancing block
    endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === undefined)
            throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
    }
    // `function` heading (or definition if funcBody is passed)
    func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
            this.code(funcBody).endFunc();
        return this;
    }
    // end function definition
    endFunc() {
        return this._endBlockNode(Func);
    }
    optimize(n = 1) {
        while (n-- > 0) {
            this._root.optimizeNodes();
            this._root.optimizeNames(this._root.names, this._constants);
        }
    }
    _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
    }
    _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
    }
    _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || (N2 && n instanceof N2)) {
            this._nodes.pop();
            return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
    }
    _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
            throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
    }
    get _root() {
        return this._nodes[0];
    }
    get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
    }
    set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
    }
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
    return names;
}
function addExprNames(names, from) {
    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
    if (expr instanceof code_1.Name)
        return replaceName(expr);
    if (!canOptimize(expr))
        return expr;
    return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
            c = replaceName(c);
        if (c instanceof code_1._Code)
            items.push(...c._items);
        else
            items.push(c);
        return items;
    }, []));
    function replaceName(n) {
        const c = constants[n.str];
        if (c === undefined || names[n.str] !== 1)
            return n;
        delete names[n.str];
        return c;
    }
    function canOptimize(e) {
        return (e instanceof code_1._Code &&
            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
    }
}
function subtractNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
    return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
    return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/codegen/index.ts"],"names":[],"mappings":";;;AACA,iCAA8F;AAC9F,mCAAuC;AAEvC,+BAA6F;AAArF,yFAAA,CAAC,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,iGAA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AG,CAAC,CAAA;AAEtC,wDAAwD;AACxD,SAAgB,GAAG,CAAC,GAAG,IAAY;IACjC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,CAAC;AAFD,kBAEC;AAED,MAAM,MAAM,GAAG,OAAO,CAAC,iBAAS,CAAC,EAAE,CAAC,CAAA;AAEpC,uDAAuD;AACvD,SAAgB,EAAE,CAAC,GAAG,IAAY;IAChC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;AAC5B,CAAC;AAFD,gBAEC;AAID,SAAS,OAAO,CAAC,EAAQ;IACvB,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,UAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,UAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AACjF,CAAC;AAED,SAAS,GAAG,CAAC,CAAO;IAClB,OAAO,CAAC,YAAY,WAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,CAAC,GAAG,CAAA;AAC1C,CAAC"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = require("./code");
class ValueError extends Error {
    constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
    }
}
var UsedValueState;
(function (UsedValueState) {
    UsedValueState[UsedValueState["Started"] = 0] = "Started";
    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
    const: new code_1.Name("const"),
    let: new code_1.Name("let"),
    var: new code_1.Name("var"),
};
class Scope {
    constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
    }
    toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
    }
    name(prefix) {
        return new code_1.Name(this._newName(prefix));
    }
    _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
    }
    _nameGroup(prefix) {
        var _a, _b;
        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return (this._names[prefix] = { prefix, index: 0 });
    }
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
    constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
    }
    setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
    }
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
    constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
    }
    get() {
        return this._scope;
    }
    name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
    }
    value(nameOrPrefix, value) {
        var _a;
        if (value.ref === undefined)
            throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
        let vs = this._values[prefix];
        if (vs) {
            const _name = vs.get(valueKey);
            if (_name)
                return _name;
        }
        else {
            vs = this._values[prefix] = new Map();
        }
        vs.set(valueKey, name);
        const s = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s.length;
        s[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
    }
    getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
            return;
        return vs.get(keyOrRef);
    }
    scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
            if (name.scopePath === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return (0, code_1._) `${scopeName}${name.scopePath}`;
        });
    }
    scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
            if (name.value === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return name.value.code;
        }, usedValues, getCode);
    }
    _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
            const vs = values[prefix];
            if (!vs)
                continue;
            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
            vs.forEach((name) => {
                if (nameSet.has(name))
                    return;
                nameSet.set(name, UsedValueState.Started);
                let c = valueCode(name);
                if (c) {
                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
                }
                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
                }
                else {
                    throw new ValueError(name);
                }
                nameSet.set(name, UsedValueState.Completed);
            });
        }
        return code;
    }
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../lib/compile/codegen/scope.ts"],"names":[],"mappings":";;;AAAA,iCAAyC;AAezC,MAAM,UAAW,SAAQ,KAAK;IAE5B,YAAY,IAAoB;QAC9B,KAAK,CAAC,uBAAuB,IAAI,cAAc,CAAC,CAAA;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAuBD,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,6DAAS,CAAA;AACX,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAMY,QAAA,Q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AAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK,CAAA;oBACzD,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACxD,CAAC;qBAAM,IAAI,CAAC,CAAC,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,IAAI,CAAC,CAAC,EAAE,CAAC;oBACjC,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACtC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,CAAA;gBAC5B,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;YAC7C,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAjGD,gCAiGC"}extends: eslint:recommended
env:
  node: true
  browser: true
rules:
  block-scoped-var: 2
  complexity: [2, 15]
  curly: [2, multi-or-nest, consistent]
  dot-location: [2, property]
  dot-notation: 2
  indent: [2, 2, SwitchCase: 1]
  linebreak-style: [2, unix]
  new-cap: 2
  no-console: [2, allow: [warn, error]]
  no-else-return: 2
  no-eq-null: 2
  no-fallthrough: 2
  no-invalid-this: 2
  no-return-assign: 2
  no-shadow: 1
  no-trailing-spaces: 2
  no-use-before-define: [2, nofunc]
  quotes: [2, single, avoid-escape]
  semi: [2, always]
  strict: [2, global]
  valid-jsdoc: [2, requireReturn: false]
  no-control-regex: 0
MIT License

Copyright (c) 2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
{
  "name": "json-schema-traverse",
  "version": "1.0.0",
  "description": "Traverse JSON Schema passing each schema object to callback",
  "main": "index.js",
  "types": "index.d.ts",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/epoberezkin/json-schema-traverse.git"
  },
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "homepage": "https://github.com/epoberezkin/json-schema-traverse#readme",
  "devDependencies": {
    "eslint": "^7.3.1",
    "mocha": "^8.0.1",
    "nyc": "^15.0.0",
    "pre-commit": "^1.2.2"
  }
}parserOptions:
  ecmaVersion: 6
globals:
  beforeEach: false
  describe: false
  it: false
'use strict';

var traverse = require('../index');
var assert = require('assert');

describe('json-schema-traverse', function() {
  var calls;

  beforeEach(function() {
    calls = [];
  });

  it('should traverse all keywords containing schemas recursively', function() {
    var schema = require('./fixtures/schema').schema;
    var expectedCalls = require('./fixtures/schema').expectedCalls;

    traverse(schema, {cb: callback});
    assert.deepStrictEqual(calls, expectedCalls);
  });

  describe('Legacy v0.3.1 API', function() {
    it('should traverse all keywords containing schemas recursively', function() {
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should work when an options object is provided', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, {}, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });


  describe('allKeys option', function() {
    var schema = {
      someObject: {
        minimum: 1,
        maximum: 2
      }
    };

    it('should traverse objects with allKeys: true option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined],
        [schema.someObject, '/someObject', schema, '', 'someObject', schema, undefined]
      ];

      traverse(schema, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects with allKeys: false option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {allKeys: false, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects without allKeys option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT travers objects in standard keywords which value is not a schema', function() {
      var schema2 = {
        const: {foo: 'bar'},
        enum: ['a', 'b'],
        required: ['foo'],
        another: {

        },
        patternProperties: {}, // will not traverse - no properties
        dependencies: true, // will not traverse - invalid
        properties: {
          smaller: {
            type: 'number'
          },
          larger: {
            type: 'number',
            minimum: {$data: '1/smaller'}
          }
        }
      };

      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema2, '', schema2, undefined, undefined, undefined, undefined],
        [schema2.another, '/another', schema2, '', 'another', schema2, undefined],
        [schema2.properties.smaller, '/properties/smaller', schema2, '', 'properties', schema2, 'smaller'],
        [schema2.properties.larger, '/properties/larger', schema2, '', 'properties', schema2, 'larger'],
      ];

      traverse(schema2, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  describe('pre and post', function() {
    var schema = {
      type: 'object',
      properties: {
        name: {type: 'string'},
        age: {type: 'number'}
      }
    };

    it('should traverse schema in pre-order', function() {
      traverse(schema, {cb: {pre}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in post-order', function() {
      traverse(schema, {cb: {post}});
      var expectedCalls = [
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in pre- and post-order at the same time', function() {
      traverse(schema, {cb: {pre, post}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  function callback() {
    calls.push(Array.prototype.slice.call(arguments));
  }

  function pre() {
    calls.push(['pre'].concat(Array.prototype.slice.call(arguments)));
  }

  function post() {
    calls.push(['post'].concat(Array.prototype.slice.call(arguments)));
  }
});
'use strict';

var schema = {
  additionalItems: subschema('additionalItems'),
  items: subschema('items'),
  contains: subschema('contains'),
  additionalProperties: subschema('additionalProperties'),
  propertyNames: subschema('propertyNames'),
  not: subschema('not'),
  allOf: [
    subschema('allOf_0'),
    subschema('allOf_1'),
    {
      items: [
        subschema('items_0'),
        subschema('items_1'),
      ]
    }
  ],
  anyOf: [
    subschema('anyOf_0'),
    subschema('anyOf_1'),
  ],
  oneOf: [
    subschema('oneOf_0'),
    subschema('oneOf_1'),
  ],
  definitions: {
    foo: subschema('definitions_foo'),
    bar: subschema('definitions_bar'),
  },
  properties: {
    foo: subschema('properties_foo'),
    bar: subschema('properties_bar'),
  },
  patternProperties: {
    foo: subschema('patternProperties_foo'),
    bar: subschema('patternProperties_bar'),
  },
  dependencies: {
    foo: subschema('dependencies_foo'),
    bar: subschema('dependencies_bar'),
  },
  required: ['foo', 'bar']
};


function subschema(keyword) {
  var sch = {
    properties: {},
    additionalProperties: false,
    additionalItems: false,
    anyOf: [
      {format: 'email'},
      {format: 'hostname'}
    ]
  };
  sch.properties['foo_' + keyword] = {title: 'foo'};
  sch.properties['bar_' + keyword] = {title: 'bar'};
  return sch;
}


module.exports = {
  schema: schema,

  // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
  expectedCalls: [[schema, '', schema, undefined, undefined, undefined, undefined]]
    .concat(expectedCalls('additionalItems'))
    .concat(expectedCalls('items'))
    .concat(expectedCalls('contains'))
    .concat(expectedCalls('additionalProperties'))
    .concat(expectedCalls('propertyNames'))
    .concat(expectedCalls('not'))
    .concat(expectedCallsChild('allOf', 0))
    .concat(expectedCallsChild('allOf', 1))
    .concat([
      [schema.allOf[2], '/allOf/2', schema, '', 'allOf', schema, 2],
      [schema.allOf[2].items[0], '/allOf/2/items/0', schema, '/allOf/2', 'items', schema.allOf[2], 0],
      [schema.allOf[2].items[0].properties.foo_items_0, '/allOf/2/items/0/properties/foo_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'foo_items_0'],
      [schema.allOf[2].items[0].properties.bar_items_0, '/allOf/2/items/0/properties/bar_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'bar_items_0'],
      [schema.allOf[2].items[0].anyOf[0], '/allOf/2/items/0/anyOf/0', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 0],
      [schema.allOf[2].items[0].anyOf[1], '/allOf/2/items/0/anyOf/1', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 1],

      [schema.allOf[2].items[1], '/allOf/2/items/1', schema, '/allOf/2', 'items', schema.allOf[2], 1],
      [schema.allOf[2].items[1].properties.foo_items_1, '/allOf/2/items/1/properties/foo_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'foo_items_1'],
      [schema.allOf[2].items[1].properties.bar_items_1, '/allOf/2/items/1/properties/bar_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'bar_items_1'],
      [schema.allOf[2].items[1].anyOf[0], '/allOf/2/items/1/anyOf/0', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 0],
      [schema.allOf[2].items[1].anyOf[1], '/allOf/2/items/1/anyOf/1', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 1]
    ])
    .concat(expectedCallsChild('anyOf', 0))
    .concat(expectedCallsChild('anyOf', 1))
    .concat(expectedCallsChild('oneOf', 0))
    .concat(expectedCallsChild('oneOf', 1))
    .concat(expectedCallsChild('definitions', 'foo'))
    .concat(expectedCallsChild('definitions', 'bar'))
    .concat(expectedCallsChild('properties', 'foo'))
    .concat(expectedCallsChild('properties', 'bar'))
    .concat(expectedCallsChild('patternProperties', 'foo'))
    .concat(expectedCallsChild('patternProperties', 'bar'))
    .concat(expectedCallsChild('dependencies', 'foo'))
    .concat(expectedCallsChild('dependencies', 'bar'))
};


function expectedCalls(keyword) {
  return [
    [schema[keyword], `/${keyword}`, schema, '', keyword, schema, undefined],
    [schema[keyword].properties[`foo_${keyword}`], `/${keyword}/properties/foo_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `foo_${keyword}`],
    [schema[keyword].properties[`bar_${keyword}`], `/${keyword}/properties/bar_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `bar_${keyword}`],
    [schema[keyword].anyOf[0], `/${keyword}/anyOf/0`, schema, `/${keyword}`, 'anyOf', schema[keyword], 0],
    [schema[keyword].anyOf[1], `/${keyword}/anyOf/1`, schema, `/${keyword}`, 'anyOf', schema[keyword], 1]
  ];
}


function expectedCallsChild(keyword, i) {
  return [
    [schema[keyword][i], `/${keyword}/${i}`, schema, '', keyword, schema, i],
    [schema[keyword][i].properties[`foo_${keyword}_${i}`], `/${keyword}/${i}/properties/foo_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `foo_${keyword}_${i}`],
    [schema[keyword][i].properties[`bar_${keyword}_${i}`], `/${keyword}/${i}/properties/bar_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `bar_${keyword}_${i}`],
    [schema[keyword][i].anyOf[0], `/${keyword}/${i}/anyOf/0`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 0],
    [schema[keyword][i].anyOf[1], `/${keyword}/${i}/anyOf/1`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 1]
  ];
}
'use strict';

const mimicFn = (to, from) => {
	for (const prop of Reflect.ownKeys(from)) {
		Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
	}

	return to;
};

module.exports = mimicFn;
// TODO: Remove this for the next major release
module.exports.default = mimicFn;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "mimic-fn",
  "version": "2.1.0",
  "description": "Make a function mimic another one",
  "license": "MIT",
  "repository": "sindresorhus/mimic-fn",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "ava": "^1.4.1",
    "tsd": "^0.7.1",
    "xo": "^0.24.0"
  }
}'use strict';
const path = require('path');
const locatePath = require('locate-path');

module.exports = (filename, opts = {}) => {
	const startDir = path.resolve(opts.cwd || '');
	const {root} = path.parse(startDir);

	const filenames = [].concat(filename);

	return new Promise(resolve => {
		(function find(dir) {
			locatePath(filenames, {cwd: dir}).then(file => {
				if (file) {
					resolve(path.join(dir, file));
				} else if (dir === root) {
					resolve(null);
				} else {
					find(path.dirname(dir));
				}
			});
		})(startDir);
	});
};

module.exports.sync = (filename, opts = {}) => {
	let dir = path.resolve(opts.cwd || '');
	const {root} = path.parse(dir);

	const filenames = [].concat(filename);

	// eslint-disable-next-line no-constant-condition
	while (true) {
		const file = locatePath.sync(filenames, {cwd: dir});

		if (file) {
			return path.join(dir, file);
		}

		if (dir === root) {
			return null;
		}

		dir = path.dirname(dir);
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "find-up",
  "version": "3.0.0",
  "description": "Find a file or directory by walking up parent directories",
  "license": "MIT",
  "repository": "sindresorhus/find-up",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "locate-path": "^3.0.0"
  },
  "devDependencies": {
    "ava": "*",
    "tempy": "^0.2.1",
    "xo": "*"
  }
}'use strict';
const path = require('path');
const pathExists = require('path-exists');
const pLocate = require('p-locate');

module.exports = (iterable, options) => {
	options = Object.assign({
		cwd: process.cwd()
	}, options);

	return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options);
};

module.exports.sync = (iterable, options) => {
	options = Object.assign({
		cwd: process.cwd()
	}, options);

	for (const el of iterable) {
		if (pathExists.sync(path.resolve(options.cwd, el))) {
			return el;
		}
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "locate-path",
  "version": "3.0.0",
  "description": "Get the first path that exists on disk of multiple paths",
  "license": "MIT",
  "repository": "sindresorhus/locate-path",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "p-locate": "^3.0.0",
    "path-exists": "^3.0.0"
  },
  "devDependencies": {
    "ava": "*",
    "xo": "*"
  }
}'use strict';
const pTry = require('p-try');

const pLimit = concurrency => {
	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
		return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
	}

	const queue = [];
	let activeCount = 0;

	const next = () => {
		activeCount--;

		if (queue.length > 0) {
			queue.shift()();
		}
	};

	const run = (fn, resolve, ...args) => {
		activeCount++;

		const result = pTry(fn, ...args);

		resolve(result);

		result.then(next, next);
	};

	const enqueue = (fn, resolve, ...args) => {
		if (activeCount < concurrency) {
			run(fn, resolve, ...args);
		} else {
			queue.push(run.bind(null, fn, resolve, ...args));
		}
	};

	const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
	Object.defineProperties(generator, {
		activeCount: {
			get: () => activeCount
		},
		pendingCount: {
			get: () => queue.length
		},
		clearQueue: {
			value: () => {
				queue.length = 0;
			}
		}
	});

	return generator;
};

module.exports = pLimit;
module.exports.default = pLimit;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "p-limit",
  "version": "2.3.0",
  "description": "Run multiple promise-returning & async functions with limited concurrency",
  "license": "MIT",
  "repository": "sindresorhus/p-limit",
  "funding": "https://github.com/sponsors/sindresorhus",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "dependencies": {
    "p-try": "^2.0.0"
  },
  "devDependencies": {
    "ava": "^1.2.1",
    "delay": "^4.1.0",
    "in-range": "^1.0.0",
    "random-int": "^1.0.0",
    "time-span": "^2.0.0",
    "tsd-check": "^0.3.0",
    "xo": "^0.24.0"
  }
}'use strict';
const pLimit = require('p-limit');

class EndError extends Error {
	constructor(value) {
		super();
		this.value = value;
	}
}

// The input can also be a promise, so we `Promise.resolve()` it
const testElement = (el, tester) => Promise.resolve(el).then(tester);

// The input can also be a promise, so we `Promise.all()` them both
const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));

module.exports = (iterable, tester, opts) => {
	opts = Object.assign({
		concurrency: Infinity,
		preserveOrder: true
	}, opts);

	const limit = pLimit(opts.concurrency);

	// Start all the promises concurrently with optional limit
	const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);

	// Check the promises either serially or concurrently
	const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);

	return Promise.all(items.map(el => checkLimit(finder, el)))
		.then(() => {})
		.catch(err => err instanceof EndError ? err.value : Promise.reject(err));
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
  "name": "p-locate",
  "version": "3.0.0",
  "description": "Get the first fulfilled promise that satisfies the provided testing function",
  "license": "MIT",
  "repository": "sindresorhus/p-locate",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=6"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "p-limit": "^2.0.0"
  },
  "devDependencies": {
    "ava": "*",
    "delay": "^3.0.0",
    "in-range": "^1.0.0",
    "time-span": "^2.0.0",
    "xo": "*"
  }
}'use strict';
const fs = require('fs');

module.exports = fp => new Promise(resolve => {
	fs.access(fp, err => {
		resolve(!err);
	});
});

module.exports.sync = fp => {
	try {
		fs.accessSync(fp);
		return true;
	} catch (err) {
		return false;
	}
};
The MIT License (MIT)

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
{
  "name": "path-exists",
  "version": "3.0.0",
  "description": "Check if a path exists",
  "license": "MIT",
  "repository": "sindresorhus/path-exists",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=4"
  },
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "ava": "*",
    "xo": "*"
  }
}